|
| 1 | +import 'dart:typed_data'; |
| 2 | + |
| 3 | +import 'package:blockchain_utils/blockchain_utils.dart'; |
| 4 | + |
| 5 | +String convertXpubToZpub(final String xpub) { |
| 6 | + try { |
| 7 | + final decoded = Base58Decoder.checkDecode(xpub); |
| 8 | + |
| 9 | + if (decoded.length < 4) { |
| 10 | + throw ArgumentError('Invalid extended public key length'); |
| 11 | + } |
| 12 | + |
| 13 | + final versionBytes = decoded.sublist(0, 4); |
| 14 | + final xpubVersionBytes = [0x04, 0x88, 0xb2, 0x1e]; // xpub mainnet version |
| 15 | + final tpubVersionBytes = [0x04, 0x35, 0x87, 0xcf]; // tpub testnet version |
| 16 | + |
| 17 | + final bool isXpub = listEquals(versionBytes, xpubVersionBytes); |
| 18 | + final bool isTpub = listEquals(versionBytes, tpubVersionBytes); |
| 19 | + |
| 20 | + if (!isXpub && !isTpub) { |
| 21 | + return xpub; |
| 22 | + } |
| 23 | + |
| 24 | + final zpubVersionBytes = isXpub |
| 25 | + ? [0x04, 0xb2, 0x47, 0x46] |
| 26 | + : // zpub mainnet |
| 27 | + [0x04, 0x5f, 0x1c, 0xf6]; // vpub testnet |
| 28 | + |
| 29 | + final newExtendedKey = Uint8List.fromList([ |
| 30 | + ...zpubVersionBytes, |
| 31 | + ...decoded.sublist(4), |
| 32 | + ]); |
| 33 | + |
| 34 | + return Base58Encoder.checkEncode(newExtendedKey); |
| 35 | + } catch (e) { |
| 36 | + throw ArgumentError('Failed to convert xpub to zpub: $e'); |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +bool listEquals<T>(final List<T> a, final List<T> b) { |
| 41 | + if (a.length != b.length) return false; |
| 42 | + for (var i = 0; i < a.length; i++) { |
| 43 | + if (a[i] != b[i]) return false; |
| 44 | + } |
| 45 | + return true; |
| 46 | +} |
0 commit comments