@cardano-sdk/key-management 0.10.3 → 0.11.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 (35) hide show
  1. package/dist/cjs/TrezorKeyAgent.d.ts +5 -8
  2. package/dist/cjs/TrezorKeyAgent.d.ts.map +1 -1
  3. package/dist/cjs/TrezorKeyAgent.js +10 -150
  4. package/dist/cjs/TrezorKeyAgent.js.map +1 -1
  5. package/dist/cjs/cip8/cip30signData.d.ts +1 -1
  6. package/dist/cjs/cip8/cip30signData.d.ts.map +1 -1
  7. package/dist/cjs/cip8/cip30signData.js +6 -0
  8. package/dist/cjs/cip8/cip30signData.js.map +1 -1
  9. package/dist/cjs/tsconfig.tsbuildinfo +1 -1
  10. package/dist/cjs/util/index.d.ts +0 -1
  11. package/dist/cjs/util/index.d.ts.map +1 -1
  12. package/dist/cjs/util/index.js +0 -1
  13. package/dist/cjs/util/index.js.map +1 -1
  14. package/dist/esm/TrezorKeyAgent.d.ts +5 -8
  15. package/dist/esm/TrezorKeyAgent.d.ts.map +1 -1
  16. package/dist/esm/TrezorKeyAgent.js +11 -125
  17. package/dist/esm/TrezorKeyAgent.js.map +1 -1
  18. package/dist/esm/cip8/cip30signData.d.ts +1 -1
  19. package/dist/esm/cip8/cip30signData.d.ts.map +1 -1
  20. package/dist/esm/cip8/cip30signData.js +7 -1
  21. package/dist/esm/cip8/cip30signData.js.map +1 -1
  22. package/dist/esm/tsconfig.tsbuildinfo +1 -1
  23. package/dist/esm/util/index.d.ts +0 -1
  24. package/dist/esm/util/index.d.ts.map +1 -1
  25. package/dist/esm/util/index.js +0 -1
  26. package/dist/esm/util/index.js.map +1 -1
  27. package/package.json +7 -7
  28. package/dist/cjs/util/mapHardwareSigningData.d.ts +0 -37
  29. package/dist/cjs/util/mapHardwareSigningData.d.ts.map +0 -1
  30. package/dist/cjs/util/mapHardwareSigningData.js +0 -885
  31. package/dist/cjs/util/mapHardwareSigningData.js.map +0 -1
  32. package/dist/esm/util/mapHardwareSigningData.d.ts +0 -37
  33. package/dist/esm/util/mapHardwareSigningData.d.ts.map +0 -1
  34. package/dist/esm/util/mapHardwareSigningData.js +0 -854
  35. package/dist/esm/util/mapHardwareSigningData.js.map +0 -1
