mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:29:40 +00:00
kernel: Add script evaluation tracer #35641
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!35641
Loading…
Reference in a new issue
No description provided.
Delete branch "kernel_script_tracer"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
This adds a callback hook to the kernel library C header for getting the current script evaluation state on each script evaluation step. This can be used for debugging scripts and gives external applications a view into how Bitcoin Core does script evaluation.
The initial sketch for this work was prepared on rust-bitcoinkernel: https://github.com/sedited/rust-bitcoinkernel/tree/feature_script_debug . That branch also includes a very rudimentary script debugger showcasing the use case for this patch. Clankers seems to do a decent job at coding up prototypes for more featureful debuggers, which seems like a fun project to hack on if anybody else wants to give it a try.
This feature is gated behind the ENABLE_SCRIPT_TRACE flag. To compile with the feature enabled, pass
-DENABLE_SCRIPT_TRACE=ON. If the feature is not manually enabled, the trace hooks are stubbed out.The traces are divided into separate frames. RAII is used to guarantee that every script evaluation has at least its start and end state captured. Each instruction generates a unique frame as well.
The ScriptError in the VerifyScript invocation run when calling script_pubkey_verify is added in order to be able to surface the error code in the trace frames.
Another use case could also be using the frames to ensure that the script interpreter is actually doing what we think it is doing during the script tests. This might prevent unit test bugs in the future, i.e. when error conditions shadow actual behaviour, and could also be interesting for fuzzing the script interpreter.
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.
External sites
Reviews
See the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste
<!--meta-tag:bot-skip-->into the comment that the bot should ignore.Conflicts
No conflicts as of last run.
Concept ACK, haven't checked the implementation. But this is something that would benefit testing greatly.
Strong Concept ACK
Does this support multi-threaded applications? If not, do we want it to?
It should be thread-safe, but I don't think this is particularly interesting to run in a multi-threaded context. I was thinking of adding an id to the trace frames, but didn't because I felt like the use case is pretty slim.
I suggest we add something like: "The callback fires once per instruction, after the opcode is decoded and before it is dispatched/executed."
Is this accurate? Couldn't a thread that copied the callback still begin an invocation?
I think it's safe, but the doc comment overpromises if I am not wrong.
Mmh, not sure how to reword this. Can you suggest something?
Maybe:
"Unregistration is not synchronized with callback execution. Pending invocations on other threads may still run to completion after this returns, but no invocations begin thereafter."
What do you think?
Taken.
Taken.
Concept ACK
Do we need a CI job to run with
ENABLE_SCRIPT_TRACE=ON?I think we have to define what each code means. What do you think?
I think we should leave this here - it's fairly straight forward to get the error code header from somewhere. I'll try to open another pull request for exposing the entire error list in the kernel header, since we'd also want to wire it through the script verification function.
I wasn't sure where to put such a job, so I didn't introduce it here. Maybe we can add a kernel-lib-only job that sets it, but not sure if that is worthwhile enough yet.
Could
ScriptTraceScopesnapshot the callback in its constructor? That takes both the mutex acquisition and the std::function copy out of the per-opcode path.Done.
Thanks! Can we rebase, so we can pull in the changes to rust-bitcoinkernel without reverting commits?
Done.
ACK 114e48e968a087f74c1ab611ac2a31a9266812e1
I had some fun and tested this with a clanker.
Added python bindings:
github.com/elmeriniemela/pybitcoinkernel@a3017b277f (diff-203e11f272)Made a visualizer using the traces: https://eniemela.fi/bitcoin/tx/8e2ee13d2a19951c2777bb3a54f0cb69a2f76dae8baa954cd86149ed1138cb6c
FWIW, found no issues :)
I kept playing with this, and one weirdness that I found is that a trace can be invalid, but the related script error code is still OK. My clanker added a condition for this + its own logic to figure out what the real error is:
github.com/elmeriniemela/pybitcoinkernel@f67613ce47/src/pybitcoinkernel/debugger.py (L809)I can reach the if condition above with this command:
I'm not competent enough to say if this is how it should be or not (still learning about bitcoin), but I just thought it might be useful to let you know.
What you are seeing is the intended behaviour here. Your LLM seems to already have inferred the correct scenario from the context. The verification of the full script fails, because the remaining stack element (OP_0) is false.
VerifyScript(which is what we call here), checks this after script evaluation script/interpreter.cpp:2092. The tracer however is limited to theEvalScriptfunction, which does not enforce this final stack condition. This should be communicated by exposing the full script verification error codes when callingbtck_script_pubkey_verify, but as I said here https://github.com/bitcoin/bitcoin/pull/35641#discussion_r3560152977 , I'd prefer doing that in a separate pull request.Perhaps it is better to use an exhaustive switch for
kindandsig_versionas well, in both directions (bitcoinkernel.cppand the C++ wrapper), like the existing enum conversions in the kernel?I noticed kernel is zero-copy where possible for frames (e.g. the stack item bytes are borrowed; only the pointer and size arrays are built per frame), and then the C++ wrapper deep-copies every frame unconditionally. If an owning copy is what consumers need anyway, why not do it in the library instead?
Also, would it make sense to make the frame opaque like other
btck_*types, with getters, instead of a public struct (perhaps an opaque pointer to ashared_ptr, so copying a frame is just a refcount bump)? The C++ wrapper could then use the existingView/Handlepattern.My understanding is that
f_execis only meaningful in step frames, where it says whether the current opcode is about to be evaluated. If so, can we drop the closure and give it a fixed dummy in begin and end frames?ScriptTraceScopelearns the outcome only fromm_error.set_errorinEvalScriptalso communicates through the returned bool, but the end frame only has access to the error object, so a nullm_errormakes a successful eval reportSCRIPT_ERR_UNKNOWN_ERROR. The kernel path always passes&error, but in case any non-kernel callers want to use the tracer, would it make sense to assert it in the ctor?Suggested change
🐙 This pull request conflicts with the target branch and needs rebase.
Concept ACK
Should we clearly comment that user data is destroyed in any case, whether tracing enabled/succeeds or not, to avoid problems like double free?
Should we extend the test to cover this callback replacement contract? For example, register tracer A, then register tracer B, perform a new script evaluation, and verify that only tracer B receives frames.
Nit:
stateis already passed by value here, som_state.emplace_back(state)performs an extra copy of theScriptTraceFrame. Would it make sense to move it instead?m_state.emplace_back(std::move(state));Should we verify unregistering actually stops tracing?
Something like:
BOOST_CHECK_EQUAL(states.size(), 11)is non-fatal, but the test checksstates[0]throughstates[10]after this. So if the size check fails, the test still continues and may access out-of-bound items, resulting in an undefined behavior instead of a clean test failure. Would it make sense to useBOOST_REQUIRE_EQUAL(states.size(), 11)instead?Should we also verify other fields besides
m_kindandm_script_errorto see if the deep-copy conversion works fully correctly? For example, checking at least one STEP frame with a non-empty stack and verifying that stack items are copied correctly would help catch pointer/size conversion bugs (if there's any).Thank you for the review @stringintech and @haanhvu,
Rebased and updated 114e48e968a087f74c1ab611ac2a31a9266812e1 -> 20fb03490d1f38dde67f058acd68e816595d9222 (kernel_script_tracer_0 -> kernel_script_tracer_1, compare)
I don't think this needs an extra comment. To me it seems self-explanatory.
I don't think this matters in a test. Besides, the new type is hardly worth the move now.
I'm not sure if this is still relevant after the last push. In any case, I don't want the tests here to be exhaustive.
Needs a
///@}Add
ScriptTraceUnsetCallback()to avoid the next test case push into a destroyed vector. Test suite currently does not pass with the feature flag.Updated 20fb03490d1f38dde67f058acd68e816595d9222 ->
97462c683d(kernel_script_tracer_1 -> kernel_script_tracer_2, compare)The tracing code assumes
serroris non-null whenever a callback is registered, butEvalScriptpermitsnullptrfor example,CheckSignetBlockSolution()callsVerifyScript()without an error pointer.This triggers the assertion
assert(!m_callback || error);when tracing is enabled.Suggestion:
EvalScriptrejects oversized scripts before constructingScriptTraceScope, so a registered callback receives neitherBEGINnorEND.Moving the size check below scope construction produces:
Non-tracing behavior remains the same.
Suggestion:
Is there a specific reason these need to be function-like macros? Expanding them at their sole call site makes the object lifetime and
Step()call explicit and easier to debug, while the#ifdefsstill prevent argument evaluation when tracing is disabled.The trade-off is some additional preprocessor noise and repetition if more step sites are added, but with only one scope and one
Step()call, this seems worthwhile.Possible version without the tracing helper macros:
Updated
97462c683d->12f4b91477(kernel_script_tracer_2 -> kernel_script_tracer_3, compare)-1as a nullopt. This gets rid of the assertion and has no effect on what gets executed during evaluation.Re https://github.com/bitcoin/bitcoin/pull/35641#issuecomment-5499715130 (adding size check to the evaluation): I don't want to change anything in the interpreter in this pull request. When running through the kernel lib's script verification, the length check will already be caught accurately without going through the tracer, so I don't think much information is lost.
Re https://github.com/bitcoin/bitcoin/pull/35641#issuecomment-5500100550 (swapping function macros with ifdefs): I'd like to keep the lines changed in the interpreter to an absolute minimum. My preference style-wise is the function macros. It's also a pattern that is already used by both the logging and existing trace infrastructure. If other reviewers press on this too, I'll be open to changing it though.
The tracer uses
fExecto indicates whether the current conditional branch is active. But the interpreter needs to process control-flow opcodes even inside inactive branches.For example, in:
OP_0 OP_IF OP_1 OP_ELSE OP_1 OP_ENDIFThe first
OP_1is skipped because the condition is false.OP_ELSEstill executes to activate the else branch, but the tracer incorrectly reported it as skipped becausefExecwas still false before execution.Suggestion:
Updated
12f4b91477->37f3b85710(kernel_script_tracer_3 -> kernel_script_tracer_4, compare)Base:
a773e1e33b349dc819b5a0edc1c7a4839dc73b48Head:
0161ebdbf62cb6357ee4eb8432a900f354aa66a6Findings
Minor
Trace oversized scripts rejected before the scope is created (src/script/interpreter.cpp:448, head)
For BASE and WITNESS_V0, an oversized script returns SCRIPT_ERR_SCRIPT_SIZE before SCRIPT_TRACE_SCOPE is constructed, so the trace receives neither a BEGIN nor an END frame for that evaluation. The C API accepts serialized script bytes and passes the scriptPubKey through VerifyScript to EvalScript without an earlier size check. No current production caller supplying an oversized script was identified, so production impact is unconfirmed.
Suggestions
Document concurrent trace callback invocations (src/kernel/bitcoinkernel.h:2282, head)
ScriptTraceScope snapshots the global callback, and TraceScript invokes that copy outside the registration mutex. Concurrent calls to btck_script_pubkey_verify can therefore invoke the same registered callback simultaneously with the same user_data, and frames from separate evaluations may overlap in a collector. The registration documentation describes replacement and frame lifetime but not this behavior. Document that callbacks and shared user_data must be thread-safe and that consumers should not assume a serialized stream.
Add a release note for the tracing API and build option (src/kernel/bitcoinkernel.h:2291, head)
This adds exported kernel tracing functions and the ENABLE_SCRIPT_TRACE build option, but no PR-specific release note is present. Developer notes call for release notes when a PR changes an API or configuration. Add one describing the tracing API and its opt-in build flag so downstream kernel-library users can discover them.
Review coverage was incomplete.
Review limitations
Full review report
Missing some
BITCOINKERNEL_WARN_UNUSED_RESULTI think.This needs a
BITCOINKERNEL_WARN_UNUSED_RESULTThis needs a
BITCOINKERNEL_WARN_UNUSED_RESULTThis needs a
BITCOINKERNEL_WARN_UNUSED_RESULTUpdated
37f3b85710->e8a8daf3fa(kernel_script_tracer_4 -> kernel_script_tracer_5, compare)BITCOINKERNEL_WARN_UNUSED_RESULT🐙 This pull request conflicts with the target branch and needs rebase.
Rebased
e8a8daf3fa->0161ebdbf6(kernel_script_tracer_5 -> kernel_script_tracer_6, compare)tACK
0161ebdbf6I drove the tracer through the C API over 32,535 spends: legacy, P2SH, P2WSH and tapscript, valid and invalid, with branches not taken,
OP_CODESEPARATOR,OP_SUCCESSxand scripts that fail on their last opcode. I compared each frame with a step trace of a script interpreter I maintain. All 158,683 step frames matched: opcode, position, exec flag, both stacks, op count and code separator position. The 31 spends that differed, 30 in the stack left by a refused tapscript signature check and one in a failing position, were bugs in my interpreter.test_kernelpasses.One cost remains with
ENABLE_SCRIPT_TRACE=ONand no tracer registered. Snapshotting the callback inScriptTraceScope, after alexanderwiederin's comment, took the lock out of the per-opcode path.ScriptTraceGetCallback()still locksg_script_trace_mutexon everyEvalScriptcall, so parallel script checks contend on it. I measured Release builds of the shared library on an Apple M5, as medians of 9 rounds interleaved with the base. Three threads verifying a one-opcode script take 301 ns per input, against 45 ns with the option OFF or on the base. With a signature check in the script the difference is within noise.Could
ScriptTraceGetCallback()read anstd::atomic<bool>, set inScriptTraceRegisterCallback(), before taking the lock? That four-line change brings the case above to 50 ns, andtest_kernelstill passes. I can share the diff and the harness.nit: seems a newline is added here by accident. :)
I see both
VerifyScriptandEvalScriptoverwrite the error withSCRIPT_ERR_UNKNOWN_ERRORfirst thing, so the initial value here doesn't actually matter. But I was wondering if it'd be better to initialize it toSCRIPT_ERR_UNKNOWN_ERRORtoo, for consistency?I think this is left over from when the frame struct was exposed directly in the header, but would it make sense to now keep the field types in
ScriptTraceFramethe same as in the interpreter and only convert in the getters? That would avoid the double cast here, and i think the same applies toopcodeandtapleaf_hash.It could be better to make the documentation format for the getters consistent with the existing API docs, which use separate descriptions for
@param,@return, etc.To find where a failed evaluation went wrong, a consumer currently has to cross-check the end frame's
opcode_posagainst the last step frame's, and then against the error code, since both codes below are also set from inside the loop:SCRIPT_ERR_BAD_OPCODESCRIPT_ERR_UNBALANCED_CONDITIONALOP_ELSE/OP_ENDIFOP_ENDIF(post-loop check, no opcode at fault)The end frame's
opcode_poslooks like a position in every case, but after the loop completes (success or the post-loop check) it is really the opcode count.Would it be simpler to let the end frame answer this directly? Every return inside the loop is a failure at the current
opcode_pos, so the scope only needs to know whether the loop completed, e.g. via a one-lineSCRIPT_TRACE_LOOP_DONE()right after the try/catch. Then the end frame could report:opcode_posis the opcode at which evaluation failed (decoding or executing it)opcode_posis0xFFFFFFFF(no opcode at fault), same convention ascodeseparator_posAnd then for the getter doc:
Going one step further: if the scope keeps a reference to
opcode(as suggested in my other comment), the end frame could also report the opcode at fault, and0when no opcode is at fault (success or post-loop failure). On a decode failureGetScriptOphas already setopcodetoOP_INVALIDOPCODE, so the end frame would report0xffthere.Do we need to keep the
btck_ScriptEvalStackItemopaque type? I'm wondering if we can just have abtck_script_eval_stack_get_item_atthat returns the bytes directly (mirroringbtck_witness_stack_get_item_at)?We seem to be using a mixed pattern for naming the getters for this class and across the whole file - some come with a
Getprefix and some don't like this one; not sure which is more idiomatic, but i think it is good to use one consistently at least for this class.The rest of the wrapper seem to expose hashes as
std::array<std::byte, 32>.Would it make sense to change this to snake_case same as other free functions like
logging_set_min_level,set_mock_time, ...? AlsoScriptTraceUnsetCallbackfor the same reason.(
CheckTransactionseem to be an exception here; also i'm not sure why it didn't follow theBlock::Checkpattern to be a member function)Also, instead of set/unset, can we mirror the C API naming and use register/unregister (or change the C API to use set/unset which seems to be more common in the API)?
Could we hold a reference to
opcodeinScriptTraceScopetoo, like we already do for others?Step()would read it, while Begin and End keep passing0explicitly. And just leavefExecas an argument since it is computed inside the loop.Would the following suggestion reflect the intention more accurately here?
Can we make all fields of
ScriptTraceScopeconst (also ctor parameters), indicating this class would not be modifying them? The scope only reads the interpreter state it references, so the references can beconst&?I think it would be helpful to add a comment here:
@fametrano, from what I understand
ENABLE_SCRIPT_TRACEis only meant for debugging builds, not for production validation, so per-call cost under parallel verification shouldn't be a goal here. I would try to keep the code simple. Maybe we can do a better job at documenting in what context this feature should be used. Do you see a use case for this in production where speed matters?Concept ACK