-
Notifications
You must be signed in to change notification settings - Fork 36
/
cardano-wallet.ts
159 lines (144 loc) · 5.01 KB
/
cardano-wallet.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
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable unicorn/no-null */
import {
AssetProvider,
Cardano,
ChainHistoryProvider,
NetworkInfoProvider,
RewardsProvider,
StakePoolProvider,
TxSubmitProvider,
util as coreUtil,
UtxoProvider
} from '@cardano-sdk/core';
import { ObservableWallet, BaseWalletDependencies, storage, restoreKeyAgent } from '@cardano-sdk/wallet';
import * as KeyManagement from '@cardano-sdk/key-management';
import { AnyWallet, Bip32WalletAccount, SigningCoordinatorConfirmationApi } from '@cardano-sdk/web-extension';
import { ChainName } from '../types';
import * as Crypto from '@cardano-sdk/crypto';
import { Wallet } from '@src/index';
import { HexBlob } from '@cardano-sdk/util';
export const bip32Ed25519 = new Crypto.SodiumBip32Ed25519();
export type KeyAgentsByChain = Record<ChainName, { keyAgentData: KeyManagement.SerializableKeyAgentData }>;
export interface WalletMetadata {
name: string;
lockValue?: HexBlob;
lastActiveAccountIndex?: number;
walletAddresses?: Cardano.PaymentAddress[];
}
export interface AccountMetadata {
name: string;
}
export interface CardanoWallet {
wallet: ObservableWallet;
source: {
wallet: AnyWallet<WalletMetadata, AccountMetadata>;
account?: Bip32WalletAccount<AccountMetadata>;
};
name: string;
signingCoordinator: SigningCoordinatorConfirmationApi<WalletMetadata, AccountMetadata>;
}
export type CreateStores = (name: string) => storage.WalletStores;
export interface WalletProvidersDependencies {
stakePoolProvider: StakePoolProvider;
assetProvider: AssetProvider;
txSubmitProvider: TxSubmitProvider;
networkInfoProvider: NetworkInfoProvider;
utxoProvider: UtxoProvider;
rewardsProvider: RewardsProvider;
chainHistoryProvider: ChainHistoryProvider;
}
export interface CreatePersonalWallet {
providers: WalletProvidersDependencies;
name: string;
logger: BaseWalletDependencies['logger'];
stores: storage.WalletStores;
keyAgent: KeyManagement.AsyncKeyAgent;
}
/**
* Restores a wallet from a serializable key agent data.
*/
export const restoreWallet = async (
keyAgentData: KeyManagement.SerializableKeyAgentData,
getPassword: () => Promise<Uint8Array>
): Promise<{ keyAgent: KeyManagement.KeyAgent }> => {
const keyAgent = await restoreKeyAgent(keyAgentData, { logger: console, bip32Ed25519 }, getPassword);
return { keyAgent };
};
type Challenge = KeyManagement.SignBlobResult;
const Challenge = {
/**
* Trigger `keyAgent` to ask for password and thus - verify if the right key/password is provided
*/
sign: async (keyAgent: KeyManagement.KeyAgent): Promise<Challenge> => {
const addressPath: KeyManagement.AccountKeyDerivationPath = { role: KeyManagement.KeyRole.External, index: 0 };
const challengeBlob = coreUtil.bytesToHex(Buffer.from('challenge', 'utf8'));
return keyAgent.signBlob(addressPath, challengeBlob);
},
/**
* Check, whether received challenge maches the expected one
*/
check: (expected: Challenge, actual: Challenge): boolean =>
expected.signature === actual.signature && expected.publicKey === actual.publicKey
};
export const validateWalletPassword = async (
keyAgentData: KeyManagement.InMemoryKeyAgent['serializableData'],
// Password as string as we don't need it after validating
password: string
): Promise<boolean> => {
const getPassword = async () => Buffer.from(password);
const keyAgent = await restoreKeyAgent(
keyAgentData,
// Not needed for this
{
logger: console,
bip32Ed25519
},
getPassword
);
try {
// Trigger getPassword without reaching for the private key directly
await Challenge.sign(keyAgent);
} catch {
// If password is wrong it will throw `Failed to decrypt root private key`
return false;
}
return true;
};
/**
* Compare extended account public key derived from the mnemonic with the provided one.
*/
export const validateWalletMnemonic = async (
mnemonicWords: string[],
expectedExtendedAccountPublicKey: Wallet.Crypto.Bip32PublicKeyHex
): Promise<boolean> => {
// To verify password
const validatingKeyAgent = await KeyManagement.InMemoryKeyAgent.fromBip39MnemonicWords(
{
mnemonicWords,
// XPUB is the same for all networks, but we're deriving it by creating a key agent which has chainId as a required parameter.
// Ideally we would have a util that just derives the xpub without the redundant parameters.
chainId: Cardano.ChainIds.Mainnet, // does not matter
getPassphrase: async () => Buffer.from('doesnt matter')
},
{
logger: console,
bip32Ed25519
}
);
const originalPublicKey = expectedExtendedAccountPublicKey;
const validatingPublicKey = validatingKeyAgent.extendedAccountPublicKey;
return originalPublicKey === validatingPublicKey;
};
export const createKeyAgent = (
keyAgentData: KeyManagement.SerializableKeyAgentData,
getPassword: () => Promise<Uint8Array>
): Promise<KeyManagement.KeyAgent> =>
restoreKeyAgent(
keyAgentData,
{
logger: console,
bip32Ed25519
},
getPassword
);