@odatano/core 2.0.0-rc.30 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@odatano/core",
3
- "version": "2.0.0-rc.30",
3
+ "version": "2.0.0-rc.31",
4
4
  "description": "SAP CAP plugin for Cardano blockchain OData V4 integration",
5
5
  "imports": {
6
6
  "#cds-models/*": "./@cds-models/*/index.js"
@@ -544,6 +544,8 @@ class CardanoIndexer {
544
544
  * cannot answer. Runs on `cds.db`, i.e. inside the caller's request transaction when there is one.
545
545
  */
546
546
  async localAddressUtxos(address) {
547
+ if (!cds_1.default.db)
548
+ return null;
547
549
  return (await this.localAddress(cds_1.default.db, address))?.utxos ?? null;
548
550
  }
549
551
  /**
@@ -90,6 +90,13 @@ export declare class BuildooorTxBuilder implements CardanoTxBuilder {
90
90
  * which mismatches once the on-chain cost model grows). Recomputed even when units match.
91
91
  */
92
92
  private _stampExecUnits;
93
+ /** Language views the scriptDataHash covers, from the chain's cost models. */
94
+ private _languageViews;
95
+ /**
96
+ * Check a witness datum against the datum hash its script UTxO is locked with: the ledger
97
+ * finds the datum by the hash of its bytes. Inline-datum UTxOs need no witness datum.
98
+ */
99
+ private _checkWitnessDatum;
93
100
  /**
94
101
  * Language-view selection for scriptDataHash, mirroring Buildooor's initTxBuild
95
102
  * (which flags the languages of *executed* scripts). This builder only attaches
@@ -368,6 +368,9 @@ class BuildooorTxBuilder {
368
368
  const datum = plutusScriptExecution.datum
369
369
  ? (0, tx_build_helper_1.jsonToPlutusData)((0, plutus_placeholders_1.resolveIndexPlaceholders)(plutusScriptExecution.datum, resolveCtx))
370
370
  : "inline";
371
+ if (datum !== "inline") {
372
+ this._checkWitnessDatum(scriptOdatanoUtxo, (0, plutus_data_1.dataToCbor)(datum), 'datumJson', '; BuildPlutusTransaction takes the datum as datumCbor with the bytes the UTxO was locked with');
373
+ }
371
374
  const resolvedPrimaryInlineDatum = req.inlineDatum
372
375
  ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(req.inlineDatum, resolveCtx)
373
376
  : undefined;
@@ -591,10 +594,20 @@ class BuildooorTxBuilder {
591
594
  const sortedInputs = this._computeSortedInputs(req.scriptInputs, forced, this._extractFundingRefs(selectedFundingInputs));
592
595
  const sortedWithdrawals = this._ledgerWithdrawalOrder(withdrawalEntries);
593
596
  const resolveCtx = { sortedInputs, sortedReferenceInputs, sortedWithdrawals };
594
- const scriptInputs = scriptEntries.map(({ si, utxo, script, refLedgerUtxo }) => {
597
+ const witnessDatums = [];
598
+ const scriptInputs = scriptEntries.map(({ si, utxo, script, refLedgerUtxo }, i) => {
595
599
  const redeemer = si.redeemerCbor ? (0, plutus_data_1.dataFromCbor)(si.redeemerCbor) : (0, tx_build_helper_1.jsonToPlutusData)((0, plutus_placeholders_1.resolveIndexPlaceholders)(si.redeemer, resolveCtx));
596
- const datum = si.datumCbor ? (0, plutus_data_1.dataFromCbor)(si.datumCbor)
597
- : si.datum !== undefined ? (0, tx_build_helper_1.jsonToPlutusData)((0, plutus_placeholders_1.resolveIndexPlaceholders)(si.datum, resolveCtx)) : "inline";
600
+ let datum = "inline";
601
+ if (si.datumCbor) {
602
+ const bytes = Buffer.from(si.datumCbor, 'hex');
603
+ this._checkWitnessDatum(utxo, bytes, `scriptInputs[${i}].datumCbor`, '');
604
+ witnessDatums.push(bytes);
605
+ datum = (0, plutus_data_1.dataFromCbor)(bytes);
606
+ }
607
+ else if (si.datum !== undefined) {
608
+ datum = (0, tx_build_helper_1.jsonToPlutusData)((0, plutus_placeholders_1.resolveIndexPlaceholders)(si.datum, resolveCtx));
609
+ this._checkWitnessDatum(utxo, (0, plutus_data_1.dataToCbor)(datum), `scriptInputs[${i}].datumJson`, '; pass datumCbor with the bytes the UTxO was locked with');
610
+ }
598
611
  const ledgerUtxo = this._mapMultiAssetUtxoToLedgerUtxo(utxo);
599
612
  return script
600
613
  ? { utxo: ledgerUtxo, inputScript: { script, datum, redeemer } }
@@ -634,7 +647,7 @@ class BuildooorTxBuilder {
634
647
  ...(withdrawals.length > 0 && { withdrawals }),
635
648
  ...(certificates.length > 0 && { certificates })
636
649
  };
637
- const tx = await this._buildScriptTx(buildParams, ctx.evaluateTransaction, callerDatums);
650
+ const tx = await this._buildScriptTx(buildParams, ctx.evaluateTransaction, callerDatums, witnessDatums);
638
651
  const details = this._extractTxDetails(tx);
639
652
  const maxTxSize = Number(this.txBuilder.protocolParamters.maxTxSize);
640
653
  if (details.sizeBytes > maxTxSize) {
@@ -759,7 +772,7 @@ class BuildooorTxBuilder {
759
772
  * budgets and ignores caller-supplied units, so build once, evaluate via Ogmios when available,
760
773
  * rebuild with a fee floor for the target units, then stamp them and recompute scriptDataHash.
761
774
  */
762
- async _buildScriptTx(buildParams, evaluator, callerDatums = new Map()) {
775
+ async _buildScriptTx(buildParams, evaluator, callerDatums = new Map(), witnessDatums = []) {
763
776
  const pass1Failures = [];
764
777
  const tx1 = await this.txBuilder.build(buildParams, makeScriptBuildOpts(pass1Failures));
765
778
  if (!tx1) {
@@ -783,13 +796,14 @@ class BuildooorTxBuilder {
783
796
  const feeFloor = BigInt(tx1.body.fee.toString())
784
797
  + this._exUnitsPriceDelta(rdmrs1, targets1)
785
798
  + this._exUnitsSizeDelta(rdmrs1, targets1) * this._txFeePerByte()
786
- + BigInt((0, caller_datums_1.callerDatumsGrowth)(callerDatums)) * this._txFeePerByte()
799
+ + BigInt((0, caller_datums_1.callerDatumsGrowth)(callerDatums) + (0, caller_datums_1.witnessDatumsGrowth)(witnessDatums)) * this._txFeePerByte()
787
800
  + 10n * this._txFeePerByte();
788
801
  const pass2Failures = [];
789
802
  const tx2 = await this.txBuilder.build({ ...buildParams, fee: feeFloor }, makeScriptBuildOpts(pass2Failures));
790
803
  const rdmrs2 = tx2.witnesses.redeemers ?? [];
791
804
  const targets2 = this._resolveTargetExUnits(rdmrs2, evaluatedUnits, pass2Failures);
792
- return (0, caller_datums_1.writeCallerDatums)(this._stampExecUnits(tx2, targets2), callerDatums);
805
+ const tx = (0, caller_datums_1.writeCallerDatums)(this._stampExecUnits(tx2, targets2), callerDatums);
806
+ return (0, caller_datums_1.writeWitnessDatums)(tx, witnessDatums, this._languageViews(tx));
793
807
  }
794
808
  /**
795
809
  * Evaluate via Ogmios; returns cushioned budgets keyed `tag:index`, or undefined when the
@@ -921,8 +935,7 @@ class BuildooorTxBuilder {
921
935
  execUnits: new buildooor_1.ExBudget({ mem: targets[i].mem, cpu: targets[i].cpu })
922
936
  }));
923
937
  const newWitnesses = new cardano_ledger_ts_1.TxWitnessSet({ ...tx.witnesses, vkeyWitnesses: [], redeemers: stamped });
924
- const languageViews = (0, buildooor_1.costModelsToLanguageViewCbor)(this._languageViewCostModels(), this._usedLanguageViewOpts(tx));
925
- const newBody = new cardano_ledger_ts_1.TxBody({ ...tx.body, scriptDataHash: (0, buildooor_1.getScriptDataHash)(newWitnesses, languageViews) });
938
+ const newBody = new cardano_ledger_ts_1.TxBody({ ...tx.body, scriptDataHash: (0, buildooor_1.getScriptDataHash)(newWitnesses, this._languageViews(tx)) });
926
939
  const finalTx = new cardano_ledger_ts_1.Tx({ ...tx, body: newBody, witnesses: newWitnesses });
927
940
  if (!unchanged) {
928
941
  logger.info(`Stamped execution units into ${stamped.length} redeemer(s): ` +
@@ -930,6 +943,22 @@ class BuildooorTxBuilder {
930
943
  }
931
944
  return finalTx;
932
945
  }
946
+ /** Language views the scriptDataHash covers, from the chain's cost models. */
947
+ _languageViews(tx) {
948
+ return (0, buildooor_1.costModelsToLanguageViewCbor)(this._languageViewCostModels(), this._usedLanguageViewOpts(tx));
949
+ }
950
+ /**
951
+ * Check a witness datum against the datum hash its script UTxO is locked with: the ledger
952
+ * finds the datum by the hash of its bytes. Inline-datum UTxOs need no witness datum.
953
+ */
954
+ _checkWitnessDatum(utxo, datum, field, hint) {
955
+ if (!utxo.datumHash || utxo.inlineDatum)
956
+ return;
957
+ const hash = (0, caller_datums_1.datumHashOf)(datum);
958
+ if (hash !== utxo.datumHash.toLowerCase()) {
959
+ throw new errors_1.TransactionValidationError(`${field} hashes to ${hash}, but ${utxo.txHash}#${utxo.outputIndex} is locked with datum hash ${utxo.datumHash}${hint}`);
960
+ }
961
+ }
933
962
  /**
934
963
  * Language-view selection for scriptDataHash, mirroring Buildooor's initTxBuild
935
964
  * (which flags the languages of *executed* scripts). This builder only attaches
@@ -14,4 +14,16 @@ export declare function callerDatumsGrowth(datums: CallerDatums): number;
14
14
  * Only the datum bytes change. Containers in CBOR count items, not bytes, so the rest stays valid.
15
15
  */
16
16
  export declare function writeCallerDatums(tx: Tx, datums: CallerDatums): Tx;
17
+ /** Datum hash as the ledger computes it: blake2b-256 of the datum bytes. */
18
+ export declare function datumHashOf(datum: Uint8Array): string;
19
+ /** Bytes the witness set gains from the caller's datums, never below zero. */
20
+ export declare function witnessDatumsGrowth(datums: Uint8Array[]): number;
21
+ /**
22
+ * Replace Buildooor's encoding of the witness datums with the caller's bytes, then recompute
23
+ * scriptDataHash over redeemers, datums and language views as they now stand in the transaction.
24
+ * The ledger finds a witness datum by the hash of its bytes, so a re-encoded datum is missing to it.
25
+ */
26
+ export declare function writeWitnessDatums(tx: Tx, datums: Uint8Array[], languageViews: Uint8Array): Tx;
27
+ /** scriptDataHash of a transaction over its redeemer and datum bytes as they stand, laid out like Buildooor's getScriptDataHash. */
28
+ export declare function scriptDataHashOf(txBytes: Uint8Array, languageViews: Uint8Array): Uint8Array;
17
29
  //# sourceMappingURL=caller-datums.d.ts.map
@@ -3,9 +3,14 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.callerDatumGrowth = callerDatumGrowth;
4
4
  exports.callerDatumsGrowth = callerDatumsGrowth;
5
5
  exports.writeCallerDatums = writeCallerDatums;
6
+ exports.datumHashOf = datumHashOf;
7
+ exports.witnessDatumsGrowth = witnessDatumsGrowth;
8
+ exports.writeWitnessDatums = writeWitnessDatums;
9
+ exports.scriptDataHashOf = scriptDataHashOf;
6
10
  const cbor_1 = require("@harmoniclabs/cbor");
7
11
  const plutus_data_1 = require("@harmoniclabs/plutus-data");
8
12
  const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
13
+ const crypto_1 = require("@harmoniclabs/crypto");
9
14
  const uint8array_utils_1 = require("@harmoniclabs/uint8array-utils");
10
15
  /** Output map entry `2 => [1, #6.24(datum)]` that holds an inline datum. */
11
16
  function inlineDatumEntry(datum) {
@@ -47,4 +52,88 @@ function writeCallerDatums(tx, datums) {
47
52
  }
48
53
  return cardano_ledger_ts_1.Tx.fromCbor((0, uint8array_utils_1.toHex)(bytes));
49
54
  }
55
+ /** Datum hash as the ledger computes it: blake2b-256 of the datum bytes. */
56
+ function datumHashOf(datum) {
57
+ return (0, uint8array_utils_1.toHex)((0, crypto_1.blake2b_256)(datum));
58
+ }
59
+ /** Bytes the witness set gains from the caller's datums, never below zero. */
60
+ function witnessDatumsGrowth(datums) {
61
+ let growth = 0;
62
+ for (const datum of datums)
63
+ growth += datum.length - (0, plutus_data_1.dataToCbor)((0, plutus_data_1.dataFromCbor)(datum)).length;
64
+ return Math.max(0, growth);
65
+ }
66
+ /** End offset of a parsed item; a tag carries no offset of its own, its content does. */
67
+ function endOf(item) {
68
+ let inner = item;
69
+ while (inner instanceof cbor_1.CborTag)
70
+ inner = inner.data;
71
+ return inner.subCborRef.end;
72
+ }
73
+ /** Length of a CBOR item head, from its first byte. */
74
+ function headLength(first) {
75
+ const info = first & 0x1f;
76
+ return info < 24 || info === 31 ? 1 : info === 24 ? 2 : info === 25 ? 3 : info === 26 ? 5 : 9;
77
+ }
78
+ function entryOf(map, key) {
79
+ return map.map.find(e => e.k instanceof cbor_1.CborUInt && Number(e.k.num) === key);
80
+ }
81
+ /** Bytes of a map entry's value as they stand in `bytes`. */
82
+ function valueBytes(bytes, entry) {
83
+ return bytes.subarray(entry.k.subCborRef.end, endOf(entry.v));
84
+ }
85
+ /**
86
+ * Replace Buildooor's encoding of the witness datums with the caller's bytes, then recompute
87
+ * scriptDataHash over redeemers, datums and language views as they now stand in the transaction.
88
+ * The ledger finds a witness datum by the hash of its bytes, so a re-encoded datum is missing to it.
89
+ */
90
+ function writeWitnessDatums(tx, datums, languageViews) {
91
+ const wanted = new Map();
92
+ for (const datum of datums) {
93
+ const built = (0, uint8array_utils_1.toHex)((0, plutus_data_1.dataToCbor)((0, plutus_data_1.dataFromCbor)(datum)));
94
+ if (built !== (0, uint8array_utils_1.toHex)(datum))
95
+ wanted.set(built, datum);
96
+ }
97
+ if (wanted.size === 0)
98
+ return tx;
99
+ let bytes = Buffer.from(tx.toCbor());
100
+ let root = cbor_1.Cbor.parse(bytes, { keepRef: true });
101
+ const datumsEntry = entryOf(root.array[1], 4);
102
+ let list = datumsEntry?.v;
103
+ while (list instanceof cbor_1.CborTag)
104
+ list = list.data;
105
+ if (!(list instanceof cbor_1.CborArray))
106
+ throw new Error('the built transaction carries no witness datums');
107
+ // Rebuild the datum list item by item: head, items, and the break byte of an indefinite list
108
+ const listStart = list.subCborRef.start;
109
+ const listEnd = list.subCborRef.end;
110
+ let at = listStart + headLength(bytes[listStart]);
111
+ const parts = [bytes.subarray(listStart, at)];
112
+ for (const item of list.array) {
113
+ const end = endOf(item);
114
+ parts.push(wanted.get((0, uint8array_utils_1.toHex)(bytes.subarray(at, end))) ?? bytes.subarray(at, end));
115
+ at = end;
116
+ }
117
+ parts.push(bytes.subarray(at, listEnd));
118
+ bytes = Buffer.concat([bytes.subarray(0, listStart), ...parts, bytes.subarray(listEnd)]);
119
+ root = cbor_1.Cbor.parse(bytes, { keepRef: true });
120
+ const hashEntry = entryOf(root.array[0], 11);
121
+ if (!hashEntry)
122
+ throw new Error('the built transaction carries no scriptDataHash');
123
+ bytes.set(scriptDataHashOf(bytes, languageViews), endOf(hashEntry.v) - 32);
124
+ return cardano_ledger_ts_1.Tx.fromCbor((0, uint8array_utils_1.toHex)(bytes));
125
+ }
126
+ /** scriptDataHash of a transaction over its redeemer and datum bytes as they stand, laid out like Buildooor's getScriptDataHash. */
127
+ function scriptDataHashOf(txBytes, languageViews) {
128
+ const bytes = Buffer.from(txBytes);
129
+ const witnesses = cbor_1.Cbor.parse(bytes, { keepRef: true }).array[1];
130
+ const redeemers = entryOf(witnesses, 5);
131
+ const datums = entryOf(witnesses, 4);
132
+ if (!redeemers && !datums)
133
+ throw new Error('the transaction carries no redeemers and no datums');
134
+ const datumBytes = datums ? valueBytes(bytes, datums) : Buffer.alloc(0);
135
+ return (0, crypto_1.blake2b_256)(redeemers
136
+ ? Buffer.concat([valueBytes(bytes, redeemers), datumBytes, languageViews])
137
+ : Buffer.concat([Buffer.from([0xa0]), datumBytes, Buffer.from([0xa0])]));
138
+ }
50
139
  //# sourceMappingURL=caller-datums.js.map
package/srv/server.js CHANGED
@@ -546,6 +546,9 @@ async function startWalletWorkerIfConfigured() {
546
546
  async function redriveInterruptedSubmissionsIfConfigured() {
547
547
  if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
548
548
  return;
549
+ // Without a database there are no signing requests to re-drive
550
+ if (!cds_1.default.db)
551
+ return;
549
552
  try {
550
553
  const { redriveInterruptedSubmissions } = require('./blockchain/signing/submission-finalizer');
551
554
  const attempted = await redriveInterruptedSubmissions();