|
| 1 | +import { CommandModule } from 'yargs'; |
| 2 | +import * as utxolib from '@bitgo/utxo-lib'; |
| 3 | +import { getNamedDescriptorsForRootWalletKeys } from '@bitgo/utxo-core/descriptor'; |
| 4 | + |
| 5 | +import { |
| 6 | + FormatTreeOrJson, |
| 7 | + formatTreeOrJson, |
| 8 | + getNetworkOptionsDemand, |
| 9 | + getRootWalletKeys, |
| 10 | + keyOptions, |
| 11 | + KeyOptions, |
| 12 | +} from '../../args'; |
| 13 | +import { formatObjAsTree } from '../../format'; |
| 14 | + |
| 15 | +type Triple<T> = [T, T, T]; |
| 16 | + |
| 17 | +type ArgsFixedScriptToDescriptor = KeyOptions & { |
| 18 | + network: utxolib.Network; |
| 19 | + format: FormatTreeOrJson; |
| 20 | +}; |
| 21 | + |
| 22 | +function mapKeyToNetwork(key: utxolib.BIP32Interface, network: utxolib.Network): utxolib.BIP32Interface { |
| 23 | + key = utxolib.bip32.fromBase58(key.toBase58()); |
| 24 | + key.network = network; |
| 25 | + return key; |
| 26 | +} |
| 27 | + |
| 28 | +function mapRootWalletKeysToNetwork( |
| 29 | + rootWalletKeys: utxolib.bitgo.RootWalletKeys, |
| 30 | + network: utxolib.Network |
| 31 | +): utxolib.bitgo.RootWalletKeys { |
| 32 | + return new utxolib.bitgo.RootWalletKeys( |
| 33 | + rootWalletKeys.triple.map((key) => mapKeyToNetwork(key, network)) as Triple<utxolib.BIP32Interface>, |
| 34 | + rootWalletKeys.derivationPrefixes |
| 35 | + ); |
| 36 | +} |
| 37 | + |
| 38 | +export const cmdFromFixedScript: CommandModule<unknown, ArgsFixedScriptToDescriptor> = { |
| 39 | + command: 'fromFixedScript', |
| 40 | + describe: 'Convert BitGo FixedScript RootWalletKeys to output descriptors', |
| 41 | + builder(b) { |
| 42 | + return b.option(getNetworkOptionsDemand('bitcoin')).options(keyOptions).options({ format: formatTreeOrJson }); |
| 43 | + }, |
| 44 | + handler(argv): void { |
| 45 | + let rootWalletKeys = getRootWalletKeys(argv); |
| 46 | + if (argv.network !== utxolib.networks.bitcoin) { |
| 47 | + rootWalletKeys = mapRootWalletKeysToNetwork(rootWalletKeys, argv.network); |
| 48 | + } |
| 49 | + const descriptorMap = getNamedDescriptorsForRootWalletKeys(rootWalletKeys); |
| 50 | + const obj = Object.fromEntries( |
| 51 | + [...descriptorMap].map(([name, descriptor]) => [name, descriptor?.toString() ?? null]) |
| 52 | + ); |
| 53 | + if (argv.format === 'tree') { |
| 54 | + console.log(formatObjAsTree('descriptors', obj)); |
| 55 | + } else if (argv.format === 'json') { |
| 56 | + console.log(JSON.stringify(obj, null, 2)); |
| 57 | + } else { |
| 58 | + throw new Error(`Invalid format: ${argv.format}. Expected 'tree' or 'json'.`); |
| 59 | + } |
| 60 | + }, |
| 61 | +}; |
0 commit comments