-
Notifications
You must be signed in to change notification settings - Fork 55
/
ownSignatureKeyPaths.ts
374 lines (336 loc) · 13.7 KB
/
ownSignatureKeyPaths.ts
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
import * as Crypto from '@cardano-sdk/crypto';
import { AccountKeyDerivationPath, GroupedAddress, TxInId, TxInKeyPathMap } from '../types';
import { Cardano } from '@cardano-sdk/core';
import { DREP_KEY_DERIVATION_PATH } from './key';
import { isNotNil } from '@cardano-sdk/util';
import isEqual from 'lodash/isEqual';
import uniqBy from 'lodash/uniqBy';
import uniqWith from 'lodash/uniqWith';
export type StakeKeySignerData = {
poolId: Cardano.PoolId;
rewardAccount: Cardano.RewardAccount;
stakeKeyHash: Crypto.Ed25519KeyHashHex;
derivationPath: AccountKeyDerivationPath;
};
/** Return type of functions that inspect transaction parts for signatures */
type SignatureCheck = {
/** Signature derivation paths */
derivationPaths: AccountKeyDerivationPath[];
/** Whether foreign signatures (not owned by wallet) are needed */
requiresForeignSignatures: boolean;
};
/** Checks whether the transaction withdrawals contain foreign signatures and returns known derivation paths */
const checkWithdrawals = (
{ withdrawals }: Pick<Cardano.TxBody, 'withdrawals'>,
accounts: StakeKeySignerData[]
): SignatureCheck => {
const signatureCheck: SignatureCheck = { derivationPaths: [], requiresForeignSignatures: false };
if (withdrawals) {
for (const withdrawal of withdrawals) {
const account = accounts.find((acct) => acct.rewardAccount === withdrawal.stakeAddress);
if (account) {
signatureCheck.derivationPaths.push(account.derivationPath);
} else {
signatureCheck.requiresForeignSignatures = true;
}
}
}
return signatureCheck;
};
const checkStakeKeyHashCertificate = (
certificate: Cardano.Certificate,
accounts: StakeKeySignerData[]
): SignatureCheck => {
const signatureCheck: SignatureCheck = { derivationPaths: [], requiresForeignSignatures: false };
switch (certificate.__typename) {
case Cardano.CertificateType.VoteDelegation:
case Cardano.CertificateType.StakeVoteDelegation:
case Cardano.CertificateType.StakeRegistrationDelegation:
case Cardano.CertificateType.VoteRegistrationDelegation:
case Cardano.CertificateType.StakeVoteRegistrationDelegation:
case Cardano.CertificateType.Registration:
case Cardano.CertificateType.Unregistration:
case Cardano.CertificateType.StakeDeregistration:
case Cardano.CertificateType.StakeDelegation: {
const account = accounts.find(
(acct) =>
certificate.stakeCredential.type === Cardano.CredentialType.KeyHash &&
acct.stakeKeyHash === (certificate.stakeCredential.hash as unknown as Crypto.Ed25519KeyHashHex)
);
if (account) {
signatureCheck.derivationPaths = [account.derivationPath];
} else {
signatureCheck.requiresForeignSignatures = true;
}
}
}
return signatureCheck;
};
const checkPoolRegistrationCertificate = (
certificate: Cardano.Certificate,
accounts: StakeKeySignerData[]
): SignatureCheck => {
const signatureCheck: SignatureCheck = { derivationPaths: [], requiresForeignSignatures: false };
if (certificate.__typename === Cardano.CertificateType.PoolRegistration) {
for (const owner of certificate.poolParameters.owners) {
const account = accounts.find((acct) => acct.rewardAccount === owner);
if (account) {
signatureCheck.derivationPaths.push(account.derivationPath);
} else {
signatureCheck.requiresForeignSignatures = true;
}
}
}
return signatureCheck;
};
const checkPoolRetirementCertificate = (
certificate: Cardano.Certificate,
accounts: StakeKeySignerData[]
): SignatureCheck => {
const signatureCheck: SignatureCheck = { derivationPaths: [], requiresForeignSignatures: false };
if (certificate.__typename === Cardano.CertificateType.PoolRetirement) {
const account = accounts.find((acct) => acct.poolId === certificate.poolId);
if (account) {
signatureCheck.derivationPaths.push(account.derivationPath);
} else {
signatureCheck.requiresForeignSignatures = true;
}
}
return signatureCheck;
};
const checkMirCertificate = (certificate: Cardano.Certificate, accounts: StakeKeySignerData[]): SignatureCheck => {
const signatureCheck: SignatureCheck = { derivationPaths: [], requiresForeignSignatures: false };
if (certificate.__typename === Cardano.CertificateType.MIR) {
if (certificate.kind === Cardano.MirCertificateKind.ToStakeCreds) {
const account = accounts.find(
(acct) => Crypto.Hash28ByteBase16(acct.stakeKeyHash) === certificate.stakeCredential!.hash
);
if (account) {
signatureCheck.derivationPaths.push(account.derivationPath);
} else {
signatureCheck.requiresForeignSignatures = true;
}
} else {
signatureCheck.requiresForeignSignatures = true;
}
}
return signatureCheck;
};
/**
* Inspect certificates against own stake credentials. Determines the signature derivation paths, and wether there
* are certificates it cannot sign (foreign signatures).
*/
export const checkStakeCredentialCertificates = (
accounts: StakeKeySignerData[],
{ certificates }: Pick<Cardano.TxBody, 'certificates'>
): SignatureCheck => {
const signatureCheck: SignatureCheck = { derivationPaths: [], requiresForeignSignatures: false };
if (!certificates?.length) {
return signatureCheck;
}
for (const certificate of certificates) {
const stakeKeyHashCheck = checkStakeKeyHashCertificate(certificate, accounts);
signatureCheck.requiresForeignSignatures ||= stakeKeyHashCheck.requiresForeignSignatures;
signatureCheck.derivationPaths.push(...stakeKeyHashCheck.derivationPaths);
const poolOwnerCheck = checkPoolRegistrationCertificate(certificate, accounts);
signatureCheck.requiresForeignSignatures ||= poolOwnerCheck.requiresForeignSignatures;
signatureCheck.derivationPaths.push(...poolOwnerCheck.derivationPaths);
const poolIdCheck = checkPoolRetirementCertificate(certificate, accounts);
signatureCheck.requiresForeignSignatures ||= poolIdCheck.requiresForeignSignatures;
signatureCheck.derivationPaths.push(...poolIdCheck.derivationPaths);
const mirCheck = checkMirCertificate(certificate, accounts);
signatureCheck.requiresForeignSignatures ||= mirCheck.requiresForeignSignatures;
signatureCheck.derivationPaths.push(...mirCheck.derivationPaths);
// StakeRegistration and GenesisKeyDelegation do not require signing
}
signatureCheck.derivationPaths = uniqWith(signatureCheck.derivationPaths, isEqual);
return signatureCheck;
};
const getSignersData = (groupedAddresses: GroupedAddress[]): StakeKeySignerData[] =>
uniqBy(groupedAddresses, 'rewardAccount')
.map((groupedAddress) => {
const stakeKeyHash = Cardano.RewardAccount.toHash(groupedAddress.rewardAccount);
const poolId = Cardano.PoolId.fromKeyHash(stakeKeyHash);
return {
derivationPath: groupedAddress.stakeKeyDerivationPath,
poolId,
rewardAccount: groupedAddress.rewardAccount,
stakeKeyHash
};
})
.filter((acct): acct is StakeKeySignerData => acct.derivationPath !== undefined);
/**
* Gets whether withdrawals or any certificate in the provided certificate list requires a stake key signature.
*
* @param groupedAddresses The known grouped addresses.
* @param txBody The transaction body.
*/
const getStakeCredentialKeyPaths = (groupedAddresses: GroupedAddress[], txBody: Cardano.TxBody) => {
let requiresForeignSignatures = false;
const paths: AccountKeyDerivationPath[] = [];
const uniqueAccounts = getSignersData(groupedAddresses);
const withdrawalCheck = checkWithdrawals(txBody, uniqueAccounts);
requiresForeignSignatures ||= withdrawalCheck.requiresForeignSignatures;
paths.push(...withdrawalCheck.derivationPaths);
const stakeCredentialCertificatesCheck = checkStakeCredentialCertificates(uniqueAccounts, txBody);
requiresForeignSignatures ||= stakeCredentialCertificatesCheck.requiresForeignSignatures;
paths.push(...stakeCredentialCertificatesCheck.derivationPaths);
return { derivationPaths: new Set(paths), requiresForeignSignatures };
};
/**
* Depending on transaction `voting_procedures = { + voter => { + gov_action_id => voting_procedure } }`
* ; Constitutional Committee Hot KeyHash: 0
* ; Constitutional Committee Hot ScriptHash: 1
* ; DRep KeyHash: 2
* ; DRep ScriptHash: 3
* ; StakingPool KeyHash: 4
* voter =
* [ 0, addr_keyhash
* // 1, scripthash
* // 2, addr_keyhash
* // 3, scripthash
* // 4, addr_keyhash
* ]
*/
export const getVotingProcedureKeyPaths = ({
groupedAddresses,
dRepKeyHash,
txBody
}: {
groupedAddresses: GroupedAddress[];
dRepKeyHash?: Crypto.Ed25519KeyHashHex;
txBody: Cardano.TxBody;
}): SignatureCheck => {
const signatureCheck: SignatureCheck = { derivationPaths: [], requiresForeignSignatures: false };
const accounts = getSignersData(groupedAddresses);
for (const { voter } of txBody.votingProcedures || []) {
switch (voter.__typename) {
case Cardano.VoterType.dRepKeyHash: {
if (dRepKeyHash && voter.credential.hash === Crypto.Hash28ByteBase16.fromEd25519KeyHashHex(dRepKeyHash)) {
signatureCheck.derivationPaths.push(DREP_KEY_DERIVATION_PATH);
} else {
signatureCheck.requiresForeignSignatures = true;
}
break;
}
case Cardano.VoterType.stakePoolKeyHash: {
const account = accounts.find(
(acct) => Crypto.Hash28ByteBase16.fromEd25519KeyHashHex(acct.stakeKeyHash) === voter.credential.hash
);
if (account) {
signatureCheck.derivationPaths.push(account.derivationPath);
} else {
signatureCheck.requiresForeignSignatures = true;
}
break;
}
default:
// case Cardano.VoterType.ccHotKeyHash:
// case Cardano.VoterType.ccHotScriptHash:
// case Cardano.VoterType.dRepScriptHash:
signatureCheck.requiresForeignSignatures = true;
break;
}
}
return signatureCheck;
};
/**
* Search for the key hashes provided in the requiredSigners in our current set of known addresses.
*
* @param groupedAddresses The known grouped addresses.
* @param keyHashes The list of required signers key hashes (or undefined if none).
* @returns A set of derivation paths if any of the key hashes is found.
*/
const getRequiredSignersKeyPaths = (
groupedAddresses: GroupedAddress[],
keyHashes?: Crypto.Ed25519KeyHashHex[]
): AccountKeyDerivationPath[] => {
const paths: AccountKeyDerivationPath[] = [];
if (!keyHashes) return paths;
for (const keyHash of keyHashes) {
for (const address of groupedAddresses) {
const paymentCredential = Cardano.Address.fromBech32(address.address)?.asBase()?.getPaymentCredential().hash;
const stakeCredential = Cardano.RewardAccount.toHash(address.rewardAccount);
if (paymentCredential && paymentCredential.toString() === keyHash) {
paths.push({ index: address.index, role: Number(address.type) });
}
if (stakeCredential && address.stakeKeyDerivationPath && stakeCredential.toString() === keyHash) {
paths.push(address.stakeKeyDerivationPath);
}
}
}
return paths;
};
/** Check if there are certificates that require DRep credentials and if we own them */
export const getDRepCredentialKeyPaths = ({
dRepKeyHash,
txBody
}: {
dRepKeyHash?: Crypto.Ed25519KeyHashHex;
txBody: Cardano.TxBody;
}): SignatureCheck => {
const signature: SignatureCheck = { derivationPaths: [], requiresForeignSignatures: false };
for (const certificate of txBody.certificates || []) {
if (
certificate.__typename === Cardano.CertificateType.UnregisterDelegateRepresentative ||
certificate.__typename === Cardano.CertificateType.UpdateDelegateRepresentative ||
certificate.__typename === Cardano.CertificateType.RegisterDelegateRepresentative
) {
if (
certificate.dRepCredential.type === Cardano.CredentialType.ScriptHash ||
!dRepKeyHash ||
certificate.dRepCredential.hash !== Crypto.Hash28ByteBase16.fromEd25519KeyHashHex(dRepKeyHash)
) {
// Scripts are foreign
signature.requiresForeignSignatures = true;
} else {
// There's only one drep key that the wallet owns.
signature.derivationPaths = [DREP_KEY_DERIVATION_PATH];
}
}
}
return signature;
};
// TODO: test
export const createTxInKeyPathMap = async (
txBody: Cardano.TxBody,
knownAddresses: GroupedAddress[],
inputResolver: Cardano.InputResolver
) => {
const result: TxInKeyPathMap = {};
const txInputs = [...txBody.inputs, ...(txBody.collaterals ? txBody.collaterals : [])];
await Promise.all(
txInputs.map(async (txIn) => {
const resolution = await inputResolver.resolveInput(txIn);
if (!resolution) return;
const ownAddress = knownAddresses.find(({ address }) => address === resolution.address);
if (!ownAddress) return;
result[TxInId(txIn)] = { index: ownAddress.index, role: Number(ownAddress.type) };
})
);
return result;
};
/**
* Assumes that a single stake key is used for all addresses (index=0)
*
* @returns {AccountKeyDerivationPath[]} derivation paths for keys to sign transaction with
*/
export const ownSignatureKeyPaths = (
txBody: Cardano.TxBody,
knownAddresses: GroupedAddress[],
txInKeyPathMap: TxInKeyPathMap,
dRepKeyHash?: Crypto.Ed25519KeyHashHex
): AccountKeyDerivationPath[] => {
// TODO: add `proposal_procedure` witnesses.
const paymentKeyPaths = Object.values(txInKeyPathMap).filter(isNotNil);
return uniqWith(
[
...paymentKeyPaths,
...getStakeCredentialKeyPaths(knownAddresses, txBody).derivationPaths,
...getDRepCredentialKeyPaths({ dRepKeyHash, txBody }).derivationPaths,
...getRequiredSignersKeyPaths(knownAddresses, txBody.requiredExtraSignatures),
...getVotingProcedureKeyPaths({ dRepKeyHash, groupedAddresses: knownAddresses, txBody }).derivationPaths
],
isEqual
);
};