@@ -1,885 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.txToTrezor = exports.txToLedger = void 0;
30
- const ledger = __importStar(require("@cardano-foundation/ledgerjs-hw-app-cardano"));
31
- const trezor = __importStar(require("@trezor/connect"));
32
- const core_1 = require("@cardano-sdk/core");
33
- const types_1 = require("../types");
34
- const errors_1 = require("../errors");
35
- const util_1 = require("@cardano-sdk/util");
36
- const key_1 = require("./key");
37
- const concat_1 = __importDefault(require("lodash/concat"));
38
- const uniq_1 = __importDefault(require("lodash/uniq"));
39
- const sortTokensCanonically = (tokens) => {
40
- tokens.sort((a, b) => {
41
- const assetNameA = 'assetNameBytes' in a ? a.assetNameBytes : a.assetNameHex;
42
- const assetNameB = 'assetNameBytes' in b ? b.assetNameBytes : b.assetNameHex;
43
- if (assetNameA.length === assetNameB.length) {
44
- return assetNameA > assetNameB ? 1 : -1;
45
- }
46
- else if (assetNameA.length > assetNameB.length)
47
- return 1;
48
- return -1;
49
- });
50
- };
51
- const getRewardAccountKeyHash = (rewardAccount) => core_1.Cardano.RewardAccount.toHash(rewardAccount);
52
- const bytesToIp = (bytes) => {
53
- if (!bytes)
54
- return null;
55
- if (bytes.length === 4) {
56
- return bytes.join('.');
57
- }
58
- else if (bytes.length === 16) {
59
- let ipv6 = '';
60
- for (let i = 0; i < bytes.length; i += 2) {
61
- ipv6 += `${bytes[i].toString(16) + bytes[i + 1].toString(16)}:`;
62
- }
63
- ipv6 = ipv6.slice(0, -1);
64
- return ipv6;
65
- }
66
- return null;
67
- };
68
- const matchGroupedAddress = (knownAddresses, outputAddress) => {
69
- const outputAddressBech32 = ledger.utils.bech32_encodeAddress(outputAddress);
70
- return knownAddresses.find(({ address }) => address === outputAddressBech32);
71
- };
72
- const prepareTrezorInputs = async (inputs, inputResolver, knownAddresses) => {
73
- const scope = new util_1.ManagedFreeableScope();
74
- const trezorInputs = [];
75
- for (let i = 0; i < inputs.len(); i++) {
76
- const input = scope.manage(inputs.get(i));
77
- const inputTxId = scope.manage(input.transaction_id());
78
- const coreInput = core_1.cmlToCore.txIn(input);
79
- const resolution = await inputResolver.resolveInput(coreInput);
80
- let trezorInput = {
81
- prev_hash: Buffer.from(inputTxId.to_bytes()).toString('hex'),
82
- prev_index: Number(scope.manage(input.index()).to_str())
83
- };
84
- let paymentKeyPath = null;
85
- if (resolution?.address) {
86
- const knownAddress = knownAddresses.find(({ address }) => address === resolution.address);
87
- if (knownAddress) {
88
- paymentKeyPath = [
89
- (0, key_1.harden)(types_1.CardanoKeyConst.PURPOSE),
90
- (0, key_1.harden)(types_1.CardanoKeyConst.COIN_TYPE),
91
- (0, key_1.harden)(knownAddress.accountIndex),
92
- knownAddress.type,
93
- knownAddress.index
94
- ];
95
- trezorInput = {
96
- ...trezorInput,
97
- path: paymentKeyPath
98
- };
99
- }
100
- }
101
- trezorInputs.push(trezorInput);
102
- }
103
- scope.dispose();
104
- return trezorInputs;
105
- };
106
- const prepareTrezorOutputs = (outputs, knownAddresses) => (0, util_1.usingAutoFree)((scope) => {
107
- const trezorOutputs = [];
108
- for (let i = 0; i < outputs.len(); i++) {
109
- const output = scope.manage(outputs.get(i));
110
- const outputAmount = scope.manage(output.amount());
111
- const outputAddress = scope.manage(output.address());
112
- const multiAsset = scope.manage(outputAmount.multiasset());
113
- const tokenBundle = [];
114
- if (multiAsset) {
115
- const multiAssetKeys = scope.manage(multiAsset.keys());
116
- for (let j = 0; j < multiAssetKeys.len(); j++) {
117
- const policy = scope.manage(multiAssetKeys.get(j));
118
- const assets = scope.manage(multiAsset.get(policy));
119
- const tokens = [];
120
- const assetsKeys = scope.manage(assets.keys());
121
- for (let k = 0; k < assetsKeys.len(); k++) {
122
- const assetName = scope.manage(assetsKeys.get(k));
123
- const amount = scope.manage(assets.get(assetName));
124
- if (assetName && amount) {
125
- tokens.push({
126
- amount: amount.to_str(),
127
- assetNameBytes: Buffer.from(assetName.name()).toString('hex')
128
- });
129
- }
130
- }
131
- sortTokensCanonically(tokens);
132
- tokenBundle.push({
133
- policyId: Buffer.from(policy.to_bytes()).toString('hex'),
134
- tokenAmounts: tokens
135
- });
136
- }
137
- }
138
- const outputAddressBytes = Buffer.from(outputAddress.to_bytes());
139
- const ownAddress = matchGroupedAddress(knownAddresses, outputAddressBytes);
140
- const destination = ownAddress
141
- ? {
142
- addressParameters: {
143
- addressType: trezor.PROTO.CardanoAddressType.BASE,
144
- path: `m/${types_1.CardanoKeyConst.PURPOSE}'/${types_1.CardanoKeyConst.COIN_TYPE}'/${ownAddress.accountIndex}'/${ownAddress.type}/${ownAddress.index}`,
145
- stakingPath: `m/${types_1.CardanoKeyConst.PURPOSE}'/${types_1.CardanoKeyConst.COIN_TYPE}'/${ownAddress.accountIndex}'/${key_1.STAKE_KEY_DERIVATION_PATH.role}/${key_1.STAKE_KEY_DERIVATION_PATH.index}`
146
- }
147
- }
148
- : {
149
- address: outputAddress.to_bech32()
150
- };
151
- const outputRes = {
152
- ...destination,
153
- amount: scope.manage(outputAmount.coin()).to_str(),
154
- tokenBundle
155
- };
156
- trezorOutputs.push(outputRes);
157
- }
158
- return trezorOutputs;
159
- });
160
- const prepareTrezorCertificates = (certificates, rewardAccountKeyPath, rewardAccountKeyHash) => (0, util_1.usingAutoFree)((scope) => {
161
- let signingMode;
162
- const certs = [];
163
- for (let i = 0; i < certificates.len(); i++) {
164
- const cert = scope.manage(certificates.get(i));
165
- const certificate = {};
166
- if (cert.kind() === 0) {
167
- const stakeRegistration = scope.manage(cert.as_stake_registration());
168
- const credential = scope.manage(stakeRegistration?.stake_credential());
169
- const credentialScriptHash = scope.manage(credential?.to_scripthash());
170
- certificate.type = trezor.PROTO.CardanoCertificateType.STAKE_REGISTRATION;
171
- if (credential?.kind() === 0) {
172
- certificate.path = rewardAccountKeyPath;
173
- }
174
- else if (credential && credentialScriptHash) {
175
- certificate.scriptHash = Buffer.from(credentialScriptHash.to_bytes()).toString('hex');
176
- }
177
- }
178
- else if (cert.kind() === 1) {
179
- const stakeDeregistration = scope.manage(cert.as_stake_deregistration());
180
- const credential = scope.manage(stakeDeregistration?.stake_credential());
181
- const credentialScriptHash = scope.manage(credential?.to_scripthash());
182
- certificate.type = trezor.PROTO.CardanoCertificateType.STAKE_DEREGISTRATION;
183
- if (credential?.kind() === 0) {
184
- certificate.path = rewardAccountKeyPath;
185
- }
186
- else if (credential && credentialScriptHash) {
187
- certificate.scriptHash = Buffer.from(credentialScriptHash.to_bytes()).toString('hex');
188
- }
189
- }
190
- else if (cert.kind() === 2) {
191
- const delegation = scope.manage(cert.as_stake_delegation());
192
- const delegationPoolKeyHash = scope.manage(delegation?.pool_keyhash());
193
- const credential = scope.manage(delegation?.stake_credential());
194
- const credentialScriptHash = scope.manage(credential?.to_scripthash());
195
- certificate.type = trezor.PROTO.CardanoCertificateType.STAKE_DELEGATION;
196
- if (credential?.kind() === 0) {
197
- certificate.path = rewardAccountKeyPath;
198
- }
199
- else if (credentialScriptHash) {
200
- certificate.scriptHash = Buffer.from(credentialScriptHash.to_bytes()).toString('hex');
201
- }
202
- if (delegationPoolKeyHash) {
203
- certificate.pool = Buffer.from(delegationPoolKeyHash.to_bytes()).toString('hex');
204
- }
205
- }
206
- else if (cert.kind() === 3) {
207
- const poolRegistration = scope.manage(cert.as_pool_registration());
208
- const params = scope.manage(poolRegistration?.pool_params());
209
- if (!params) {
210
- throw new errors_1.HwMappingError('Missing pool registration pool parameters.');
211
- }
212
- certificate.type = trezor.PROTO.CardanoCertificateType.STAKE_POOL_REGISTRATION;
213
- const owners = scope.manage(params?.pool_owners());
214
- const poolOwners = [];
215
- if (owners) {
216
- for (let j = 0; j < owners.len(); j++) {
217
- const owner = scope.manage(owners.get(j));
218
- const keyHash = Buffer.from(owner.to_bytes()).toString('hex');
219
- if (keyHash === rewardAccountKeyHash) {
220
- signingMode = trezor.PROTO.CardanoTxSigningMode.POOL_REGISTRATION_AS_OWNER;
221
- poolOwners.push({
222
- stakingKeyPath: rewardAccountKeyPath
223
- });
224
- }
225
- else {
226
- poolOwners.push({
227
- stakingKeyHash: keyHash
228
- });
229
- }
230
- }
231
- }
232
- const relays = scope.manage(params?.relays());
233
- const trezorRelays = [];
234
- if (relays) {
235
- for (let k = 0; k < relays.len(); k++) {
236
- const relay = scope.manage(relays.get(k));
237
- if (relay.kind() === 0) {
238
- const singleHostAddr = scope.manage(relay.as_single_host_addr());
239
- const type = trezor.PROTO.CardanoPoolRelayType.SINGLE_HOST_IP;
240
- const port = singleHostAddr?.port();
241
- const ipv4 = scope.manage(singleHostAddr?.ipv4());
242
- const ipv4Address = ipv4 ? bytesToIp(ipv4?.ip()) : null;
243
- const ipv6 = scope.manage(singleHostAddr?.ipv6());
244
- const ipv6Address = ipv6 ? bytesToIp(ipv6?.ip()) : null;
245
- trezorRelays.push({
246
- ipv4Address: ipv4Address || undefined,
247
- ipv6Address: ipv6Address || undefined,
248
- port,
249
- type
250
- });
251
- }
252
- else if (relay.kind() === 1) {
253
- const type = trezor.PROTO.CardanoPoolRelayType.SINGLE_HOST_NAME;
254
- const singleHostName = scope.manage(relay.as_single_host_name());
255
- if (singleHostName) {
256
- const port = singleHostName.port();
257
- const hostName = scope.manage(singleHostName.dns_name()).record();
258
- trezorRelays.push({
259
- hostName,
260
- port,
261
- type
262
- });
263
- }
264
- }
265
- else if (relay.kind() === 2) {
266
- const type = trezor.PROTO.CardanoPoolRelayType.MULTIPLE_HOST_NAME;
267
- const multiHostName = scope.manage(relay.as_multi_host_name());
268
- const hostName = scope.manage(multiHostName?.dns_name())?.record();
269
- if (hostName) {
270
- trezorRelays.push({
271
- hostName,
272
- type
273
- });
274
- }
275
- }
276
- }
277
- }
278
- const cost = scope.manage(params?.cost()).to_str();
279
- const margin = scope.manage(params?.margin());
280
- const pledge = scope.manage(params?.pledge()).to_str();
281
- const poolId = Buffer.from(scope.manage(params.operator()).to_bytes()).toString('hex');
282
- const poolMetadata = scope.manage(params.pool_metadata());
283
- if (!poolMetadata) {
284
- throw new errors_1.HwMappingError('Missing pool metadata.');
285
- }
286
- const metadata = {
287
- hash: Buffer.from(scope.manage(poolMetadata.pool_metadata_hash()).to_bytes()).toString('hex'),
288
- url: scope.manage(poolMetadata.url()).url()
289
- };
290
- const rewardAccount = scope.manage(params.reward_account());
291
- const rewardAccountBech32 = scope.manage(rewardAccount.to_address()).to_bech32();
292
- const vrfKeyHash = Buffer.from(scope.manage(params.vrf_keyhash()).to_bytes()).toString('hex');
293
- certificate.poolParameters = {
294
- cost,
295
- margin: {
296
- denominator: margin.denominator().to_str(),
297
- numerator: margin.numerator().to_str()
298
- },
299
- metadata,
300
- owners: poolOwners,
301
- pledge,
302
- poolId,
303
- relays: trezorRelays,
304
- rewardAccount: rewardAccountBech32,
305
- vrfKeyHash
306
- };
307
- }
308
- certs.push(certificate);
309
- }
310
- return {
311
- certs,
312
- signingMode
313
- };
314
- });
315
- const prepareTrezorWithdrawals = (withdrawals, rewardAccountKeyPath) => (0, util_1.usingAutoFree)((scope) => {
316
- const trezorWithdrawals = [];
317
- const withdrawalsKeys = scope.manage(withdrawals.keys());
318
- for (let i = 0; i < withdrawalsKeys.len(); i++) {
319
- const withdrawal = {};
320
- const rewardAddress = scope.manage(withdrawalsKeys.get(i));
321
- const paymentCredentials = scope.manage(rewardAddress.payment_cred());
322
- const paymentCredentialsScriptHash = scope.manage(paymentCredentials.to_scripthash());
323
- if (paymentCredentials.kind() === 0) {
324
- withdrawal.path = rewardAccountKeyPath;
325
- }
326
- else if (paymentCredentialsScriptHash) {
327
- withdrawal.scriptHash = Buffer.from(paymentCredentialsScriptHash.to_bytes()).toString('hex');
328
- }
329
- const withdrawalAmount = scope.manage(withdrawals.get(rewardAddress));
330
- if (!withdrawalAmount) {
331
- throw new errors_1.HwMappingError('Withdrawal amount is not defined.');
332
- }
333
- withdrawal.amount = withdrawalAmount.to_str();
334
- trezorWithdrawals.push(withdrawal);
335
- }
336
- return trezorWithdrawals;
337
- });
338
- const prepareTrezorMintBundle = (mint, paymentKeyPaths, rewardAccountKeyPath) => (0, util_1.usingAutoFree)((scope) => {
339
- const additionalWitnessPaths = [];
340
- const mintAssetsGroup = [];
341
- const mintKeys = scope.manage(mint.keys());
342
- for (let j = 0; j < mintKeys.len(); j++) {
343
- const policy = scope.manage(mintKeys.get(j));
344
- const assets = scope.manage(mint.get(policy));
345
- const tokens = [];
346
- if (assets) {
347
- const assetsKeys = scope.manage(assets.keys());
348
- for (let k = 0; k < assetsKeys.len(); k++) {
349
- const assetName = scope.manage(assetsKeys.get(k));
350
- const amount = scope.manage(assets.get(assetName));
351
- if (amount) {
352
- tokens.push({
353
- amount: amount.to_str(),
354
- assetNameBytes: Buffer.from(assetName.name()).toString('hex')
355
- });
356
- }
357
- }
358
- }
359
- sortTokensCanonically(tokens);
360
- mintAssetsGroup.push({
361
- policyId: Buffer.from(policy.to_bytes()).toString('hex'),
362
- tokenAmounts: tokens
363
- });
364
- }
365
- if (paymentKeyPaths)
366
- (0, concat_1.default)(additionalWitnessPaths, paymentKeyPaths);
367
- if (rewardAccountKeyPath)
368
- additionalWitnessPaths.push(rewardAccountKeyPath);
369
- return {
370
- additionalWitnessPaths,
371
- mintAssetsGroup
372
- };
373
- });
374
- const prepareLedgerInputs = async (inputs, inputResolver, knownAddresses) => {
375
- const scope = new util_1.ManagedFreeableScope();
376
- const ledgerInputs = [];
377
- for (let i = 0; i < inputs.len(); i++) {
378
- const input = scope.manage(inputs.get(i));
379
- const coreInput = core_1.cmlToCore.txIn(input);
380
- const resolution = await inputResolver.resolveInput(coreInput);
381
- let paymentKeyPath = null;
382
- if (resolution?.address) {
383
- const knownAddress = knownAddresses.find(({ address }) => address === resolution.address);
384
- if (knownAddress) {
385
- paymentKeyPath = [
386
- (0, key_1.harden)(types_1.CardanoKeyConst.PURPOSE),
387
- (0, key_1.harden)(types_1.CardanoKeyConst.COIN_TYPE),
388
- (0, key_1.harden)(knownAddress.accountIndex),
389
- knownAddress.type,
390
- knownAddress.index
391
- ];
392
- }
393
- }
394
- ledgerInputs.push({
395
- outputIndex: Number(scope.manage(input.index()).to_str()),
396
- path: paymentKeyPath,
397
- txHashHex: Buffer.from(scope.manage(input.transaction_id()).to_bytes()).toString('hex')
398
- });
399
- }
400
- scope.dispose();
401
- return ledgerInputs;
402
- };
403
- const prepareLedgerOutputs = (outputs, knownAddresses) => (0, util_1.usingAutoFree)((scope) => {
404
- const ledgerOutputs = [];
405
- for (let i = 0; i < outputs.len(); i++) {
406
- const output = scope.manage(outputs.get(i));
407
- const outputAmount = scope.manage(output.amount());
408
- const multiAsset = scope.manage(outputAmount.multiasset());
409
- const tokenBundle = [];
410
- if (multiAsset) {
411
- const multiAssetKeys = scope.manage(multiAsset.keys());
412
- for (let j = 0; j < multiAssetKeys.len(); j++) {
413
- const policy = scope.manage(multiAssetKeys.get(j));
414
- const assets = scope.manage(multiAsset.get(policy));
415
- const tokens = [];
416
- const assetsKeys = scope.manage(assets.keys());
417
- for (let k = 0; k < assetsKeys.len(); k++) {
418
- const assetName = scope.manage(assetsKeys.get(k));
419
- const amount = scope.manage(assets.get(assetName));
420
- if (assetName && amount) {
421
- tokens.push({
422
- amount: amount.to_str(),
423
- assetNameHex: Buffer.from(assetName.name()).toString('hex')
424
- });
425
- }
426
- }
427
- sortTokensCanonically(tokens);
428
- tokenBundle.push({
429
- policyIdHex: Buffer.from(policy.to_bytes()).toString('hex'),
430
- tokens
431
- });
432
- }
433
- }
434
- const outputAddress = Buffer.from(scope.manage(output.address()).to_bytes());
435
- const ownAddress = matchGroupedAddress(knownAddresses, outputAddress);
436
- const destination = ownAddress
437
- ? {
438
- params: {
439
- params: {
440
- spendingPath: [
441
- (0, key_1.harden)(types_1.CardanoKeyConst.PURPOSE),
442
- (0, key_1.harden)(types_1.CardanoKeyConst.COIN_TYPE),
443
- (0, key_1.harden)(ownAddress.accountIndex),
444
- ownAddress.type,
445
- ownAddress.index
446
- ],
447
- stakingPath: [
448
- (0, key_1.harden)(types_1.CardanoKeyConst.PURPOSE),
449
- (0, key_1.harden)(types_1.CardanoKeyConst.COIN_TYPE),
450
- (0, key_1.harden)(ownAddress.accountIndex),
451
- key_1.STAKE_KEY_DERIVATION_PATH.role,
452
- key_1.STAKE_KEY_DERIVATION_PATH.index
453
- ]
454
- },
455
- type: ledger.AddressType.BASE_PAYMENT_KEY_STAKE_KEY
456
- },
457
- type: ledger.TxOutputDestinationType.DEVICE_OWNED
458
- }
459
- : {
460
- params: {
461
- addressHex: outputAddress.toString('hex')
462
- },
463
- type: ledger.TxOutputDestinationType.THIRD_PARTY
464
- };
465
- const outputDataHash = scope.manage(scope.manage(output.datum())?.as_data_hash());
466
- const datumHashHex = outputDataHash ? Buffer.from(outputDataHash.to_bytes()).toString('hex') : null;
467
- const outputRes = {
468
- amount: scope.manage(outputAmount.coin()).to_str(),
469
- datumHashHex,
470
- destination,
471
- tokenBundle
472
- };
473
- ledgerOutputs.push(outputRes);
474
- }
475
- return ledgerOutputs;
476
- });
477
- const prepareLedgerCertificates = (certificates, knownAddresses, rewardAccountKeyPath, rewardAccountKeyHash) => (0, util_1.usingAutoFree)((scope) => {
478
- let signingMode;
479
- const certs = [];
480
- for (let i = 0; i < certificates.len(); i++) {
481
- const cert = scope.manage(certificates.get(i));
482
- const certificate = {};
483
- if (cert.kind() === 0) {
484
- const stakeRegistration = scope.manage(cert.as_stake_registration());
485
- const credential = scope.manage(stakeRegistration?.stake_credential());
486
- const credentialScriptHash = scope.manage(credential?.to_scripthash());
487
- certificate.type = ledger.CertificateType.STAKE_REGISTRATION;
488
- if (credential?.kind() === 0) {
489
- certificate.params = {
490
- stakeCredential: {
491
- keyPath: rewardAccountKeyPath,
492
- type: ledger.StakeCredentialParamsType.KEY_PATH
493
- }
494
- };
495
- }
496
- else if (credential && credentialScriptHash) {
497
- const scriptHashHex = Buffer.from(credentialScriptHash.to_bytes()).toString('hex');
498
- certificate.params = {
499
- stakeCredential: {
500
- scriptHashHex,
501
- type: ledger.StakeCredentialParamsType.SCRIPT_HASH
502
- }
503
- };
504
- }
505
- }
506
- else if (cert.kind() === 1) {
507
- const stakeDeregistration = scope.manage(cert.as_stake_deregistration());
508
- const credential = scope.manage(stakeDeregistration?.stake_credential());
509
- const credentialScriptHash = scope.manage(credential?.to_scripthash());
510
- certificate.type = ledger.CertificateType.STAKE_DEREGISTRATION;
511
- if (credential?.kind() === 0) {
512
- certificate.params = {
513
- stakeCredential: {
514
- keyPath: rewardAccountKeyPath,
515
- type: ledger.StakeCredentialParamsType.KEY_PATH
516
- }
517
- };
518
- }
519
- else if (credential && credentialScriptHash) {
520
- const scriptHashHex = Buffer.from(credentialScriptHash.to_bytes()).toString('hex');
521
- certificate.params = {
522
- stakeCredential: {
523
- scriptHashHex,
524
- type: ledger.StakeCredentialParamsType.SCRIPT_HASH
525
- }
526
- };
527
- }
528
- }
529
- else if (cert.kind() === 2) {
530
- const delegation = scope.manage(cert.as_stake_delegation());
531
- const delegationPoolKeyHash = scope.manage(delegation?.pool_keyhash());
532
- const credential = scope.manage(delegation?.stake_credential());
533
- const credentialScriptHash = scope.manage(credential?.to_scripthash());
534
- certificate.type = ledger.CertificateType.STAKE_DELEGATION;
535
- if (credential?.kind() === 0) {
536
- certificate.params = {
537
- stakeCredential: {
538
- keyPath: rewardAccountKeyPath,
539
- type: ledger.StakeCredentialParamsType.KEY_PATH
540
- }
541
- };
542
- }
543
- else if (credentialScriptHash) {
544
- const scriptHashHex = Buffer.from(credentialScriptHash.to_bytes()).toString('hex');
545
- certificate.params = {
546
- stakeCredential: {
547
- scriptHashHex,
548
- type: ledger.StakeCredentialParamsType.SCRIPT_HASH
549
- }
550
- };
551
- }
552
- if (delegationPoolKeyHash) {
553
- certificate.params = {
554
- ...certificate.params,
555
- poolKeyHashHex: Buffer.from(delegationPoolKeyHash.to_bytes()).toString('hex')
556
- };
557
- }
558
- }
559
- else if (cert.kind() === 3) {
560
- const poolRegistration = scope.manage(cert.as_pool_registration());
561
- const params = scope.manage(poolRegistration?.pool_params());
562
- if (!params) {
563
- throw new errors_1.HwMappingError('Missing pool registration pool parameters.');
564
- }
565
- certificate.type = ledger.CertificateType.STAKE_POOL_REGISTRATION;
566
- const owners = scope.manage(params?.pool_owners());
567
- const poolOwners = [];
568
- if (owners) {
569
- for (let j = 0; j < owners.len(); j++) {
570
- const keyHash = Buffer.from(scope.manage(owners.get(j)).to_bytes()).toString('hex');
571
- if (keyHash === rewardAccountKeyHash) {
572
- signingMode = ledger.TransactionSigningMode.POOL_REGISTRATION_AS_OWNER;
573
- poolOwners.push({
574
- params: {
575
- stakingPath: rewardAccountKeyPath
576
- },
577
- type: ledger.PoolOwnerType.DEVICE_OWNED
578
- });
579
- }
580
- else {
581
- poolOwners.push({
582
- params: {
583
- stakingKeyHashHex: keyHash
584
- },
585
- type: ledger.PoolOwnerType.THIRD_PARTY
586
- });
587
- }
588
- }
589
- }
590
- const relays = scope.manage(params?.relays());
591
- const ledgerRelays = [];
592
- if (relays) {
593
- for (let k = 0; k < relays.len(); k++) {
594
- const relay = scope.manage(relays.get(k));
595
- if (relay.kind() === 0) {
596
- const singleHostAddr = scope.manage(relay.as_single_host_addr());
597
- const type = 0;
598
- const portNumber = singleHostAddr?.port();
599
- const ipv4 = scope.manage(singleHostAddr?.ipv4());
600
- const ipv6 = scope.manage(singleHostAddr?.ipv6());
601
- const ipv4Address = ipv4 ? bytesToIp(ipv4.ip()) : null;
602
- const ipv6Address = ipv6 ? bytesToIp(ipv6.ip()) : null;
603
- ledgerRelays.push({ params: { ipv4: ipv4Address, ipv6: ipv6Address, portNumber }, type });
604
- }
605
- else if (relay.kind() === 1) {
606
- const type = 1;
607
- const singleHostName = scope.manage(relay.as_single_host_name());
608
- if (singleHostName) {
609
- const portNumber = singleHostName.port();
610
- const dnsName = scope.manage(singleHostName.dns_name()).record();
611
- ledgerRelays.push({
612
- params: { dnsName, portNumber },
613
- type
614
- });
615
- }
616
- }
617
- else if (relay.kind() === 2) {
618
- const type = 2;
619
- const multiHostName = scope.manage(relay.as_multi_host_name());
620
- const dnsName = scope.manage(multiHostName?.dns_name())?.record();
621
- if (dnsName) {
622
- ledgerRelays.push({
623
- params: { dnsName },
624
- type
625
- });
626
- }
627
- }
628
- }
629
- }
630
- const cost = scope.manage(params?.cost()).to_str();
631
- const margin = scope.manage(params?.margin());
632
- const pledge = scope.manage(params?.pledge()).to_str();
633
- const operator = Buffer.from(scope.manage(params.operator()).to_bytes()).toString('hex');
634
- let poolKey;
635
- if (operator === rewardAccountKeyHash) {
636
- signingMode = ledger.TransactionSigningMode.POOL_REGISTRATION_AS_OPERATOR;
637
- poolKey = {
638
- params: { path: rewardAccountKeyPath },
639
- type: ledger.PoolKeyType.DEVICE_OWNED
640
- };
641
- }
642
- else {
643
- poolKey = {
644
- params: { keyHashHex: operator },
645
- type: ledger.PoolKeyType.THIRD_PARTY
646
- };
647
- }
648
- const poolMetadata = scope.manage(params.pool_metadata());
649
- const metadata = poolMetadata
650
- ? {
651
- metadataHashHex: Buffer.from(scope.manage(poolMetadata.pool_metadata_hash()).to_bytes()).toString('hex'),
652
- metadataUrl: scope.manage(poolMetadata.url()).url()
653
- }
654
- : null;
655
- const poolRewardAccount = scope.manage(params.reward_account());
656
- const rewardAccountBytes = Buffer.from(scope.manage(poolRewardAccount.to_address()).to_bytes());
657
- const isDeviceOwned = knownAddresses.some(({ address }) => address === ledger.utils.bech32_encodeAddress(rewardAccountBytes));
658
- const rewardAccount = isDeviceOwned
659
- ? {
660
- params: { path: rewardAccountKeyPath },
661
- type: ledger.PoolRewardAccountType.DEVICE_OWNED
662
- }
663
- : {
664
- params: { rewardAccountHex: rewardAccountBytes.toString('hex') },
665
- type: ledger.PoolRewardAccountType.THIRD_PARTY
666
- };
667
- const vrfKeyHashHex = Buffer.from(scope.manage(params.vrf_keyhash()).to_bytes()).toString('hex');
668
- certificate.params = {
669
- cost,
670
- margin: {
671
- denominator: scope.manage(margin.denominator()).to_str(),
672
- numerator: scope.manage(margin.numerator()).to_str()
673
- },
674
- metadata,
675
- pledge,
676
- poolKey,
677
- poolOwners,
678
- relays: ledgerRelays,
679
- rewardAccount,
680
- vrfKeyHashHex
681
- };
682
- }
683
- certs.push(certificate);
684
- }
685
- return {
686
- certs,
687
- signingMode
688
- };
689
- });
690
- const prepareLedgerWithdrawals = (withdrawals, rewardAccountKeyPath) => (0, util_1.usingAutoFree)((scope) => {
691
- const ledgerWithdrawals = [];
692
- const withdrawalsKeys = scope.manage(withdrawals.keys());
693
- for (let i = 0; i < withdrawalsKeys.len(); i++) {
694
- const withdrawal = { stakeCredential: {} };
695
- const rewardAddress = scope.manage(withdrawalsKeys.get(i));
696
- const paymentCredentials = scope.manage(rewardAddress.payment_cred());
697
- const paymentCredentialsScriptHash = scope.manage(paymentCredentials.to_scripthash());
698
- if (paymentCredentials.kind() === 0) {
699
- const stakeCredential = {
700
- keyPath: rewardAccountKeyPath,
701
- type: ledger.StakeCredentialParamsType.KEY_PATH
702
- };
703
- withdrawal.stakeCredential = stakeCredential;
704
- }
705
- else if (paymentCredentialsScriptHash) {
706
- const stakeCredential = {
707
- scriptHashHex: Buffer.from(paymentCredentialsScriptHash.to_bytes()).toString('hex'),
708
- type: ledger.StakeCredentialParamsType.SCRIPT_HASH
709
- };
710
- withdrawal.stakeCredential = stakeCredential;
711
- }
712
- const withdrawalAmount = scope.manage(withdrawals.get(rewardAddress));
713
- if (!withdrawalAmount) {
714
- throw new errors_1.HwMappingError('Withdrawal amount is not defined.');
715
- }
716
- ledgerWithdrawals.push({
717
- ...withdrawal,
718
- amount: withdrawalAmount.to_str()
719
- });
720
- }
721
- return ledgerWithdrawals;
722
- });
723
- const prepareLedgerMintBundle = (mint, paymentKeyPaths, rewardAccountKeyPath) => (0, util_1.usingAutoFree)((scope) => {
724
- const additionalWitnessPaths = [];
725
- const mintAssetsGroup = [];
726
- const mintKeys = scope.manage(mint.keys());
727
- for (let j = 0; j < mintKeys.len(); j++) {
728
- const policy = scope.manage(mintKeys.get(j));
729
- const assets = scope.manage(mint.get(policy));
730
- const tokens = [];
731
- if (assets) {
732
- const assetsKeys = assets.keys();
733
- for (let k = 0; k < assetsKeys.len(); k++) {
734
- const assetName = scope.manage(assetsKeys.get(k));
735
- const amount = scope.manage(assets.get(assetName));
736
- if (amount)
737
- tokens.push({
738
- amount: amount.to_str(),
739
- assetNameHex: Buffer.from(assetName.name()).toString('hex')
740
- });
741
- }
742
- }
743
- sortTokensCanonically(tokens);
744
- mintAssetsGroup.push({
745
- policyIdHex: Buffer.from(policy.to_bytes()).toString('hex'),
746
- tokens
747
- });
748
- }
749
- if (paymentKeyPaths)
750
- (0, concat_1.default)(additionalWitnessPaths, paymentKeyPaths);
751
- if (rewardAccountKeyPath)
752
- additionalWitnessPaths.push(rewardAccountKeyPath);
753
- return {
754
- additionalWitnessPaths,
755
- mintAssetsGroup
756
- };
757
- });
758
- const txToLedger = async ({ cslTxBody, chainId, inputResolver: inputAddressResolver, knownAddresses }) => {
759
- const scope = new util_1.ManagedFreeableScope();
760
- const accountAddress = knownAddresses[0];
761
- const rewardAccount = accountAddress.rewardAccount;
762
- const rewardAccountKeyHash = getRewardAccountKeyHash(rewardAccount);
763
- const rewardAccountKeyPath = [
764
- (0, key_1.harden)(types_1.CardanoKeyConst.PURPOSE),
765
- (0, key_1.harden)(types_1.CardanoKeyConst.COIN_TYPE),
766
- (0, key_1.harden)(accountAddress.accountIndex),
767
- key_1.STAKE_KEY_DERIVATION_PATH.role,
768
- key_1.STAKE_KEY_DERIVATION_PATH.index
769
- ];
770
- const ledgerInputs = await prepareLedgerInputs(scope.manage(cslTxBody.inputs()), inputAddressResolver, knownAddresses);
771
- const ledgerOutputs = prepareLedgerOutputs(scope.manage(cslTxBody.outputs()), knownAddresses);
772
- const cslWithdrawals = scope.manage(cslTxBody.withdrawals());
773
- const ledgerWithdrawals = cslWithdrawals ? prepareLedgerWithdrawals(cslWithdrawals, rewardAccountKeyPath) : null;
774
- const cslCertificates = scope.manage(cslTxBody.certs());
775
- const ledgerCertificatesData = cslCertificates
776
- ? prepareLedgerCertificates(cslCertificates, knownAddresses, rewardAccountKeyPath, rewardAccountKeyHash)
777
- : null;
778
- const signingMode = ledgerCertificatesData?.signingMode || ledger.TransactionSigningMode.ORDINARY_TRANSACTION;
779
- const fee = scope.manage(cslTxBody.fee()).to_str();
780
- const ttl = Number(scope.manage(cslTxBody.ttl())?.to_str());
781
- const validityIntervalStart = Number(scope.manage(cslTxBody.validity_start_interval())?.to_str());
782
- const txBodyAuxDataHash = scope.manage(cslTxBody.auxiliary_data_hash());
783
- const auxiliaryData = txBodyAuxDataHash
784
- ? {
785
- params: {
786
- hashHex: Buffer.from(txBodyAuxDataHash.to_bytes()).toString('hex')
787
- },
788
- type: ledger.TxAuxiliaryDataType.ARBITRARY_HASH
789
- }
790
- : null;
791
- const cslMint = scope.manage(cslTxBody.multiassets());
792
- let ledgerMintBundle = null;
793
- if (cslMint) {
794
- const paymentKeyPaths = (0, uniq_1.default)(ledgerInputs.map((ledgerInput) => ledgerInput.path).filter(util_1.isNotNil));
795
- ledgerMintBundle = prepareLedgerMintBundle(cslMint, paymentKeyPaths, rewardAccountKeyPath);
796
- }
797
- const additionalWitnessPaths = ledgerMintBundle?.additionalWitnessPaths || [];
798
- const ledgerTx = {
799
- auxiliaryData,
800
- certificates: ledgerCertificatesData?.certs,
801
- fee,
802
- inputs: ledgerInputs,
803
- mint: ledgerMintBundle?.mintAssetsGroup,
804
- network: {
805
- networkId: chainId.networkId,
806
- protocolMagic: chainId.networkMagic
807
- },
808
- outputs: ledgerOutputs,
809
- ttl,
810
- validityIntervalStart,
811
- withdrawals: ledgerWithdrawals
812
- };
813
- for (const key of Object.keys(ledgerTx)) {
814
- const objKey = key;
815
- !ledgerTx[objKey] && ledgerTx[objKey] !== 0 && delete ledgerTx[objKey];
816
- }
817
- scope.dispose();
818
- return {
819
- additionalWitnessPaths,
820
- signingMode,
821
- tx: ledgerTx
822
- };
823
- };
824
- exports.txToLedger = txToLedger;
825
- const txToTrezor = async ({ cslTxBody, chainId, inputResolver: inputAddressResolver, knownAddresses }) => {
826
- const scope = new util_1.ManagedFreeableScope();
827
- const accountAddress = knownAddresses[0];
828
- const rewardAccount = accountAddress.rewardAccount;
829
- const rewardAccountKeyHash = getRewardAccountKeyHash(rewardAccount);
830
- const rewardAccountKeyPath = [
831
- (0, key_1.harden)(types_1.CardanoKeyConst.PURPOSE),
832
- (0, key_1.harden)(types_1.CardanoKeyConst.COIN_TYPE),
833
- (0, key_1.harden)(accountAddress.accountIndex),
834
- key_1.STAKE_KEY_DERIVATION_PATH.role,
835
- key_1.STAKE_KEY_DERIVATION_PATH.index
836
- ];
837
- const trezorInputs = await prepareTrezorInputs(scope.manage(cslTxBody.inputs()), inputAddressResolver, knownAddresses);
838
- const trezorOutputs = prepareTrezorOutputs(scope.manage(cslTxBody.outputs()), knownAddresses);
839
- const cslWithdrawals = scope.manage(cslTxBody.withdrawals());
840
- const trezorWithdrawals = cslWithdrawals ? prepareTrezorWithdrawals(cslWithdrawals, rewardAccountKeyPath) : undefined;
841
- const cslCertificates = scope.manage(cslTxBody.certs());
842
- let trezorCertificatesData;
843
- if (cslCertificates) {
844
- trezorCertificatesData = prepareTrezorCertificates(cslCertificates, rewardAccountKeyPath, rewardAccountKeyHash);
845
- }
846
- const signingMode = trezorCertificatesData?.signingMode || trezor.PROTO.CardanoTxSigningMode.ORDINARY_TRANSACTION;
847
- const fee = scope.manage(cslTxBody.fee()).to_str();
848
- let ttl;
849
- const cslTTL = cslTxBody.ttl();
850
- if (cslTTL) {
851
- ttl = cslTTL.to_str();
852
- }
853
- const validityIntervalStart = cslTxBody.validity_start_interval()?.to_str();
854
- const txBodyAuxDataHash = scope.manage(cslTxBody.auxiliary_data_hash());
855
- let auxiliaryData;
856
- if (txBodyAuxDataHash) {
857
- auxiliaryData = {
858
- hash: Buffer.from(txBodyAuxDataHash.to_bytes()).toString('hex')
859
- };
860
- }
861
- const cslMint = scope.manage(cslTxBody.multiassets());
862
- let trezorMintBundle = null;
863
- if (cslMint) {
864
- const paymentKeyPaths = (0, uniq_1.default)(trezorInputs.map((trezorInput) => trezorInput.path).filter(util_1.isNotNil));
865
- trezorMintBundle = prepareTrezorMintBundle(cslMint, paymentKeyPaths, rewardAccountKeyPath);
866
- }
867
- scope.dispose();
868
- return {
869
- additionalWitnessRequests: trezorMintBundle?.additionalWitnessPaths,
870
- auxiliaryData,
871
- certificates: trezorCertificatesData?.certs,
872
- fee,
873
- inputs: trezorInputs,
874
- mint: trezorMintBundle?.mintAssetsGroup,
875
- networkId: chainId.networkId,
876
- outputs: trezorOutputs,
877
- protocolMagic: chainId.networkMagic,
878
- signingMode,
879
- ttl,
880
- validityIntervalStart,
881
- withdrawals: trezorWithdrawals
882
- };
883
- };
884
- exports.txToTrezor = txToTrezor;
885
- //# sourceMappingURL=mapHardwareSigningData.js.map