Here is an article that explains what the “non-mandatory-script-verify-flag (Witness program hash mismatch)” error means and why you might see it when trying to send a raw signed transaction via Bitcoinlib:
Error Information: Non-mandatory script verification flag
When sending raw Bitcoin transactions, you need to make sure that all mandatory flags are turned on. One of these mandatory flags is the script-verify
flag, which allows the transaction script (the code that performs various operations on the input) to be verified. However, there is a problem: some scripts rely on the presence of specific hashes from the witness program.
What causes the error?
The “non-mandatory-script-verify-flag (Witness program hash mismatch)” error usually occurs when the script-verify
flag is not turned on in the transaction script. This can happen if your code doesn’t handle witness programs properly, or if there are dependencies between scripts that haven’t been executed.
What does it mean?
When a transaction is submitted, Bitcoin checks several flags to make sure everything is valid and functional. The script-verify
flag is critical to this process because some transactions rely on witness-specific hashes in the script. If these hashes don’t match, the transaction may be rejected.
Simple sample code:
Here is a simple example of how you can create a transaction using Bitcoinlib:
from bitcoinlib.transactions import Output, Key
Create a key for the sendersender_key = Key.from_str("my-sender-key", "hex")
Define the output script (simple example)output_script = "0c6f1d2c6e8b76e42f8..."
Create an input script that relies on a specific hash from the following programinput_script = "0b95fa7f3e4daeb5d34..."
def main():
Create input and output scriptsoutput_output = Output.from_str("0c6f1d2c6e8b76e42f8...", sender_key, "hex", None)
No flags to verify the scriptinput_input = Input.from_str(input_script, sender_key, "hex")
Send the transactiontx_hash = bitcoinlib.utils.hash(output_output)
print(f"Transaction hash: {tx_hash}")
if __name__ == "__main__":
main()
Conclusion
In this example, we created a simple transaction with multiple outputs and inputs. However, when we sent this transaction via Bitcoinlib, an “optional-script-verify-flag (Witness hash mismatch)” error occurred because the script-verify
flag was missing from one of the input scripts.
Best practices:
To avoid similar issues in the future:
- Always include the
script-verify
flag in your transaction script.
- Make sure all witness hashes are present and correct.
- Consider adding dependencies between scripts to minimize the risk of errors.
By following these best practices, you can ensure that your transactions pass verification and avoid receiving error messages like “optional-script-verification-flag (witness hash mismatch)”.