Would you like to clone this notebook?

When you clone a notebook you are able to make changes without affecting the original notebook.

Cancel

CashAddress Encoding, Decoding, and Error Correction

node v10.24.1
version: 1.0.0
endpointsharetweet
const { instantiateSecp256k1, instantiateRipemd160, instantiateSha256, hexToBin, encodeCashAddress, encodeCashAddressFormat, decodeCashAddress, decodeCashAddressFormat, CashAddressType, attemptCashAddressFormatErrorCorrection } = require('bitcoin-ts'); const [secp256k1, sha256, ripemd160] = [await instantiateSecp256k1(), await instantiateSha256(), await instantiateRipemd160()]; // Create an address from a private key const privateKey = hexToBin('f85d4bd8a03ca106c9deb47b791803dac7f0333809e3f1dd04d182e0aba6e553'); const publicKey = secp256k1.derivePublicKeyCompressed(privateKey); const publicKeyHash = ripemd160.hash(sha256.hash(publicKey)); // Encode a P2PKH CashAddress const cashAddress = encodeCashAddress('bchtest', CashAddressType.P2PKH, publicKeyHash); // Decode a CashAddress const cashAddressDecoded = decodeCashAddress('bchtest:qq2azmyyv6dtgczexyalqar70q036yund53jvfde0x'); // Encode a P2PKH SLP Address (uses the CashAddress format) const slpAddress = encodeCashAddressFormat('slptest', 0, publicKeyHash); // Decode an SLP Address (uses the CashAddress format) const slpDecoded = decodeCashAddressFormat('slptest:qq2azmyyv6dtgczexyalqar70q036yund52xtjhwam'); console.log(cashAddress, cashAddressDecoded, slpAddress, slpDecoded); // Fix up to 2 errors in a CashAddress-formatted string const broken = 'bitauth:qwtcxp42fcp06phz2xec6t5krau0ftewxefy50j9xyfxwa38df40zp5xz6t5w'; const result = attemptCashAddressFormatErrorCorrection(broken); console.log(result); // Example prompt to correct a Bitauth ID const pointToCorrections = (c) => Array.from({length: c[c.length - 1]+1}, (_, i) => c.includes(i) ? '^' : '-').join(''); `You entered: ${broken} ${pointToCorrections(result.corrections)} Did you mean: ${result.address}?`
Loading…

no comments

    sign in to comment