-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathaddress_utils.dart
More file actions
504 lines (451 loc) · 15.2 KB
/
address_utils.dart
File metadata and controls
504 lines (451 loc) · 15.2 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
/*
* This file is part of Stack Wallet.
*
* Copyright (c) 2023 Cypher Stack
* All Rights Reserved.
* The code is distributed under GPLv3 license, see LICENSE file for details.
* Generated by Cypher Stack on 2023-05-26
*
*/
import 'dart:convert';
import '../app_config.dart';
import '../wallets/crypto_currency/crypto_currency.dart';
import 'logger.dart';
class AddressUtils {
static final Set<String> recognizedParams = {
'amount',
'label',
'message',
'tx_amount', // For Monero/Wownero.
'tx_payment_id',
'recipient_name',
'tx_description',
// TODO [prio=med]: Add more recognized params for other coins.
};
static String condenseAddress(String address) {
if (address.length < 10) return address;
return '${address.substring(0, 5)}...${address.substring(address.length - 5)}';
}
/// Return only recognized parameters.
static Map<String, String> _filterParams(Map<String, String> params) {
return Map.fromEntries(
params.entries.where(
(entry) => recognizedParams.contains(entry.key.toLowerCase()),
),
);
}
/// Parses a URI string and returns a map with parsed components.
static Map<String, String> _parseUri(String uri) {
final Map<String, String> result = {};
try {
final u = Uri.parse(uri);
if (u.hasScheme) {
result["scheme"] = u.scheme.toLowerCase();
// Handle different URI formats.
if (result["scheme"] == "bitcoin" ||
result["scheme"] == "bitcoincash") {
result["address"] = u.path;
} else if (result["scheme"] == "monero") {
// Monero addresses can contain '?' which Uri.parse interprets as query start.
final addressEnd = uri.indexOf(
'?',
7,
); // 7 is the length of "monero:".
if (addressEnd != -1) {
result["address"] = uri.substring(7, addressEnd);
} else {
result["address"] = uri.substring(7);
}
} else {
// Default case, treat path as address.
result["address"] = u.path;
}
// Parse query parameters.
result.addAll(_parseQueryParameters(u.queryParameters));
// Handle Monero-specific fragment (tx_description).
if (u.fragment.isNotEmpty && result["scheme"] == "monero") {
result["tx_description"] = Uri.decodeComponent(u.fragment);
}
}
} catch (e, s) {
Logging.instance.d(
"Exception caught in parseUri($uri): $e",
error: e,
stackTrace: s,
);
}
return result;
}
/// Strips surrounding single or double quotes from a string.
static String _stripQuotes(String value) {
if (value.length >= 2 &&
((value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'")))) {
return value.substring(1, value.length - 1);
}
return value;
}
/// Helper method to parse and normalize query parameters.
///
/// Keys are lowercased and dashes are replaced with underscores so that
/// e.g. `spend-key` and `spend_key` are treated identically.
/// Surrounding quotation marks on values are stripped.
static Map<String, String> _parseQueryParameters(Map<String, String> params) {
final Map<String, String> result = {};
params.forEach((key, value) {
// Normalize: lowercase + dashes → underscores.
final normalizedKey = key.toLowerCase().replaceAll('-', '_');
final strippedValue = _stripQuotes(value);
if (recognizedParams.contains(normalizedKey)) {
switch (normalizedKey) {
case 'amount':
case 'tx_amount':
result['amount'] = _normalizeAmount(strippedValue);
break;
case 'label':
case 'recipient_name':
result['label'] = Uri.decodeComponent(strippedValue);
break;
case 'message':
case 'tx_description':
result['message'] = Uri.decodeComponent(strippedValue);
break;
case 'tx_payment_id':
result['tx_payment_id'] = Uri.decodeComponent(strippedValue);
break;
default:
result[normalizedKey] = Uri.decodeComponent(strippedValue);
}
} else {
// Include unrecognized parameters with normalized key.
result[normalizedKey] = Uri.decodeComponent(strippedValue);
}
});
return result;
}
/// Normalizes amount value to a standard format.
static String _normalizeAmount(String amount) {
// Remove any non-numeric characters except for '.'
final sanitized = amount.replaceAll(RegExp(r'[^\d.]'), '');
// Ensure only one decimal point
final parts = sanitized.split('.');
if (parts.length > 2) {
return '${parts[0]}.${parts.sublist(1).join()}';
}
return sanitized;
}
/// Centralized method to handle various cryptocurrency URIs and return a common object.
///
/// Returns null on failure to parse
static PaymentUriData? parsePaymentUri(String uri, {Logging? logging}) {
// hacky check its not just a bcash, ecash, or xel address
final parts = uri.split(":");
if (parts.length == 2) {
if ([
"xel",
"bitcoincash",
"bchtest",
"ecash",
"ectest",
].contains(parts.first.toLowerCase())) {
return null;
}
}
try {
final Map<String, String> parsedData = _parseUri(uri);
// Normalize the URI scheme.
final String scheme = parsedData['scheme'] ?? '';
parsedData.remove('scheme');
// Filter out unrecognized parameters.
final filteredParams = _filterParams(parsedData);
return PaymentUriData(
scheme: scheme,
address: parsedData['address']!.trim(),
amount: filteredParams['amount'] ?? filteredParams['tx_amount'],
label: filteredParams['label'] ?? filteredParams['recipient_name'],
message: filteredParams['message'] ?? filteredParams['tx_description'],
paymentId: filteredParams['tx_payment_id'],
// Specific to Monero
additionalParams: filteredParams,
);
} catch (e, s) {
logging?.i("Invalid payment URI: $uri", error: e, stackTrace: s);
return null;
}
}
/// Parses a wallet URI and returns a Map.
///
/// Returns null on failure to parse.
static Map<String, dynamic>? _parseWalletUri(String uri) {
final String scheme;
final Map<String, dynamic> parsedData = {};
final rawScheme = uri.split(":")[0];
final normalizedScheme = rawScheme.replaceAll("-", "_");
if (normalizedScheme != rawScheme) {
uri = normalizedScheme + uri.substring(rawScheme.length);
}
if (uri.split(":")[0].contains("_")) {
// We need to check if the uri is compatible because RFC 3986
// does not allow underscores in the scheme.
final String compatibleUri = uri.replaceFirst("_", "");
scheme = uri.split(":")[0];
parsedData.addAll(_parseUri(compatibleUri));
} else {
parsedData.addAll(_parseUri(uri));
scheme = parsedData['scheme'] as String? ?? '';
}
// not sure this is the best way to handle this but will leave
// as is for now
final possibleCoins = AppConfig.coins.where(
(e) => "${e.uriScheme}_wallet".contains(scheme),
);
if (possibleCoins.length != 1) {
return null;
}
parsedData["coin"] = possibleCoins.first;
return parsedData;
}
/// Builds a uri string with the given address and query parameters (if any)
static String buildUriString(
String scheme,
String address,
Map<String, String> params,
) {
// Filter unrecognized parameters.
final filteredParams = _filterParams(params);
String uriString;
// cashaddrs strike again
if (address.startsWith("$scheme:")) {
uriString = address;
} else {
uriString = "$scheme:$address";
}
if (scheme.toLowerCase() == "monero") {
// Handle Monero-specific formatting.
if (filteredParams.containsKey("tx_description")) {
final description = filteredParams.remove("tx_description")!;
if (filteredParams.isNotEmpty) {
uriString += Uri(queryParameters: filteredParams).toString();
}
uriString += "#${Uri.encodeComponent(description)}";
} else if (filteredParams.isNotEmpty) {
uriString += Uri(queryParameters: filteredParams).toString();
}
} else {
// General case for other cryptocurrencies.
if (filteredParams.isNotEmpty) {
uriString += Uri(queryParameters: filteredParams).toString();
}
}
return uriString;
}
/// returns empty if bad data
static Map<String, dynamic> decodeQRSeedData(String data) {
Map<String, dynamic> result = {};
try {
result = Map<String, dynamic>.from(jsonDecode(data) as Map);
} catch (e, s) {
Logging.instance.d(
"Exception caught in parseQRSeedData($data)",
error: e,
stackTrace: s,
);
}
return result;
}
/// encode mnemonic words to qrcode formatted string
static String encodeQRSeedData(List<String> words) {
return jsonEncode({"mnemonic": words});
}
/// Method to get CryptoCurrency based on URI scheme.
static CryptoCurrency? _getCryptoCurrencyByScheme(String scheme) {
if (AppConfig.coins.map((e) => e.uriScheme).toSet().contains(scheme)) {
return AppConfig.coins.firstWhere((e) => e.uriScheme == scheme);
} else {
return null;
// throw UnsupportedError('Unsupported URI scheme: $scheme');
}
}
/// Formats an address string to remove any unnecessary prefixes or suffixes.
String formatEpicCashAddress(String epicAddress) {
// strip http:// or https:// prefixes if the address contains an @ symbol (and is thus an epicbox address)
if ((epicAddress.startsWith("http://") ||
epicAddress.startsWith("https://")) &&
epicAddress.contains("@")) {
epicAddress = epicAddress.replaceAll("http://", "");
epicAddress = epicAddress.replaceAll("https://", "");
}
// strip mailto: prefix
if (epicAddress.startsWith("mailto:")) {
epicAddress = epicAddress.replaceAll("mailto:", "");
}
// strip / suffix if the address contains an @ symbol (and is thus an epicbox address)
if (epicAddress.endsWith("/") && epicAddress.contains("@")) {
epicAddress = epicAddress.substring(0, epicAddress.length - 1);
}
return epicAddress;
}
/// Formats an address string to remove any unnecessary prefixes or suffixes.
String formatAddressMwc(String mimblewimblecoinAddress) {
// strip http:// or https:// prefixes if the address contains an @ symbol (and is thus an mwcmqs address)
if ((mimblewimblecoinAddress.startsWith("http://") ||
mimblewimblecoinAddress.startsWith("https://")) &&
mimblewimblecoinAddress.contains("@")) {
mimblewimblecoinAddress =
mimblewimblecoinAddress.replaceAll("http://", "");
mimblewimblecoinAddress =
mimblewimblecoinAddress.replaceAll("https://", "");
}
// strip mailto: prefix
if (mimblewimblecoinAddress.startsWith("mailto:")) {
mimblewimblecoinAddress =
mimblewimblecoinAddress.replaceAll("mailto:", "");
}
// strip / suffix if the address contains an @ symbol (and is thus an mwcmqs address)
if (mimblewimblecoinAddress.endsWith("/") &&
mimblewimblecoinAddress.contains("@")) {
mimblewimblecoinAddress = mimblewimblecoinAddress.substring(
0, mimblewimblecoinAddress.length - 1);
}
return mimblewimblecoinAddress;
}
}
class PaymentUriData {
final String address;
final String? scheme;
final String? amount;
final String? label;
final String? message;
final String? paymentId; // Specific to Monero.
final Map<String, String> additionalParams;
CryptoCurrency? get coin => AddressUtils._getCryptoCurrencyByScheme(
scheme ?? "", // empty will just return null
);
PaymentUriData({
required this.address,
this.scheme,
this.amount,
this.label,
this.message,
this.paymentId,
required this.additionalParams,
});
@override
String toString() =>
"PaymentUriData { "
"coin: $coin, "
"address: $address, "
"amount: $amount, "
"scheme: $scheme, "
"label: $label, "
"message: $message, "
"paymentId: $paymentId, "
"additionalParams: $additionalParams"
" }";
}
class WalletUriData {
final CryptoCurrency coin;
final String? address;
final String? seed;
final String? spendKey;
final String? viewKey;
final int? height;
final List<String>? txids;
bool get isViewOnly => spendKey == null && seed == null;
WalletUriData({
required this.coin,
this.address,
this.seed,
this.spendKey,
this.viewKey,
this.height,
this.txids,
});
factory WalletUriData.fromUriString(String uri) {
final map = AddressUtils._parseWalletUri(uri);
if (map == null) {
throw Exception("Invalid wallet URI");
}
return WalletUriData.fromJson(map, map["coin"] as CryptoCurrency);
}
/// Factory constructor with validation logic according to the spec:
/// https://github.com/monero-project/monero/wiki/URI-Formatting#wallet-definition-scheme
factory WalletUriData.fromJson(
Map<String, dynamic> json,
CryptoCurrency coin,
) {
final address = json["address"] as String?;
final spendKey = json["spend_key"] as String?;
final viewKey = json["view_key"] as String?;
final seed = json["seed"] as String?;
final height = json["height"] != null
? int.tryParse(json["height"].toString())
: null;
final txid = json["txid"] as String?;
// Must have seed XOR view_key (spend_key is optional).
// May have seed only, view_key + spend_key, or view_key only.
final hasSeed = seed != null;
final hasKeys = viewKey != null;
if (hasSeed && hasKeys) {
throw const FormatException(
"Invalid: cannot specify both seed and keys.",
);
}
if (!hasSeed && !hasKeys) {
throw const FormatException(
"Invalid: must specify either seed or view_key.",
);
}
// Spend_key requires view_key.
if (spendKey != null && viewKey == null) {
throw const FormatException("Invalid: spend_key requires view_key.");
}
// Height requires absence of txid.
if (height != null && txid != null) {
throw const FormatException(
"Invalid: cannot specify both height and txid.",
);
}
// Parse txids if present.
List<String>? txids;
if (txid != null && txid.isNotEmpty) {
txids = txid
.split(";")
.map((s) => s.trim())
.where((s) => s.isNotEmpty)
.toList();
}
return WalletUriData(
coin: coin,
address: address,
spendKey: spendKey,
viewKey: viewKey,
seed: seed,
height: height,
txids: txids,
);
}
@override
String toString() {
return "WalletUriData { "
"coin: $coin, "
"address: $address, "
"seed: $seed, "
"spendKey: $spendKey, "
"viewKey: $viewKey, "
"height: $height, "
"txids: $txids"
" }";
}
String toJson() {
return jsonEncode({
"coin": coin.prettyName,
"address": address,
"seed": seed,
"spendKey": spendKey,
"viewKey": viewKey,
"height": height,
"txids": txids,
});
}
}