/
utils.js
452 lines (420 loc) · 15.5 KB
/
utils.js
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
// @flow
import type { CoreAddressT } from '../database/primitives/enums';
import { CoreAddressTypes } from '../database/primitives/enums';
import { Bech32Prefix } from '../../../../../config/stringConfig';
import { RustModule } from '../../cardanoCrypto/rustLoader';
import type { NetworkRow } from '../database/primitives/tables';
import { isJormungandr, isCardanoHaskell, isErgo } from '../database/prepackaged/networks';
import { defineMessages, } from 'react-intl';
import type { $npm$ReactIntl$MessageDescriptor, } from 'react-intl';
export function tryAddressToKind(
address: string,
parseAs: 'bech32' | 'bytes',
network: $ReadOnly<NetworkRow>,
): void | CoreAddressT {
try {
return addressToKind(address, parseAs, network);
} catch (_e) {
return undefined;
}
}
export function addressToKind(
address: string,
parseAs: 'bech32' | 'bytes',
network: $ReadOnly<NetworkRow>,
): CoreAddressT {
try {
if (isJormungandr(network)) {
// Need to try parsing as a legacy address first
// Since parsing as bech32 directly may give a wrong result if the address contains a 1
if (RustModule.WalletV4.ByronAddress.is_valid(address)) {
return CoreAddressTypes.CARDANO_LEGACY;
}
const wasmAddr = parseAs === 'bytes'
? RustModule.WalletV3.Address.from_bytes(Buffer.from(address, 'hex'))
: RustModule.WalletV3.Address.from_string(address);
switch (wasmAddr.get_kind()) {
case RustModule.WalletV3.AddressKind.Single: return CoreAddressTypes.JORMUNGANDR_SINGLE;
case RustModule.WalletV3.AddressKind.Group: return CoreAddressTypes.JORMUNGANDR_GROUP;
case RustModule.WalletV3.AddressKind.Account: return CoreAddressTypes.JORMUNGANDR_ACCOUNT;
case RustModule.WalletV3.AddressKind.Multisig: return CoreAddressTypes.JORMUNGANDR_MULTISIG;
default: throw new Error(`${nameof(addressToKind)} unknown address type ` + address);
}
}
if (isCardanoHaskell(network)) {
// Need to try parsing as a legacy address first
// Since parsing as bech32 directly may give a wrong result if the address contains a 1
if (RustModule.WalletV4.ByronAddress.is_valid(address)) {
return CoreAddressTypes.CARDANO_LEGACY;
}
const wasmAddr = parseAs === 'bytes'
? RustModule.WalletV4.Address.from_bytes(Buffer.from(address, 'hex'))
: RustModule.WalletV4.Address.from_bech32(address);
{
const byronAddr = RustModule.WalletV4.ByronAddress.from_address(wasmAddr);
if (byronAddr) return CoreAddressTypes.CARDANO_LEGACY;
}
{
const baseAddr = RustModule.WalletV4.BaseAddress.from_address(wasmAddr);
if (baseAddr) return CoreAddressTypes.CARDANO_BASE;
}
{
const ptrAddr = RustModule.WalletV4.PointerAddress.from_address(wasmAddr);
if (ptrAddr) return CoreAddressTypes.CARDANO_PTR;
}
{
const enterpriseAddr = RustModule.WalletV4.EnterpriseAddress.from_address(wasmAddr);
if (enterpriseAddr) return CoreAddressTypes.CARDANO_ENTERPRISE;
}
{
const rewardAddr = RustModule.WalletV4.RewardAddress.from_address(wasmAddr);
if (rewardAddr) return CoreAddressTypes.CARDANO_REWARD;
}
throw new Error(`${nameof(addressToKind)} unknown address type`);
}
if (isErgo(network)) {
const ergoAddress = parseAs === 'bytes'
? RustModule.SigmaRust.NetworkAddress.from_bytes(Buffer.from(address, 'hex'))
: RustModule.SigmaRust.NetworkAddress.from_base58(address);
return ergoAddressToType(ergoAddress);
}
throw new Error(`${nameof(addressToKind)} not implemented for network ${network.NetworkId}`);
} catch (e1) {
throw new Error(`${nameof(addressToKind)} failed to parse address type ${e1} ${address}`);
}
}
export function ergoAddressToType(
address: RustModule.SigmaRust.NetworkAddress,
): CoreAddressT {
switch (address.address().address_type_prefix()) {
case RustModule.SigmaRust.AddressTypePrefix.P2Pk: return CoreAddressTypes.ERGO_P2PK;
case RustModule.SigmaRust.AddressTypePrefix.Pay2Sh: return CoreAddressTypes.ERGO_P2SH;
case RustModule.SigmaRust.AddressTypePrefix.Pay2S: return CoreAddressTypes.ERGO_P2S;
default: throw new Error(`${nameof(ergoAddressToType)} unknown Ergo address type ${address.to_base58()}`);
}
}
export function isValidReceiveAddress(
bech32: string,
network: $ReadOnly<NetworkRow>,
): true | [false, $Exact<$npm$ReactIntl$MessageDescriptor>] {
const messages = defineMessages({
invalidAddress: {
id: 'wallet.send.form.errors.invalidAddress',
defaultMessage: '!!!Please enter a valid address.',
},
cannotSendToLegacy: {
id: 'wallet.send.form.cannotSendToLegacy',
defaultMessage: '!!!You cannot send to legacy addresses (any address created before November 29th, 2019)',
},
cannotSendToReward: {
id: 'wallet.send.form.cannotSendToReward',
defaultMessage: '!!!You cannot send to a reward account',
},
cannotSendToP2SH: {
id: 'wallet.send.form.cannotSendToP2SH',
defaultMessage: '!!!You cannot send to pay-to-script-hash addresses',
},
wrongNetwork: {
id: 'global.wrongNetwork.address',
defaultMessage: '!!!Wrong network for address.',
},
});
const kind = tryAddressToKind(bech32, 'bech32', network);
if (kind == null) {
return [false, messages.invalidAddress];
}
if (isErgo(network)) {
if (kind === CoreAddressTypes.ERGO_P2SH) {
return [false, messages.cannotSendToP2SH];
}
if (isErgoAddress(kind)) {
return true;
}
return [false, messages.invalidAddress];
}
if (isJormungandr(network)) {
if (kind === CoreAddressTypes.CARDANO_LEGACY) {
return [false, messages.cannotSendToLegacy];
}
if (isJormungandrAddress(kind)) {
return true;
}
return [false, messages.invalidAddress];
}
if (isCardanoHaskell(network)) {
if (kind === CoreAddressTypes.CARDANO_REWARD) {
return [false, messages.cannotSendToReward];
}
if (isCardanoHaskellAddress(kind)) {
const addr = normalizeToAddress(bech32);
if (addr == null) throw new Error('Should never happen');
const expectedNetworkId = Number.parseInt(network.BaseConfig[0].ChainNetworkId, 10);
if (addr.network_id() !== expectedNetworkId) {
return [false, messages.wrongNetwork];
}
return true;
}
return [false, messages.invalidAddress];
}
throw new Error(`${nameof(isValidReceiveAddress)} Unsupported network ${JSON.stringify(network)}`);
}
export function byronAddrToHex(
base58Addr: string
): string {
return Buffer.from(RustModule.WalletV4.ByronAddress.from_base58(
base58Addr
).to_bytes()).toString('hex');
}
export function normalizeToBase58(
addr: string
): void | string {
// in Shelley, addresses can be base16, bech32 or base58
// this function normalizes everything to base58
// 1) If already base58, simply return
if (RustModule.WalletV4.ByronAddress.is_valid(addr)) {
return addr;
}
// 2) Try converting from base16
try {
const wasmAddr = RustModule.WalletV4.Address.from_bytes(
Buffer.from(addr, 'hex')
);
const byronAddr = RustModule.WalletV4.ByronAddress.from_address(wasmAddr);
if (byronAddr) return byronAddr.to_base58();
return undefined; // wrong address kind
} catch (_e) {} // eslint-disable-line no-empty
// 3) Try converting from base32
try {
const wasmAddr = RustModule.WalletV4.Address.from_bech32(addr);
const byronAddr = RustModule.WalletV4.ByronAddress.from_address(wasmAddr);
if (byronAddr) return byronAddr.to_base58();
return undefined; // wrong address kind
} catch (_e) {} // eslint-disable-line no-empty
return undefined;
}
export function normalizeToAddress(
addr: string
): void | RustModule.WalletV4.Address {
// in Shelley, addresses can be base16, bech32 or base58
// this function, we try parsing in all encodings possible
// 1) Try converting from base58
if (RustModule.WalletV4.ByronAddress.is_valid(addr)) {
return RustModule.WalletV4.ByronAddress.from_base58(addr).to_address();
}
// 2) If already base16, simply return
try {
return RustModule.WalletV4.Address.from_bytes(
Buffer.from(addr, 'hex')
);
} catch (_e) {} // eslint-disable-line no-empty
// 3) Try converting from base32
try {
return RustModule.WalletV4.Address.from_bech32(addr);
} catch (_e) {} // eslint-disable-line no-empty
return undefined;
}
export function isJormungandrAddress(
kind: CoreAddressT
): boolean {
// note: excluding legacy byron addresses
if (kind === CoreAddressTypes.JORMUNGANDR_SINGLE) return true;
if (kind === CoreAddressTypes.JORMUNGANDR_GROUP) return true;
if (kind === CoreAddressTypes.JORMUNGANDR_ACCOUNT) return true;
if (kind === CoreAddressTypes.JORMUNGANDR_MULTISIG) return true;
return false;
}
export function isErgoAddress(
kind: CoreAddressT
): boolean {
if (kind === CoreAddressTypes.ERGO_P2PK) return true;
if (kind === CoreAddressTypes.ERGO_P2SH) return true;
if (kind === CoreAddressTypes.ERGO_P2S) return true;
return false;
}
export function toEnterprise(
address: string
): (void | RustModule.WalletV4.EnterpriseAddress) {
if (RustModule.WalletV4.ByronAddress.is_valid(address)) {
return undefined;
}
const wasmAddr = RustModule.WalletV4.Address.from_bytes(
Buffer.from(address, 'hex')
);
const spendingKey = getCardanoSpendingKeyHash(wasmAddr);
if (spendingKey == null) return undefined;
const singleAddr = RustModule.WalletV4.EnterpriseAddress.new(
wasmAddr.network_id(),
RustModule.WalletV4.StakeCredential.from_keyhash(
spendingKey
),
);
return singleAddr;
}
export function isCardanoHaskellAddress(
kind: CoreAddressT
): boolean {
if (kind === CoreAddressTypes.CARDANO_LEGACY) return true;
if (kind === CoreAddressTypes.CARDANO_BASE) return true;
if (kind === CoreAddressTypes.CARDANO_PTR) return true;
if (kind === CoreAddressTypes.CARDANO_ENTERPRISE) return true;
if (kind === CoreAddressTypes.CARDANO_REWARD) return true;
return false;
}
export function getCardanoSpendingKeyHash(
addr: RustModule.WalletV4.Address,
): (
// null -> legacy address (no key hash)
// undefined -> script hash instead of key hash
RustModule.WalletV4.Ed25519KeyHash | null | void
) {
{
const byronAddr = RustModule.WalletV4.ByronAddress.from_address(addr);
if (byronAddr) return null;
}
{
const baseAddr = RustModule.WalletV4.BaseAddress.from_address(addr);
if (baseAddr) return baseAddr.payment_cred().to_keyhash();
}
{
const ptrAddr = RustModule.WalletV4.PointerAddress.from_address(addr);
if (ptrAddr) return ptrAddr.payment_cred().to_keyhash();
}
{
const enterpriseAddr = RustModule.WalletV4.EnterpriseAddress.from_address(addr);
if (enterpriseAddr) return enterpriseAddr.payment_cred().to_keyhash();
}
{
const rewardAddr = RustModule.WalletV4.RewardAddress.from_address(addr);
if (rewardAddr) return rewardAddr.payment_cred().to_keyhash();
}
throw new Error(`${nameof(getCardanoSpendingKeyHash)} unknown address type`);
}
export function getJormungandrSpendingKey(
addr: RustModule.WalletV3.Address,
): (
// null -> legacy address (no key hash)
RustModule.WalletV3.PublicKey | null
) {
{
const groupAddr = addr.to_group_address();
if (groupAddr) return groupAddr.get_spending_key();
}
{
const multisig = addr.to_multisig_address();
if (multisig) throw new Error(`${nameof(getJormungandrSpendingKey)} multisig not supported`);
}
{
const singleAddr = addr.to_single_address();
if (singleAddr) return singleAddr.get_spending_key();
}
{
const accountAddr = addr.to_account_address();
if (accountAddr) return accountAddr.get_account_key();
}
throw new Error(`${nameof(getJormungandrSpendingKey)} unknown address type`);
}
export function addressToDisplayString(
address: string,
network: $ReadOnly<NetworkRow>,
): string {
try {
if (isJormungandr(network)) {
// Need to try parsing as a legacy address first
// Since parsing as bech32 directly may give a wrong result if the address contains a 1
if (RustModule.WalletV4.ByronAddress.is_valid(address)) {
return address;
}
const wasmAddr = RustModule.WalletV3.Address.from_bytes(
Buffer.from(address, 'hex')
);
return wasmAddr.to_string(Bech32Prefix.ADDRESS);
}
if (isCardanoHaskell(network)) {
// Need to try parsing as a legacy address first
// Since parsing as bech32 directly may give a wrong result if the address contains a 1
if (RustModule.WalletV4.ByronAddress.is_valid(address)) {
return address;
}
const wasmAddr = RustModule.WalletV4.Address.from_bytes(
Buffer.from(address, 'hex')
);
const byronAddr = RustModule.WalletV4.ByronAddress.from_address(wasmAddr);
if (byronAddr == null) {
return wasmAddr.to_bech32();
}
return byronAddr.to_base58();
}
if (isErgo(network)) {
const ergoAddr = RustModule.SigmaRust.NetworkAddress.from_bytes(
Buffer.from(address, 'hex')
);
return ergoAddr.to_base58();
}
throw new Error(`${nameof(addressToDisplayString)} not implemented for network ${network.NetworkId}`);
} catch (_e2) {
throw new Error(`${nameof(addressToDisplayString)} failed to parse address type ` + address);
}
}
// need to format shelley addresses as base16 but only legacy addresses as base58
export function toHexOrBase58(
address: RustModule.WalletV4.Address,
): string {
const asByron = RustModule.WalletV4.ByronAddress.from_address(address);
if (asByron == null) {
return Buffer.from(address.to_bytes()).toString('hex');
}
return asByron.to_base58();
}
export function getAddressPayload(
address: string,
network: $ReadOnly<NetworkRow>,
): string {
try {
if (isJormungandr(network)) {
// Need to try parsing as a legacy address first
// Since parsing as bech32 directly may give a wrong result if the address contains a 1
if (RustModule.WalletV4.ByronAddress.is_valid(address)) {
return address;
}
return Buffer.from(
// bech32
RustModule.WalletV3.Address.from_string(address).as_bytes()
).toString('hex');
}
if (isCardanoHaskell(network)) {
// Need to try parsing as a legacy address first
// Since parsing as bech32 directly may give a wrong result if the address contains a 1
if (RustModule.WalletV4.ByronAddress.is_valid(address)) {
return address;
}
const wasmAddr = RustModule.WalletV4.Address.from_bech32(address);
const byronAddr = RustModule.WalletV4.ByronAddress.from_address(wasmAddr);
if (byronAddr == null) {
return Buffer.from(wasmAddr.to_bytes()).toString('hex');
}
return byronAddr.to_base58();
}
if (isErgo(network)) {
const ergoAddr = RustModule.SigmaRust.NetworkAddress.from_base58(address);
return Buffer.from(ergoAddr.to_bytes()).toString('hex');
}
throw new Error(`${nameof(getAddressPayload)} not implemented for network ${network.NetworkId}`);
} catch (_e2) {
throw new Error(`${nameof(getAddressPayload)} failed to parse address type ` + address);
}
}
export function unwrapStakingKey(
stakingAddress: string,
): RustModule.WalletV4.StakeCredential {
const accountAddress =
RustModule.WalletV4.RewardAddress.from_address(
RustModule.WalletV4.Address.from_bytes(
Buffer.from(stakingAddress, 'hex')
)
);
if (accountAddress == null) {
throw new Error(`${nameof(unwrapStakingKey)} staking key invalid`);
}
const stakingKey = accountAddress.payment_cred();
return stakingKey;
}