@tezos-x/octez.js-sapling 0.9.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 (39) hide show
  1. package/README.md +95 -0
  2. package/dist/lib/constants.js +7 -0
  3. package/dist/lib/errors.js +83 -0
  4. package/dist/lib/octez.js-sapling.js +274 -0
  5. package/dist/lib/sapling-forger/sapling-forger.js +100 -0
  6. package/dist/lib/sapling-keys/helpers.js +46 -0
  7. package/dist/lib/sapling-keys/in-memory-proving-key.js +81 -0
  8. package/dist/lib/sapling-keys/in-memory-spending-key.js +139 -0
  9. package/dist/lib/sapling-keys/in-memory-viewing-key.js +99 -0
  10. package/dist/lib/sapling-module-wrapper.js +82 -0
  11. package/dist/lib/sapling-state/sapling-state.js +171 -0
  12. package/dist/lib/sapling-state/utils.js +59 -0
  13. package/dist/lib/sapling-tx-builder/sapling-transactions-builder.js +293 -0
  14. package/dist/lib/sapling-tx-viewer/helpers.js +29 -0
  15. package/dist/lib/sapling-tx-viewer/sapling-transaction-viewer.js +227 -0
  16. package/dist/lib/types.js +2 -0
  17. package/dist/lib/version.js +8 -0
  18. package/dist/octez.js-sapling.es6.js +1482 -0
  19. package/dist/octez.js-sapling.es6.js.map +1 -0
  20. package/dist/octez.js-sapling.umd.js +1501 -0
  21. package/dist/octez.js-sapling.umd.js.map +1 -0
  22. package/dist/types/constants.d.ts +4 -0
  23. package/dist/types/errors.d.ts +52 -0
  24. package/dist/types/octez.js-sapling.d.ts +81 -0
  25. package/dist/types/sapling-forger/sapling-forger.d.ts +29 -0
  26. package/dist/types/sapling-keys/helpers.d.ts +1 -0
  27. package/dist/types/sapling-keys/in-memory-proving-key.d.ts +35 -0
  28. package/dist/types/sapling-keys/in-memory-spending-key.d.ts +53 -0
  29. package/dist/types/sapling-keys/in-memory-viewing-key.d.ts +47 -0
  30. package/dist/types/sapling-module-wrapper.d.ts +18 -0
  31. package/dist/types/sapling-state/sapling-state.d.ts +56 -0
  32. package/dist/types/sapling-state/utils.d.ts +22 -0
  33. package/dist/types/sapling-tx-builder/sapling-transactions-builder.d.ts +31 -0
  34. package/dist/types/sapling-tx-viewer/helpers.d.ts +10 -0
  35. package/dist/types/sapling-tx-viewer/sapling-transaction-viewer.d.ts +50 -0
  36. package/dist/types/types.d.ts +146 -0
  37. package/dist/types/version.d.ts +4 -0
  38. package/fetch-sapling-params.js +39 -0
  39. package/package.json +108 -0
