I have my x (0xca668a8b5f71e8724aada4b5343c28702a481787855cc42228b8fff97fe94d6a) and y (0x19dd3a603a55b3d8c5f62cbe177b9b63693fb8c91d76845bafc843a7aa19ea55) coordinates generated by ecdsa with a private key. But don't know yet how to get the public address from (x,y) coordinates and a compressed bitcoin address ?
1 Answer
This depends largely on which type of address you want to generate. First, you will need to encode your public key into compressed form. This is done by taking the x-coordinate, and prepending 0x02
if the y-coordinate is even, or 0x03
if the y-coordinate is odd.
A legacy P2PKH address (starting with a 1
) is generated by the following process:
- Taking the compressed form of your public key.
- Hash it with SHA-256 and then hash the resulting 256-bit hash with RIPEMD-160 to get a 160-bit hash value. Call this result
hash
. - Prepend the version byte (
0x00
for Bitcoin mainnet - this gives the 1 at the start of the address). So we haveversion || hash
. - Hash
version || hash
twice with SHA-256 and take the first four bytes of the result as a checksum. - Encode
version || hash || checksum
in Bitcoin's Base58 encoding format.
This is described on the bitcoin wiki here.
If you want to create a P2WPKH Bech32 address (starting with bc1
), the process is simpler. The witness version is 0x00
and the witness program is a push of the RIPEMD-160(SHA-256(compressed public key))
hash. To push a 20-byte hash like this, we use 0x14
(which is 20 in hex). So the total scriptPubKey is 0x0014{20-byte hash}
(as described in BIP-141). You then simply encode this scriptPubKey using Bech32 encoding as defined in BIP-173.
There are other types of address too, of course, including P2SH, P2WSH, and P2TR (as well as P2SH wrapped segwit v0 addresses). These all deal with scripts too though, rather than just single keys.