Skip to content

kernel: Add script evaluation tracer - #35641

Open
sedited wants to merge 1 commit into
bitcoin:masterfrom
sedited:kernel_script_tracer
Open

sedited wants to merge 1 commit into
bitcoin:masterfrom
sedited:kernel_script_tracer

Conversation

@sedited

@sedited sedited commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

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.

@DrahtBot

DrahtBot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

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.

@github-project-automation github-project-automation Bot moved this to Architecture & Performance in The libbitcoinkernel Project Jul 2, 2026
@sedited sedited moved this from Architecture & Performance to API Development in The libbitcoinkernel Project Jul 2, 2026
@furszy

furszy commented Jul 2, 2026

Copy link
Copy Markdown
Member

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

@w0xlt

w0xlt commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

Strong Concept ACK

@alexanderwiederin

alexanderwiederin commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

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

@sedited

sedited commented Jul 6, 2026

Copy link
Copy Markdown
Contributor Author

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.

Comment thread src/kernel/bitcoinkernel.h Resolved
Comment thread src/kernel/bitcoinkernel.h Resolved
@sedited
sedited force-pushed the kernel_script_tracer branch from 31a5c98 to 2df591d Compare July 8, 2026 15:26
@theStack

theStack commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Concept ACK

@alexanderwiederin alexanderwiederin left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread src/kernel/bitcoinkernel.h Outdated
btck_SigVersion sig_version; //!< Signature version.
const unsigned char* tapleaf_hash; //!< Either null if not evaluating a tapleaf, or points to exactly 32 bytes (and sig_version is TAPSCRIPT).
uint32_t codeseparator_pos; //!< Opcode position of the last evaluated OP_CODESEPARATOR. 0xFFFFFFFF if none.
int32_t script_error; //!< Script error code. Only meaningful in end frames.

@alexanderwiederin alexanderwiederin Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

sedited commented Jul 10, 2026

Copy link
Copy Markdown
Contributor Author

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.

Comment thread src/script/trace.cpp Outdated
void TraceScript(const ScriptTraceFrame& trace_frame)
{
// Copy the callback in case another thread attempts to de-register
ScriptTraceCallback callback{WITH_LOCK(g_script_trace_mutex, return g_script_trace_callback)};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

@sedited
sedited force-pushed the kernel_script_tracer branch from 2df591d to a131d01 Compare July 13, 2026 20:19
@alexanderwiederin

Copy link
Copy Markdown
Contributor

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

@sedited
sedited force-pushed the kernel_script_tracer branch from a131d01 to 114e48e Compare July 14, 2026 10:46
@w0xlt

w0xlt commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

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
 }

@w0xlt

w0xlt commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

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

alexanderwiederin added a commit to alexanderwiederin/rust-bitcoinkernel that referenced this pull request Sep 2, 2026
…acer

Declare the btck_script_trace_* and btck_script_eval_stack_* API added
in bitcoin/bitcoin#35641, which invokes a globally registered callback
on entry to script evaluation, once per decoded opcode and on exit.

The three new opaque handles (btck_ScriptTraceFrame,
btck_ScriptEvalStack and btck_ScriptEvalStack_item) are all views owned
by the kernel, so none need a destroy function. btck_ScriptTraceCallback
is declared as a bare function pointer rather than an Option, matching
btck_LogCallback, since the parameter is marked
BITCOINKERNEL_ARG_NONNULL(1).
@sedited
sedited force-pushed the kernel_script_tracer branch from 97462c6 to 12f4b91 Compare September 24, 2026 11:19
@sedited

sedited commented Sep 24, 2026

Copy link
Copy Markdown
Contributor Author

