Decrypting Raw ScriptOutput: Extracting ScriptPubKey
When receiving transactions from Bitcoin Core using zeroMQ, you are likely dealing with raw script output in JSON format. The script
field contains a serialized version of a Bitcoin script, which is what we need to extract the scriptPubKey
. This type represents the public key that can be used for digital signatures and other cryptographic operations.
In this article, we will walk through how to retrieve the scriptpubkey (the actual bytes representing the public key) from the raw script output.
Understanding Bitcoin ScriptFormat
Before we dive into the code, let’s quickly review the format of a Bitcoin script. The “script” field in Bitcoin Core transactions typically consists of a serialized version of the following:
OP_DUP
: duplicates the current operand (in this case, the value)
OP_P2PKH
: specifies that we are dealing with private keys
OP_D2SH
: converts the script to a human-readable format
- …and so on
The raw script output typically looks like this:
{ value: 200000,
script: }
Decoding ScriptOutput
To extractscriptPubKey, you need to we decode the raw script output. We can use the following Python code snippet as an example:
“python
import json
def extract_scriptpubkey(script_output):
Split the script into individual elements
elements = script_output[‘script’].split(‘\x00’)
Initialize the scriptpubkey variable
script_pubkey = None
Iterate through each element and try to decode it as a script signature
for element in elements:
if element.startswith(‘OP_DUP’):
Extract the value of the duplicate operand (the input)
value = int.from_bytes(element[7:9], byteorder=’big’)
Check if this is an OP_P2PKH instruction with a private key signature
if “P2SH” in element and “OP_01” in element:
Extract the public key from the input (assuming 1-based indexing)
public_key = int.from_bytes(element[9:16], byteorder=’big’)
Set the scriptpubkey variable with the extracted public key
if scriptpubkey is None:
scriptpubkey = bytes([public_key])
else:
scriptpubkey += bytes([public_key])
elif “P2SH” in element and “OP_01” in element:
Extract the public key from the input (assuming it is a 1-based indexing)
public_key = int.from_bytes(element[9:16], byteorder=’big’)
Set the scriptpubkey variable with an inactive value for the OP_DUP statement
if scriptpubkey is None:
scriptpubkey = bytes([public_key])
else:
scriptpubkey += bytes([public_key])
elif “OP_01” in element:
Extract the public key from the input (assuming it is a 1-based indexing)
public_key = int.from_bytes(element[8:16], byteorder=’big’)
Set the scriptpubkey variable to an inactive value for the OP_DUP statement
if script_pubkey is None:
script_pubkey = bytes([public_key])
else:
script_pubkey += bytes([public_key])
return script_pubkey
Usage example
script_output = json.loads(‘{“value”: 200000, “script”: “ script_pubkey = extract_scriptpubkey(script_output)
print(script_pubkey.