kernel: Add script evaluation tracer #35641

Open
sedited wants to merge 1 commit from kernel_script_tracer into master AGit
sedited commented 2026-07-02 15:00:17 +00:00 (Migrated from github.com)

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.

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](https://github.com/bitcoin/bitcoin/pull/33961), and could also be interesting for fuzzing the script interpreter.
DrahtBot commented 2026-07-02 15:00:25 +00:00 (Migrated from github.com)

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.

Type Reviewers
ACK fametrano
Concept ACK furszy, w0xlt, theStack, yuvicc
Approach ACK haanhvu
Stale ACK alexanderwiederin

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.

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/35641 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/35641.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/35641#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | ACK | [fametrano](https://github.com/bitcoin/bitcoin/pull/35641#issuecomment-6397209605) | | Concept ACK | [furszy](https://github.com/bitcoin/bitcoin/pull/35641#issuecomment-4867757550), [w0xlt](https://github.com/bitcoin/bitcoin/pull/35641#issuecomment-4869011143), [theStack](https://github.com/bitcoin/bitcoin/pull/35641#issuecomment-4918882553), [yuvicc](https://github.com/bitcoin/bitcoin/pull/35641#issuecomment-7164384184) | | Approach ACK | [haanhvu](https://github.com/bitcoin/bitcoin/pull/35641#pullrequestreview-4772166308) | | Stale ACK | [alexanderwiederin](https://github.com/bitcoin/bitcoin/pull/35641#pullrequestreview-4701828768) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts No conflicts as of last run. <!--5faf32d7da4f0f540f40219e4f7537a3-->
furszy commented 2026-07-02 16:04:03 +00:00 (Migrated from github.com)

Concept ACK, haven't checked the implementation. But this is something that would benefit testing greatly.

Concept ACK, haven't checked the implementation. But this is something that would benefit testing greatly.
w0xlt commented 2026-07-02 17:57:29 +00:00 (Migrated from github.com)

Strong Concept ACK

Strong Concept ACK
alexanderwiederin commented 2026-07-06 09:31:56 +00:00 (Migrated from github.com)

Does this support multi-threaded applications? If not, do we want it to?

Does this support multi-threaded applications? If not, do we want it to?
sedited commented 2026-07-06 09:37:01 +00:00 (Migrated from github.com)

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.

> 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.
alexanderwiederin (Migrated from github.com) reviewed 2026-07-08 13:09:33 +00:00
Lines 2025-2035
alexanderwiederin (Migrated from github.com) commented 2026-07-08 07:38:48 +00:00

I suggest we add something like: "The callback fires once per instruction, after the opcode is decoded and before it is dispatched/executed."

I suggest we add something like: "The callback fires once per instruction, _after_ the opcode is decoded and _before_ it is dispatched/executed."
Lines 2035-2036
alexanderwiederin (Migrated from github.com) commented 2026-07-08 07:42:30 +00:00

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.

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.
sedited (Migrated from github.com) reviewed 2026-07-08 13:46:46 +00:00
Lines 2035-2036
sedited (Migrated from github.com) commented 2026-07-08 13:46:46 +00:00

Mmh, not sure how to reword this. Can you suggest something?

Mmh, not sure how to reword this. Can you suggest something?
alexanderwiederin (Migrated from github.com) reviewed 2026-07-08 14:20:15 +00:00
Lines 2035-2036
alexanderwiederin (Migrated from github.com) commented 2026-07-08 14:20:15 +00:00

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?

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?
sedited (Migrated from github.com) reviewed 2026-07-08 15:26:48 +00:00
Lines 2035-2036
sedited (Migrated from github.com) commented 2026-07-08 15:26:48 +00:00

Taken.

Taken.
sedited (Migrated from github.com) reviewed 2026-07-08 15:26:57 +00:00
Lines 2027-2039
sedited (Migrated from github.com) commented 2026-07-08 15:26:57 +00:00

Taken.

Taken.
theStack commented 2026-07-08 20:22:44 +00:00 (Migrated from github.com)

Concept ACK

Concept ACK
alexanderwiederin (Migrated from github.com) reviewed 2026-07-10 15:36:10 +00:00
alexanderwiederin (Migrated from github.com) left a comment

Do we need a CI job to run with ENABLE_SCRIPT_TRACE=ON?

Do we need a CI job to run with `ENABLE_SCRIPT_TRACE=ON`?
alexanderwiederin (Migrated from github.com) commented 2026-07-10 15:23:49 +00:00

I think we have to define what each code means. What do you think?

I think we have to define what each code means. What do you think?
sedited (Migrated from github.com) reviewed 2026-07-10 15:40:03 +00:00
sedited (Migrated from github.com) commented 2026-07-10 15:40:03 +00:00

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 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.
sedited commented 2026-07-10 15:42:23 +00:00 (Migrated from github.com)

Do we need a CI job to run with ENABLE_SCRIPT_TRACE=ON?

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.

> Do we need a CI job to run with ENABLE_SCRIPT_TRACE=ON? 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.
alexanderwiederin (Migrated from github.com) reviewed 2026-07-10 16:14:56 +00:00
alexanderwiederin (Migrated from github.com) commented 2026-07-10 16:14:53 +00:00

Could ScriptTraceScope snapshot the callback in its constructor? That takes both the mutex acquisition and the std::function copy out of the per-opcode path.

Could `ScriptTraceScope` snapshot the callback in its constructor? That takes both the mutex acquisition and the std::function copy out of the per-opcode path.
sedited (Migrated from github.com) reviewed 2026-07-13 20:19:54 +00:00
sedited (Migrated from github.com) commented 2026-07-13 20:19:54 +00:00

Done.

Done.
alexanderwiederin commented 2026-07-14 10:32:40 +00:00 (Migrated from github.com)

Thanks! Can we rebase, so we can pull in the changes to rust-bitcoinkernel without reverting commits?

Thanks! Can we rebase, so we can pull in the changes to rust-bitcoinkernel without reverting commits?
sedited commented 2026-07-14 10:47:00 +00:00 (Migrated from github.com)

Thanks! Can we rebase, so we can pull in the changes to rust-bitcoinkernel without reverting commits?

Done.

> Thanks! Can we rebase, so we can pull in the changes to rust-bitcoinkernel without reverting commits? Done.
alexanderwiederin (Migrated from github.com) reviewed 2026-07-15 07:20:05 +00:00
alexanderwiederin (Migrated from github.com) left a comment

ACK 114e48e968a087f74c1ab611ac2a31a9266812e1

ACK 114e48e968a087f74c1ab611ac2a31a9266812e1
elmeriniemela commented 2026-07-22 09:44:23 +00:00 (Migrated from github.com)
I had some fun and tested this with a clanker. Added python bindings: https://github.com/elmeriniemela/pybitcoinkernel/commit/a3017b277fa1f8ca877218869049f8a35233d69e#diff-203e11f27272eb568dbda09906ba8c8aa6718c4816d32310c279cd1e521e35e8 Made a visualizer using the traces: https://eniemela.fi/bitcoin/tx/8e2ee13d2a19951c2777bb3a54f0cb69a2f76dae8baa954cd86149ed1138cb6c FWIW, found no issues :)
elmeriniemela commented 2026-07-24 10:10:25 +00:00 (Migrated from github.com)

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:

$ python scripts/manual_debug.py 02000000013f7cebd65c27431a90bba7f796914fe8cc2ddfc3f2cbd6f7e5f2fc854534da95000000006b483045022100de1ac3bcdfb0332207c4a91f3832bd2c2915840165f876ab47c5f8996b971c3602201c6c053d750fadde599e6f5c4e1963df0f01fc0d97815e8157e3d59fe09ca30d012103699b464d1d8bc9e47d4fb1cdaa89a1c5783d68363c4dbc4b524ed3d857148617feffffff02836d3c01000000001976a914fc25d6d5c94003bf5b0c7b640a248e2c637fcfb088ac7ada8202000000001976a914fbed3d9b11183209a57999d54d59f67c019e756c88ac6acb0700 --spent 00 0
transaction script verification: INVALID (1 input(s))

########## input 0 ##########
script verification: INVALID  (error: OK)

=== script #0: input script (scriptSig) · BASE · 107 bytes ===
    483045022100de1ac3bcdfb0332207c4a91f3832bd2c2915840165f876ab47c5f8996b971c3602201c6c053d750fadde599e6f5c4e1963df0f01fc0d97815e8157e3d59fe09ca30d012103699b464d1d8bc9e47d4fb1cdaa89a1c5783d68363c4dbc4b524ed3d857148617
  #0000  OP_PUSHBYTES_72        Push the next 72 bytes onto the stack.
         stack: []
  #0001  OP_PUSHBYTES_33        Push the next 33 bytes onto the stack.
         stack: [3045022100de1ac3bcdfb0332207c4a9...(72 bytes)]
  result: [3045022100de1ac3bcdfb0332207c4a9...(72 bytes), 03699b464d1d8bc9e47d4fb1cdaa89a1...(33 bytes)]  -> OK

=== script #1: output script (scriptPubkey) · BASE · 1 bytes ===
    00
  #0000  OP_0                   Push an empty byte vector (represents false / zero).
         stack: [3045022100de1ac3bcdfb0332207c4a9...(72 bytes), 03699b464d1d8bc9e47d4fb1cdaa89a1...(33 bytes)]
  result: [3045022100de1ac3bcdfb0332207c4a9...(72 bytes), 03699b464d1d8bc9e47d4fb1cdaa89a1...(33 bytes), 0x]  -> OK

  note: scripts evaluated without error, but verification failed (top of stack is false).

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.

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: https://github.com/elmeriniemela/pybitcoinkernel/blob/f67613ce47dbf142ba1d6f9746153d9e3e39878d/src/pybitcoinkernel/debugger.py#L809 I can reach the if condition above with this command: ```sh $ python scripts/manual_debug.py 02000000013f7cebd65c27431a90bba7f796914fe8cc2ddfc3f2cbd6f7e5f2fc854534da95000000006b483045022100de1ac3bcdfb0332207c4a91f3832bd2c2915840165f876ab47c5f8996b971c3602201c6c053d750fadde599e6f5c4e1963df0f01fc0d97815e8157e3d59fe09ca30d012103699b464d1d8bc9e47d4fb1cdaa89a1c5783d68363c4dbc4b524ed3d857148617feffffff02836d3c01000000001976a914fc25d6d5c94003bf5b0c7b640a248e2c637fcfb088ac7ada8202000000001976a914fbed3d9b11183209a57999d54d59f67c019e756c88ac6acb0700 --spent 00 0 transaction script verification: INVALID (1 input(s)) ########## input 0 ########## script verification: INVALID (error: OK) === script #0: input script (scriptSig) · BASE · 107 bytes === 483045022100de1ac3bcdfb0332207c4a91f3832bd2c2915840165f876ab47c5f8996b971c3602201c6c053d750fadde599e6f5c4e1963df0f01fc0d97815e8157e3d59fe09ca30d012103699b464d1d8bc9e47d4fb1cdaa89a1c5783d68363c4dbc4b524ed3d857148617 #0000 OP_PUSHBYTES_72 Push the next 72 bytes onto the stack. stack: [] #0001 OP_PUSHBYTES_33 Push the next 33 bytes onto the stack. stack: [3045022100de1ac3bcdfb0332207c4a9...(72 bytes)] result: [3045022100de1ac3bcdfb0332207c4a9...(72 bytes), 03699b464d1d8bc9e47d4fb1cdaa89a1...(33 bytes)] -> OK === script #1: output script (scriptPubkey) · BASE · 1 bytes === 00 #0000 OP_0 Push an empty byte vector (represents false / zero). stack: [3045022100de1ac3bcdfb0332207c4a9...(72 bytes), 03699b464d1d8bc9e47d4fb1cdaa89a1...(33 bytes)] result: [3045022100de1ac3bcdfb0332207c4a9...(72 bytes), 03699b464d1d8bc9e47d4fb1cdaa89a1...(33 bytes), 0x] -> OK note: scripts evaluated without error, but verification failed (top of stack is false). ``` 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.
sedited commented 2026-07-25 14:26:49 +00:00 (Migrated from github.com)

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 the EvalScript function, which does not enforce this final stack condition. This should be communicated by exposing the full script verification error codes when calling btck_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.

> 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 the `EvalScript` function, which does not enforce this final stack condition. This should be communicated by exposing the full script verification error codes when calling `btck_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.
stringintech (Migrated from github.com) reviewed 2026-08-11 15:04:41 +00:00
stringintech (Migrated from github.com) commented 2026-08-11 13:20:21 +00:00

Perhaps it is better to use an exhaustive switch for kind and sig_version as well, in both directions (bitcoinkernel.cpp and the C++ wrapper), like the existing enum conversions in the kernel?

Perhaps it is better to use an exhaustive switch for `kind` and `sig_version` as well, in both directions (`bitcoinkernel.cpp` and the C++ wrapper), like the existing enum conversions in the kernel?
stringintech (Migrated from github.com) commented 2026-08-11 13:20:21 +00:00

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 a shared_ptr, so copying a frame is just a refcount bump)? The C++ wrapper could then use the existing View/Handle pattern.

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 a `shared_ptr`, so copying a frame is just a refcount bump)? The C++ wrapper could then use the existing `View`/`Handle` pattern.
stringintech (Migrated from github.com) commented 2026-08-11 13:20:21 +00:00

My understanding is that f_exec is 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?

My understanding is that `f_exec` is 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?
stringintech (Migrated from github.com) commented 2026-08-11 13:20:21 +00:00

ScriptTraceScope learns the outcome only from m_error. set_error in EvalScript also communicates through the returned bool, but the end frame only has access to the error object, so a null m_error makes a successful eval report SCRIPT_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
@@
         m_error{error}
     {
+        assert(!m_callback || error);
         Emit(ScriptTraceFrameKind::Begin, m_exec_fn(), /*opcode=*/0, SCRIPT_ERR_OK);
     }
`ScriptTraceScope` learns the outcome only from `m_error`. `set_error` in `EvalScript` also communicates through the returned bool, but the end frame only has access to the error object, so a null `m_error` makes a successful eval report `SCRIPT_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? <details> <summary>Suggested change</summary> ```diff @@ m_error{error} { + assert(!m_callback || error); Emit(ScriptTraceFrameKind::Begin, m_exec_fn(), /*opcode=*/0, SCRIPT_ERR_OK); } ``` </details>
DrahtBot commented 2026-08-11 21:12:36 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
haanhvu (Migrated from github.com) reviewed 2026-08-14 10:07:58 +00:00
haanhvu (Migrated from github.com) left a comment

Concept ACK

Concept ACK
haanhvu (Migrated from github.com) commented 2026-07-24 10:31:39 +00:00

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 clearly comment that user data is destroyed in any case, whether tracing enabled/succeeds or not, to avoid problems like double free?
Lines 2031-2032
haanhvu (Migrated from github.com) commented 2026-08-01 10:14:07 +00:00

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.

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.
haanhvu (Migrated from github.com) commented 2026-08-01 08:59:57 +00:00

Nit: state is already passed by value here, so m_state.emplace_back(state) performs an extra copy of the ScriptTraceFrame. Would it make sense to move it instead? m_state.emplace_back(std::move(state));

Nit: `state` is already passed by value here, so `m_state.emplace_back(state)` performs an extra copy of the `ScriptTraceFrame`. Would it make sense to move it instead? `m_state.emplace_back(std::move(state));`
haanhvu (Migrated from github.com) commented 2026-07-30 10:36:04 +00:00

Should we verify unregistering actually stops tracing?

Something like:

// Before unregistering
const auto frame_count = states.size();

// After unregistering
BOOST_CHECK(legacy_spent_script_pubkey.Verify(...));
BOOST_CHECK_EQUAL(states.size(), frame_count);
Should we verify unregistering actually stops tracing? Something like: ``` // Before unregistering const auto frame_count = states.size(); // After unregistering BOOST_CHECK(legacy_spent_script_pubkey.Verify(...)); BOOST_CHECK_EQUAL(states.size(), frame_count); ```
haanhvu (Migrated from github.com) commented 2026-07-29 15:11:48 +00:00

BOOST_CHECK_EQUAL(states.size(), 11) is non-fatal, but the test checks states[0] through states[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 use BOOST_REQUIRE_EQUAL(states.size(), 11) instead?

`BOOST_CHECK_EQUAL(states.size(), 11)` is non-fatal, but the test checks `states[0]` through `states[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 use `BOOST_REQUIRE_EQUAL(states.size(), 11)` instead?
haanhvu (Migrated from github.com) commented 2026-08-14 09:22:36 +00:00

Should we also verify other fields besides m_kind and m_script_error to 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).

Should we also verify other fields besides `m_kind` and `m_script_error` to 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).
sedited commented 2026-08-28 20:39:53 +00:00 (Migrated from github.com)

Thank you for the review @stringintech and @haanhvu,

Rebased and updated 114e48e968a087f74c1ab611ac2a31a9266812e1 -> 20fb03490d1f38dde67f058acd68e816595d9222 (kernel_script_tracer_0 -> kernel_script_tracer_1, compare)

  • Addressed @stringintech's comment, wrapped the frame into nested opaque types and getters.
  • Addressed @stringintech's comment, use exhaustive enum conversions.
  • Addressed @stringintech's comment, dropped f_exec pre-loading with a lambda. As suggested, the begin and end frames now contain dummy values that are documented as such.
  • Addressed @stringintech's comment, added the suggested assertion for passing in the error.
  • Addressed @haanhvu's comment, made the boost size check a hard requirement.
  • Addressed @haanhvu's comment, added a quick verification that unregistering the tracer actually works.
  • Addressed @haanhvu's comment, added a verification that re-registering the tracer works.
Thank you for the review @stringintech and @haanhvu, Rebased and updated 114e48e968a087f74c1ab611ac2a31a9266812e1 -> 20fb03490d1f38dde67f058acd68e816595d9222 ([kernel_script_tracer_0](https://github.com/sedited/bitcoin/tree/kernel_script_tracer_0) -> [kernel_script_tracer_1](https://github.com/sedited/bitcoin/tree/kernel_script_tracer_1), [compare](https://github.com/sedited/bitcoin/compare/kernel_script_tracer_0..kernel_script_tracer_1)) * Addressed @stringintech's [comment](https://github.com/bitcoin/bitcoin/pull/35641#discussion_r3758299206), wrapped the frame into nested opaque types and getters. * Addressed @stringintech's [comment](https://github.com/bitcoin/bitcoin/pull/35641#discussion_r3758299213), use exhaustive enum conversions. * Addressed @stringintech's [comment](https://github.com/bitcoin/bitcoin/pull/35641#discussion_r3758299219), dropped f_exec pre-loading with a lambda. As suggested, the begin and end frames now contain dummy values that are documented as such. * Addressed @stringintech's [comment](https://github.com/bitcoin/bitcoin/pull/35641#discussion_r3758299224), added the suggested assertion for passing in the error. * Addressed @haanhvu's [comment](https://github.com/bitcoin/bitcoin/pull/35641#discussion_r3675592714), made the boost size check a hard requirement. * Addressed @haanhvu's [comment](https://github.com/bitcoin/bitcoin/pull/35641#discussion_r3681990206), added a quick verification that unregistering the tracer actually works. * Addressed @haanhvu's [comment](https://github.com/bitcoin/bitcoin/pull/35641/changes#r3695400629), added a verification that re-registering the tracer works.
sedited (Migrated from github.com) reviewed 2026-08-28 20:53:03 +00:00
sedited (Migrated from github.com) commented 2026-08-28 20:53:03 +00:00

I don't think this needs an extra comment. To me it seems self-explanatory.

I don't think this needs an extra comment. To me it seems self-explanatory.
sedited (Migrated from github.com) reviewed 2026-08-28 20:54:01 +00:00
sedited (Migrated from github.com) commented 2026-08-28 20:54:01 +00:00

I don't think this matters in a test. Besides, the new type is hardly worth the move now.

I don't think this matters in a test. Besides, the new type is hardly worth the move now.
sedited (Migrated from github.com) reviewed 2026-08-28 20:54:21 +00:00
sedited (Migrated from github.com) commented 2026-08-28 20:54:21 +00:00

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.

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.
alexanderwiederin (Migrated from github.com) reviewed 2026-08-31 08:23:05 +00:00
alexanderwiederin (Migrated from github.com) commented 2026-08-31 08:23:05 +00:00

Needs a ///@}

Needs a `///@}`
alexanderwiederin (Migrated from github.com) reviewed 2026-08-31 10:39:25 +00:00
alexanderwiederin (Migrated from github.com) commented 2026-08-31 10:39:25 +00:00

Add ScriptTraceUnsetCallback() to avoid the next test case push into a destroyed vector. Test suite currently does not pass with the feature flag.

Add `ScriptTraceUnsetCallback()` to avoid the next test case push into a destroyed vector. Test suite currently does not pass with the feature flag.
sedited commented 2026-08-31 15:46:00 +00:00 (Migrated from github.com)

Updated 20fb03490d1f38dde67f058acd68e816595d9222 -> 97462c683d (kernel_script_tracer_1 -> kernel_script_tracer_2, compare)

  • Addressed @alexanderwiederin's comment, added close tag for new doxygen section.
  • Addressed @alexanderwiederin's comment, unsetting the callback after the trace tests are complete.
Updated 20fb03490d1f38dde67f058acd68e816595d9222 -> 97462c683d49792a58ba954723a205cda86a5e0b ([kernel_script_tracer_1](https://github.com/sedited/bitcoin/tree/kernel_script_tracer_1) -> [kernel_script_tracer_2](https://github.com/sedited/bitcoin/tree/kernel_script_tracer_2), [compare](https://github.com/sedited/bitcoin/compare/kernel_script_tracer_1..kernel_script_tracer_2)) * Addressed @alexanderwiederin's [comment](https://github.com/bitcoin/bitcoin/pull/35641#discussion_r3892814321), added close tag for new doxygen section. * Addressed @alexanderwiederin's [comment](https://github.com/bitcoin/bitcoin/pull/35641#discussion_r3893679920), unsetting the callback after the trace tests are complete.
w0xlt commented 2026-09-01 19:40:13 +00:00 (Migrated from github.com)

The tracing code assumes serror is non-null whenever a callback is registered, but EvalScript permits nullptr for example, CheckSignetBlockSolution() calls VerifyScript() without an error pointer.

This triggers the assertion assert(!m_callback || error); when tracing is enabled.

Suggestion:
diff --git a/src/script/interpreter.cpp b/src/script/interpreter.cpp
index 45e7f48cd0..a7d2ce7440 100644
--- a/src/script/interpreter.cpp
+++ b/src/script/interpreter.cpp
@@ -417,6 +417,12 @@ static bool EvalChecksig(const valtype& sig, const valtype& pubkey, CScript::con
 
 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, script_verify_flags flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptExecutionData& execdata, ScriptError* serror)
 {
+#ifdef ENABLE_SCRIPT_TRACE
+    // END frames report the result even when the caller does not request it.
+    ScriptError trace_error{SCRIPT_ERR_UNKNOWN_ERROR};
+    if (serror == nullptr) serror = &trace_error;
+#endif
+
     static const CScriptNum bnZero(0);
     static const CScriptNum bnOne(1);
     // static const CScriptNum bnFalse(0);
diff --git a/src/test/kernel/test_kernel.cpp b/src/test/kernel/test_kernel.cpp
index 5b97321367..cbb7464197 100644
--- a/src/test/kernel/test_kernel.cpp
+++ b/src/test/kernel/test_kernel.cpp
@@ -463,6 +463,22 @@ BOOST_AUTO_TEST_CASE(btck_script_trace_tests)
         status));
     BOOST_CHECK_EQUAL(states.size(), 22);
     ScriptTraceUnsetCallback();
+
+    // Script errors are optional for internal EvalScript callers. Exercise the
+    // signet validation path, which intentionally does not request one.
+    states.clear();
+    ChainParams signet_params{ChainType::SIGNET};
+    Block signet_block{hex_string_to_byte_vec(
+        "00000020f61eee3b63a380a477a063af32b2bbc97c9ff9f01f2c4225e973988108000000f575c83235984e7dc4afc1f30944c170462e84437ab6f2d52e16878a79e4678bd1914d5fae77031eccf4070001010000000001010000000000000000000000000000000000000000000000000000000000000000ffffffff025151feffffff0200f2052a010000001600149243f727dd5343293eb83174324019ec16c2630f0000000000000000776a24aa21a9ede2f61c3f71d1defd3fa999dfa36953755c690689799962b48bebd836974e8cf94c4fecc7daa2490047304402205e423a8754336ca99dbe16509b877ef1bf98d008836c725005b3c787c41ebe46022047246e4467ad7cc7f1ad98662afcaf14c115e0095a227c7b05c5182591c23e7e01000120000000000000000000000000000000000000000000000000000000000000000000000000")};
+    BlockValidationState validation_state;
+    ScriptTraceSetCallback(std::make_unique<ScriptTracer>(states));
+    const bool valid{signet_block.Check(signet_params.GetConsensusParams(), BlockCheckFlags::ALL, validation_state)};
+    ScriptTraceUnsetCallback();
+
+    BOOST_CHECK(valid);
+    BOOST_REQUIRE(!states.empty());
+    BOOST_CHECK(states.back().m_kind == ScriptTraceFrameKind::END);
+    BOOST_CHECK_EQUAL(states.back().m_script_error, 0);
 #endif
 }
The tracing code assumes `serror` is non-null whenever a callback is registered, but `EvalScript` permits `nullptr` for example, `CheckSignetBlockSolution()` calls `VerifyScript()` without an error pointer. This triggers the assertion `assert(!m_callback || error);` when tracing is enabled. <details> <summary>Suggestion:</summary> ```diff diff --git a/src/script/interpreter.cpp b/src/script/interpreter.cpp index 45e7f48cd0..a7d2ce7440 100644 --- a/src/script/interpreter.cpp +++ b/src/script/interpreter.cpp @@ -417,6 +417,12 @@ static bool EvalChecksig(const valtype& sig, const valtype& pubkey, CScript::con bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, script_verify_flags flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptExecutionData& execdata, ScriptError* serror) { +#ifdef ENABLE_SCRIPT_TRACE + // END frames report the result even when the caller does not request it. + ScriptError trace_error{SCRIPT_ERR_UNKNOWN_ERROR}; + if (serror == nullptr) serror = &trace_error; +#endif + static const CScriptNum bnZero(0); static const CScriptNum bnOne(1); // static const CScriptNum bnFalse(0); diff --git a/src/test/kernel/test_kernel.cpp b/src/test/kernel/test_kernel.cpp index 5b97321367..cbb7464197 100644 --- a/src/test/kernel/test_kernel.cpp +++ b/src/test/kernel/test_kernel.cpp @@ -463,6 +463,22 @@ BOOST_AUTO_TEST_CASE(btck_script_trace_tests) status)); BOOST_CHECK_EQUAL(states.size(), 22); ScriptTraceUnsetCallback(); + + // Script errors are optional for internal EvalScript callers. Exercise the + // signet validation path, which intentionally does not request one. + states.clear(); + ChainParams signet_params{ChainType::SIGNET}; + Block signet_block{hex_string_to_byte_vec( + "00000020f61eee3b63a380a477a063af32b2bbc97c9ff9f01f2c4225e973988108000000f575c83235984e7dc4afc1f30944c170462e84437ab6f2d52e16878a79e4678bd1914d5fae77031eccf4070001010000000001010000000000000000000000000000000000000000000000000000000000000000ffffffff025151feffffff0200f2052a010000001600149243f727dd5343293eb83174324019ec16c2630f0000000000000000776a24aa21a9ede2f61c3f71d1defd3fa999dfa36953755c690689799962b48bebd836974e8cf94c4fecc7daa2490047304402205e423a8754336ca99dbe16509b877ef1bf98d008836c725005b3c787c41ebe46022047246e4467ad7cc7f1ad98662afcaf14c115e0095a227c7b05c5182591c23e7e01000120000000000000000000000000000000000000000000000000000000000000000000000000")}; + BlockValidationState validation_state; + ScriptTraceSetCallback(std::make_unique<ScriptTracer>(states)); + const bool valid{signet_block.Check(signet_params.GetConsensusParams(), BlockCheckFlags::ALL, validation_state)}; + ScriptTraceUnsetCallback(); + + BOOST_CHECK(valid); + BOOST_REQUIRE(!states.empty()); + BOOST_CHECK(states.back().m_kind == ScriptTraceFrameKind::END); + BOOST_CHECK_EQUAL(states.back().m_script_error, 0); #endif } ``` </details>
w0xlt commented 2026-09-01 20:05:12 +00:00 (Migrated from github.com)

EvalScript rejects oversized scripts before constructing ScriptTraceScope, so a registered callback receives neither BEGIN nor END.
Moving the size check below scope construction produces:

create scope → BEGIN
size check → set SCRIPT_ERR_SCRIPT_SIZE → return
scope destructor → END with SCRIPT_ERR_SCRIPT_SIZE

Non-tracing behavior remains the same.

Suggestion:
diff --git a/src/script/interpreter.cpp b/src/script/interpreter.cpp
index 45e7f48cd0..1116ffd9c2 100644
--- a/src/script/interpreter.cpp
+++ b/src/script/interpreter.cpp
@@ -436,9 +436,6 @@ bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript&
     ConditionStack vfExec;
     std::vector<valtype> altstack;
     set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
-    if ((sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) && script.size() > MAX_SCRIPT_SIZE) {
-        return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
-    }
     int nOpCount = 0;
     bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
     uint32_t opcode_pos = 0;
@@ -447,6 +444,10 @@ bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript&
 
     SCRIPT_TRACE_SCOPE(stack, script, opcode_pos, altstack, nOpCount, sigversion, execdata.m_tapleaf_hash_init ? execdata.m_tapleaf_hash.data() : nullptr, execdata.m_codeseparator_pos, serror);
 
+    if ((sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) && script.size() > MAX_SCRIPT_SIZE) {
+        return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
+    }
+
     try
     {
         for (; pc < pend; ++opcode_pos) {
diff --git a/src/test/kernel/test_kernel.cpp b/src/test/kernel/test_kernel.cpp
index 5b97321367..999199bb3b 100644
--- a/src/test/kernel/test_kernel.cpp
+++ b/src/test/kernel/test_kernel.cpp
@@ -4,6 +4,7 @@
 
 #include <kernel/bitcoinkernel.h>
 #include <kernel/bitcoinkernel_wrapper.h>
+#include <script/script_error.h>
 #include <util/byte_units.h>
 #include <util/fs.h>
 
@@ -463,6 +464,23 @@ BOOST_AUTO_TEST_CASE(btck_script_trace_tests)
         status));
     BOOST_CHECK_EQUAL(states.size(), 22);
     ScriptTraceUnsetCallback();
+
+    std::vector<ScriptTracer::Snapshot> oversized_states;
+    ScriptPubkey oversized_script_pubkey{std::vector<std::byte>(10'001)};
+    ScriptTraceSetCallback(std::make_unique<ScriptTracer>(oversized_states));
+    BOOST_CHECK(!oversized_script_pubkey.Verify(
+        /*amount=*/0,
+        /*tx_to=*/legacy_spending_tx,
+        /*precomputed_txdata=*/nullptr,
+        /*input_index=*/0,
+        VERIFY_ALL_PRE_TAPROOT,
+        status));
+    ScriptTraceUnsetCallback();
+
+    BOOST_REQUIRE(oversized_states.size() >= 2);
+    BOOST_CHECK(oversized_states[oversized_states.size() - 2].m_kind == ScriptTraceFrameKind::BEGIN);
+    BOOST_CHECK(oversized_states.back().m_kind == ScriptTraceFrameKind::END);
+    BOOST_CHECK_EQUAL(oversized_states.back().m_script_error, SCRIPT_ERR_SCRIPT_SIZE);
 #endif
 }
`EvalScript` rejects oversized scripts before constructing `ScriptTraceScope`, so a registered callback receives neither `BEGIN` nor `END`. Moving the size check below scope construction produces: ``` create scope → BEGIN size check → set SCRIPT_ERR_SCRIPT_SIZE → return scope destructor → END with SCRIPT_ERR_SCRIPT_SIZE ``` Non-tracing behavior remains the same. <details> <summary>Suggestion:</summary> ```diff diff --git a/src/script/interpreter.cpp b/src/script/interpreter.cpp index 45e7f48cd0..1116ffd9c2 100644 --- a/src/script/interpreter.cpp +++ b/src/script/interpreter.cpp @@ -436,9 +436,6 @@ bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& ConditionStack vfExec; std::vector<valtype> altstack; set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR); - if ((sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) && script.size() > MAX_SCRIPT_SIZE) { - return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE); - } int nOpCount = 0; bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0; uint32_t opcode_pos = 0; @@ -447,6 +444,10 @@ bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& SCRIPT_TRACE_SCOPE(stack, script, opcode_pos, altstack, nOpCount, sigversion, execdata.m_tapleaf_hash_init ? execdata.m_tapleaf_hash.data() : nullptr, execdata.m_codeseparator_pos, serror); + if ((sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0) && script.size() > MAX_SCRIPT_SIZE) { + return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE); + } + try { for (; pc < pend; ++opcode_pos) { diff --git a/src/test/kernel/test_kernel.cpp b/src/test/kernel/test_kernel.cpp index 5b97321367..999199bb3b 100644 --- a/src/test/kernel/test_kernel.cpp +++ b/src/test/kernel/test_kernel.cpp @@ -4,6 +4,7 @@ #include <kernel/bitcoinkernel.h> #include <kernel/bitcoinkernel_wrapper.h> +#include <script/script_error.h> #include <util/byte_units.h> #include <util/fs.h> @@ -463,6 +464,23 @@ BOOST_AUTO_TEST_CASE(btck_script_trace_tests) status)); BOOST_CHECK_EQUAL(states.size(), 22); ScriptTraceUnsetCallback(); + + std::vector<ScriptTracer::Snapshot> oversized_states; + ScriptPubkey oversized_script_pubkey{std::vector<std::byte>(10'001)}; + ScriptTraceSetCallback(std::make_unique<ScriptTracer>(oversized_states)); + BOOST_CHECK(!oversized_script_pubkey.Verify( + /*amount=*/0, + /*tx_to=*/legacy_spending_tx, + /*precomputed_txdata=*/nullptr, + /*input_index=*/0, + VERIFY_ALL_PRE_TAPROOT, + status)); + ScriptTraceUnsetCallback(); + + BOOST_REQUIRE(oversized_states.size() >= 2); + BOOST_CHECK(oversized_states[oversized_states.size() - 2].m_kind == ScriptTraceFrameKind::BEGIN); + BOOST_CHECK(oversized_states.back().m_kind == ScriptTraceFrameKind::END); + BOOST_CHECK_EQUAL(oversized_states.back().m_script_error, SCRIPT_ERR_SCRIPT_SIZE); #endif } ``` </details>
w0xlt commented 2026-09-01 20:37:18 +00:00 (Migrated from github.com)

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 #ifdefs still 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:
diff --git a/src/script/interpreter.cpp b/src/script/interpreter.cpp
index 45e7f48cd0..f23673007f 100644
--- a/src/script/interpreter.cpp
+++ b/src/script/interpreter.cpp
@@ -445,7 +445,19 @@ bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript&
     execdata.m_codeseparator_pos = 0xFFFFFFFFUL;
     execdata.m_codeseparator_pos_init = true;
 
-    SCRIPT_TRACE_SCOPE(stack, script, opcode_pos, altstack, nOpCount, sigversion, execdata.m_tapleaf_hash_init ? execdata.m_tapleaf_hash.data() : nullptr, execdata.m_codeseparator_pos, serror);
+#ifdef ENABLE_SCRIPT_TRACE
+    ScriptTraceScope script_trace_scope{
+        stack,
+        script,
+        opcode_pos,
+        altstack,
+        nOpCount,
+        static_cast<uint8_t>(sigversion),
+        execdata.m_tapleaf_hash_init ? execdata.m_tapleaf_hash.data() : nullptr,
+        execdata.m_codeseparator_pos,
+        serror,
+    };
+#endif
 
     try
     {
@@ -459,7 +471,9 @@ bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript&
                 return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
             }
 
-            SCRIPT_TRACE_STEP(fExec, opcode);
+#ifdef ENABLE_SCRIPT_TRACE
+            script_trace_scope.Step(fExec, static_cast<uint8_t>(opcode));
+#endif
 
             if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
                 return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
diff --git a/src/script/trace.h b/src/script/trace.h
index 7cd63fffdd..1f1e6aec8e 100644
--- a/src/script/trace.h
+++ b/src/script/trace.h
@@ -104,15 +104,6 @@ private:
     }
 };
 
-#define SCRIPT_TRACE_SCOPE(stack, script, opcode_pos, altstack, nOpCount, sigversion, tapleaf_hash, codeseparator_pos, error) \
-    ScriptTraceScope script_trace_scope { stack, script, opcode_pos, altstack, nOpCount, static_cast<uint8_t>(sigversion), tapleaf_hash, codeseparator_pos, error }
-
-#define SCRIPT_TRACE_STEP(fExec, opcode) \
-    script_trace_scope.Step(fExec, static_cast<uint8_t>(opcode))
-
-#else
-#define SCRIPT_TRACE_SCOPE(stack, script, opcode_pos, altstack, nOpCount, sigversion, tapleaf_hash, codeseparator_pos, error) static_assert(true)
-#define SCRIPT_TRACE_STEP(fExec, opcode) static_assert(true)
 #endif // ENABLE_SCRIPT_TRACE
 
 #endif // BITCOIN_SCRIPT_TRACE_H
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 `#ifdefs` still 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. <details> <summary>Possible version without the tracing helper macros:</summary> ```diff diff --git a/src/script/interpreter.cpp b/src/script/interpreter.cpp index 45e7f48cd0..f23673007f 100644 --- a/src/script/interpreter.cpp +++ b/src/script/interpreter.cpp @@ -445,7 +445,19 @@ bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& execdata.m_codeseparator_pos = 0xFFFFFFFFUL; execdata.m_codeseparator_pos_init = true; - SCRIPT_TRACE_SCOPE(stack, script, opcode_pos, altstack, nOpCount, sigversion, execdata.m_tapleaf_hash_init ? execdata.m_tapleaf_hash.data() : nullptr, execdata.m_codeseparator_pos, serror); +#ifdef ENABLE_SCRIPT_TRACE + ScriptTraceScope script_trace_scope{ + stack, + script, + opcode_pos, + altstack, + nOpCount, + static_cast<uint8_t>(sigversion), + execdata.m_tapleaf_hash_init ? execdata.m_tapleaf_hash.data() : nullptr, + execdata.m_codeseparator_pos, + serror, + }; +#endif try { @@ -459,7 +471,9 @@ bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& return set_error(serror, SCRIPT_ERR_BAD_OPCODE); } - SCRIPT_TRACE_STEP(fExec, opcode); +#ifdef ENABLE_SCRIPT_TRACE + script_trace_scope.Step(fExec, static_cast<uint8_t>(opcode)); +#endif if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE) return set_error(serror, SCRIPT_ERR_PUSH_SIZE); diff --git a/src/script/trace.h b/src/script/trace.h index 7cd63fffdd..1f1e6aec8e 100644 --- a/src/script/trace.h +++ b/src/script/trace.h @@ -104,15 +104,6 @@ private: } }; -#define SCRIPT_TRACE_SCOPE(stack, script, opcode_pos, altstack, nOpCount, sigversion, tapleaf_hash, codeseparator_pos, error) \ - ScriptTraceScope script_trace_scope { stack, script, opcode_pos, altstack, nOpCount, static_cast<uint8_t>(sigversion), tapleaf_hash, codeseparator_pos, error } - -#define SCRIPT_TRACE_STEP(fExec, opcode) \ - script_trace_scope.Step(fExec, static_cast<uint8_t>(opcode)) - -#else -#define SCRIPT_TRACE_SCOPE(stack, script, opcode_pos, altstack, nOpCount, sigversion, tapleaf_hash, codeseparator_pos, error) static_assert(true) -#define SCRIPT_TRACE_STEP(fExec, opcode) static_assert(true) #endif // ENABLE_SCRIPT_TRACE #endif // BITCOIN_SCRIPT_TRACE_H ``` </details>
sedited commented 2026-09-24 11:19:47 +00:00 (Migrated from github.com)

Updated 97462c683d -> 12f4b91477 (kernel_script_tracer_2 -> kernel_script_tracer_3, compare)

  • Addressed @w0xlt's comment, making the error code "optional" by encoding -1 as a nullopt. This gets rid of the assertion and has no effect on what gets executed during evaluation.
  • Some small style and formatting cleanups.

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.

Updated 97462c683d49792a58ba954723a205cda86a5e0b -> 12f4b91477dcb6f18c4ce4f70212f3f292398b67 ([kernel_script_tracer_2](https://github.com/sedited/bitcoin/tree/kernel_script_tracer_2) -> [kernel_script_tracer_3](https://github.com/sedited/bitcoin/tree/kernel_script_tracer_3), [compare](https://github.com/sedited/bitcoin/compare/kernel_script_tracer_2..kernel_script_tracer_3)) * Addressed @w0xlt's [comment](https://github.com/bitcoin/bitcoin/pull/35641#issuecomment-5499409957), making the error code "optional" by encoding `-1` as a nullopt. This gets rid of the assertion and has no effect on what gets executed during evaluation. * Some small style and formatting cleanups. 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.
w0xlt commented 2026-09-24 21:02:58 +00:00 (Migrated from github.com)

The tracer uses fExec to 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_ENDIF

The first OP_1 is skipped because the condition is false. OP_ELSE still executes to activate the else branch, but the tracer incorrectly reported it as skipped because fExec was still false before execution.

Suggestion:
diff --git a/src/script/interpreter.cpp b/src/script/interpreter.cpp
index 45e7f48cd0..34d23edea2 100644
--- a/src/script/interpreter.cpp
+++ b/src/script/interpreter.cpp
@@ -459,7 +459,7 @@ bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript&
                 return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
             }
 
-            SCRIPT_TRACE_STEP(fExec, opcode);
+            SCRIPT_TRACE_STEP(fExec || (OP_IF <= opcode && opcode <= OP_ENDIF), opcode);
 
             if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
                 return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
diff --git a/src/test/kernel/test_kernel.cpp b/src/test/kernel/test_kernel.cpp
index c28de42fc6..126bc8c399 100644
--- a/src/test/kernel/test_kernel.cpp
+++ b/src/test/kernel/test_kernel.cpp
@@ -479,6 +479,64 @@ BOOST_AUTO_TEST_CASE(btck_script_trace_tests)
 #endif
 }
 
+#ifdef ENABLE_SCRIPT_TRACE
+BOOST_AUTO_TEST_CASE(btck_script_trace_exec_tests)
+{
+    struct ExecTracer {
+        std::vector<bool>& m_exec;
+
+        void ScriptTrace(const ScriptTraceFrameView& frame)
+        {
+            if (frame.Kind() == ScriptTraceFrameKind::STEP) {
+                m_exec.push_back(frame.Exec());
+            }
+        }
+    };
+
+    struct TestCase {
+        std::string_view script_hex;
+        std::vector<bool> expected_exec;
+    };
+    const TestCase test_cases[]{
+        // OP_0 OP_IF OP_1 OP_ELSE OP_1 OP_ENDIF
+        {"006351675168", {true, true, false, true, true, true}},
+        // OP_1 OP_IF OP_1 OP_ELSE OP_1 OP_ENDIF
+        {"516351675168", {true, true, true, true, false, true}},
+        // OP_0 OP_NOTIF OP_1 OP_ELSE OP_1 OP_ENDIF
+        {"006451675168", {true, true, true, true, false, true}},
+        // OP_1 OP_NOTIF OP_1 OP_ELSE OP_1 OP_ENDIF
+        {"516451675168", {true, true, false, true, true, true}},
+        // OP_0 OP_IF OP_IF OP_1 OP_ELSE OP_1 OP_ENDIF OP_ELSE OP_1 OP_ENDIF
+        {"00636351675168675168", {true, true, true, false, true, false, true, true, true, true}},
+        // OP_0 OP_IF OP_NOTIF OP_1 OP_ELSE OP_1 OP_ENDIF OP_ELSE OP_1 OP_ENDIF
+        {"00636451675168675168", {true, true, true, false, true, false, true, true, true, true}},
+    };
+
+    // One input with an empty scriptSig, so only the scriptPubKey emits step frames.
+    const Transaction tx{hex_string_to_byte_vec("020000000100000000000000000000000000000000000000000000000000000000000000000000000000ffffffff0100000000000000000000000000")};
+    for (const auto& test : test_cases) {
+        BOOST_TEST_CONTEXT(test.script_hex) {
+            const ScriptPubkey script{hex_string_to_byte_vec(test.script_hex)};
+            std::vector<bool> exec;
+            auto status{ScriptVerifyStatus::OK};
+            ScriptTraceSetCallback(std::make_unique<ExecTracer>(exec));
+            const bool valid{script.Verify(
+                /*amount=*/0,
+                /*tx_to=*/tx,
+                /*precomputed_txdata=*/nullptr,
+                /*input_index=*/0,
+                ScriptVerificationFlags::NONE,
+                status)};
+            ScriptTraceUnsetCallback();
+
+            BOOST_CHECK(valid);
+            BOOST_CHECK(status == ScriptVerifyStatus::OK);
+            BOOST_CHECK_EQUAL_COLLECTIONS(exec.begin(), exec.end(), test.expected_exec.begin(), test.expected_exec.end());
+        }
+    }
+}
+#endif
+
 BOOST_AUTO_TEST_CASE(btck_transaction_tests)
 {
     auto tx_data{hex_string_to_byte_vec("02000000013f7cebd65c27431a90bba7f796914fe8cc2ddfc3f2cbd6f7e5f2fc854534da95000000006b483045022100de1ac3bcdfb0332207c4a91f3832bd2c2915840165f876ab47c5f8996b971c3602201c6c053d750fadde599e6f5c4e1963df0f01fc0d97815e8157e3d59fe09ca30d012103699b464d1d8bc9e47d4fb1cdaa89a1c5783d68363c4dbc4b524ed3d857148617feffffff02836d3c01000000001976a914fc25d6d5c94003bf5b0c7b640a248e2c637fcfb088ac7ada8202000000001976a914fbed3d9b11183209a57999d54d59f67c019e756c88ac6acb0700")};

The tracer uses `fExec` to 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_ENDIF` The first `OP_1` is skipped because the condition is false. `OP_ELSE` still executes to activate the else branch, but the tracer incorrectly reported it as skipped because `fExec` was still false before execution. <details> <summary>Suggestion:</summary> ```diff diff --git a/src/script/interpreter.cpp b/src/script/interpreter.cpp index 45e7f48cd0..34d23edea2 100644 --- a/src/script/interpreter.cpp +++ b/src/script/interpreter.cpp @@ -459,7 +459,7 @@ bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& return set_error(serror, SCRIPT_ERR_BAD_OPCODE); } - SCRIPT_TRACE_STEP(fExec, opcode); + SCRIPT_TRACE_STEP(fExec || (OP_IF <= opcode && opcode <= OP_ENDIF), opcode); if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE) return set_error(serror, SCRIPT_ERR_PUSH_SIZE); diff --git a/src/test/kernel/test_kernel.cpp b/src/test/kernel/test_kernel.cpp index c28de42fc6..126bc8c399 100644 --- a/src/test/kernel/test_kernel.cpp +++ b/src/test/kernel/test_kernel.cpp @@ -479,6 +479,64 @@ BOOST_AUTO_TEST_CASE(btck_script_trace_tests) #endif } +#ifdef ENABLE_SCRIPT_TRACE +BOOST_AUTO_TEST_CASE(btck_script_trace_exec_tests) +{ + struct ExecTracer { + std::vector<bool>& m_exec; + + void ScriptTrace(const ScriptTraceFrameView& frame) + { + if (frame.Kind() == ScriptTraceFrameKind::STEP) { + m_exec.push_back(frame.Exec()); + } + } + }; + + struct TestCase { + std::string_view script_hex; + std::vector<bool> expected_exec; + }; + const TestCase test_cases[]{ + // OP_0 OP_IF OP_1 OP_ELSE OP_1 OP_ENDIF + {"006351675168", {true, true, false, true, true, true}}, + // OP_1 OP_IF OP_1 OP_ELSE OP_1 OP_ENDIF + {"516351675168", {true, true, true, true, false, true}}, + // OP_0 OP_NOTIF OP_1 OP_ELSE OP_1 OP_ENDIF + {"006451675168", {true, true, true, true, false, true}}, + // OP_1 OP_NOTIF OP_1 OP_ELSE OP_1 OP_ENDIF + {"516451675168", {true, true, false, true, true, true}}, + // OP_0 OP_IF OP_IF OP_1 OP_ELSE OP_1 OP_ENDIF OP_ELSE OP_1 OP_ENDIF + {"00636351675168675168", {true, true, true, false, true, false, true, true, true, true}}, + // OP_0 OP_IF OP_NOTIF OP_1 OP_ELSE OP_1 OP_ENDIF OP_ELSE OP_1 OP_ENDIF + {"00636451675168675168", {true, true, true, false, true, false, true, true, true, true}}, + }; + + // One input with an empty scriptSig, so only the scriptPubKey emits step frames. + const Transaction tx{hex_string_to_byte_vec("020000000100000000000000000000000000000000000000000000000000000000000000000000000000ffffffff0100000000000000000000000000")}; + for (const auto& test : test_cases) { + BOOST_TEST_CONTEXT(test.script_hex) { + const ScriptPubkey script{hex_string_to_byte_vec(test.script_hex)}; + std::vector<bool> exec; + auto status{ScriptVerifyStatus::OK}; + ScriptTraceSetCallback(std::make_unique<ExecTracer>(exec)); + const bool valid{script.Verify( + /*amount=*/0, + /*tx_to=*/tx, + /*precomputed_txdata=*/nullptr, + /*input_index=*/0, + ScriptVerificationFlags::NONE, + status)}; + ScriptTraceUnsetCallback(); + + BOOST_CHECK(valid); + BOOST_CHECK(status == ScriptVerifyStatus::OK); + BOOST_CHECK_EQUAL_COLLECTIONS(exec.begin(), exec.end(), test.expected_exec.begin(), test.expected_exec.end()); + } + } +} +#endif + BOOST_AUTO_TEST_CASE(btck_transaction_tests) { auto tx_data{hex_string_to_byte_vec("02000000013f7cebd65c27431a90bba7f796914fe8cc2ddfc3f2cbd6f7e5f2fc854534da95000000006b483045022100de1ac3bcdfb0332207c4a91f3832bd2c2915840165f876ab47c5f8996b971c3602201c6c053d750fadde599e6f5c4e1963df0f01fc0d97815e8157e3d59fe09ca30d012103699b464d1d8bc9e47d4fb1cdaa89a1c5783d68363c4dbc4b524ed3d857148617feffffff02836d3c01000000001976a914fc25d6d5c94003bf5b0c7b640a248e2c637fcfb088ac7ada8202000000001976a914fbed3d9b11183209a57999d54d59f67c019e756c88ac6acb0700")}; ``` </details>
sedited commented 2026-09-25 10:57:31 +00:00 (Migrated from github.com)

