bitcoin core – How to get scriptPubKey from public key hash


Clarification on what is the difference between these things: public key hash, scriptPubKey, addresses.

Public key hash represents, as it name says, the hash of the public key. So you take the public key and first do SHA256 hash function on it, and then RIPEMD160.

scriptPubKey represents a locking script that you use to lock satoshis. To unlock them, you must provide a valid unlocking script, also known as scriptSig.

Addresses does not actually exist in Bitcoin protocol. They are just called like that in Blockchain explorer to simplify Bitcoin protocol for end users. Addresses actually represent just a hash of the public key, nothing else (in case of P2PKH). It is worth mentioning that they are more often represented in some encoded form like Bech32 or Base58check.

Implementable steps to get the scriptPubKey

There are no implementable steps to get the scriptPubKey. You can lock your satoshis the way you want. You just need to take care that you are using valid opcodes and that your locking logic is valid since if it is not, you won’t be able to unlock funds. There are some standard ways to create this locking script like P2PKH, P2SH etc.

I realise that using this hash of the public key, I can send transactions directly to it and treat it as an address and some explorer calls it address, how is that possible?

It is the one of the standard scriptPubKey, where you lock your funds to hash of the public key. It is called P2PKH.

Resource recommendation to go further in the understanding.

Master Bitcoin book (Andreas Antonopolus), Grokking Bitcoin, Programming Bitcoin (Jimmy Song).

All the mentioned books take you in detail through how to create scripts and how bitcoin works in general. They are worth reading and will give you answers to many questions, including the one you asked.

I believe by reverting this process, I could get the public key and generate an address and get the scriptPubKey from the address, but I believe there can be better way to do it.

You can’t revert hashing. Hash functions are one way functions. However, you do not even need to revert it. Since the hash of the public key represents address, you are creating scriptPubKey using it, not directly public key.



Source link

Author

Leave a Comment