'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 1:[1]
You must have node and npm downloaded on your computer.
npm install bitcoinjs-lib
Download bitcoinjs library from your node terminal.
var bitcoin = require("bitcoinjs-lib")
Require bitcoinjs-lib.
var keyPair = bitcoin.ECPair.makeRandom(); or var keyPair = "03745AAAF364030720B2D14DE50A3310EEF521C91E36353DCA20813713535C005A"
Make variable for keyPair.
console.log(keyPair.getAddress());
Test address by logging address to console. A valid bitcoin address should be returned.
var address = keyPair.getAddress();
Save bitcoin address result to a variable.
console.log(keyPair.toWif());
Test private key by logging to console. A valid bitcoin private key should be returned.
var pkey = keyPair.toWIF();
Save bitcoin private key result to a variable.
Solution 2:[2]
Bitcoin uses "Elliptic Curve Digital Signature Algorithm", therefore I use https://www.npmjs.com/package/elliptic
import EC from "elliptic";
// use a prime number to generate the curve. that p i 256 bits.
// ec works better with hashed values. we always hash the data.
const ec = new EC.ec("secp256k1");
create public key
const keyPair = ec.genKeyPair();
// ec returns x,y points of elliptic curve. so we convert it to hex.
const publicKey = keyPair.getPublic().encode("hex");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Putti |
| Solution 2 | Yilmaz |
