-
Notifications
You must be signed in to change notification settings - Fork 55
/
SigningCoordinator.ts
210 lines (196 loc) · 7.23 KB
/
SigningCoordinator.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
import { Cardano, Serialization } from '@cardano-sdk/core';
import { CustomError } from 'ts-custom-error';
import { InMemoryWallet, WalletType } from '../types';
import { KeyAgent, SignBlobResult, TrezorConfig, errors } from '@cardano-sdk/key-management';
import { KeyAgentFactory } from './KeyAgentFactory';
import { Logger } from 'ts-log';
import {
RequestBase,
RequestContext,
SignDataProps,
SignDataRequest,
SignOptions,
SignRequest,
SignTransactionProps,
SigningCoordinatorConfirmationApi,
SigningCoordinatorSignApi,
TransactionWitnessRequest
} from './types';
import { Subject } from 'rxjs';
import { WrongTargetError } from '../../messaging';
import { contextLogger } from '@cardano-sdk/util';
export type HardwareKeyAgentOptions = TrezorConfig;
export type SigningCoordinatorProps = {
hwOptions: HardwareKeyAgentOptions;
};
export type SigningCoordinatorDependencies = {
keyAgentFactory: KeyAgentFactory;
logger: Logger;
};
class NoRejectError extends CustomError {
constructor(public actualError: unknown) {
super();
}
}
const throwMaybeWrappedWithNoRejectError = (error: unknown, options?: SignOptions): never => {
if (options?.willRetryOnFailure) throw new NoRejectError(error);
throw error;
};
const clearPassphrase = (passphrase: Uint8Array) => {
for (let i = 0; i < passphrase.length; i++) {
passphrase[i] = 0;
}
};
const bubbleResolveReject = async <R>(
action: () => Promise<R>,
resolve: (result: R | Promise<R>) => void,
reject: (error: unknown) => void
): Promise<R> => {
try {
const result = await action();
resolve(result);
return result;
} catch (error) {
if (error instanceof NoRejectError) {
throw error.actualError;
}
reject(error);
throw error;
}
};
export class SigningCoordinator<WalletMetadata extends {}, AccountMetadata extends {}>
implements
SigningCoordinatorConfirmationApi<WalletMetadata, AccountMetadata>,
SigningCoordinatorSignApi<WalletMetadata, AccountMetadata>
{
readonly transactionWitnessRequest$ = new Subject<TransactionWitnessRequest<WalletMetadata, AccountMetadata>>();
readonly signDataRequest$ = new Subject<SignDataRequest<WalletMetadata, AccountMetadata>>();
readonly #hwOptions: HardwareKeyAgentOptions;
readonly #keyAgentFactory: KeyAgentFactory;
readonly #logger: Logger;
constructor(props: SigningCoordinatorProps, { keyAgentFactory, logger }: SigningCoordinatorDependencies) {
this.#hwOptions = props.hwOptions;
this.#keyAgentFactory = keyAgentFactory;
this.#logger = contextLogger(logger, 'SigningCoordinator');
}
async signTransaction(
{ tx, signContext, options }: SignTransactionProps,
requestContext: RequestContext<WalletMetadata, AccountMetadata>
): Promise<Cardano.Signatures> {
const transaction = Serialization.Transaction.fromCbor(tx);
return this.#signRequest(
this.transactionWitnessRequest$,
{
requestContext,
signContext,
transaction,
walletType: requestContext.wallet.type
},
(keyAgent) => {
const hash = transaction.getId();
this.#logger.info('Signing transaction', hash);
return keyAgent.signTransaction(
{
body: transaction.body().toCore(),
hash
},
signContext,
options
);
}
);
}
async signData(
props: SignDataProps,
requestContext: RequestContext<WalletMetadata, AccountMetadata>
): Promise<SignBlobResult> {
return this.#signRequest(
this.signDataRequest$,
{
...props,
requestContext,
walletType: requestContext.wallet.type
},
(keyAgent) => keyAgent.signBlob(props.derivationPath, props.blob)
);
}
#signRequest<R, Req extends RequestBase<WalletMetadata, AccountMetadata> & SignRequest<R>>(
emitter$: Subject<Req>,
request: Omit<Req, 'reject' | 'sign'>,
sign: (keyAgent: KeyAgent) => Promise<R>
) {
return new Promise<R>((resolve, reject) => {
if (!emitter$.observed) {
return reject(new WrongTargetError('Not expecting sign requests at this time'));
}
const account = request.requestContext.wallet.accounts.find(
({ accountIndex }) => accountIndex === request.requestContext.accountIndex
);
if (!account) {
return reject(new errors.ProofGenerationError(`Account not found: ${request.requestContext.accountIndex}`));
}
const commonRequestProps = {
...request,
reject: async (reason: string) => reject(new errors.AuthenticationError(reason))
};
emitter$.next(
request.walletType === WalletType.InMemory
? ({
...commonRequestProps,
sign: async (passphrase: Uint8Array, options?: SignOptions) =>
bubbleResolveReject(
async () => {
const wallet = request.requestContext.wallet as InMemoryWallet<WalletMetadata, AccountMetadata>;
try {
const result = await sign(
this.#keyAgentFactory.InMemory({
accountIndex: account.accountIndex,
chainId: request.requestContext.chainId,
encryptedRootPrivateKeyBytes: [
...Buffer.from(wallet.encryptedSecrets.rootPrivateKeyBytes, 'hex')
],
extendedAccountPublicKey: account.extendedAccountPublicKey,
getPassphrase: async () => passphrase
})
);
clearPassphrase(passphrase);
return result;
} catch (error) {
clearPassphrase(passphrase);
return throwMaybeWrappedWithNoRejectError(error, options);
}
},
resolve,
reject
),
walletType: request.walletType
} as Req)
: ({
...commonRequestProps,
sign: async (): Promise<R> =>
bubbleResolveReject(
async (options?: SignOptions) =>
sign(
request.walletType === WalletType.Ledger
? this.#keyAgentFactory.Ledger({
accountIndex: request.requestContext.accountIndex,
chainId: request.requestContext.chainId,
communicationType: this.#hwOptions.communicationType,
extendedAccountPublicKey: account.extendedAccountPublicKey
})
: this.#keyAgentFactory.Trezor({
accountIndex: request.requestContext.accountIndex,
chainId: request.requestContext.chainId,
extendedAccountPublicKey: account.extendedAccountPublicKey,
trezorConfig: this.#hwOptions
})
).catch((error) => throwMaybeWrappedWithNoRejectError(error, options)),
resolve,
reject
),
walletType: request.walletType
} as Req)
);
});
}
}