-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaddress-converter.js
executable file
·56 lines (48 loc) · 1.44 KB
/
address-converter.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
#!/usr/bin/env node
const { Option, Command } = require("commander");
const program = new Command();
const bitcoin = require("bitcoinjs-lib");
const { BIP32Factory } = require("bip32");
const ecc = require("tiny-secp256k1");
const bip32 = BIP32Factory(ecc);
const { networks } = require("./networks");
program
.addHelpText("before", "converts a given address between networks.")
.requiredOption("-a, --address <address>", "the address to convert")
.addOption(
new Option("-n, --network <network>", "the network to convert to").choices([
"mainnet",
"bitcoin",
"testnet",
"regtest",
])
)
.parse(process.argv);
const options = program.opts();
const convertBech32 = (address, targetNetwork) => {
const decoded = bitcoin.address.fromBech32(address);
const { data } = decoded;
const newAddress = bitcoin.address.toBech32(
data,
decoded.version,
targetNetwork.bech32
);
return newAddress;
};
const convertBase58 = (address, targetNetwork) => {
const decoded = bitcoin.address.fromBase58Check(address);
const { hash } = decoded;
const newAddress = bitcoin.address.toBase58Check(
hash,
targetNetwork.pubKeyHash
);
return newAddress;
};
const targetNetwork = networks[options.network];
let converted;
if (/^(bc|tb)/.test(options.address)) {
converted = convertBech32(options.address, targetNetwork);
} else {
converted = convertBase58(options.address, targetNetwork);
}
console.log(converted);