Updated 12f4b91477 -> 37f3b85710 (kernel_script_tracer_3 -> kernel_script_tracer_4, compare)

  • Addressed @w0xlt's comment, added a sentence in the docs that conditional opcodes are indeed processed when fexec is set. I don't think it is a good idea to mutate its meaning from the interpreter. The effect also doesn't seem directly observable. Still added a test case that exercises this with one of the proposed script pubkeys to show its capability of executing these custom scripts.
Updated 12f4b91477dcb6f18c4ce4f70212f3f292398b67 -> 37f3b857103e5b95c4c3b895d1b03f45419f5278 ([kernel_script_tracer_3](https://github.com/sedited/bitcoin/tree/kernel_script_tracer_3) -> [kernel_script_tracer_4](https://github.com/sedited/bitcoin/tree/kernel_script_tracer_4), [compare](https://github.com/sedited/bitcoin/compare/kernel_script_tracer_3..kernel_script_tracer_4)) * Addressed @w0xlt's [comment](https://github.com/bitcoin/bitcoin/pull/35641#issuecomment-5822201480), added a sentence in the docs that conditional opcodes are indeed processed when fexec is set. I don't think it is a good idea to mutate its meaning from the interpreter. The effect also doesn't seem directly observable. Still added a test case that exercises this with one of the proposed script pubkeys to show its capability of executing these custom scripts.
First-time contributor

Base: a773e1e33b349dc819b5a0edc1c7a4839dc73b48
Head: 0161ebdbf62cb6357ee4eb8432a900f354aa66a6

Findings

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
  • adversarial_deepseek: Stage reported incomplete evidence without identifying the missing evidence.
  • verifier: The linked #33961 discussion in the concept archaeology was not independently inspected; its historical characterization was not used to establish a code finding or the concept disposition.
  • verifier: The internal CScriptCheck-to-VerifyScript worker path was not fully followed. The callback-concurrency finding rests on unlocked trace dispatch and the public verifier's lack of serialization, not on an identified in-repository concurrent caller.
  • verifier: Finding withheld: Source evidence does not match the snapshot

Full review report

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:1e40d4c29146a38cb238a037edaa35c22b13996a5383ed7a85e089a15d569009:c9412d948811529792d161d97aa6951829440e3d548b7c576bb8d4df4183e0d0 --> Base: `a773e1e33b349dc819b5a0edc1c7a4839dc73b48` Head: `0161ebdbf62cb6357ee4eb8432a900f354aa66a6` ##### Findings **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. <details> <summary>Review limitations</summary> - adversarial_deepseek: Stage reported incomplete evidence without identifying the missing evidence. - verifier: The linked #33961 discussion in the concept archaeology was not independently inspected; its historical characterization was not used to establish a code finding or the concept disposition. - verifier: The internal CScriptCheck-to-VerifyScript worker path was not fully followed. The callback-concurrency finding rests on unlocked trace dispatch and the public verifier's lack of serialization, not on an identified in-repository concurrent caller. - verifier: Finding withheld: Source evidence does not match the snapshot </details> [Full review report](<https://review.fish.foo/traces/35641-0161ebdbf62cb6357ee4eb8432a900f354aa66a6-1337-4.html>)
alexanderwiederin (Migrated from github.com) reviewed 2026-10-05 12:18:38 +00:00
alexanderwiederin (Migrated from github.com) left a comment

Missing some BITCOINKERNEL_WARN_UNUSED_RESULT I think.

Missing some `BITCOINKERNEL_WARN_UNUSED_RESULT` I think.
alexanderwiederin (Migrated from github.com) commented 2026-10-05 12:11:43 +00:00

This needs a BITCOINKERNEL_WARN_UNUSED_RESULT

This needs a `BITCOINKERNEL_WARN_UNUSED_RESULT`
alexanderwiederin (Migrated from github.com) commented 2026-10-05 12:13:03 +00:00

This needs a BITCOINKERNEL_WARN_UNUSED_RESULT

This needs a `BITCOINKERNEL_WARN_UNUSED_RESULT`
alexanderwiederin (Migrated from github.com) commented 2026-08-31 18:29:20 +00:00

This needs a BITCOINKERNEL_WARN_UNUSED_RESULT

This needs a `BITCOINKERNEL_WARN_UNUSED_RESULT`
sedited commented 2026-10-06 13:22:26 +00:00 (Migrated from github.com)

Updated 37f3b85710 -> e8a8daf3fa (kernel_script_tracer_4 -> kernel_script_tracer_5, compare)

  • Addressed @alexanderwiederin's comment, added suggested BITCOINKERNEL_WARN_UNUSED_RESULT
Updated 37f3b857103e5b95c4c3b895d1b03f45419f5278 -> e8a8daf3fad1043b082d4728886c481b658147d3 ([kernel_script_tracer_4](https://github.com/sedited/bitcoin/tree/kernel_script_tracer_4) -> [kernel_script_tracer_5](https://github.com/sedited/bitcoin/tree/kernel_script_tracer_5), [compare](https://github.com/sedited/bitcoin/compare/kernel_script_tracer_4..kernel_script_tracer_5)) * Addressed @alexanderwiederin's [comment](https://github.com/bitcoin/bitcoin/pull/35641#pullrequestreview-5069824273), added suggested `BITCOINKERNEL_WARN_UNUSED_RESULT`
DrahtBot commented 2026-10-08 16:25:51 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
sedited commented 2026-10-09 12:29:39 +00:00 (Migrated from github.com)
Rebased e8a8daf3fad1043b082d4728886c481b658147d3 -> 0161ebdbf62cb6357ee4eb8432a900f354aa66a6 ([kernel_script_tracer_5](https://github.com/sedited/bitcoin/tree/kernel_script_tracer_5) -> [kernel_script_tracer_6](https://github.com/sedited/bitcoin/tree/kernel_script_tracer_6), [compare](https://github.com/sedited/bitcoin/compare/kernel_script_tracer_5..kernel_script_tracer_6)) * Fixed conflict with #34374
fametrano commented 2026-10-25 11:44:23 +00:00 (Migrated from github.com)

tACK 0161ebdbf6

I 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_SUCCESSx and 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_kernel passes.

One cost remains with ENABLE_SCRIPT_TRACE=ON and no tracer registered. Snapshotting the callback in ScriptTraceScope, after alexanderwiederin's comment, took the lock out of the per-opcode path. ScriptTraceGetCallback() still locks g_script_trace_mutex on every EvalScript call, 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 an std::atomic<bool>, set in ScriptTraceRegisterCallback(), before taking the lock? That four-line change brings the case above to 50 ns, and test_kernel still passes. I can share the diff and the harness.

tACK 0161ebdbf62cb6357ee4eb8432a900f354aa66a6 I 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_SUCCESSx` and 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_kernel` passes. One cost remains with `ENABLE_SCRIPT_TRACE=ON` and no tracer registered. Snapshotting the callback in `ScriptTraceScope`, after alexanderwiederin's [comment](https://github.com/bitcoin/bitcoin/pull/35641#discussion_r3560371508), took the lock out of the per-opcode path. `ScriptTraceGetCallback()` still locks `g_script_trace_mutex` on every `EvalScript` call, 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 an `std::atomic<bool>`, set in `ScriptTraceRegisterCallback()`, before taking the lock? That four-line change brings the case above to 50 ns, and `test_kernel` still passes. I can share the diff and the harness.
stringintech (Migrated from github.com) reviewed 2026-11-12 16:38:49 +00:00
stringintech (Migrated from github.com) commented 2026-11-11 15:55:54 +00:00

nit: seems a newline is added here by accident. :)

nit: seems a newline is added here by accident. :)
stringintech (Migrated from github.com) commented 2026-11-12 08:52:55 +00:00

I see both VerifyScript and EvalScript overwrite the error with SCRIPT_ERR_UNKNOWN_ERROR first thing, so the initial value here doesn't actually matter. But I was wondering if it'd be better to initialize it to SCRIPT_ERR_UNKNOWN_ERROR too, for consistency?

    ScriptError error = SCRIPT_ERR_UNKNOWN_ERROR;
I see both `VerifyScript` and `EvalScript` overwrite the error with `SCRIPT_ERR_UNKNOWN_ERROR` first thing, so the initial value here doesn't actually matter. But I was wondering if it'd be better to initialize it to `SCRIPT_ERR_UNKNOWN_ERROR` too, for consistency? ```suggestion ScriptError error = SCRIPT_ERR_UNKNOWN_ERROR; ```
stringintech (Migrated from github.com) commented 2026-11-12 10:15:03 +00:00

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 ScriptTraceFrame the same as in the interpreter and only convert in the getters? That would avoid the double cast here, and i think the same applies to opcode and tapleaf_hash.

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 `ScriptTraceFrame` the same as in the interpreter and only convert in the getters? That would avoid the double cast here, and i think the same applies to `opcode` and `tapleaf_hash`.
stringintech (Migrated from github.com) commented 2026-11-11 10:31:10 +00:00
/**
 * Opaque data structure for holding a view to the script interpreter state at
 * one point during script evaluation.
 */
typedef struct btck_ScriptTraceFrame btck_ScriptTraceFrame;
```suggestion /** * Opaque data structure for holding a view to the script interpreter state at * one point during script evaluation. */ typedef struct btck_ScriptTraceFrame btck_ScriptTraceFrame; ```
Lines 2213-2216
stringintech (Migrated from github.com) commented 2026-09-01 17:47:25 +00:00
 * @param[in] frame      Pointer to the current execution state snapshot. Data
 *                       accessed through getters is only valid for the duration of this callback.
 */
typedef void (*btck_ScriptTraceCallback)(
```suggestion * @param[in] frame Pointer to the current execution state snapshot. Data * accessed through getters is only valid for the duration of this callback. */ typedef void (*btck_ScriptTraceCallback)( ```
Lines 2219-2221
stringintech (Migrated from github.com) commented 2026-09-02 15:54:04 +00:00

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.

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.
Lines 2235-2237
stringintech (Migrated from github.com) commented 2026-11-12 15:54:46 +00:00

To find where a failed evaluation went wrong, a consumer currently has to cross-check the end frame's opcode_pos against the last step frame's, and then against the error code, since both codes below are also set from inside the loop:

error end pos == last step pos end pos == last step pos + 1
SCRIPT_ERR_BAD_OPCODE executed a bad opcode failed to decode the opcode at end pos
SCRIPT_ERR_UNBALANCED_CONDITIONAL stray OP_ELSE/OP_ENDIF missing OP_ENDIF (post-loop check, no opcode at fault)
any other failed executing that opcode —

The end frame's opcode_pos looks 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-line SCRIPT_TRACE_LOOP_DONE() right after the try/catch. Then the end frame could report:

  • loop not completed: opcode_pos is the opcode at which evaluation failed (decoding or executing it)
  • loop completed: opcode_pos is 0xFFFFFFFF (no opcode at fault), same convention as codeseparator_pos

And then for the getter doc:

/**
 * @brief Get the index of the opcode under evaluation (step frames) or at which
 * evaluation failed (end frames).
 *
 * Counts opcodes, not bytes. A failure can happen while decoding or executing
 * the opcode. End frames report 0xFFFFFFFF if no opcode is at fault: either
 * evaluation succeeded, or it failed in a check after the last opcode (e.g. a
 * missing OP_ENDIF), in which case the end frame's script error is set.
 *
 * @param[in] frame Non-null.
 * @return          The opcode index, or 0xFFFFFFFF.
 */
 BITCOINKERNEL_API uint32_t btck_script_trace_frame_get_opcode_pos(
    const btck_ScriptTraceFrame* frame) BITCOINKERNEL_ARG_NONNULL(1);

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, and 0 when no opcode is at fault (success or post-loop failure). On a decode failure GetScriptOp has already set opcode to OP_INVALIDOPCODE, so the end frame would report 0xff there.

To find where a failed evaluation went wrong, a consumer currently has to cross-check the end frame's `opcode_pos` against the last step frame's, and then against the error code, since both codes below are also set from inside the loop: | error | end pos == last step pos | end pos == last step pos + 1 | |---|---|---| | `SCRIPT_ERR_BAD_OPCODE` | executed a bad opcode | failed to decode the opcode at end pos | | `SCRIPT_ERR_UNBALANCED_CONDITIONAL` | stray `OP_ELSE`/`OP_ENDIF` | missing `OP_ENDIF` (post-loop check, no opcode at fault) | | any other | failed executing that opcode | — | The end frame's `opcode_pos` looks 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-line `SCRIPT_TRACE_LOOP_DONE()` right after the try/catch. Then the end frame could report: - loop not completed: `opcode_pos` is the opcode at which evaluation failed (decoding or executing it) - loop completed: `opcode_pos` is `0xFFFFFFFF` (no opcode at fault), same convention as `codeseparator_pos` And then for the getter doc: ```suggestion /** * @brief Get the index of the opcode under evaluation (step frames) or at which * evaluation failed (end frames). * * Counts opcodes, not bytes. A failure can happen while decoding or executing * the opcode. End frames report 0xFFFFFFFF if no opcode is at fault: either * evaluation succeeded, or it failed in a check after the last opcode (e.g. a * missing OP_ENDIF), in which case the end frame's script error is set. * * @param[in] frame Non-null. * @return The opcode index, or 0xFFFFFFFF. */ BITCOINKERNEL_API uint32_t btck_script_trace_frame_get_opcode_pos( const btck_ScriptTraceFrame* frame) BITCOINKERNEL_ARG_NONNULL(1); ``` 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, and `0` when no opcode is at fault (success or post-loop failure). On a decode failure `GetScriptOp` has already set `opcode` to `OP_INVALIDOPCODE`, so the end frame would report `0xff` there.
Lines 2276-2282
stringintech (Migrated from github.com) commented 2026-11-12 10:33:47 +00:00

Do we need to keep the btck_ScriptEvalStackItem opaque type? I'm wondering if we can just have a btck_script_eval_stack_get_item_at that returns the bytes directly (mirroring btck_witness_stack_get_item_at)?

Do we need to keep the `btck_ScriptEvalStackItem` opaque type? I'm wondering if we can just have a `btck_script_eval_stack_get_item_at` that returns the bytes directly (mirroring `btck_witness_stack_get_item_at`)?
stringintech (Migrated from github.com) commented 2026-11-11 11:05:01 +00:00
 * evaluator, on exit, and once per instruction - after the opcode is successfully decoded
```suggestion * evaluator, on exit, and once per instruction - after the opcode is successfully decoded ```
stringintech (Migrated from github.com) commented 2026-11-10 15:38:33 +00:00

We seem to be using a mixed pattern for naming the getters for this class and across the whole file - some come with a Get prefix 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.

We seem to be using a mixed pattern for naming the getters for this class and across the whole file - some come with a `Get` prefix 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.
stringintech (Migrated from github.com) commented 2026-11-10 15:44:09 +00:00

The rest of the wrapper seem to expose hashes as std::array<std::byte, 32>.

The rest of the wrapper seem to expose hashes as `std::array<std::byte, 32>`.
stringintech (Migrated from github.com) commented 2026-11-10 15:22:42 +00:00

Would it make sense to change this to snake_case same as other free functions likelogging_set_min_level, set_mock_time, ...? Also ScriptTraceUnsetCallback for the same reason.

void script_trace_set_callback(std::unique_ptr<T> trace)

(CheckTransaction seem to be an exception here; also i'm not sure why it didn't follow the Block::Check pattern 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)?

Would it make sense to change this to snake_case same as other free functions like`logging_set_min_level`, `set_mock_time`, ...? Also `ScriptTraceUnsetCallback` for the same reason. ```suggestion void script_trace_set_callback(std::unique_ptr<T> trace) ``` (`CheckTransaction` seem to be an exception here; also i'm not sure why it didn't follow the `Block::Check` pattern 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)?
stringintech (Migrated from github.com) commented 2026-11-12 12:28:01 +00:00

Could we hold a reference to opcode in ScriptTraceScope too, like we already do for others? Step() would read it, while Begin and End keep passing 0 explicitly. And just leave fExec as an argument since it is computed inside the loop.

Could we hold a reference to `opcode` in `ScriptTraceScope` too, like we already do for others? `Step()` would read it, while Begin and End keep passing `0` explicitly. And just leave `fExec` as an argument since it is computed inside the loop.
stringintech (Migrated from github.com) commented 2026-11-11 13:16:53 +00:00

Would the following suggestion reflect the intention more accurately here?

    // Move the old callback out so it is destroyed after the lock is released:
    // destroying it may run the user's destroy callback, and we don't need to
    // hold the lock for that.
Would the following suggestion reflect the intention more accurately here? ```suggestion // Move the old callback out so it is destroyed after the lock is released: // destroying it may run the user's destroy callback, and we don't need to // hold the lock for that. ```
Lines 60-75
stringintech (Migrated from github.com) commented 2026-11-12 12:10:04 +00:00

Can we make all fields of ScriptTraceScope const (also ctor parameters), indicating this class would not be modifying them? The scope only reads the interpreter state it references, so the references can be const&?

Can we make all fields of `ScriptTraceScope` const (also ctor parameters), indicating this class would not be modifying them? The scope only reads the interpreter state it references, so the references can be `const&`?
stringintech (Migrated from github.com) commented 2026-11-10 13:48:07 +00:00

I think it would be helpful to add a comment here:

    ScriptPubkey script_pubkey{hex_string_to_byte_vec("00636451675168675168")}; // OP_0 OP_IF OP_NOTIF OP_1 OP_ELSE OP_1 OP_ENDIF OP_ELSE OP_1 OP_ENDIF
I think it would be helpful to add a comment here: ```suggestion ScriptPubkey script_pubkey{hex_string_to_byte_vec("00636451675168675168")}; // OP_0 OP_IF OP_NOTIF OP_1 OP_ELSE OP_1 OP_ENDIF OP_ELSE OP_1 OP_ENDIF ```
alexanderwiederin commented 2026-11-20 13:34:30 +00:00 (Migrated from github.com)

@fametrano, from what I understand ENABLE_SCRIPT_TRACE is 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?

@fametrano, from what I understand `ENABLE_SCRIPT_TRACE` is 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?
yuvicc commented 2026-11-25 13:51:10 +00:00 (Migrated from github.com)

Concept ACK

Concept ACK
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!35641
No description provided.