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