| 1 | import 'dart:typed_data'; |
| 2 | |
| 3 | import 'package:blockchain_utils/blockchain_utils.dart'; |
| 4 | |
| 5 | String convertAnyToXpub(String any) { |
| 6 | if (any.toLowerCase().startsWith("zpub")) { |
| 7 | return convertZpubToXpub(any); |
| 8 | } else if (any.toLowerCase().startsWith("ltub")) { |
| 9 | return convertLtubToXpub(any); |
| 10 | } |
| 11 | return any; |
| 12 | } |
| 13 | |
| 14 | String convertZpubToXpub(String zpub) { |
| 15 | try { |
| 16 | final decoded = Base58Decoder.checkDecode(zpub); |
| 17 | |
| 18 | if (decoded.length < 4) { |
| 19 | throw ArgumentError('Invalid extended public key length'); |
| 20 | } |
| 21 | |
| 22 | final versionBytes = decoded.sublist(0, 4); |
| 23 | final zpubVersionBytes = [0x04, 0xb2, 0x47, 0x46]; // zpub mainnet version |
| 24 | final zpubTestnetVersionBytes = [0x04, 0x5f, 0x1c, 0xf6]; // vpub testnet version |
| 25 | |
| 26 | bool isZpub = listEquals(versionBytes, zpubVersionBytes); |
| 27 | bool isVpub = listEquals(versionBytes, zpubTestnetVersionBytes); |
| 28 | |
| 29 | if (!isZpub && !isVpub) { |
| 30 | return zpub; |
| 31 | } |
| 32 | |
| 33 | final xpubVersionBytes = isZpub |
| 34 | ? [0x04, 0x88, 0xb2, 0x1e] |
| 35 | : // xpub mainnet |
| 36 | [0x04, 0x35, 0x87, 0xcf]; // tpub testnet |
| 37 | |
| 38 | final newExtendedKey = Uint8List.fromList([ |
| 39 | ...xpubVersionBytes, |
| 40 | ...decoded.sublist(4), |
| 41 | ]); |
| 42 | |
| 43 | return Base58Encoder.checkEncode(newExtendedKey); |
| 44 | } catch (e) { |
| 45 | throw ArgumentError('Failed to convert zpub to xpub: $e'); |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | String convertLtubToXpub(String ltub) { |
| 50 | try { |
| 51 | final decoded = Base58Decoder.checkDecode(ltub); |
| 52 | |
| 53 | if (decoded.length < 4) { |
| 54 | throw ArgumentError('Invalid extended public key length'); |
| 55 | } |
| 56 | |
| 57 | final versionBytes = decoded.sublist(0, 4); |
| 58 | final ltubVersionBytes = [0x01, 0x9D, 0xA4, 0x62]; // Ltub mainnet version |
| 59 | |
| 60 | bool isLtub = listEquals(versionBytes, ltubVersionBytes); |
| 61 | |
| 62 | if (!isLtub) { |
| 63 | return ltub; |
| 64 | } |
| 65 | |
| 66 | final xpubVersionBytes = [0x04, 0x88, 0xb2, 0x1e]; |
| 67 | |
| 68 | final newExtendedKey = Uint8List.fromList([ |
| 69 | ...xpubVersionBytes, |
| 70 | ...decoded.sublist(4), |
| 71 | ]); |
| 72 | |
| 73 | return Base58Encoder.checkEncode(newExtendedKey); |
| 74 | } catch (e) { |
| 75 | throw ArgumentError('Failed to convert ltub to xpub: $e'); |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | bool listEquals<T>(List<T> a, List<T> b) { |
| 80 | if (a.length != b.length) return false; |
| 81 | for (int i = 0; i < a.length; i++) { |
| 82 | if (a[i] != b[i]) return false; |
| 83 | } |
| 84 | return true; |
| 85 | } |