@@ -0,0 +1,1501 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('bignumber.js'), require('@tezos-x/octez.js'), require('@tezos-x/octez.js-utils'), require('@tezos-x/octez.js-core'), require('@airgap/sapling-wasm'), require('blakejs'), require('@stablelib/nacl'), require('@stablelib/random'), require('typedarray-to-buffer'), require('pbkdf2'), require('bip39')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'bignumber.js', '@tezos-x/octez.js', '@tezos-x/octez.js-utils', '@tezos-x/octez.js-core', '@airgap/sapling-wasm', 'blakejs', '@stablelib/nacl', '@stablelib/random', 'typedarray-to-buffer', 'pbkdf2', 'bip39'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.octezJsSapling = {}, global.BigNumber, global.octezJs, global.utils, global.core, global.sapling, global.blake, global.nacl, global.random, global.toBuffer, global.pbkdf2, global.bip39));
5
+ })(this, (function (exports, BigNumber, octez_js, octez_jsUtils, octez_jsCore, sapling, blake, nacl, random, toBuffer, pbkdf2, bip39) { 'use strict';
6
+
7
+ function _interopNamespaceDefault(e) {
8
+ var n = Object.create(null);
9
+ if (e) {
10
+ Object.keys(e).forEach(function (k) {
11
+ if (k !== 'default') {
12
+ var d = Object.getOwnPropertyDescriptor(e, k);
13
+ Object.defineProperty(n, k, d.get ? d : {
14
+ enumerable: true,
15
+ get: function () { return e[k]; }
16
+ });
17
+ }
18
+ });
19
+ }
20
+ n.default = e;
21
+ return Object.freeze(n);
22
+ }
23
+
24
+ var sapling__namespace = /*#__PURE__*/_interopNamespaceDefault(sapling);
25
+ var bip39__namespace = /*#__PURE__*/_interopNamespaceDefault(bip39);
26
+
27
+ /******************************************************************************
28
+ Copyright (c) Microsoft Corporation.
29
+
30
+ Permission to use, copy, modify, and/or distribute this software for any
31
+ purpose with or without fee is hereby granted.
32
+
33
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
34
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
35
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
36
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
37
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
38
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
39
+ PERFORMANCE OF THIS SOFTWARE.
40
+ ***************************************************************************** */
41
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
42
+
43
+
44
+ function __rest(s, e) {
45
+ var t = {};
46
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
47
+ t[p] = s[p];
48
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
49
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
50
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
51
+ t[p[i]] = s[p[i]];
52
+ }
53
+ return t;
54
+ }
55
+
56
+ function __awaiter(thisArg, _arguments, P, generator) {
57
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
58
+ return new (P || (P = Promise))(function (resolve, reject) {
59
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
60
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
61
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
62
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
63
+ });
64
+ }
65
+
66
+ function __classPrivateFieldGet(receiver, state, kind, f) {
67
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
68
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
69
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
70
+ }
71
+
72
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
73
+ if (kind === "m") throw new TypeError("Private method is not writable");
74
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
75
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
76
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
77
+ }
78
+
79
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
80
+ var e = new Error(message);
81
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
82
+ };
83
+
84
+ /**
85
+ * @category Error
86
+ * @description Error indicates the spending key is invalid
87
+ */
88
+ class InvalidSpendingKey extends octez_jsCore.ParameterValidationError {
89
+ constructor(sk, errorDetail) {
90
+ super();
91
+ this.sk = sk;
92
+ this.errorDetail = errorDetail;
93
+ this.name = 'InvalidSpendingKey';
94
+ this.message = `Invalid spending key "${sk}" ${errorDetail}.`;
95
+ }
96
+ }
97
+ /**
98
+ * @category Error
99
+ * @description Error indicates an invalid Merkle tree being passed
100
+ */
101
+ class InvalidMerkleTreeError extends octez_jsCore.ParameterValidationError {
102
+ constructor(root) {
103
+ super();
104
+ this.root = root;
105
+ this.name = 'InvalidMerkleTreeError';
106
+ this.message = `Invalid merkle tree has root "${JSON.stringify(root)}" different from expected root.`;
107
+ }
108
+ }
109
+ /**
110
+ * @category Error
111
+ * @description Error indicates a failure when trying to construct the Merkle tree
112
+ */
113
+ class TreeConstructionFailure extends octez_jsCore.TaquitoError {
114
+ constructor(message) {
115
+ super();
116
+ this.message = message;
117
+ this.name = 'TreeConstructionFailure';
118
+ }
119
+ }
120
+ /**
121
+ * @category Error
122
+ * @description Error indicates the memo is invalid
123
+ */
124
+ class InvalidMemo extends octez_jsCore.ParameterValidationError {
125
+ constructor(memo, errorDetails) {
126
+ super();
127
+ this.memo = memo;
128
+ this.errorDetails = errorDetails;
129
+ this.name = 'InvalidMemo';
130
+ this.message = `Invalid memo "${memo}" with length ${memo.length} ${errorDetails}`;
131
+ }
132
+ }
133
+ /**
134
+ * @category Error
135
+ * @description Error indicates not enough balance to prepare the sapling transaction
136
+ */
137
+ class InsufficientBalance extends octez_jsCore.TaquitoError {
138
+ constructor(realBalance, amountToSpend) {
139
+ super();
140
+ this.realBalance = realBalance;
141
+ this.amountToSpend = amountToSpend;
142
+ this.name = 'InsufficientBalance';
143
+ this.message = `Unable to spend "${amountToSpend}" mutez while the balance is only ${realBalance} mutez.`;
144
+ }
145
+ }
146
+ /**
147
+ * @category Error
148
+ * @description Error indicates SaplingTransactionViewer failure
149
+ */
150
+ class SaplingTransactionViewerError extends octez_jsCore.TaquitoError {
151
+ constructor(message) {
152
+ super();
153
+ this.message = message;
154
+ this.name = 'SaplingTransactionViewerError';
155
+ }
156
+ }
157
+
158
+ function memoHexToUtf8(memo) {
159
+ const memoNoPadding = removeZeroPaddedBytesRight(memo);
160
+ return memoNoPadding === '' ? memoNoPadding : octez_jsUtils.bytesToString(memoNoPadding);
161
+ }
162
+ function removeZeroPaddedBytesRight(memo) {
163
+ const matchZeroRight = memo.match(/^(.*?)(00)+$/);
164
+ return matchZeroRight ? matchZeroRight[1] : memo;
165
+ }
166
+ function readableFormat(saplingTransactionProperties) {
167
+ return {
168
+ value: convertValueToBigNumber(saplingTransactionProperties.value),
169
+ memo: memoHexToUtf8(Buffer.from(saplingTransactionProperties.memo).toString('hex')),
170
+ paymentAddress: octez_jsUtils.b58Encode(saplingTransactionProperties.paymentAddress, octez_jsUtils.PrefixV2.SaplingAddress),
171
+ };
172
+ }
173
+ function convertValueToBigNumber(value) {
174
+ return new BigNumber(Buffer.from(value).toString('hex'), 16);
175
+ }
176
+ function bufToUint8Array(buffer) {
177
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength / Uint8Array.BYTES_PER_ELEMENT);
178
+ }
179
+
180
+ class SaplingForger {
181
+ /**
182
+ * @description Forge sapling transactions
183
+ * @param spendDescriptions the list of spend descriptions
184
+ * @param outputDescriptions the list of output descriptions
185
+ * @param signature signature hash
186
+ * @param balance balance of the Sapling contract (input/output difference)
187
+ * @param root root of the merkle tree
188
+ * @returns Forged sapling transaction of type Buffer
189
+ */
190
+ forgeSaplingTransaction(tx) {
191
+ const spendBuf = this.forgeSpendDescriptions(tx.inputs);
192
+ const spend = Buffer.concat([octez_jsUtils.toHexBuf(spendBuf.length, 32), spendBuf]);
193
+ const outputBuf = this.forgeOutputDescriptions(tx.outputs);
194
+ const output = Buffer.concat([octez_jsUtils.toHexBuf(outputBuf.length, 32), outputBuf]);
195
+ const root = Buffer.from(tx.root, 'hex');
196
+ return Buffer.concat([
197
+ spend,
198
+ output,
199
+ tx.signature,
200
+ octez_jsUtils.toHexBuf(tx.balance, 64),
201
+ root,
202
+ octez_jsUtils.toHexBuf(tx.boundData.length, 32),
203
+ tx.boundData,
204
+ ]);
205
+ }
206
+ /**
207
+ * @description Forge list of spend descriptions
208
+ * @param spendDescriptions list of spend descriptions
209
+ * @returns concatenated forged bytes of type Buffer
210
+ */
211
+ forgeSpendDescriptions(spendDescriptions) {
212
+ const descriptions = [];
213
+ for (const i of spendDescriptions) {
214
+ const buff = this.forgeSpendDescription(i);
215
+ descriptions.push(buff);
216
+ }
217
+ return Buffer.concat(descriptions);
218
+ }
219
+ forgeSpendDescription(desc) {
220
+ return Buffer.concat([
221
+ desc.commitmentValue,
222
+ desc.nullifier,
223
+ desc.publicKeyReRandomization,
224
+ desc.proof,
225
+ desc.signature,
226
+ ]);
227
+ }
228
+ /**
229
+ * @description Forge list of output descriptions
230
+ * @param outputDescriptions list of output descriptions
231
+ * @returns concatenated forged bytes of type Buffer
232
+ */
233
+ forgeOutputDescriptions(outputDescriptions) {
234
+ const descriptions = [];
235
+ for (const i of outputDescriptions) {
236
+ const buff = this.forgeOutputDescription(i);
237
+ descriptions.push(buff);
238
+ }
239
+ return Buffer.concat(descriptions);
240
+ }
241
+ forgeOutputDescription(desc) {
242
+ const ct = desc.ciphertext;
243
+ return Buffer.concat([
244
+ desc.commitment,
245
+ desc.proof,
246
+ ct.commitmentValue,
247
+ ct.ephemeralPublicKey,
248
+ octez_jsUtils.toHexBuf(ct.payloadEnc.length, 32),
249
+ ct.payloadEnc,
250
+ ct.nonceEnc,
251
+ ct.payloadOut,
252
+ ct.nonceOut,
253
+ ]);
254
+ }
255
+ forgeUnsignedTxInput(unsignedSpendDescription) {
256
+ return Buffer.concat([
257
+ unsignedSpendDescription.commitmentValue,
258
+ unsignedSpendDescription.nullifier,
259
+ unsignedSpendDescription.publicKeyReRandomization,
260
+ unsignedSpendDescription.proof,
261
+ ]);
262
+ }
263
+ forgeTransactionPlaintext(txPlainText) {
264
+ const encodedMemo = Buffer.from(octez_jsUtils.stringToBytes(txPlainText.memo).padEnd(txPlainText.memoSize, '0'), 'hex');
265
+ return Buffer.concat([
266
+ txPlainText.diversifier,
267
+ octez_jsUtils.toHexBuf(new BigNumber(txPlainText.amount), 64),
268
+ txPlainText.randomCommitmentTrapdoor,
269
+ octez_jsUtils.toHexBuf(txPlainText.memoSize, 32),
270
+ encodedMemo,
271
+ ]);
272
+ }
273
+ }
274
+
275
+ const KDF_KEY = 'KDFSaplingForTezosV1';
276
+ const OCK_KEY = 'OCK_keystringderivation_TEZOS';
277
+ const DEFAULT_MEMO = '';
278
+ const DEFAULT_BOUND_DATA = Buffer.from('', 'hex');
279
+
280
+ var _SaplingTransactionViewer_viewingKeyProvider, _SaplingTransactionViewer_readProvider, _SaplingTransactionViewer_saplingContractId;
281
+ /**
282
+ * @description Allows to retrieve and decrypt sapling transactions using on a viewing key
283
+ *
284
+ * @param inMemoryViewingKey Holds the sapling viewing key
285
+ * @param saplingContractId Address of the sapling contract or sapling id if the smart contract contains multiple sapling states
286
+ * @param readProvider Allows to read data from the blockchain
287
+ */
288
+ class SaplingTransactionViewer {
289
+ constructor(inMemoryViewingKey, saplingContractId, readProvider) {
290
+ _SaplingTransactionViewer_viewingKeyProvider.set(this, void 0);
291
+ _SaplingTransactionViewer_readProvider.set(this, void 0);
292
+ _SaplingTransactionViewer_saplingContractId.set(this, void 0);
293
+ __classPrivateFieldSet(this, _SaplingTransactionViewer_viewingKeyProvider, inMemoryViewingKey, "f");
294
+ __classPrivateFieldSet(this, _SaplingTransactionViewer_saplingContractId, saplingContractId, "f");
295
+ __classPrivateFieldSet(this, _SaplingTransactionViewer_readProvider, readProvider, "f");
296
+ }
297
+ /**
298
+ * @description Retrieve the unspent balance associated with the configured viewing key and sapling state
299
+ *
300
+ * @returns the balance in mutez represented as a BigNumber
301
+ *
302
+ */
303
+ getBalance() {
304
+ return __awaiter(this, void 0, void 0, function* () {
305
+ let balance = new BigNumber(0);
306
+ const { commitments_and_ciphertexts, nullifiers } = yield this.getSaplingDiff();
307
+ for (let i = 0; i < commitments_and_ciphertexts.length; i++) {
308
+ const decrypted = yield this.decryptCiphertextAsReceiver(commitments_and_ciphertexts[i]);
309
+ if (decrypted) {
310
+ const valueBigNumber = convertValueToBigNumber(decrypted.value);
311
+ const isSpent = yield this.isSpent(decrypted.paymentAddress, valueBigNumber.toString(), decrypted.randomCommitmentTrapdoor, i, nullifiers);
312
+ if (!isSpent) {
313
+ balance = balance.plus(valueBigNumber);
314
+ }
315
+ }
316
+ }
317
+ return balance;
318
+ });
319
+ }
320
+ /**
321
+ * @description Retrieve all the incoming and outgoing transactions associated with the configured viewing key.
322
+ * The response properties are in Uint8Array format; use the getIncomingAndOutgoingTransactions method for readable properties
323
+ *
324
+ */
325
+ getIncomingAndOutgoingTransactionsRaw() {
326
+ return __awaiter(this, void 0, void 0, function* () {
327
+ const incoming = [];
328
+ const outgoing = [];
329
+ const { commitments_and_ciphertexts, nullifiers } = yield this.getSaplingDiff();
330
+ for (let i = 0; i < commitments_and_ciphertexts.length; i++) {
331
+ const decryptedAsReceiver = yield this.decryptCiphertextAsReceiver(commitments_and_ciphertexts[i]);
332
+ const decryptedAsSender = yield this.decryptCiphertextAsSender(commitments_and_ciphertexts[i]);
333
+ if (decryptedAsReceiver) {
334
+ const balance = convertValueToBigNumber(decryptedAsReceiver.value);
335
+ const isSpent = yield this.isSpent(decryptedAsReceiver.paymentAddress, balance.toString(), decryptedAsReceiver.randomCommitmentTrapdoor, i, nullifiers);
336
+ incoming.push(Object.assign(Object.assign({}, decryptedAsReceiver), { isSpent, position: i }));
337
+ }
338
+ if (decryptedAsSender) {
339
+ outgoing.push(decryptedAsSender);
340
+ }
341
+ }
342
+ return {
343
+ incoming,
344
+ outgoing,
345
+ };
346
+ });
347
+ }
348
+ /**
349
+ * @description Retrieve all the incoming and outgoing decoded transactions associated with the configured viewing key
350
+ *
351
+ */
352
+ getIncomingAndOutgoingTransactions() {
353
+ return __awaiter(this, void 0, void 0, function* () {
354
+ const tx = yield this.getIncomingAndOutgoingTransactionsRaw();
355
+ const incoming = tx.incoming.map((_a) => {
356
+ var { isSpent } = _a, rest = __rest(_a, ["isSpent"]);
357
+ return Object.assign(Object.assign({}, readableFormat(rest)), { isSpent });
358
+ });
359
+ const outgoing = tx.outgoing.map((outgoingTx) => {
360
+ return readableFormat(outgoingTx);
361
+ });
362
+ return { incoming, outgoing };
363
+ });
364
+ }
365
+ getSaplingDiff() {
366
+ return __awaiter(this, void 0, void 0, function* () {
367
+ let saplingDiffResponse;
368
+ if (__classPrivateFieldGet(this, _SaplingTransactionViewer_saplingContractId, "f").saplingId) {
369
+ saplingDiffResponse = yield __classPrivateFieldGet(this, _SaplingTransactionViewer_readProvider, "f").getSaplingDiffById({ id: __classPrivateFieldGet(this, _SaplingTransactionViewer_saplingContractId, "f").saplingId }, 'head');
370
+ }
371
+ else if (__classPrivateFieldGet(this, _SaplingTransactionViewer_saplingContractId, "f").contractAddress) {
372
+ saplingDiffResponse = yield __classPrivateFieldGet(this, _SaplingTransactionViewer_readProvider, "f").getSaplingDiffByContract(__classPrivateFieldGet(this, _SaplingTransactionViewer_saplingContractId, "f").contractAddress, 'head');
373
+ }
374
+ else {
375
+ throw new SaplingTransactionViewerError('A contract address or a sapling id was expected in the SaplingTransactionViewer constructor.');
376
+ }
377
+ return saplingDiffResponse;
378
+ });
379
+ }
380
+ decryptCiphertextAsReceiver(commitmentsAndCiphertexts) {
381
+ return __awaiter(this, void 0, void 0, function* () {
382
+ const commitment = commitmentsAndCiphertexts[0];
383
+ const { epk, payload_enc, nonce_enc } = commitmentsAndCiphertexts[1];
384
+ const incomingViewingKey = yield __classPrivateFieldGet(this, _SaplingTransactionViewer_viewingKeyProvider, "f").getIncomingViewingKey();
385
+ const keyAgreement = yield sapling__namespace.keyAgreement(epk, incomingViewingKey);
386
+ const keyAgreementHash = blake.blake2b(keyAgreement, Buffer.from(KDF_KEY), 32);
387
+ const decrypted = yield this.decryptCiphertext(keyAgreementHash, octez_jsUtils.hex2buf(nonce_enc), octez_jsUtils.hex2buf(payload_enc));
388
+ if (decrypted) {
389
+ const { diversifier, value, randomCommitmentTrapdoor: rcm, memo, } = this.extractTransactionProperties(decrypted);
390
+ const paymentAddress = bufToUint8Array(yield sapling__namespace.getRawPaymentAddressFromIncomingViewingKey(incomingViewingKey, diversifier));
391
+ try {
392
+ const valid = yield sapling__namespace.verifyCommitment(commitment, paymentAddress, convertValueToBigNumber(value).toString(), rcm);
393
+ if (valid) {
394
+ return { value, memo, paymentAddress, randomCommitmentTrapdoor: rcm };
395
+ }
396
+ }
397
+ catch (ex) {
398
+ if (!/invalid value/.test(ex)) {
399
+ throw ex;
400
+ }
401
+ }
402
+ }
403
+ });
404
+ }
405
+ decryptCiphertextAsSender(commitmentsAndCiphertexts) {
406
+ return __awaiter(this, void 0, void 0, function* () {
407
+ const commitment = commitmentsAndCiphertexts[0];
408
+ const { epk, payload_enc, nonce_enc, payload_out, nonce_out, cv } = commitmentsAndCiphertexts[1];
409
+ const outgoingViewingKey = yield __classPrivateFieldGet(this, _SaplingTransactionViewer_viewingKeyProvider, "f").getOutgoingViewingKey();
410
+ const concat = cv.concat(commitment, epk, outgoingViewingKey.toString('hex'));
411
+ const outgoingCipherKey = blake.blake2b(Buffer.from(concat, 'hex'), Buffer.from(OCK_KEY), 32);
412
+ const decryptedOut = yield this.decryptCiphertext(outgoingCipherKey, octez_jsUtils.hex2buf(nonce_out), octez_jsUtils.hex2buf(payload_out));
413
+ if (decryptedOut) {
414
+ const { recipientDiversifiedTransmissionKey: pkd, ephemeralPrivateKey: esk } = this.extractPkdAndEsk(decryptedOut);
415
+ const keyAgreement = yield sapling__namespace.keyAgreement(pkd, esk);
416
+ const keyAgreementHash = blake.blake2b(keyAgreement, Buffer.from(KDF_KEY), 32);
417
+ const decryptedEnc = yield this.decryptCiphertext(keyAgreementHash, octez_jsUtils.hex2buf(nonce_enc), octez_jsUtils.hex2buf(payload_enc));
418
+ if (decryptedEnc) {
419
+ const { diversifier, value, randomCommitmentTrapdoor: rcm, memo, } = this.extractTransactionProperties(decryptedEnc);
420
+ const paymentAddress = octez_jsUtils.mergebuf(diversifier, pkd);
421
+ try {
422
+ const isValid = yield sapling__namespace.verifyCommitment(commitment, paymentAddress, convertValueToBigNumber(value).toString(), rcm);
423
+ if (isValid) {
424
+ return { value, memo, paymentAddress, randomCommitmentTrapdoor: rcm };
425
+ }
426
+ }
427
+ catch (ex) {
428
+ if (!/invalid value/.test(ex)) {
429
+ throw ex;
430
+ }
431
+ }
432
+ }
433
+ }
434
+ });
435
+ }
436
+ decryptCiphertext(keyAgreementHash, nonce, payload) {
437
+ return __awaiter(this, void 0, void 0, function* () {
438
+ return nacl.openSecretBox(keyAgreementHash, nonce, payload);
439
+ });
440
+ }
441
+ extractTransactionProperties(decrypted) {
442
+ return {
443
+ diversifier: decrypted.slice(0, 11),
444
+ value: decrypted.slice(11, 19),
445
+ randomCommitmentTrapdoor: decrypted.slice(19, 51),
446
+ memoSize: decrypted.slice(51, 55),
447
+ memo: decrypted.slice(55),
448
+ };
449
+ }
450
+ extractPkdAndEsk(decrypted) {
451
+ return {
452
+ recipientDiversifiedTransmissionKey: decrypted.slice(0, 32),
453
+ ephemeralPrivateKey: decrypted.slice(32),
454
+ };
455
+ }
456
+ isSpent(address, value, randomCommitmentTrapdoor, position, nullifiers) {
457
+ return __awaiter(this, void 0, void 0, function* () {
458
+ const computedNullifier = yield sapling__namespace.computeNullifier(__classPrivateFieldGet(this, _SaplingTransactionViewer_viewingKeyProvider, "f").getFullViewingKey(), address, value, randomCommitmentTrapdoor, position);
459
+ return nullifiers.includes(computedNullifier.toString('hex'));
460
+ });
461
+ }
462
+ }
463
+ _SaplingTransactionViewer_viewingKeyProvider = new WeakMap(), _SaplingTransactionViewer_readProvider = new WeakMap(), _SaplingTransactionViewer_saplingContractId = new WeakMap();
464
+
465
+ /**
466
+ *
467
+ * @param leaves nodes in the tree that we would like to make pairs from
468
+ * @returns a paired/chunked array: [a, b, c, d] => [[a, b], [c, d]]
469
+ */
470
+ function pairNodes(leaves) {
471
+ const pairs = new Array(Math.ceil(leaves.length / 2));
472
+ for (let i = 0; i < leaves.length / 2; i++) {
473
+ pairs[i] = leaves.slice(i * 2, i * 2 + 2);
474
+ }
475
+ return pairs;
476
+ }
477
+ /**
478
+ * @description helper function to assist in Lazy initializing an object
479
+ */
480
+ class Lazy {
481
+ constructor(init) {
482
+ this.init = init;
483
+ this.isInitialized = false;
484
+ this.value = undefined;
485
+ }
486
+ // initializes the lazily initiated object
487
+ get() {
488
+ return __awaiter(this, void 0, void 0, function* () {
489
+ if (!this.isInitialized) {
490
+ this.value = yield this.init();
491
+ this.isInitialized = true;
492
+ }
493
+ return this.value;
494
+ });
495
+ }
496
+ }
497
+ /**
498
+ *
499
+ * @param hex hexadecimal string we would like to swap
500
+ * @returns a hexadecimal string with swapped endians
501
+ */
502
+ const changeEndianness = (hex) => {
503
+ if (hex.length % 2 != 0) {
504
+ hex = '0' + hex;
505
+ }
506
+ const bytes = hex.match(/.{2}/g) || [];
507
+ return bytes.reverse().join('');
508
+ };
509
+
510
+ /**
511
+ * Some code in this file was originally written or inspired by Airgap-it
512
+ * https://github.com/airgap-it/airgap-coin-lib/blob/master/LICENSE.md
513
+ *
514
+ */
515
+ /**
516
+ * @description The SaplingState class's main purpose is to provide a Merkle path for the forger and the transaction builder, so that it may verify that the Sapling transaction is valid
517
+ *
518
+ */
519
+ class SaplingState {
520
+ constructor(height) {
521
+ this.height = height;
522
+ this.uncommittedMerkleHash = '0100000000000000000000000000000000000000000000000000000000000000';
523
+ this.uncommittedMerkleHashes = new Lazy(() => this.createUncommittedMerkleHashes());
524
+ }
525
+ getStateTree(stateDiff_1) {
526
+ return __awaiter(this, arguments, void 0, function* (stateDiff, constructTree = true) {
527
+ if (this.stateTree !== undefined && this.stateTree.root === stateDiff.root) {
528
+ return this.stateTree;
529
+ }
530
+ const commitments = stateDiff.commitments_and_ciphertexts.map(([commitment, _]) => commitment);
531
+ let merkleTree;
532
+ if (constructTree) {
533
+ merkleTree = yield this.constructMerkleTree(commitments, 0);
534
+ yield this.validateMerkleTree(merkleTree, stateDiff.root);
535
+ }
536
+ this.stateTree = {
537
+ height: this.height,
538
+ size: commitments.length,
539
+ root: stateDiff.root,
540
+ tree: merkleTree,
541
+ };
542
+ return this.stateTree;
543
+ });
544
+ }
545
+ /**
546
+ *
547
+ * @param stateTree stateTree parameter that holds information details on our Merkle tree
548
+ * @param position position of the hash in the Merkle tree
549
+ * @returns a promise of a string that serves as the Merkle path that can be passed on to the Sapling forger or the transaction builder
550
+ */
551
+ getWitness(stateTree, position) {
552
+ return __awaiter(this, void 0, void 0, function* () {
553
+ const heightBuffer = octez_jsUtils.hex2Bytes(changeEndianness(octez_jsUtils.num2PaddedHex(stateTree.height)));
554
+ const posBuffer = octez_jsUtils.hex2Bytes(changeEndianness(octez_jsUtils.num2PaddedHex(position, 64)));
555
+ const neighbouringHashes = yield this.getNeighbouringHashes([], stateTree.height, position, stateTree.tree);
556
+ const witness = neighbouringHashes
557
+ .map((hash) => Buffer.concat([octez_jsUtils.hex2Bytes(changeEndianness(octez_jsUtils.num2PaddedHex(hash.length))), hash]))
558
+ .reverse()
559
+ .reduce((acc, next) => Buffer.concat([acc, next]));
560
+ return Buffer.concat([heightBuffer, witness, posBuffer]).toString('hex');
561
+ });
562
+ }
563
+ /**
564
+ *
565
+ * @param leaves array of leaves or nodes that we want to construct the Merkle tree from
566
+ * @param height height of the desired Merkle tree
567
+ * @returns a promise of MerkleTree type object
568
+ */
569
+ constructMerkleTree(leaves, height) {
570
+ return __awaiter(this, void 0, void 0, function* () {
571
+ if (height === this.height && leaves.length === 1) {
572
+ return leaves[0];
573
+ }
574
+ if (height === this.height || leaves.length > Math.pow(2, this.height - 1 - height)) {
575
+ throw new TreeConstructionFailure('Children length exceeds maximum number of nodes in a merkle tree');
576
+ }
577
+ const pairedLeaves = pairNodes(leaves);
578
+ const updatedLeaves = yield Promise.all(pairedLeaves.map((chunk) => __awaiter(this, void 0, void 0, function* () {
579
+ const left = yield this.getMerkleHash(chunk[0], height);
580
+ const right = yield this.getMerkleHash(chunk[1], height);
581
+ const parentHash = yield sapling.merkleHash(height, left, right);
582
+ return [parentHash.toString('hex'), chunk[0], chunk[1]];
583
+ })));
584
+ return this.constructMerkleTree(updatedLeaves, height + 1);
585
+ });
586
+ }
587
+ getMerkleHash(tree, height) {
588
+ return __awaiter(this, void 0, void 0, function* () {
589
+ if (tree === undefined) {
590
+ return (yield this.uncommittedMerkleHashes.get())[height];
591
+ }
592
+ else if (typeof tree === 'string') {
593
+ return Buffer.from(tree, 'hex');
594
+ }
595
+ else {
596
+ return Buffer.from(tree[0], 'hex');
597
+ }
598
+ });
599
+ }
600
+ /**
601
+ *
602
+ * @returns hashes of empty or null values to fill in the Merkle tree
603
+ */
604
+ createUncommittedMerkleHashes() {
605
+ return __awaiter(this, void 0, void 0, function* () {
606
+ const res = new Array(this.height);
607
+ res[0] = Buffer.from(this.uncommittedMerkleHash, 'hex');
608
+ for (let i = 0; i < this.height; i++) {
609
+ const hash = res[i];
610
+ res[i + 1] = yield sapling.merkleHash(i, hash, hash);
611
+ }
612
+ return res;
613
+ });
614
+ }
615
+ /**
616
+ *
617
+ * @param tree Merkle tree to validate
618
+ * @param expectedRoot the expected merkle root to validate against
619
+ * @throws {@link InvalidMerkleTreeError}
620
+ */
621
+ validateMerkleTree(tree, expectedRoot) {
622
+ return __awaiter(this, void 0, void 0, function* () {
623
+ const root = yield this.getMerkleHash(tree, this.height - 1);
624
+ if (root.toString('hex') !== expectedRoot) {
625
+ throw new InvalidMerkleTreeError(root.toString('hex'));
626
+ }
627
+ });
628
+ }
629
+ /**
630
+ *
631
+ * @param acc accumulator variable for the recursive function
632
+ * @param height height of the tree
633
+ * @param position position of the hash we would like find the neighbours of
634
+ * @param tree the Merkle tree that we want to traverse
635
+ * @returns the accumulated Buffer array of neighbouring hashes
636
+ */
637
+ getNeighbouringHashes(acc, height, position, tree) {
638
+ return __awaiter(this, void 0, void 0, function* () {
639
+ if (typeof tree === 'undefined') {
640
+ throw new Error();
641
+ }
642
+ else if (typeof tree === 'string') {
643
+ return acc;
644
+ }
645
+ else {
646
+ let nextPos, nextTree, otherTree;
647
+ const fullTree = new BigNumber(2).pow(height - 1);
648
+ if (position.lt(fullTree)) {
649
+ nextPos = position;
650
+ nextTree = tree[1];
651
+ otherTree = tree[2];
652
+ }
653
+ else {
654
+ nextPos = position.minus(fullTree);
655
+ nextTree = tree[2];
656
+ otherTree = tree[1];
657
+ }
658
+ return this.getNeighbouringHashes([yield this.getMerkleHash(otherTree, height - 1), ...acc], height - 1, nextPos, nextTree);
659
+ }
660
+ });
661
+ }
662
+ }
663
+
664
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
665
+ const saplingOutputParams = require('../saplingOutputParams');
666
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
667
+ const saplingSpendParams = require('../saplingSpendParams');
668
+ class SaplingWrapper {
669
+ withProvingContext(action) {
670
+ return __awaiter(this, void 0, void 0, function* () {
671
+ yield this.initSaplingParameters();
672
+ return sapling__namespace.withProvingContext(action);
673
+ });
674
+ }
675
+ getRandomBytes(length) {
676
+ return random.randomBytes(length);
677
+ }
678
+ randR() {
679
+ return __awaiter(this, void 0, void 0, function* () {
680
+ return sapling__namespace.randR();
681
+ });
682
+ }
683
+ getOutgoingViewingKey(vk) {
684
+ return __awaiter(this, void 0, void 0, function* () {
685
+ return sapling__namespace.getOutgoingViewingKey(vk);
686
+ });
687
+ }
688
+ preparePartialOutputDescription(parametersOutputProof) {
689
+ return __awaiter(this, void 0, void 0, function* () {
690
+ const partialOutputDesc = yield sapling__namespace.preparePartialOutputDescription(parametersOutputProof.saplingContext, parametersOutputProof.address, parametersOutputProof.randomCommitmentTrapdoor, parametersOutputProof.ephemeralPrivateKey, parametersOutputProof.amount);
691
+ return {
692
+ commitmentValue: partialOutputDesc.cv,
693
+ commitment: partialOutputDesc.cm,
694
+ proof: partialOutputDesc.proof,
695
+ };
696
+ });
697
+ }
698
+ getDiversifiedFromRawPaymentAddress(decodedDestination) {
699
+ return __awaiter(this, void 0, void 0, function* () {
700
+ return sapling__namespace.getDiversifiedFromRawPaymentAddress(decodedDestination);
701
+ });
702
+ }
703
+ deriveEphemeralPublicKey(diversifier, esk) {
704
+ return __awaiter(this, void 0, void 0, function* () {
705
+ return sapling__namespace.deriveEphemeralPublicKey(diversifier, esk);
706
+ });
707
+ }
708
+ getPkdFromRawPaymentAddress(destination) {
709
+ return __awaiter(this, void 0, void 0, function* () {
710
+ return sapling__namespace.getPkdFromRawPaymentAddress(destination);
711
+ });
712
+ }
713
+ keyAgreement(p, sk) {
714
+ return __awaiter(this, void 0, void 0, function* () {
715
+ return sapling__namespace.keyAgreement(p, sk);
716
+ });
717
+ }
718
+ createBindingSignature(saplingContext, balance, transactionSigHash) {
719
+ return __awaiter(this, void 0, void 0, function* () {
720
+ return sapling__namespace.createBindingSignature(saplingContext, balance, transactionSigHash);
721
+ });
722
+ }
723
+ initSaplingParameters() {
724
+ return __awaiter(this, void 0, void 0, function* () {
725
+ const spendParams = Buffer.from(saplingSpendParams.saplingSpendParams, 'base64');
726
+ const outputParams = Buffer.from(saplingOutputParams.saplingOutputParams, 'base64');
727
+ return sapling__namespace.initParameters(spendParams, outputParams);
728
+ });
729
+ }
730
+ }
731
+
732
+ var _SaplingTransactionBuilder_inMemorySpendingKey, _SaplingTransactionBuilder_inMemoryProvingKey, _SaplingTransactionBuilder_saplingForger, _SaplingTransactionBuilder_contractAddress, _SaplingTransactionBuilder_saplingId, _SaplingTransactionBuilder_memoSize, _SaplingTransactionBuilder_readProvider, _SaplingTransactionBuilder_saplingWrapper, _SaplingTransactionBuilder_chainId, _SaplingTransactionBuilder_saplingState;
733
+ class SaplingTransactionBuilder {
734
+ constructor(keys, saplingForger, saplingContractDetails, readProvider, saplingWrapper = new SaplingWrapper()) {
735
+ _SaplingTransactionBuilder_inMemorySpendingKey.set(this, void 0);
736
+ _SaplingTransactionBuilder_inMemoryProvingKey.set(this, void 0);
737
+ _SaplingTransactionBuilder_saplingForger.set(this, void 0);
738
+ _SaplingTransactionBuilder_contractAddress.set(this, void 0);
739
+ _SaplingTransactionBuilder_saplingId.set(this, void 0);
740
+ _SaplingTransactionBuilder_memoSize.set(this, void 0);
741
+ _SaplingTransactionBuilder_readProvider.set(this, void 0);
742
+ _SaplingTransactionBuilder_saplingWrapper.set(this, void 0);
743
+ _SaplingTransactionBuilder_chainId.set(this, void 0);
744
+ _SaplingTransactionBuilder_saplingState.set(this, void 0);
745
+ __classPrivateFieldSet(this, _SaplingTransactionBuilder_saplingForger, saplingForger, "f");
746
+ __classPrivateFieldSet(this, _SaplingTransactionBuilder_contractAddress, saplingContractDetails.contractAddress, "f");
747
+ __classPrivateFieldSet(this, _SaplingTransactionBuilder_memoSize, saplingContractDetails.memoSize, "f");
748
+ __classPrivateFieldSet(this, _SaplingTransactionBuilder_inMemorySpendingKey, keys.saplingSigner, "f");
749
+ __classPrivateFieldSet(this, _SaplingTransactionBuilder_inMemoryProvingKey, keys.saplingProver, "f");
750
+ __classPrivateFieldSet(this, _SaplingTransactionBuilder_saplingState, new SaplingState(32), "f");
751
+ __classPrivateFieldSet(this, _SaplingTransactionBuilder_saplingId, saplingContractDetails.saplingId, "f");
752
+ __classPrivateFieldSet(this, _SaplingTransactionBuilder_saplingWrapper, saplingWrapper, "f");
753
+ __classPrivateFieldSet(this, _SaplingTransactionBuilder_readProvider, readProvider, "f");
754
+ }
755
+ createShieldedTx(saplingTransactionParams, txTotalAmount, boundData) {
756
+ return __awaiter(this, void 0, void 0, function* () {
757
+ const rcm = yield __classPrivateFieldGet(this, _SaplingTransactionBuilder_saplingWrapper, "f").randR();
758
+ const balance = this.calculateTransactionBalance('0', txTotalAmount.toString());
759
+ const { signature, inputs, outputs } = yield __classPrivateFieldGet(this, _SaplingTransactionBuilder_saplingWrapper, "f").withProvingContext((saplingContext) => __awaiter(this, void 0, void 0, function* () {
760
+ const outputs = [];
761
+ const inputs = [];
762
+ for (const i in saplingTransactionParams) {
763
+ const [address] = octez_jsUtils.b58DecodeAndCheckPrefix(saplingTransactionParams[i].to, [
764
+ octez_jsUtils.PrefixV2.SaplingAddress,
765
+ ]);
766
+ outputs.push(yield this.prepareSaplingOutputDescription({
767
+ saplingContext,
768
+ address,
769
+ amount: saplingTransactionParams[i].amount,
770
+ memo: saplingTransactionParams[i].memo,
771
+ randomCommitmentTrapdoor: rcm,
772
+ }));
773
+ }
774
+ const signature = yield this.createBindingSignature({
775
+ saplingContext,
776
+ inputs,
777
+ outputs,
778
+ balance,
779
+ boundData,
780
+ });
781
+ return { signature, inputs, outputs };
782
+ }));
783
+ return {
784
+ inputs,
785
+ outputs,
786
+ signature,
787
+ balance,
788
+ };
789
+ });
790
+ }
791
+ createSaplingTx(saplingTransactionParams, txTotalAmount, boundData, chosenInputs) {
792
+ return __awaiter(this, void 0, void 0, function* () {
793
+ const randomCommitmentTrapdoor = yield __classPrivateFieldGet(this, _SaplingTransactionBuilder_saplingWrapper, "f").randR();
794
+ const saplingViewer = yield __classPrivateFieldGet(this, _SaplingTransactionBuilder_inMemorySpendingKey, "f").getSaplingViewingKeyProvider();
795
+ const outgoingViewingKey = yield saplingViewer.getOutgoingViewingKey();
796
+ const { signature, balance, inputs, outputs } = yield __classPrivateFieldGet(this, _SaplingTransactionBuilder_saplingWrapper, "f").withProvingContext((saplingContext) => __awaiter(this, void 0, void 0, function* () {
797
+ const outputs = [];
798
+ const inputs = [];
799
+ inputs.push(...(yield this.prepareSaplingSpendDescription(saplingContext, chosenInputs.inputsToSpend)));
800
+ let sumAmountOutput = new BigNumber(0);
801
+ for (const i in saplingTransactionParams) {
802
+ sumAmountOutput = sumAmountOutput.plus(new BigNumber(saplingTransactionParams[i].amount));
803
+ const [address] = octez_jsUtils.b58DecodeAndCheckPrefix(saplingTransactionParams[i].to, [
804
+ octez_jsUtils.PrefixV2.SaplingAddress,
805
+ ]);
806
+ outputs.push(yield this.prepareSaplingOutputDescription({
807
+ saplingContext,
808
+ address,
809
+ amount: saplingTransactionParams[i].amount,
810
+ memo: saplingTransactionParams[i].memo,
811
+ randomCommitmentTrapdoor,
812
+ outgoingViewingKey,
813
+ }));
814
+ }
815
+ if (chosenInputs.sumSelectedInputs.isGreaterThan(sumAmountOutput)) {
816
+ const payBackAddress = (yield saplingViewer.getAddress()).address;
817
+ const [address] = octez_jsUtils.b58DecodeAndCheckPrefix(payBackAddress, [octez_jsUtils.PrefixV2.SaplingAddress]);
818
+ const { payBackOutput, payBackAmount } = yield this.createPaybackOutput({
819
+ saplingContext,
820
+ address,
821
+ amount: txTotalAmount.toString(),
822
+ memo: DEFAULT_MEMO,
823
+ randomCommitmentTrapdoor: randomCommitmentTrapdoor,
824
+ outgoingViewingKey: outgoingViewingKey,
825
+ }, chosenInputs.sumSelectedInputs);
826
+ sumAmountOutput = sumAmountOutput.plus(new BigNumber(payBackAmount));
827
+ outputs.push(payBackOutput);
828
+ }
829
+ const balance = this.calculateTransactionBalance(chosenInputs.sumSelectedInputs.toString(), sumAmountOutput.toString());
830
+ const signature = yield this.createBindingSignature({
831
+ saplingContext,
832
+ inputs,
833
+ outputs,
834
+ balance,
835
+ boundData,
836
+ });
837
+ return { signature, balance, inputs, outputs };
838
+ }));
839
+ return {
840
+ inputs,
841
+ outputs,
842
+ signature,
843
+ balance,
844
+ };
845
+ });
846
+ }
847
+ // sum of values of inputs minus sums of values of output equals balance
848
+ calculateTransactionBalance(inputTotal, outputTotal) {
849
+ return new BigNumber(inputTotal).minus(new BigNumber(outputTotal));
850
+ }
851
+ prepareSaplingOutputDescription(parametersOutputDescription) {
852
+ return __awaiter(this, void 0, void 0, function* () {
853
+ const ephemeralPrivateKey = yield __classPrivateFieldGet(this, _SaplingTransactionBuilder_saplingWrapper, "f").randR();
854
+ const { commitmentValue, commitment, proof } = yield __classPrivateFieldGet(this, _SaplingTransactionBuilder_saplingWrapper, "f").preparePartialOutputDescription({
855
+ saplingContext: parametersOutputDescription.saplingContext,
856
+ address: parametersOutputDescription.address,
857
+ randomCommitmentTrapdoor: parametersOutputDescription.randomCommitmentTrapdoor,
858
+ ephemeralPrivateKey,
859
+ amount: parametersOutputDescription.amount,
860
+ });
861
+ const diversifier = yield __classPrivateFieldGet(this, _SaplingTransactionBuilder_saplingWrapper, "f").getDiversifiedFromRawPaymentAddress(parametersOutputDescription.address);
862
+ const ephemeralPublicKey = yield __classPrivateFieldGet(this, _SaplingTransactionBuilder_saplingWrapper, "f").deriveEphemeralPublicKey(diversifier, ephemeralPrivateKey);
863
+ const outgoingCipherKey = parametersOutputDescription.outgoingViewingKey
864
+ ? blake.blake2b(Buffer.concat([
865
+ commitmentValue,
866
+ commitment,
867
+ ephemeralPublicKey,
868
+ parametersOutputDescription.outgoingViewingKey,
869
+ ]), Buffer.from(OCK_KEY), 32)
870
+ : __classPrivateFieldGet(this, _SaplingTransactionBuilder_saplingWrapper, "f").getRandomBytes(32);
871
+ const ciphertext = yield this.encryptCiphertext({
872
+ address: parametersOutputDescription.address,
873
+ ephemeralPrivateKey,
874
+ diversifier,
875
+ outgoingCipherKey,
876
+ amount: parametersOutputDescription.amount,
877
+ randomCommitmentTrapdoor: parametersOutputDescription.randomCommitmentTrapdoor,
878
+ memo: parametersOutputDescription.memo,
879
+ });
880
+ return {
881
+ commitment,
882
+ proof,
883
+ ciphertext: Object.assign(Object.assign({}, ciphertext), { commitmentValue,
884
+ ephemeralPublicKey }),
885
+ };
886
+ });
887
+ }
888
+ prepareSaplingSpendDescription(saplingContext, inputsToSpend) {
889
+ return __awaiter(this, void 0, void 0, function* () {
890
+ const publicKeyReRandomization = yield __classPrivateFieldGet(this, _SaplingTransactionBuilder_saplingWrapper, "f").randR();
891
+ let stateDiff;
892
+ if (__classPrivateFieldGet(this, _SaplingTransactionBuilder_saplingId, "f")) {
893
+ stateDiff = yield __classPrivateFieldGet(this, _SaplingTransactionBuilder_readProvider, "f").getSaplingDiffById({ id: __classPrivateFieldGet(this, _SaplingTransactionBuilder_saplingId, "f") }, 'head');
894
+ }
895
+ else {
896
+ stateDiff = yield __classPrivateFieldGet(this, _SaplingTransactionBuilder_readProvider, "f").getSaplingDiffByContract(__classPrivateFieldGet(this, _SaplingTransactionBuilder_contractAddress, "f"), 'head');
897
+ }
898
+ const stateTree = yield __classPrivateFieldGet(this, _SaplingTransactionBuilder_saplingState, "f").getStateTree(stateDiff, true);
899
+ const saplingSpendDescriptions = [];
900
+ for (let i = 0; i < inputsToSpend.length; i++) {
901
+ const amount = convertValueToBigNumber(inputsToSpend[i].value).toString();
902
+ const witness = yield __classPrivateFieldGet(this, _SaplingTransactionBuilder_saplingState, "f").getWitness(stateTree, new BigNumber(inputsToSpend[i].position));
903
+ const unsignedSpendDescription = __classPrivateFieldGet(this, _SaplingTransactionBuilder_inMemoryProvingKey, "f")
904
+ ? yield __classPrivateFieldGet(this, _SaplingTransactionBuilder_inMemoryProvingKey, "f").prepareSpendDescription({
905
+ saplingContext,
906
+ address: inputsToSpend[i].paymentAddress,
907
+ randomCommitmentTrapdoor: inputsToSpend[i].randomCommitmentTrapdoor,
908
+ publicKeyReRandomization,
909
+ amount,
910
+ root: stateDiff.root,
911
+ witness,
912
+ })
913
+ : yield __classPrivateFieldGet(this, _SaplingTransactionBuilder_inMemorySpendingKey, "f").prepareSpendDescription({
914
+ saplingContext,
915
+ address: inputsToSpend[i].paymentAddress,
916
+ randomCommitmentTrapdoor: inputsToSpend[i].randomCommitmentTrapdoor,
917
+ publicKeyReRandomization,
918
+ amount,
919
+ root: stateDiff.root,
920
+ witness,
921
+ });
922
+ const unsignedSpendDescriptionBytes = __classPrivateFieldGet(this, _SaplingTransactionBuilder_saplingForger, "f").forgeUnsignedTxInput(unsignedSpendDescription);
923
+ const hash = blake.blake2b(unsignedSpendDescriptionBytes, yield this.getAntiReplay(), 32);
924
+ const spendDescription = yield __classPrivateFieldGet(this, _SaplingTransactionBuilder_inMemorySpendingKey, "f").signSpendDescription({
925
+ publicKeyReRandomization,
926
+ unsignedSpendDescription,
927
+ hash,
928
+ });
929
+ if (spendDescription.signature === undefined) {
930
+ throw new Error('Spend signing failed');
931
+ }
932
+ saplingSpendDescriptions.push(spendDescription);
933
+ }
934
+ return saplingSpendDescriptions;
935
+ });
936
+ }
937
+ encryptCiphertext(parametersCiphertext) {
938
+ return __awaiter(this, void 0, void 0, function* () {
939
+ const recipientDiversifiedTransmissionKey = yield __classPrivateFieldGet(this, _SaplingTransactionBuilder_saplingWrapper, "f").getPkdFromRawPaymentAddress(parametersCiphertext.address);
940
+ const keyAgreement = yield __classPrivateFieldGet(this, _SaplingTransactionBuilder_saplingWrapper, "f").keyAgreement(recipientDiversifiedTransmissionKey, parametersCiphertext.ephemeralPrivateKey);
941
+ const keyAgreementHash = blake.blake2b(keyAgreement, Buffer.from(KDF_KEY), 32);
942
+ const nonceEnc = Buffer.from(__classPrivateFieldGet(this, _SaplingTransactionBuilder_saplingWrapper, "f").getRandomBytes(24));
943
+ const transactionPlaintext = __classPrivateFieldGet(this, _SaplingTransactionBuilder_saplingForger, "f").forgeTransactionPlaintext({
944
+ diversifier: parametersCiphertext.diversifier,
945
+ amount: parametersCiphertext.amount,
946
+ randomCommitmentTrapdoor: parametersCiphertext.randomCommitmentTrapdoor,
947
+ memoSize: __classPrivateFieldGet(this, _SaplingTransactionBuilder_memoSize, "f") * 2,
948
+ memo: parametersCiphertext.memo,
949
+ });
950
+ const nonceOut = Buffer.from(__classPrivateFieldGet(this, _SaplingTransactionBuilder_saplingWrapper, "f").getRandomBytes(24));
951
+ const payloadEnc = Buffer.from(nacl.secretBox(keyAgreementHash, nonceEnc, transactionPlaintext));
952
+ const payloadOut = Buffer.from(nacl.secretBox(parametersCiphertext.outgoingCipherKey, nonceOut, Buffer.concat([
953
+ recipientDiversifiedTransmissionKey,
954
+ parametersCiphertext.ephemeralPrivateKey,
955
+ ])));
956
+ return { payloadEnc, nonceEnc, payloadOut, nonceOut };
957
+ });
958
+ }
959
+ createPaybackOutput(params, sumSelectedInputs) {
960
+ return __awaiter(this, void 0, void 0, function* () {
961
+ const payBackAmount = sumSelectedInputs.minus(params.amount).toString();
962
+ const payBackOutput = yield this.prepareSaplingOutputDescription({
963
+ saplingContext: params.saplingContext,
964
+ address: params.address,
965
+ amount: payBackAmount,
966
+ memo: params.memo,
967
+ randomCommitmentTrapdoor: params.randomCommitmentTrapdoor,
968
+ outgoingViewingKey: params.outgoingViewingKey,
969
+ });
970
+ return { payBackOutput, payBackAmount };
971
+ });
972
+ }
973
+ createBindingSignature(parametersBindingSig) {
974
+ return __awaiter(this, void 0, void 0, function* () {
975
+ const outputs = __classPrivateFieldGet(this, _SaplingTransactionBuilder_saplingForger, "f").forgeOutputDescriptions(parametersBindingSig.outputs);
976
+ const inputs = __classPrivateFieldGet(this, _SaplingTransactionBuilder_saplingForger, "f").forgeSpendDescriptions(parametersBindingSig.inputs);
977
+ const transactionSigHash = blake.blake2b(Buffer.concat([inputs, outputs, parametersBindingSig.boundData]), yield this.getAntiReplay(), 32);
978
+ return __classPrivateFieldGet(this, _SaplingTransactionBuilder_saplingWrapper, "f").createBindingSignature(parametersBindingSig.saplingContext, parametersBindingSig.balance.toFixed(), transactionSigHash);
979
+ });
980
+ }
981
+ getAntiReplay() {
982
+ return __awaiter(this, void 0, void 0, function* () {
983
+ let chainId = __classPrivateFieldGet(this, _SaplingTransactionBuilder_chainId, "f");
984
+ if (!chainId) {
985
+ chainId = yield __classPrivateFieldGet(this, _SaplingTransactionBuilder_readProvider, "f").getChainId();
986
+ __classPrivateFieldSet(this, _SaplingTransactionBuilder_chainId, chainId, "f");
987
+ }
988
+ return Buffer.from(`${__classPrivateFieldGet(this, _SaplingTransactionBuilder_contractAddress, "f")}${chainId}`);
989
+ });
990
+ }
991
+ }
992
+ _SaplingTransactionBuilder_inMemorySpendingKey = new WeakMap(), _SaplingTransactionBuilder_inMemoryProvingKey = new WeakMap(), _SaplingTransactionBuilder_saplingForger = new WeakMap(), _SaplingTransactionBuilder_contractAddress = new WeakMap(), _SaplingTransactionBuilder_saplingId = new WeakMap(), _SaplingTransactionBuilder_memoSize = new WeakMap(), _SaplingTransactionBuilder_readProvider = new WeakMap(), _SaplingTransactionBuilder_saplingWrapper = new WeakMap(), _SaplingTransactionBuilder_chainId = new WeakMap(), _SaplingTransactionBuilder_saplingState = new WeakMap();
993
+
994
+ function decryptKey(spendingKey, password) {
995
+ const [keyArr, pre] = (() => {
996
+ try {
997
+ return octez_jsUtils.b58DecodeAndCheckPrefix(spendingKey, [
998
+ octez_jsUtils.PrefixV2.SaplingSpendingKey,
999
+ octez_jsUtils.PrefixV2.EncryptedSaplingSpendingKey,
1000
+ ]);
1001
+ }
1002
+ catch (err) {
1003
+ if (err instanceof octez_jsCore.ParameterValidationError) {
1004
+ throw new InvalidSpendingKey(spendingKey, 'invalid spending key');
1005
+ }
1006
+ else {
1007
+ throw err;
1008
+ }
1009
+ }
1010
+ })();
1011
+ if (pre === octez_jsUtils.PrefixV2.EncryptedSaplingSpendingKey) {
1012
+ if (!password) {
1013
+ throw new InvalidSpendingKey(spendingKey, 'no password provided to decrypt');
1014
+ }
1015
+ const salt = toBuffer(keyArr.slice(0, 8));
1016
+ const encryptedSk = toBuffer(keyArr.slice(8));
1017
+ const encryptionKey = pbkdf2.pbkdf2Sync(password, salt, 32768, 32, 'sha512');
1018
+ // Zero nonce is safe: fresh random salt per encryption produces unique PBKDF2-derived key.
1019
+ // See: https://gitlab.com/tezos/tezos/-/blob/master/src/lib_signer_backends/encrypted.ml
1020
+ const decrypted = nacl.openSecretBox(new Uint8Array(encryptionKey), new Uint8Array(24), // zero nonce - uniqueness provided by per-encryption derived key
1021
+ new Uint8Array(encryptedSk));
1022
+ if (!decrypted) {
1023
+ throw new InvalidSpendingKey(spendingKey, 'incorrect password or unable to decrypt');
1024
+ }
1025
+ return toBuffer(decrypted);
1026
+ }
1027
+ else {
1028
+ return toBuffer(keyArr);
1029
+ }
1030
+ }
1031
+
1032
+ var _InMemoryViewingKey_fullViewingKey;
1033
+ /**
1034
+ * @description Holds the viewing key
1035
+ */
1036
+ class InMemoryViewingKey {
1037
+ constructor(fullViewingKey) {
1038
+ _InMemoryViewingKey_fullViewingKey.set(this, void 0);
1039
+ __classPrivateFieldSet(this, _InMemoryViewingKey_fullViewingKey, Buffer.from(fullViewingKey, 'hex'), "f");
1040
+ }
1041
+ /**
1042
+ * @description Allows to instantiate the InMemoryViewingKey from an encrypted/unencrypted spending key
1043
+ *
1044
+ * @param spendingKey Base58Check-encoded spending key
1045
+ * @param password Optional password to decrypt the spending key
1046
+ * @example
1047
+ * ```
1048
+ * await InMemoryViewingKey.fromSpendingKey('sask27SLmU9herddHz4qFJBLMjWYMbJF8RtS579w9ej9mfCYK7VUdyCJPHK8AzW9zMsopGZEkYeNjAY7Zz1bkM7CGu8eKLzrjBLTMC5wWJDhxiK91ahA29rhDRsHdJDV2u2jFwb2MNUix8JW7sAkAqYVaJpCehTBPgRQ1KqKwqqUaNmuD8kazd4Q8MCWmgbWs21Yuomdqyi9FLigjRp7oY4m5adaVU19Nj1AHvsMY2tePeU2L')
1049
+ * ```
1050
+ *
1051
+ */
1052
+ static fromSpendingKey(spendingKey, password) {
1053
+ return __awaiter(this, void 0, void 0, function* () {
1054
+ const spendingKeyBuf = decryptKey(spendingKey, password);
1055
+ const viewingKey = yield sapling__namespace.getExtendedFullViewingKeyFromSpendingKey(spendingKeyBuf);
1056
+ return new InMemoryViewingKey(viewingKey.toString('hex'));
1057
+ });
1058
+ }
1059
+ /**
1060
+ * @description Retrieve the full viewing key
1061
+ * @returns Buffer representing the full viewing key
1062
+ *
1063
+ */
1064
+ getFullViewingKey() {
1065
+ return __classPrivateFieldGet(this, _InMemoryViewingKey_fullViewingKey, "f");
1066
+ }
1067
+ /**
1068
+ * @description Retrieve the outgoing viewing key
1069
+ * @returns Buffer representing the outgoing viewing key
1070
+ *
1071
+ */
1072
+ getOutgoingViewingKey() {
1073
+ return __awaiter(this, void 0, void 0, function* () {
1074
+ return sapling__namespace.getOutgoingViewingKey(__classPrivateFieldGet(this, _InMemoryViewingKey_fullViewingKey, "f"));
1075
+ });
1076
+ }
1077
+ /**
1078
+ * @description Retrieve the incoming viewing key
1079
+ * @returns Buffer representing the incoming viewing key
1080
+ *
1081
+ */
1082
+ getIncomingViewingKey() {
1083
+ return __awaiter(this, void 0, void 0, function* () {
1084
+ return sapling__namespace.getIncomingViewingKey(__classPrivateFieldGet(this, _InMemoryViewingKey_fullViewingKey, "f"));
1085
+ });
1086
+ }
1087
+ /**
1088
+ * @description Retrieve a payment address
1089
+ * @param addressIndex used to determine which diversifier should be used to derive the address, default is 0
1090
+ * @returns Base58Check-encoded address and its index
1091
+ *
1092
+ */
1093
+ getAddress(addressIndex) {
1094
+ return __awaiter(this, void 0, void 0, function* () {
1095
+ const { index, raw } = yield sapling__namespace.getPaymentAddressFromViewingKey(__classPrivateFieldGet(this, _InMemoryViewingKey_fullViewingKey, "f"), addressIndex);
1096
+ return {
1097
+ address: octez_jsUtils.b58Encode(raw, octez_jsUtils.PrefixV2.SaplingAddress),
1098
+ addressIndex: index.readInt32LE(),
1099
+ };
1100
+ });
1101
+ }
1102
+ }
1103
+ _InMemoryViewingKey_fullViewingKey = new WeakMap();
1104
+
1105
+ var _InMemorySpendingKey_spendingKeyBuf, _InMemorySpendingKey_saplingViewingKey;
1106
+ /**
1107
+ * @description holds the spending key, create proof and signature for spend descriptions
1108
+ * can instantiate from mnemonic word list or decrypt a encrypted spending key
1109
+ * with access to instantiate a InMemoryViewingKey
1110
+ */
1111
+ class InMemorySpendingKey {
1112
+ /**
1113
+ *
1114
+ * @param spendingKey unencrypted sask... or encrypted MMXj...
1115
+ * @param password required for MMXj encrypted keys
1116
+ */
1117
+ constructor(spendingKey, password) {
1118
+ _InMemorySpendingKey_spendingKeyBuf.set(this, void 0);
1119
+ _InMemorySpendingKey_saplingViewingKey.set(this, void 0);
1120
+ __classPrivateFieldSet(this, _InMemorySpendingKey_spendingKeyBuf, decryptKey(spendingKey, password), "f");
1121
+ }
1122
+ /**
1123
+ *
1124
+ * @param mnemonic string of words
1125
+ * @param derivationPath tezos current standard 'm/'
1126
+ * @returns InMemorySpendingKey class instantiated
1127
+ */
1128
+ static fromMnemonic(mnemonic_1) {
1129
+ return __awaiter(this, arguments, void 0, function* (mnemonic, derivationPath = 'm/') {
1130
+ // no password passed here. password provided only changes from sask -> MMXj
1131
+ const fullSeed = yield bip39__namespace.mnemonicToSeed(mnemonic);
1132
+ const first32 = fullSeed.slice(0, 32);
1133
+ const second32 = fullSeed.slice(32);
1134
+ // reduce seed bytes must be 32 bytes reflecting both halves
1135
+ const seed = Buffer.from(first32.map((byte, index) => byte ^ second32[index]));
1136
+ const spendingKeyArr = new Uint8Array(yield sapling__namespace.getExtendedSpendingKey(seed, derivationPath));
1137
+ const spendingKey = octez_jsUtils.b58Encode(spendingKeyArr, octez_jsUtils.PrefixV2.SaplingSpendingKey);
1138
+ return new InMemorySpendingKey(spendingKey);
1139
+ });
1140
+ }
1141
+ /**
1142
+ *
1143
+ * @returns InMemoryViewingKey instantiated class
1144
+ */
1145
+ getSaplingViewingKeyProvider() {
1146
+ return __awaiter(this, void 0, void 0, function* () {
1147
+ let viewingKey;
1148
+ if (!__classPrivateFieldGet(this, _InMemorySpendingKey_saplingViewingKey, "f")) {
1149
+ viewingKey = yield sapling__namespace.getExtendedFullViewingKeyFromSpendingKey(__classPrivateFieldGet(this, _InMemorySpendingKey_spendingKeyBuf, "f"));
1150
+ __classPrivateFieldSet(this, _InMemorySpendingKey_saplingViewingKey, new InMemoryViewingKey(viewingKey.toString('hex')), "f");
1151
+ }
1152
+ return __classPrivateFieldGet(this, _InMemorySpendingKey_saplingViewingKey, "f");
1153
+ });
1154
+ }
1155
+ /**
1156
+ * @description Prepare an unsigned sapling spend description using the spending key
1157
+ * @param parametersSpendProof.saplingContext The sapling proving context
1158
+ * @param parametersSpendProof.address The address of the input
1159
+ * @param parametersSpendProof.randomCommitmentTrapdoor The randomness of the commitment
1160
+ * @param parametersSpendProof.publicKeyReRandomization The re-randomization of the public key
1161
+ * @param parametersSpendProof.amount The value of the input
1162
+ * @param parametersSpendProof.root The root of the merkle tree
1163
+ * @param parametersSpendProof.witness The path of the commitment in the tree
1164
+ * @param derivationPath tezos current standard 'm/'
1165
+ * @returns The unsigned spend description
1166
+ */
1167
+ prepareSpendDescription(parametersSpendProof) {
1168
+ return __awaiter(this, void 0, void 0, function* () {
1169
+ const spendDescription = yield sapling__namespace.prepareSpendDescriptionWithSpendingKey(parametersSpendProof.saplingContext, __classPrivateFieldGet(this, _InMemorySpendingKey_spendingKeyBuf, "f"), parametersSpendProof.address, parametersSpendProof.randomCommitmentTrapdoor, parametersSpendProof.publicKeyReRandomization, parametersSpendProof.amount, parametersSpendProof.root, parametersSpendProof.witness);
1170
+ return {
1171
+ commitmentValue: spendDescription.cv,
1172
+ nullifier: spendDescription.nf,
1173
+ publicKeyReRandomization: spendDescription.rk,
1174
+ rtAnchor: spendDescription.rt,
1175
+ proof: spendDescription.proof,
1176
+ };
1177
+ });
1178
+ }
1179
+ /**
1180
+ * @description Sign a sapling spend description
1181
+ * @param parametersSpendSig.publicKeyReRandomization The re-randomization of the public key
1182
+ * @param parametersSpendSig.unsignedSpendDescription The unsigned Spend description
1183
+ * @param parametersSpendSig.hash The data to be signed
1184
+ * @returns The signed spend description
1185
+ */
1186
+ signSpendDescription(parametersSpendSig) {
1187
+ return __awaiter(this, void 0, void 0, function* () {
1188
+ const signedSpendDescription = yield sapling__namespace.signSpendDescription({
1189
+ cv: parametersSpendSig.unsignedSpendDescription.commitmentValue,
1190
+ rt: parametersSpendSig.unsignedSpendDescription.rtAnchor,
1191
+ nf: parametersSpendSig.unsignedSpendDescription.nullifier,
1192
+ rk: parametersSpendSig.unsignedSpendDescription.publicKeyReRandomization,
1193
+ proof: parametersSpendSig.unsignedSpendDescription.proof,
1194
+ }, __classPrivateFieldGet(this, _InMemorySpendingKey_spendingKeyBuf, "f"), parametersSpendSig.publicKeyReRandomization, parametersSpendSig.hash);
1195
+ return {
1196
+ commitmentValue: signedSpendDescription.cv,
1197
+ nullifier: signedSpendDescription.nf,
1198
+ publicKeyReRandomization: signedSpendDescription.rk,
1199
+ proof: signedSpendDescription.proof,
1200
+ signature: signedSpendDescription.spendAuthSig,
1201
+ };
1202
+ });
1203
+ }
1204
+ /**
1205
+ * @description Return a proof authorizing key from the configured spending key
1206
+ */
1207
+ getProvingKey() {
1208
+ return __awaiter(this, void 0, void 0, function* () {
1209
+ const provingKey = yield sapling__namespace.getProofAuthorizingKey(__classPrivateFieldGet(this, _InMemorySpendingKey_spendingKeyBuf, "f"));
1210
+ return provingKey.toString('hex');
1211
+ });
1212
+ }
1213
+ }
1214
+ _InMemorySpendingKey_spendingKeyBuf = new WeakMap(), _InMemorySpendingKey_saplingViewingKey = new WeakMap();
1215
+
1216
+ var _InMemoryProvingKey_provingKey;
1217
+ /**
1218
+ * @description holds the proving key, create proof for spend descriptions
1219
+ * The class can be instantiated from a proving key or a spending key
1220
+ */
1221
+ class InMemoryProvingKey {
1222
+ constructor(provingKey) {
1223
+ _InMemoryProvingKey_provingKey.set(this, void 0);
1224
+ __classPrivateFieldSet(this, _InMemoryProvingKey_provingKey, Buffer.from(provingKey, 'hex'), "f");
1225
+ }
1226
+ /**
1227
+ * @description Allows to instantiate the InMemoryProvingKey from an encrypted/unencrypted spending key
1228
+ *
1229
+ * @param spendingKey Base58Check-encoded spending key
1230
+ * @param password Optional password to decrypt the spending key
1231
+ * @example
1232
+ * ```
1233
+ * await InMemoryProvingKey.fromSpendingKey('sask27SLmU9herddHz4qFJBLMjWYMbJF8RtS579w9ej9mfCYK7VUdyCJPHK8AzW9zMsopGZEkYeNjAY7Zz1bkM7CGu8eKLzrjBLTMC5wWJDhxiK91ahA29rhDRsHdJDV2u2jFwb2MNUix8JW7sAkAqYVaJpCehTBPgRQ1KqKwqqUaNmuD8kazd4Q8MCWmgbWs21Yuomdqyi9FLigjRp7oY4m5adaVU19Nj1AHvsMY2tePeU2L')
1234
+ * ```
1235
+ *
1236
+ */
1237
+ static fromSpendingKey(spendingKey, password) {
1238
+ return __awaiter(this, void 0, void 0, function* () {
1239
+ const decodedSpendingKey = decryptKey(spendingKey, password);
1240
+ const provingKey = yield sapling__namespace.getProofAuthorizingKey(decodedSpendingKey);
1241
+ return new InMemoryProvingKey(provingKey.toString('hex'));
1242
+ });
1243
+ }
1244
+ /**
1245
+ * @description Prepare an unsigned sapling spend description using the proving key
1246
+ *
1247
+ * @param parametersSpendProof.saplingContext The sapling proving context
1248
+ * @param parametersSpendProof.address The address of the input
1249
+ * @param parametersSpendProof.randomCommitmentTrapdoor The randomness of the commitment
1250
+ * @param parametersSpendProof.publicKeyReRandomization The re-randomization of the public key
1251
+ * @param parametersSpendProof.amount The value of the input
1252
+ * @param parametersSpendProof.root The root of the merkle tree
1253
+ * @param parametersSpendProof.witness The path of the commitment in the tree
1254
+ * @param derivationPath tezos current standard 'm/'
1255
+ * @returns The unsinged spend description
1256
+ */
1257
+ prepareSpendDescription(parametersSpendProof) {
1258
+ return __awaiter(this, void 0, void 0, function* () {
1259
+ const spendDescription = yield sapling__namespace.prepareSpendDescriptionWithAuthorizingKey(parametersSpendProof.saplingContext, __classPrivateFieldGet(this, _InMemoryProvingKey_provingKey, "f"), parametersSpendProof.address, parametersSpendProof.randomCommitmentTrapdoor, parametersSpendProof.publicKeyReRandomization, parametersSpendProof.amount, parametersSpendProof.root, parametersSpendProof.witness);
1260
+ return {
1261
+ commitmentValue: spendDescription.cv,
1262
+ nullifier: spendDescription.nf,
1263
+ publicKeyReRandomization: spendDescription.rk,
1264
+ rtAnchor: spendDescription.rt,
1265
+ proof: spendDescription.proof,
1266
+ };
1267
+ });
1268
+ }
1269
+ }
1270
+ _InMemoryProvingKey_provingKey = new WeakMap();
1271
+
1272
+ /**
1273
+ * @packageDocumentation
1274
+ * @module @tezos-x/octez.js-sapling
1275
+ */
1276
+ var _SaplingToolkit_inMemorySpendingKey, _SaplingToolkit_saplingId, _SaplingToolkit_contractAddress, _SaplingToolkit_memoSize, _SaplingToolkit_readProvider, _SaplingToolkit_packer, _SaplingToolkit_saplingForger, _SaplingToolkit_saplingTxBuilder, _SaplingToolkit_saplingTransactionViewer;
1277
+ /**
1278
+ * @description Class that surfaces all of the sapling capability allowing to read from a sapling state and prepare transactions
1279
+ *
1280
+ * @param keys.saplingSigner Holds the sapling spending key
1281
+ * @param keys.saplingProver (Optional) Allows to generate the proofs with the proving key rather than the spending key
1282
+ * @param saplingContractDetails Contains the address of the sapling contract, the memo size, and an optional sapling id that must be defined if the sapling contract contains more than one sapling state
1283
+ * @param readProvider Allows to read data from the blockchain
1284
+ * @param packer (Optional) Allows packing data. Use the `MichelCodecPacker` by default.
1285
+ * @param saplingForger (Optional) Allows serializing the sapling transactions. Use the `SaplingForger` by default.
1286
+ * @param saplingTxBuilder (Optional) Allows to prepare the sapling transactions. Use the `SaplingTransactionBuilder` by default.
1287
+ * @example
1288
+ * ```
1289
+ * const inMemorySpendingKey = await InMemorySpendingKey.fromMnemonic('YOUR_MNEMONIC');
1290
+ * const readProvider = new RpcReadAdapter(new RpcClient('https://YOUR_PREFERRED_RPC_URL'))
1291
+ *
1292
+ * const saplingToolkit = new SaplingToolkit(
1293
+ * { saplingSigner: inMemorySpendingKey },
1294
+ * { contractAddress: SAPLING_CONTRACT_ADDRESS, memoSize: 8 },
1295
+ * readProvider
1296
+ * )
1297
+ * ```
1298
+ */
1299
+ class SaplingToolkit {
1300
+ constructor(keys, saplingContractDetails, readProvider, packer = new octez_js.MichelCodecPacker(), saplingForger = new SaplingForger(), saplingTxBuilder = new SaplingTransactionBuilder(keys, saplingForger, saplingContractDetails, readProvider)) {
1301
+ _SaplingToolkit_inMemorySpendingKey.set(this, void 0);
1302
+ _SaplingToolkit_saplingId.set(this, void 0);
1303
+ _SaplingToolkit_contractAddress.set(this, void 0);
1304
+ _SaplingToolkit_memoSize.set(this, void 0);
1305
+ _SaplingToolkit_readProvider.set(this, void 0);
1306
+ _SaplingToolkit_packer.set(this, void 0);
1307
+ _SaplingToolkit_saplingForger.set(this, void 0);
1308
+ _SaplingToolkit_saplingTxBuilder.set(this, void 0);
1309
+ _SaplingToolkit_saplingTransactionViewer.set(this, void 0);
1310
+ __classPrivateFieldSet(this, _SaplingToolkit_inMemorySpendingKey, keys.saplingSigner, "f");
1311
+ __classPrivateFieldSet(this, _SaplingToolkit_saplingId, saplingContractDetails.saplingId, "f");
1312
+ __classPrivateFieldSet(this, _SaplingToolkit_contractAddress, saplingContractDetails.contractAddress, "f");
1313
+ __classPrivateFieldSet(this, _SaplingToolkit_memoSize, saplingContractDetails.memoSize, "f");
1314
+ __classPrivateFieldSet(this, _SaplingToolkit_readProvider, readProvider, "f");
1315
+ __classPrivateFieldSet(this, _SaplingToolkit_packer, packer, "f");
1316
+ __classPrivateFieldSet(this, _SaplingToolkit_saplingForger, saplingForger, "f");
1317
+ __classPrivateFieldSet(this, _SaplingToolkit_saplingTxBuilder, saplingTxBuilder, "f");
1318
+ }
1319
+ /**
1320
+ * @description Get an instance of `SaplingTransactionViewer` which allows to retrieve and decrypt sapling transactions and calculate the unspent balance.
1321
+ */
1322
+ getSaplingTransactionViewer() {
1323
+ return __awaiter(this, void 0, void 0, function* () {
1324
+ let saplingTransactionViewer;
1325
+ if (!__classPrivateFieldGet(this, _SaplingToolkit_saplingTransactionViewer, "f")) {
1326
+ const saplingViewingKey = yield __classPrivateFieldGet(this, _SaplingToolkit_inMemorySpendingKey, "f").getSaplingViewingKeyProvider();
1327
+ saplingTransactionViewer = new SaplingTransactionViewer(saplingViewingKey, this.getSaplingContractId(), __classPrivateFieldGet(this, _SaplingToolkit_readProvider, "f"));
1328
+ __classPrivateFieldSet(this, _SaplingToolkit_saplingTransactionViewer, saplingTransactionViewer, "f");
1329
+ }
1330
+ return __classPrivateFieldGet(this, _SaplingToolkit_saplingTransactionViewer, "f");
1331
+ });
1332
+ }
1333
+ /**
1334
+ * @description Prepare a shielded transaction
1335
+ * @param shieldedTxParams `to` is the payment address that will receive the shielded tokens (zet).
1336
+ * `amount` is the amount of shielded tokens in tez by default.
1337
+ * `mutez` needs to be set to true if the amount of shielded tokens is in mutez.
1338
+ * `memo` is an empty string by default.
1339
+ * @returns a string representing the sapling transaction
1340
+ */
1341
+ prepareShieldedTransaction(shieldedTxParams) {
1342
+ return __awaiter(this, void 0, void 0, function* () {
1343
+ const { formatedParams, totalAmount } = this.formatTransactionParams(shieldedTxParams, this.validateDestinationSaplingAddress);
1344
+ const root = yield this.getRoot();
1345
+ const { inputs, outputs, signature, balance } = yield __classPrivateFieldGet(this, _SaplingToolkit_saplingTxBuilder, "f").createShieldedTx(formatedParams, totalAmount, DEFAULT_BOUND_DATA);
1346
+ const forgedSaplingTx = __classPrivateFieldGet(this, _SaplingToolkit_saplingForger, "f").forgeSaplingTransaction({
1347
+ inputs,
1348
+ outputs,
1349
+ balance,
1350
+ root,
1351
+ boundData: DEFAULT_BOUND_DATA,
1352
+ signature,
1353
+ });
1354
+ return forgedSaplingTx.toString('hex');
1355
+ });
1356
+ }
1357
+ /**
1358
+ * @description Prepare an unshielded transaction
1359
+ * @param unshieldedTxParams `to` is the Tezos address that will receive the unshielded tokens (tz1, tz2 or tz3).
1360
+ * `amount` is the amount of unshielded tokens in tez by default.
1361
+ * `mutez` needs to be set to true if the amount of unshielded tokens is in mutez.
1362
+ * @returns a string representing the sapling transaction.
1363
+ */
1364
+ prepareUnshieldedTransaction(unshieldedTxParams) {
1365
+ return __awaiter(this, void 0, void 0, function* () {
1366
+ const { formatedParams, totalAmount } = this.formatTransactionParams([unshieldedTxParams], this.validateDestinationImplicitAddress);
1367
+ const boundData = yield this.createBoundData(formatedParams[0].to);
1368
+ const root = yield this.getRoot();
1369
+ const chosenInputs = yield this.selectInputsToSpend(new BigNumber(formatedParams[0].amount));
1370
+ const { inputs, outputs, signature, balance } = yield __classPrivateFieldGet(this, _SaplingToolkit_saplingTxBuilder, "f").createSaplingTx([], totalAmount, boundData, chosenInputs);
1371
+ const forgedSaplingTx = __classPrivateFieldGet(this, _SaplingToolkit_saplingForger, "f").forgeSaplingTransaction({
1372
+ inputs,
1373
+ outputs,
1374
+ balance,
1375
+ root,
1376
+ boundData,
1377
+ signature,
1378
+ });
1379
+ return forgedSaplingTx.toString('hex');
1380
+ });
1381
+ }
1382
+ /**
1383
+ * @description Prepare a sapling transaction (zet to zet)
1384
+ * @param saplingTxParams `to` is the payment address that will receive the shielded tokens (zet).
1385
+ * `amount` is the amount of unshielded tokens in tez by default.
1386
+ * `mutez` needs to be set to true if the amount of unshielded tokens is in mutez.
1387
+ * `memo` is an empty string by default.
1388
+ * @returns a string representing the sapling transaction.
1389
+ */
1390
+ prepareSaplingTransaction(saplingTxParams) {
1391
+ return __awaiter(this, void 0, void 0, function* () {
1392
+ const { formatedParams, totalAmount } = this.formatTransactionParams(saplingTxParams, this.validateDestinationSaplingAddress);
1393
+ const root = yield this.getRoot();
1394
+ const chosenInputs = yield this.selectInputsToSpend(totalAmount);
1395
+ const { inputs, outputs, signature, balance } = yield __classPrivateFieldGet(this, _SaplingToolkit_saplingTxBuilder, "f").createSaplingTx(formatedParams, totalAmount, DEFAULT_BOUND_DATA, chosenInputs);
1396
+ const forgedSaplingTx = __classPrivateFieldGet(this, _SaplingToolkit_saplingForger, "f").forgeSaplingTransaction({
1397
+ inputs,
1398
+ outputs,
1399
+ balance,
1400
+ root,
1401
+ boundData: DEFAULT_BOUND_DATA,
1402
+ signature,
1403
+ });
1404
+ return forgedSaplingTx.toString('hex');
1405
+ });
1406
+ }
1407
+ formatTransactionParams(txParams, validateDestination) {
1408
+ const formatedParams = [];
1409
+ let totalAmount = new BigNumber(0);
1410
+ txParams.forEach((param) => {
1411
+ var _a;
1412
+ validateDestination(param.to);
1413
+ const amountMutez = param.mutez
1414
+ ? param.amount.toString()
1415
+ : octez_jsUtils.format('tz', 'mutez', param.amount).toString();
1416
+ totalAmount = totalAmount.plus(new BigNumber(amountMutez));
1417
+ const memo = (_a = param.memo) !== null && _a !== void 0 ? _a : DEFAULT_MEMO;
1418
+ if (memo.length > __classPrivateFieldGet(this, _SaplingToolkit_memoSize, "f")) {
1419
+ throw new InvalidMemo(memo, `expecting length to be less than ${__classPrivateFieldGet(this, _SaplingToolkit_memoSize, "f")}`);
1420
+ }
1421
+ formatedParams.push({ to: param.to, amount: amountMutez, memo });
1422
+ });
1423
+ return { formatedParams, totalAmount };
1424
+ }
1425
+ getRoot() {
1426
+ return __awaiter(this, void 0, void 0, function* () {
1427
+ if (__classPrivateFieldGet(this, _SaplingToolkit_saplingId, "f")) {
1428
+ const { root } = yield __classPrivateFieldGet(this, _SaplingToolkit_readProvider, "f").getSaplingDiffById({ id: __classPrivateFieldGet(this, _SaplingToolkit_saplingId, "f") }, 'head');
1429
+ return root;
1430
+ }
1431
+ else {
1432
+ const { root } = yield __classPrivateFieldGet(this, _SaplingToolkit_readProvider, "f").getSaplingDiffByContract(__classPrivateFieldGet(this, _SaplingToolkit_contractAddress, "f"), 'head');
1433
+ return root;
1434
+ }
1435
+ });
1436
+ }
1437
+ createBoundData(destination) {
1438
+ return __awaiter(this, void 0, void 0, function* () {
1439
+ const bytes = octez_jsUtils.b58DecodePublicKeyHash(destination, 'hex');
1440
+ const packedDestination = yield __classPrivateFieldGet(this, _SaplingToolkit_packer, "f").packData({
1441
+ data: { bytes },
1442
+ type: { prim: 'bytes' },
1443
+ });
1444
+ return Buffer.from(packedDestination.packed, 'hex');
1445
+ });
1446
+ }
1447
+ validateDestinationImplicitAddress(to) {
1448
+ const toValidation = octez_jsUtils.validateKeyHash(to);
1449
+ if (toValidation !== octez_jsUtils.ValidationResult.VALID) {
1450
+ throw new octez_jsCore.InvalidKeyHashError(to, toValidation);
1451
+ }
1452
+ }
1453
+ validateDestinationSaplingAddress(to) {
1454
+ try {
1455
+ octez_jsUtils.b58DecodeAndCheckPrefix(to, [octez_jsUtils.PrefixV2.SaplingAddress]);
1456
+ }
1457
+ catch (_a) {
1458
+ throw new octez_jsCore.InvalidAddressError(to, `expecting prefix ${octez_jsUtils.PrefixV2.SaplingAddress}.`);
1459
+ }
1460
+ }
1461
+ getSaplingContractId() {
1462
+ let saplingContractId;
1463
+ if (__classPrivateFieldGet(this, _SaplingToolkit_saplingId, "f")) {
1464
+ saplingContractId = { saplingId: __classPrivateFieldGet(this, _SaplingToolkit_saplingId, "f") };
1465
+ }
1466
+ else {
1467
+ saplingContractId = { contractAddress: __classPrivateFieldGet(this, _SaplingToolkit_contractAddress, "f") };
1468
+ }
1469
+ return saplingContractId;
1470
+ }
1471
+ selectInputsToSpend(amountMutez) {
1472
+ return __awaiter(this, void 0, void 0, function* () {
1473
+ const saplingTxViewer = yield this.getSaplingTransactionViewer();
1474
+ const { incoming } = yield saplingTxViewer.getIncomingAndOutgoingTransactionsRaw();
1475
+ const inputsToSpend = [];
1476
+ let sumSelectedInputs = new BigNumber(0);
1477
+ incoming.forEach((input) => {
1478
+ if (!input.isSpent && sumSelectedInputs.isLessThan(amountMutez)) {
1479
+ const txAmount = convertValueToBigNumber(input.value);
1480
+ sumSelectedInputs = sumSelectedInputs.plus(txAmount);
1481
+ const { isSpent: _isSpent } = input, rest = __rest(input, ["isSpent"]);
1482
+ inputsToSpend.push(rest);
1483
+ }
1484
+ });
1485
+ if (sumSelectedInputs.isLessThan(new BigNumber(amountMutez))) {
1486
+ throw new InsufficientBalance(sumSelectedInputs.toString(), amountMutez.toString());
1487
+ }
1488
+ return { inputsToSpend, sumSelectedInputs };
1489
+ });
1490
+ }
1491
+ }
1492
+ _SaplingToolkit_inMemorySpendingKey = new WeakMap(), _SaplingToolkit_saplingId = new WeakMap(), _SaplingToolkit_contractAddress = new WeakMap(), _SaplingToolkit_memoSize = new WeakMap(), _SaplingToolkit_readProvider = new WeakMap(), _SaplingToolkit_packer = new WeakMap(), _SaplingToolkit_saplingForger = new WeakMap(), _SaplingToolkit_saplingTxBuilder = new WeakMap(), _SaplingToolkit_saplingTransactionViewer = new WeakMap();
1493
+
1494
+ exports.InMemoryProvingKey = InMemoryProvingKey;
1495
+ exports.InMemorySpendingKey = InMemorySpendingKey;
1496
+ exports.InMemoryViewingKey = InMemoryViewingKey;
1497
+ exports.SaplingToolkit = SaplingToolkit;
1498
+ exports.SaplingTransactionViewer = SaplingTransactionViewer;
1499
+
1500
+ }));
1501
+ //# sourceMappingURL=octez.js-sapling.umd.js.map