I am creating a block parser and just learned about Scripts in Bitcoin yesterday which is kind of confusing so far. I want to extract the addresses involved in each transaction. Right now, I am able to read the script for each output. To extract the address, am I correct in thinking that my code will need to handle all of the different formats of scriptPubKeys? Is there any sample code out there to guide me? If I am completely wrong, how should I do it?
Yes, to get addresses from scriptPubKeys, you will need to do a pattern match. There are only a small number of address types each with their own fixed scriptPubKey pattern. Keep in mind that not all scriptPubKeys map to an address so you will find scriptPubKeys that have no address and you will need to handle those.
Bitcoin Core has a pattern matcher for going from scriptPubKeys to address types in the
solver function. The
MatchMultisig can be found higher up in that file. The
IsWitnessProgram functions can be found here.
One thing to note about the
solver is that it does not return just address types. Some of the types it returns do not map to addresses. These are TX_NULLDATA, TX_MULTISIG, TX_PUBKEY, and TX_NONSTANDARD.
It may also be useful for you to see how you get the scriptPubKey from an address. Bitcoin Core does it here.