-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathLedgerKeyAgent.ts
More file actions
893 lines (789 loc) · 30 KB
/
Copy pathLedgerKeyAgent.ts
File metadata and controls
893 lines (789 loc) · 30 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
/* eslint-disable @typescript-eslint/no-explicit-any */
import * as Crypto from '@cardano-sdk/crypto';
import * as Ledger from '@cardano-foundation/ledgerjs-hw-app-cardano';
import {
AlgorithmId,
CBORValue,
COSESign1Builder,
HeaderMap,
Headers,
Label,
ProtectedHeaderMap
} from '@emurgo/cardano-message-signing-nodejs';
import { Cardano, NotImplementedError, Serialization, util as coreUtils } from '@cardano-sdk/core';
import {
CardanoKeyConst,
Cip1852PathLevelIndexes,
CommunicationType,
GroupedAddress,
KeyAgentBase,
KeyAgentDependencies,
KeyAgentType,
KeyPurpose,
KeyRole,
SerializableLedgerKeyAgentData,
SignBlobResult,
SignTransactionContext,
cip8,
errors,
util
} from '@cardano-sdk/key-management';
import { Cip30DataSignature } from '@cardano-sdk/dapp-connector';
import { HID } from 'node-hid';
import { HexBlob, areNumbersEqualInConstantTime, areStringsEqualInConstantTime } from '@cardano-sdk/util';
import { LedgerDevice, LedgerTransportType } from './types';
import { blake2b } from '@cardano-sdk/crypto';
import { getFirstLedgerDevice } from '@ledgerhq/hw-transport-webusb/lib/webusb';
import { str_to_path } from '@cardano-foundation/ledgerjs-hw-app-cardano/dist/utils/address';
import { toLedgerTx } from './transformers';
import TransportNodeHid from '@ledgerhq/hw-transport-node-hid-noevents';
import _LedgerConnection, {
AddressType,
BIP32Path,
Certificate,
CertificateType,
CredentialParams,
CredentialParamsType,
DeviceOwnedAddress,
GetVersionResponse,
MessageAddressFieldType,
MessageData,
PoolKeyType,
PoolOwnerType,
Transaction,
TransactionSigningMode,
TxOutputDestinationType,
VoterType,
VoterVotes
} from '@cardano-foundation/ledgerjs-hw-app-cardano';
import _TransportWebUSB from '@ledgerhq/hw-transport-webusb';
import type LedgerTransport from '@ledgerhq/hw-transport';
const TransportWebUSB = (_TransportWebUSB as any).default
? ((_TransportWebUSB as any).default as typeof _TransportWebUSB)
: _TransportWebUSB;
const LedgerConnection = (_LedgerConnection as any).default
? ((_LedgerConnection as any).default as typeof _LedgerConnection)
: _LedgerConnection;
type LedgerConnection = _LedgerConnection;
const CIP08_SIGN_HASH_THRESHOLD = 100;
const isUsbDevice = (device: any): device is USBDevice =>
typeof USBDevice !== 'undefined' && device instanceof USBDevice;
/* Sets the hashed entry in the COSESign1 CBOR structure */
const setCOSESignHashed = (COSESignCbor: string, isHashed: boolean) => {
const reader = new Serialization.CborReader(HexBlob(COSESignCbor));
reader.readStartArray();
const headers = reader.readEncodedValue();
// Skip hashed entry
reader.readEncodedValue();
const payload = reader.readEncodedValue();
const signature = reader.readEncodedValue();
reader.readEndArray();
const writer = new Serialization.CborWriter();
writer.writeStartArray(4);
writer.writeEncodedValue(headers);
writer.writeStartMap(1);
writer.writeTextString('hashed');
writer.writeBoolean(isHashed);
writer.writeEncodedValue(payload);
writer.writeEncodedValue(signature);
return writer.encodeAsHex();
};
const isDeviceAlreadyOpenError = (error: unknown) => {
if (typeof error !== 'object') return false;
const innerError = (error as any).innerError;
if (typeof innerError !== 'object') return false;
return (
innerError.code === 11 ||
(typeof innerError.message === 'string' && innerError.message.includes('cannot open device with path'))
);
};
const CARDANO_APP_CONNECTION_ERROR_MESSAGE = 'Cannot communicate with Ledger Cardano App';
export interface LedgerKeyAgentProps extends Omit<SerializableLedgerKeyAgentData, '__typename'> {
deviceConnection?: LedgerConnection;
}
export interface CreateLedgerKeyAgentProps {
chainId: Cardano.ChainId;
accountIndex?: number;
communicationType: CommunicationType;
deviceConnection?: LedgerConnection | null;
purpose?: KeyPurpose;
}
export interface GetLedgerXpubProps {
deviceConnection?: LedgerConnection;
communicationType: CommunicationType;
accountIndex: number;
purpose: KeyPurpose;
}
export interface CreateLedgerTransportProps {
communicationType: CommunicationType;
nodeHidDevicePath?: string;
}
const transportTypedError = (error?: any) => new errors.TransportError('Ledger transport failed', error);
const hasRegistrationOrRetirementCerts = (certificates: Certificate[] | null | undefined): boolean => {
if (!certificates) return false;
return (
certificates.some((cert) => cert.type === CertificateType.STAKE_POOL_RETIREMENT) ||
certificates.some((cert) => cert.type === CertificateType.STAKE_POOL_REGISTRATION)
);
};
const stakeCredentialCert = (cert: Certificate) =>
cert.type === CertificateType.STAKE_REGISTRATION ||
cert.type === CertificateType.STAKE_DEREGISTRATION ||
cert.type === CertificateType.STAKE_DELEGATION;
const establishDeviceConnectionMethodName = 'establishDeviceConnection';
const parseEstablishDeviceConnectionSecondParam = (
communicationType: CommunicationType,
nodeHidDevicePathOrDevice?: string | LedgerDevice
) => {
let device: LedgerDevice | undefined;
let nodeHidDevicePath: string | undefined;
const deviceObjectRecognized =
(communicationType === CommunicationType.Node && nodeHidDevicePathOrDevice instanceof HID) ||
(communicationType === CommunicationType.Web && isUsbDevice(nodeHidDevicePathOrDevice));
const devicePathRecognized =
communicationType === CommunicationType.Node && typeof nodeHidDevicePathOrDevice === 'string';
if (deviceObjectRecognized) {
device = nodeHidDevicePathOrDevice;
} else if (devicePathRecognized) {
nodeHidDevicePath = nodeHidDevicePathOrDevice;
} else if (nodeHidDevicePathOrDevice !== undefined) {
throw new Error(`Invalid arguments of the '${establishDeviceConnectionMethodName}' method`);
}
return {
device,
nodeHidDevicePath
};
};
interface StakeCredentialCertificateParams {
stakeCredential: CredentialParams;
}
const containsOnlyScriptHashCreds = (tx: Transaction): boolean => {
const withdrawalsAllScriptHash = !tx.withdrawals?.some(
(withdrawal) => !areNumbersEqualInConstantTime(withdrawal.stakeCredential.type, CredentialParamsType.SCRIPT_HASH)
);
if (tx.certificates) {
for (const cert of tx.certificates) {
if (!stakeCredentialCert(cert)) return false;
const certParams = cert.params as unknown as StakeCredentialCertificateParams;
if (!areNumbersEqualInConstantTime(certParams.stakeCredential.type, CredentialParamsType.SCRIPT_HASH))
return false;
}
}
return withdrawalsAllScriptHash;
};
const isMultiSig = (tx: Transaction): boolean => {
const result = false;
const allThirdPartyInputs = !tx.inputs.some((input) => input.path !== null);
// Ledger doesn't allow change outputs to address controlled by your keys and instead you have to use script address for change out
const allThirdPartyOutputs = !tx.outputs.some((out) => out.destination.type !== TxOutputDestinationType.THIRD_PARTY);
if (
allThirdPartyInputs &&
allThirdPartyOutputs &&
!tx.collateralInputs &&
!tx.requiredSigners &&
!hasRegistrationOrRetirementCerts(tx.certificates) &&
containsOnlyScriptHashCreds(tx)
) {
return true;
}
return result;
};
type DeviceConnectionsWithTheirInitialParams = { deviceConnection: LedgerConnection } & (
| {
communicationType: CommunicationType.Node;
device?: HID;
nodeHidDevicePath?: string;
}
| {
communicationType: CommunicationType.Web;
device?: USBDevice;
}
);
type OpenTransportForDeviceParams = {
communicationType: CommunicationType;
device: LedgerDevice;
};
const isPaymentAddress = (
signWith: Cardano.PaymentAddress | Cardano.RewardAccount
): signWith is Cardano.PaymentAddress => signWith.startsWith('addr');
const getDerivationPath = (
signWith: Cardano.PaymentAddress | Cardano.RewardAccount,
knownAddresses: GroupedAddress[],
accountIndex: number,
purpose: number,
dRepKeyHash: Crypto.Ed25519KeyHashHex
): { signingPath: BIP32Path; addressParams?: DeviceOwnedAddress; addressFieldType: MessageAddressFieldType } => {
const isRewardAccount = signWith.startsWith('stake');
// Reward account
if (isRewardAccount) {
const knownRewardAddress = knownAddresses.find(({ rewardAccount }) => rewardAccount === signWith);
if (!knownRewardAddress)
throw new cip8.Cip30DataSignError(cip8.Cip30DataSignErrorCode.ProofGeneration, 'Unknown reward address');
const path = util.accountKeyDerivationPathToBip32Path(
accountIndex,
knownRewardAddress.stakeKeyDerivationPath || util.STAKE_KEY_DERIVATION_PATH,
purpose
);
return {
addressFieldType: MessageAddressFieldType.ADDRESS,
addressParams: {
params: {
stakingPath: path
},
type: AddressType.REWARD_KEY
},
signingPath: path
};
}
if (isPaymentAddress(signWith)) {
const drepAddr = Cardano.Address.fromString(signWith);
if (
drepAddr?.getType() === Cardano.AddressType.EnterpriseKey &&
drepAddr?.getProps().paymentPart?.hash === dRepKeyHash
) {
const path = util.accountKeyDerivationPathToBip32Path(accountIndex, util.DREP_KEY_DERIVATION_PATH, purpose);
return {
addressFieldType: MessageAddressFieldType.KEY_HASH,
signingPath: path
};
}
}
const knownAddress = knownAddresses.find(({ address }) => address === signWith);
if (!knownAddress) {
throw new cip8.Cip30DataSignError(cip8.Cip30DataSignErrorCode.ProofGeneration, 'Unknown address');
}
// Base address
if (knownAddress.rewardAccount) {
const spendingPath = util.accountKeyDerivationPathToBip32Path(
accountIndex,
{
index: knownAddress.index,
role: knownAddress.type as number as KeyRole
},
purpose
);
const stakingPath = util.accountKeyDerivationPathToBip32Path(
accountIndex,
knownAddress.stakeKeyDerivationPath || {
index: 0,
role: KeyRole.Stake
},
purpose
);
return {
addressFieldType: MessageAddressFieldType.ADDRESS,
addressParams: {
params: {
spendingPath,
stakingPath
},
type: AddressType.BASE_PAYMENT_KEY_STAKE_KEY
},
signingPath: spendingPath
};
}
const spendingPath = util.accountKeyDerivationPathToBip32Path(
accountIndex,
{
index: knownAddress.index,
role: knownAddress.type as number as KeyRole
},
purpose
);
// Enterprise Address
return {
addressFieldType: MessageAddressFieldType.ADDRESS,
addressParams: {
params: {
spendingPath
},
type: AddressType.ENTERPRISE_KEY
},
signingPath: spendingPath
};
};
const multiSigWitnessPaths: BIP32Path[] = [
util.accountKeyDerivationPathToBip32Path(0, { index: 0, role: KeyRole.External }, KeyPurpose.MULTI_SIG)
];
export class LedgerKeyAgent extends KeyAgentBase {
readonly deviceConnection?: LedgerConnection;
readonly #communicationType: CommunicationType;
static deviceConnections: DeviceConnectionsWithTheirInitialParams[] = [];
constructor({ deviceConnection, ...serializableData }: LedgerKeyAgentProps, dependencies: KeyAgentDependencies) {
super({ ...serializableData, __typename: KeyAgentType.Ledger }, dependencies);
this.deviceConnection = deviceConnection;
this.#communicationType = serializableData.communicationType;
}
private static async findConnectionByCommunicationTypeAndDevicePath(
communicationType: CommunicationType,
nodeHidDevicePath?: string,
device?: LedgerDevice
): Promise<LedgerConnection | null> {
const matchingConnectionData = this.deviceConnections?.find((connection) => {
const sameCommunication = communicationType === connection.communicationType;
if (connection.communicationType === CommunicationType.Web) {
return sameCommunication && device === connection.device;
}
if (connection.communicationType === CommunicationType.Node) {
return sameCommunication && device === connection.device && nodeHidDevicePath === connection.nodeHidDevicePath;
}
});
if (!matchingConnectionData) return null;
try {
await this.testConnection(matchingConnectionData.deviceConnection);
} catch (error) {
if (error instanceof errors.TransportError && error.message.includes(CARDANO_APP_CONNECTION_ERROR_MESSAGE)) {
this.deviceConnections = this.deviceConnections.filter(
(connectionData) => connectionData !== matchingConnectionData
);
return null;
}
throw error;
}
return matchingConnectionData.deviceConnection;
}
/**
* @throws TransportError
*/
private static async getHidDeviceList(communicationType: CommunicationType): Promise<string[]> {
try {
return communicationType === CommunicationType.Node ? TransportNodeHid.list() : TransportWebUSB.list();
} catch (error) {
throw new errors.TransportError('Cannot fetch device list', error);
}
}
private static attachDisconnectionCleanupHandler(transport: LedgerTransportType) {
const onDisconnect = async () => {
transport.off('disconnect', onDisconnect);
this.deviceConnections = this.deviceConnections.filter(
({ deviceConnection }) => deviceConnection.transport !== transport
);
try {
await transport.close();
} catch (error) {
// hw-transport-webusb also adds a disconnect event listener while creating a Ledger transport,
// so calling close() method will throw an error, since the device is already disconnected
if (error instanceof Error && error.message.includes('The device was disconnected.')) return;
throw new errors.TransportError('Failed to close transport after device disconnection', error);
}
};
transport.on('disconnect', onDisconnect);
}
/**
* @throws TransportError
*/
private static async openTransportForDevice({ communicationType, device }: OpenTransportForDeviceParams) {
let transport: LedgerTransportType;
try {
if (communicationType === CommunicationType.Node && device instanceof HID) {
transport = new TransportNodeHid(device);
} else if (communicationType === CommunicationType.Web && isUsbDevice(device)) {
transport = await TransportWebUSB.open(device);
} else {
throw new errors.TransportError(`Invalid device object provided for communication type ${communicationType}`);
}
} catch (error) {
throw new errors.TransportError('Failed to open a transport for a given device', error);
}
this.attachDisconnectionCleanupHandler(transport);
return transport;
}
/**
* @throws TransportError
*/
static async createTransport({
communicationType,
nodeHidDevicePath = ''
}: CreateLedgerTransportProps): Promise<LedgerTransportType> {
let transport: LedgerTransportType;
try {
transport =
communicationType === CommunicationType.Node
? await TransportNodeHid.open(nodeHidDevicePath)
: await TransportWebUSB.open(await getFirstLedgerDevice());
} catch (error) {
throw new errors.TransportError('Creating transport failed', error);
}
this.attachDisconnectionCleanupHandler(transport);
return transport;
}
/**
* @throws TransportError
*/
private static async testConnection(activeConnection: LedgerConnection): Promise<void> {
try {
// Perform app check to see if device can respond
await activeConnection.getVersion();
} catch (error) {
throw new errors.TransportError(CARDANO_APP_CONNECTION_ERROR_MESSAGE, error);
}
}
/**
* @throws TransportError
*/
static async createDeviceConnection(activeTransport: LedgerTransport): Promise<LedgerConnection> {
const deviceConnection = new LedgerConnection(activeTransport);
await this.testConnection(deviceConnection);
return deviceConnection;
}
private static rememberConnection({
communicationType,
device,
deviceConnection,
nodeHidDevicePath
}: {
communicationType: CommunicationType;
device?: LedgerDevice;
deviceConnection: LedgerConnection;
nodeHidDevicePath?: string;
}) {
this.deviceConnections.push({
deviceConnection,
...(communicationType === CommunicationType.Node
? {
communicationType,
...(device instanceof HID && { device }),
...(nodeHidDevicePath !== undefined && { nodeHidDevicePath })
}
: {
communicationType,
...(isUsbDevice(device) && { device })
})
});
}
/**
* @throws TransportError
*/
static async [establishDeviceConnectionMethodName](communicationType: CommunicationType): Promise<LedgerConnection>;
static async [establishDeviceConnectionMethodName](
communicationType: CommunicationType,
nodeHidDevicePath: string
): Promise<LedgerConnection>;
static async [establishDeviceConnectionMethodName](
communicationType: CommunicationType.Node,
device: HID
): Promise<LedgerConnection>;
static async [establishDeviceConnectionMethodName](
communicationType: CommunicationType.Web,
device: USBDevice
): Promise<LedgerConnection>;
static async [establishDeviceConnectionMethodName](
communicationType: CommunicationType,
nodeHidDevicePathOrDevice?: string | LedgerDevice
): Promise<LedgerConnection> {
const { device, nodeHidDevicePath } = parseEstablishDeviceConnectionSecondParam(
communicationType,
nodeHidDevicePathOrDevice
);
const matchingOpenConnection = await this.findConnectionByCommunicationTypeAndDevicePath(
communicationType,
nodeHidDevicePath,
device
);
if (matchingOpenConnection) return matchingOpenConnection;
let transport: LedgerTransportType | undefined;
try {
transport = device
? await LedgerKeyAgent.openTransportForDevice({ communicationType, device })
: await LedgerKeyAgent.createTransport({ communicationType, nodeHidDevicePath });
if (!transport || !transport.deviceModel) {
throw new errors.TransportError('Missing transport');
}
const newConnection = await LedgerKeyAgent.createDeviceConnection(transport);
this.rememberConnection({
communicationType,
device,
deviceConnection: newConnection,
nodeHidDevicePath
});
return newConnection;
} catch (error) {
if (isDeviceAlreadyOpenError(error)) {
throw new errors.TransportError('Connection already established', error);
}
// If transport is established we need to close it, so we can recover device from previous session
if (transport) {
void transport.close();
}
throw new errors.TransportError('Establishing device connection failed', error);
}
}
/**
* @throws TransportError
*/
static async checkDeviceConnection(
communicationType: CommunicationType,
deviceConnection?: LedgerConnection
): Promise<LedgerConnection> {
try {
if (!deviceConnection) {
return await LedgerKeyAgent.establishDeviceConnection(communicationType);
}
// Create / Check device connection with currently active transport
return await LedgerKeyAgent.createDeviceConnection(deviceConnection.transport);
} catch (error: any) {
// Device disconnected -> re-establish connection
if (error.name === 'DisconnectedDeviceDuringOperation') {
return await LedgerKeyAgent.establishDeviceConnection(communicationType);
}
throw error;
}
}
/**
* @throws AuthenticationError
*/
static async getXpub({
deviceConnection,
communicationType,
accountIndex,
purpose
}: GetLedgerXpubProps): Promise<Crypto.Bip32PublicKeyHex> {
try {
const recoveredDeviceConnection = await LedgerKeyAgent.checkDeviceConnection(communicationType, deviceConnection);
const derivationPath = `${purpose}'/${CardanoKeyConst.COIN_TYPE}'/${accountIndex}'`;
const extendedPublicKey = await recoveredDeviceConnection.getExtendedPublicKey({
path: str_to_path(derivationPath) // BIP32Path
});
const xPubHex = `${extendedPublicKey.publicKeyHex}${extendedPublicKey.chainCodeHex}`;
return Crypto.Bip32PublicKeyHex(xPubHex);
} catch (error: any) {
if (error.code === 28_169) {
throw new errors.AuthenticationError('Failed to export extended account public key', error);
}
throw transportTypedError(error);
}
}
/**
* @throws TransportError
*/
static async getAppVersion(
communicationType: CommunicationType,
deviceConnection?: LedgerConnection
): Promise<GetVersionResponse> {
const recoveredDeviceConnection = await LedgerKeyAgent.checkDeviceConnection(communicationType, deviceConnection);
return await recoveredDeviceConnection.getVersion();
}
/**
* @throws AuthenticationError
* @throws TransportError
*/
static async createWithDevice(
{
chainId,
accountIndex = 0,
communicationType,
deviceConnection,
purpose = KeyPurpose.STANDARD
}: CreateLedgerKeyAgentProps,
dependencies: KeyAgentDependencies
) {
const deviceListPaths = await LedgerKeyAgent.getHidDeviceList(communicationType);
// Re-use device connection if you want to create a key agent with new / additional account(s) and pass accountIndex
const activeDeviceConnection = await (deviceConnection
? LedgerKeyAgent.checkDeviceConnection(communicationType, deviceConnection)
: LedgerKeyAgent.establishDeviceConnection(communicationType, deviceListPaths[0]));
const extendedAccountPublicKey = await LedgerKeyAgent.getXpub({
accountIndex,
communicationType,
deviceConnection: activeDeviceConnection,
purpose
});
return new LedgerKeyAgent(
{
accountIndex,
chainId,
communicationType,
deviceConnection: activeDeviceConnection,
extendedAccountPublicKey,
purpose
},
dependencies
);
}
private static isKeyHashOrScriptHashVoter(votingProcedures?: VoterVotes[] | null): boolean {
return !!votingProcedures?.some((votingProcedure) => {
switch (votingProcedure.voter.type) {
case VoterType.COMMITTEE_KEY_HASH:
case VoterType.COMMITTEE_SCRIPT_HASH:
case VoterType.DREP_KEY_HASH:
case VoterType.DREP_SCRIPT_HASH:
case VoterType.STAKE_POOL_KEY_HASH:
return true;
default:
return false;
}
});
}
/**
* Gets the mode in which we want to sign the transaction.
* Ledger has certain limitations due to which it cannot sign arbitrary combination of all transaction features.
* The mode specifies which use-case the user want to use and triggers additional validation on `tx` field.
*/
static getSigningMode(tx: Transaction): TransactionSigningMode {
if (tx.certificates) {
for (const cert of tx.certificates) {
// Represents pool registration from the perspective of a pool owner.
if (
cert.type === CertificateType.STAKE_POOL_REGISTRATION &&
cert.params.poolOwners.some((owner) => owner.type === PoolOwnerType.DEVICE_OWNED)
)
return TransactionSigningMode.POOL_REGISTRATION_AS_OWNER;
// Represents pool registration from the perspective of a pool operator.
if (
cert.type === CertificateType.STAKE_POOL_REGISTRATION &&
cert.params.poolKey.type === PoolKeyType.DEVICE_OWNED
)
return TransactionSigningMode.POOL_REGISTRATION_AS_OPERATOR;
}
}
/**
* VotingProcedures: We are currently supporting only keyHash and scriptHash voter types in voting procedures.
* To sign tx with keyHash and scriptHash voter type we have to use PLUTUS_TRANSACTION signing mode
*/
if (tx.collateralInputs || LedgerKeyAgent.isKeyHashOrScriptHashVoter(tx.votingProcedures)) {
return TransactionSigningMode.PLUTUS_TRANSACTION;
}
// Represents a transaction controlled by native scripts.
// Like an ordinary transaction, but stake credentials and all similar elements are given as script hashes
if (isMultiSig(tx)) {
return TransactionSigningMode.MULTISIG_TRANSACTION;
}
// Represents an ordinary user transaction transferring funds.
return TransactionSigningMode.ORDINARY_TRANSACTION;
}
// TODO: LW-10571 - Allow additional key paths. This is necessary for multi-signature wallets
// hardware devices inspect the transaction to determine which keys to use for signing,
// however, multi sig transaction do not reference the CIP-1854 directly, but rather the script hash
// so we need to be able to instruct the HW to sign the transaction with arbitrary keys.
async signTransaction(
txBody: Serialization.TransactionBody,
{ knownAddresses, txInKeyPathMap }: SignTransactionContext
): Promise<Cardano.Signatures> {
try {
const body = txBody.toCore();
const hash = txBody.hash() as unknown as HexBlob;
const dRepPublicKey = await this.derivePublicKey(util.DREP_KEY_DERIVATION_PATH);
const dRepKeyHashHex = (await Crypto.Ed25519PublicKey.fromHex(dRepPublicKey).hash()).hex();
const outputsFormat = txBody
.outputs()
.map((out) => (out.isBabbageOutput() ? Ledger.TxOutputFormat.MAP_BABBAGE : Ledger.TxOutputFormat.ARRAY_LEGACY));
const collateralReturnFormat = txBody.collateralReturn()?.isBabbageOutput()
? Ledger.TxOutputFormat.MAP_BABBAGE
: Ledger.TxOutputFormat.ARRAY_LEGACY;
const ledgerTxData = await toLedgerTx(body, {
accountIndex: this.accountIndex,
chainId: this.chainId,
collateralReturnFormat,
dRepKeyHashHex,
knownAddresses,
outputsFormat,
txInKeyPathMap
});
const deviceConnection = await LedgerKeyAgent.checkDeviceConnection(
this.#communicationType,
this.deviceConnection
);
const signingMode = LedgerKeyAgent.getSigningMode(ledgerTxData);
const result = await deviceConnection.signTransaction({
options: {
tagCborSets: txBody.hasTaggedSets()
},
signingMode,
tx: ledgerTxData,
...(signingMode === TransactionSigningMode.MULTISIG_TRANSACTION && {
additionalWitnessPaths: multiSigWitnessPaths
})
});
if (!areStringsEqualInConstantTime(result.txHashHex, hash)) {
throw new errors.HwMappingError('Ledger computed a different transaction id');
}
return new Map<Crypto.Ed25519PublicKeyHex, Crypto.Ed25519SignatureHex>(
await Promise.all(
result.witnesses.map(async (witness) => {
const publicKey = await this.derivePublicKey({
index: witness.path[Cip1852PathLevelIndexes.INDEX],
role: witness.path[Cip1852PathLevelIndexes.ROLE]
});
const signature = Crypto.Ed25519SignatureHex(witness.witnessSignatureHex);
return [publicKey, signature] as const;
})
)
);
} catch (error: any) {
if (error.code === 28_169) {
throw new errors.AuthenticationError('Transaction signing aborted', error);
}
throw transportTypedError(error);
}
}
async signCip8Data(request: cip8.Cip8SignDataContext): Promise<Cip30DataSignature> {
const hashPayload = request.payload.length >= CIP08_SIGN_HASH_THRESHOLD;
try {
const dRepPublicKey = await this.derivePublicKey(util.DREP_KEY_DERIVATION_PATH);
const dRepKeyHashHex = (await Crypto.Ed25519PublicKey.fromHex(dRepPublicKey).hash()).hex();
const { signingPath, addressParams, addressFieldType } = getDerivationPath(
request.signWith,
request.knownAddresses,
this.accountIndex,
this.purpose,
dRepKeyHashHex
);
const messageData: MessageData =
addressFieldType === MessageAddressFieldType.ADDRESS && addressParams
? {
address: addressParams,
addressFieldType: MessageAddressFieldType.ADDRESS,
hashPayload,
messageHex: request.payload,
network: {
networkId: this.chainId.networkId,
protocolMagic: this.chainId.networkMagic
},
preferHexDisplay: false,
signingPath
}
: {
addressFieldType: MessageAddressFieldType.KEY_HASH,
hashPayload,
messageHex: request.payload,
preferHexDisplay: false,
signingPath
};
const deviceConnection = await LedgerKeyAgent.checkDeviceConnection(
this.#communicationType,
this.deviceConnection
);
const result = await deviceConnection.signMessage(messageData);
// Re-create the CIP-008 payload the same way the firmware does it internally, otherwise the signature
// will not verify.
const addressBytes = coreUtils.hexToBytes(HexBlob(result.addressFieldHex));
const protectedHeaders = HeaderMap.new();
protectedHeaders.set_algorithm_id(Label.from_algorithm_id(AlgorithmId.EdDSA));
protectedHeaders.set_header(cip8.CoseLabel.address, CBORValue.new_bytes(addressBytes));
const sigPayload = coreUtils.hexToBytes(hashPayload ? blake2b.hash(request.payload, 28) : request.payload);
const builder = COSESign1Builder.new(
Headers.new(ProtectedHeaderMap.new(protectedHeaders), HeaderMap.new()),
sigPayload,
false
);
const coseSign1 = builder.build(Buffer.from(result.signatureHex, 'hex'));
const coseKey = cip8.createCoseKey(addressBytes, Crypto.Ed25519PublicKeyHex(result.signingPublicKeyHex));
const coseSigHex = coreUtils.bytesToHex(coseSign1.to_bytes());
return {
key: coreUtils.bytesToHex(coseKey.to_bytes()),
signature: hashPayload ? setCOSESignHashed(coseSigHex, true) : coseSigHex
};
} catch (error: any) {
if (error.code === 28_169) {
throw new errors.AuthenticationError('Transaction signing aborted', error);
}
throw transportTypedError(error);
}
}
async signBlob(): Promise<SignBlobResult> {
throw new NotImplementedError('Operation not supported!');
}
async exportRootPrivateKey(): Promise<Crypto.Bip32PrivateKeyHex> {
throw new NotImplementedError('Operation not supported!');
}
}