Updated 97462c6 -> 12f4b91 (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 #35641 (comment) (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 #35641 (comment) (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

w0xlt commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

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")};

@sedited

sedited commented Sep 25, 2026

Copy link
Copy Markdown
Contributor Author

Updated 12f4b91 -> 37f3b85 (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.

alexanderwiederin added a commit to alexanderwiederin/rust-bitcoinkernel that referenced this pull request Sep 25, 2026
…acer

Declare the btck_script_trace_* and btck_script_eval_stack_* API added
in bitcoin/bitcoin#35641, which invokes a globally registered callback
on entry to script evaluation, once per decoded opcode and on exit.

The three new opaque handles (btck_ScriptTraceFrame,
btck_ScriptEvalStack and btck_ScriptEvalStack_item) are all views owned
by the kernel, so none need a destroy function. btck_ScriptTraceCallback
is declared as a bare function pointer rather than an Option, matching
btck_LogCallback, since the parameter is marked
BITCOINKERNEL_ARG_NONNULL(1).

@alexanderwiederin alexanderwiederin left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing some BITCOINKERNEL_WARN_UNUSED_RESULT I think.

Comment thread src/kernel/bitcoinkernel.h Resolved
Comment thread src/kernel/bitcoinkernel.h Resolved
Comment thread src/kernel/bitcoinkernel.h Resolved
@sedited
sedited force-pushed the kernel_script_tracer branch from 37f3b85 to e8a8daf Compare October 6, 2026 13:22
@sedited

sedited commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

Updated 37f3b85 -> e8a8daf (kernel_script_tracer_4 -> kernel_script_tracer_5, compare)

alexanderwiederin added a commit to alexanderwiederin/rust-bitcoinkernel that referenced this pull request Oct 6, 2026
…acer

Declare the btck_script_trace_* and btck_script_eval_stack_* API added
in bitcoin/bitcoin#35641, which invokes a globally registered callback
on entry to script evaluation, once per decoded opcode and on exit.

The three new opaque handles (btck_ScriptTraceFrame,
btck_ScriptEvalStack and btck_ScriptEvalStack_item) are all views owned
by the kernel, so none need a destroy function. btck_ScriptTraceCallback
is declared as a bare function pointer rather than an Option, matching
btck_LogCallback, since the parameter is marked
BITCOINKERNEL_ARG_NONNULL(1).
This adds a callback hook to the kernel library C header for getting the
current script execution 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.

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 execution 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.
@sedited
sedited force-pushed the kernel_script_tracer branch from e8a8daf to 0161ebd Compare October 9, 2026 12:29
@sedited

sedited commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

@fametrano

Copy link
Copy Markdown

tACK 0161ebd

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.

Comment on lines +2128 to +2131
* @param[in] frame Pointer to the current execution state snapshot. Data
* in the struct is only valid for the duration of this callback.
*/
typedef void (*btck_ScriptTraceCallback)(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* @param[in] frame Pointer to the current execution state snapshot. Data
* in the struct is only valid for the duration of this callback.
*/
typedef void (*btck_ScriptTraceCallback)(
* @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)(

Comment on lines +2135 to +2137
/// Whether this is a begin, step, or end frame.
BITCOINKERNEL_API btck_ScriptTraceFrameKind btck_script_trace_frame_get_kind(
const btck_ScriptTraceFrame* frame) BITCOINKERNEL_ARG_NONNULL(1);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

BOOST_REQUIRE(!states.empty());
BOOST_CHECK(!states.back().m_script_error);

ScriptPubkey script_pubkey{hex_string_to_byte_vec("00636451675168675168")};

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Suggested change
ScriptPubkey script_pubkey{hex_string_to_byte_vec("00636451675168675168")};
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

};

template <ScriptTraceT T>
void ScriptTraceSetCallback(std::unique_ptr<T> trace)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
void ScriptTraceSetCallback(std::unique_ptr<T> trace)
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)?

return script_error;
}

std::optional<std::array<unsigned char, 32>> TapleafHash() const

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.


btck_SigVersion btck_script_trace_frame_get_sig_version(const btck_ScriptTraceFrame* frame)
{
return cast_btck_sig_version(static_cast<SigVersion>(btck_ScriptTraceFrame::get(frame).sig_version));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +2270 to +2276
/// Get one of the items in the script evaluation stack.
BITCOINKERNEL_API const btck_ScriptEvalStackItem* btck_script_eval_stack_get_item_at(
const btck_ScriptEvalStack* stack, size_t index) BITCOINKERNEL_ARG_NONNULL(1);

/// Write out bytes from one of the items in the script evaluation stack.
BITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_script_eval_stack_item_to_bytes(
const btck_ScriptEvalStackItem* item, btck_WriteBytes writer, void* user_data) BITCOINKERNEL_ARG_NONNULL(1, 2);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)?

Comment thread src/script/trace.h
Comment on lines +45 to +60
struct ScriptTraceScope {
const ScriptTraceCallback m_callback;
std::vector<std::vector<unsigned char>>& m_stack;
const CScript& m_script;
uint32_t& m_opcode_pos;
std::vector<std::vector<unsigned char>>& m_altstack;
int& m_op_count;
uint8_t m_sig_version;
const unsigned char* m_tapleaf_hash;
uint32_t& m_codeseparator_pos;
const ScriptError* m_error;

ScriptTraceScope(std::vector<std::vector<unsigned char>>& stack, const CScript& script, uint32_t& opcode_pos,
std::vector<std::vector<unsigned char>>& altstack,
int& nOpCount, uint8_t sigversion, const unsigned char* tapleaf_hash,
uint32_t& codeseparator_pos, const ScriptError* error) :

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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&?

return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
}

SCRIPT_TRACE_STEP(fExec, opcode);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +2233 to +2235
/// Index of the current opcode under evaluation (counting opcodes, not bytes)
BITCOINKERNEL_API uint32_t btck_script_trace_frame_get_opcode_pos(
const btck_ScriptTraceFrame* frame) BITCOINKERNEL_ARG_NONNULL(1);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
/// Index of the current opcode under evaluation (counting opcodes, not bytes)
BITCOINKERNEL_API uint32_t btck_script_trace_frame_get_opcode_pos(
const btck_ScriptTraceFrame* frame) BITCOINKERNEL_ARG_NONNULL(1);
/**
* @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.

@alexanderwiederin

Copy link
Copy Markdown
Contributor

@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

yuvicc commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Concept ACK

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: API Development

Development

Successfully merging this pull request may close these issues.