Search code examples
node.jscryptographybitcoin

How get btc address from public key in node js


I apologize for my English!

How decode hex public key from BTC signature script to string address in node js?

For example I have the follow hex public key:

03745AAAF364030720B2D14DE50A3310EEF521C91E36353DCA20813713535C005A

after decoding I should get corresponding bitcoin address as

1GNXpcYzasmmXvM4rNgkvZ5SzXgL4L9Ch6

In https://bitcoin.stackexchange.com/questions/71867/decoding-scriptsig was question about decoding ScriptSig of btc transactions and there was the follow fragment:

...
21: OP_DATA_0x21:        compressed pub key (33 Bytes)
    03745AAAF3640307:20B2D14DE50A3310:EEF521C91E36353D:CA20813713535C00:5A
    This is MultiSig's compressed Public Key (X9.63 form)
    corresponding bitcoin address is:    1GNXpcYzasmmXvM4rNgkvZ5SzXgL4L9Ch6
...

In accordance with this question btc public key is encoded in ANSI X9.63 format.

Do nodejs have ways to decode ANSI X9.63 format?

Thank you very much!


Solution

  • I found the answer. For it can use bitcoinjs-lib and payments module:

    var bitcoin = require('bitcoinjs-lib');
    
    const pubKey = "03745AAAF364030720B2D14DE50A3310EEF521C91E36353DCA20813713535C005A";
    
    const { address } = bitcoin.payments.p2pkh({ pubkey: new Buffer(pubKey, 'hex') });
    
    console.log(address); //1GNXpcYzasmmXvM4rNgkvZ5SzXgL4L9Ch6