Repository navigation
script: store interpreter stack elements as reference-counted objects - #36721
conduition wants to merge 5 commits into
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process. ConflictsReviewers, this pull request conflicts with the following ones:
If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. |
| static const ScriptStackElem elemFalse = MakeStackElem(valtype(0)); | ||
| // static const valtype vchZero(0); | ||
| static const valtype vchTrue(1, 1); | ||
| static const ScriptStackElem elemTrue = MakeStackElem(valtype(1, 1)); |
There was a problem hiding this comment.
Wait, doesn't elemTrue introduce cross-core atomic contention in CCheckQueue?
With static const valtype vchTrue(1, 1), reads were const and the cache line remained in Shared (S) state across all core caches without bus traffic.
Copying a std::shared_ptr executes lock xaddl on _M_use_count. When parallel script verification evaluates a valid block across 16+ worker threads, almost every standard transaction ends in a successful CHECKSIG or EQUAL. All worker threads contend on this single control block, bouncing the cache line across sockets and serializing execution. In local benchmarks, multi-threaded throughput degrades by over 2x (Welch test t = -4.86, p = 1.56e-5).
Beyond contention, wrapping elements in std::shared_ptr doubles heap allocations on the hot path. Moving a valtype into the stack is a 3-pointer transfer, whereas MakeStackElem allocates a separate 48-byte control block (std::make_shared). Pushing elements becomes ~4x slower (312 ns vs 1310 ns per push).
Since the interpreter stack machine is thread-local, atomic refcounting on OP_DUP/OP_DROP adds synchronization where no cross-thread sharing exists.
There was a problem hiding this comment.
Wait, doesn't elemTrue introduce cross-core atomic contention in CCheckQueue?
Good observation. I mitigated by making elemTrue and elemFalse per-execution locals, so distinct script eval threads no longer contend with each other. 2405fe2
Since the interpreter stack machine is thread-local, atomic refcounting on OP_DUP/OP_DROP adds synchronization where no cross-thread sharing exists.
Yes, the smart pointer we use doesn't need to be atomically synchronized. I chose shared_ptr because it was readily available in std and already in use elsewhere in the code. Coming from a Rust background, i would want to use Rc (a reference counting pointer type with no cross-thread synchronization) for representing ScriptStackElem. However i found no equivalent type in the C++ standard library. shared_ptr is synchronized which we don't need here, it adds overhead. boost::intrusive_ptr is an option i suppose but isn't used elsewhere so i reasoned it'd be best to stick to repo convention. Rolling my own seemed like an even worse option. Do you have any recommendations?
Beyond contention, wrapping elements in std::shared_ptr doubles heap allocations on the hot path. Moving a valtype into the stack is a 3-pointer transfer, whereas MakeStackElem allocates a separate 48-byte control block (std::make_shared).
According to the bench_bitcoin results on my machine at least, this doesn't seem to make a big difference in terms of concrete script interpreter performance. The only benchmark that gets meaningfully worse is VerifyNestedIfScript, which slows from 11400 ns to 15600 ns (+38%), probably because its main benchmark workload is stack pushing which this PR does worsen. I expect we could improve that if we use a non-synchronized reference counter type.
The deltas for all other benchmarks (including for common standard scripts like P2PKH) are within noise.
If it would help, i could write some benchmarks that more precisely stress-test the allocations that this change introduces.
In local benchmarks, multi-threaded throughput degrades by over 2x (Welch test t = -4.86, p = 1.56e-5).
Pushing elements becomes ~4x slower (312 ns vs 1310 ns per push).
Could you show how you got those numbers? i don't see a dedicated stack-pushing or multi-threaded benchmark so maybe i'm running the wrong harness.
There was a problem hiding this comment.
Could you show how you got those numbers?
The contention was measured in CCheckQueue (16 workers) against the static instance prior to 62520cf. Moving them to locals eliminates the bus lock bouncing, but replaces it with two unconditional heap allocations on every EvalScript call before inspecting a single opcode. That allocator churn explains the +38.8% regression in your benchmark.
The larger issue is architectural. The 10KB duplication attack is consensus-invalid today under MAX_SCRIPT_ELEMENT_SIZE = 520. Any future soft fork that raises element limits must budget its own hashing costs anyway (analogous to BIP 342 sigops), rather than penalizing existing mainnet script evaluation. Also, pointer identity does not imply data equality. Pushing identical elements separately creates distinct allocations, bypassing a pointer-keyed cache entirely while pinning dropped elements in memory.
Do you have any recommendations?
I don't recommend alternative smart pointers here. The interpreter hot path shouldn't pay heap or refcounting overhead for a non-existent attack. Concept NACK.
There was a problem hiding this comment.
The contention was measured in CCheckQueue (16 workers) against the static instance prior to 62520cf.
I ran the CCheckQueueSpeedPrevectorJob benchmark on this branch and it doesn't seem to give any worse results on than master. Could you please provide links or instructions for how to replicate your benchmark?
That allocator churn explains the +38.8% regression in your benchmark.
The VerifyNestedIfScript benchmark only allocates those locals once per benchmark loop. One allocation does not a benchmark kill. The other benchmarks that do this (e.g. VerifyScriptP2WPKH) have not regressed. The +38% slowdown in VerifyNestedIfScript i believe is coming from the additional allocations involved in pushing each of the 1000 stack elements (any elements, including elemTrue and elemFalse).
The larger issue is architectural. The 10KB duplication attack is consensus-invalid today under MAX_SCRIPT_ELEMENT_SIZE = 520. Any future soft fork that raises element limits must budget its own hashing costs anyway (analogous to BIP 342 sigops), rather than penalizing existing mainnet script evaluation.
We did consider enforcing new consensus rules as a solution. See this section. The most obvious option is to merely prohibit duplication or hashing opcodes from executing on inputs larger than today's 520b limit. A more subtle sigops-like budget system is also an option.
However, we reasoned that additional implementation complexity (pointers and caching) was worth it for a simpler and more permissive consensus rule set, with less arbitrary discontinuities.
Also, pointer identity does not imply data equality. Pushing identical elements separately creates distinct allocations, bypassing a pointer-keyed cache entirely while pinning dropped elements in memory.
I don't think we need be concerned with attacks that push identical elements, because such pushes must be paid for by the attacker in bandwidth and fees. We are concerned with duplicate-and-hash attacks which are cheap and asymmetrical to their validation cost.
The cache does not need to guarantee "if we hashed the bytes 0xABCD... then we never need to hash them again". We only need to guarantee "if a spender pays to push some large stack elements, we only hash each such element at most once".
Put another way... It's OK if two distinct pointers refer to the same bytes cause two cache misses. What would NOT be OK would be if a pointer is reallocated to store a different byte vector, after a prior cache insertion for that pointer, leading to a cache hit that yields the wrong hash. We prevent this by pinning any such elements' pointers for the duration of script evaluation. For details, see my working branch for stage 2: https://github.com/conduition/bitcoin/compare/scriptvalptr-stage1..scriptvalptr-stage2
This design would break if we had opcodes that allowed users to modify or push large stack elements, such as OP_CAT for example. But under the current script system, it seems robust and simple.
|
🚧 At least one of the CI tasks failed. HintsTry to run the tests locally, according to the documentation. However, a CI failure may still
Leave a comment here, if you need help tracking down a confusing failure. |
ismaelsadeeq
left a comment
There was a problem hiding this comment.
I looked at this issue in the past and concluded it wasn't worth the effort, but from the angle of increasing the max stack element size, it does become an attack vector.
Did you benchmark the cost of making the inner vector a shared pointer for current regular scripts? I'd expect it to be slightly worse.
I think we can do better by turning the stack element into a standalone class that is either a prevector or a std::shared_ptr<std::vector> depending on the element's size. That should be more efficient than the status quo for small elements and no worse for regular scripts, while keeping cheap duplication for large ones.
Also, my agent and Ralph (https://git.fish.foo/bitcoin/bitcoin/pulls/36721#issuecomment-619311) flagged potential contention on the shared shared_ptr reference count might be worth looking at under parallel validation context.
|
Please fold the fixups back or turn it into a draft to signal that it's not ready for review yet |
d66809c to
4b60e31
Compare
|
@l0rinc Folded |
@ismaelsadeeq I used the existing benchmarks and the delta is negligible or better for regular scripts. The only one meaningfully worsened by this PR is
run-to-run noise on my machine seems to be +/- 7%, so everything but I did not go so far as to write any new benchmarks, but I will try to hammer some together that better demonstrate the costs this PR introduces.
Neat idea. In my current stage 2 impl, the hash cache has a minimum input size needed to trigger it (currently set to 128 bytes). If we arrange so that the prevector's small-buffer size limit matches the hash cache minimum threshold, then we'd never hit the prevector's small-buffer size limit. Add in the fact that stack elements are never grown, so their size is fixed at constructor time. So we could have a Is that worth the complexity in consensus-critical code though? the benchmarks don't seem to indicate any major issues with the present design. @Yudis-bit did find benchmarks that slowed down, but i need to see how he got those numbers first before i can figure out why. |
Yeah, I was just after the numbers. Signature verification dominates the interpreter today, so per-push cost is noise. But that's an artifact of where the cost sits right now, not a permanent property: if sigop verification moves off the hot path — batched or offloaded (e.g. to a GPU), with optimistic script execution that defers the actual signature checks and only fails later if one doesn't verify — then stack-op work becomes the dominant interpreter cost, and a few ns per push starts to matter. So the +38% on pushes isn't irrelevant forever; it's just hidden behind ECDSA/Schnorr for now.
Nice, curious to see them.
Really like this.
Yep, thin motivation while the underlying proposal is speculative. But it's a nice problem to brainstorm, and if we're doing the refactor anyway, doing the more optimal change is better for me. Another potential direction is to have the (proposed sigop) opcode read from multiple stack elements instead of one. Then the signature stays as ≤520-byte chunks and gets streamed into the verifier, and we never raise the element-size limit at all, so the large-element attack surface is never opened in the first place. |
4b60e31 to
35d0834
Compare
|
@ismaelsadeeq Benchmarks pushed. I added them as earlier commits so they can be tested with or without the
So basically it seems like this change makes simple data pushing slower, but makes duplication much cheaper. I will look into the union type idea and see whether that improves the situation at all.
We did consider this type of chunking as an option. Ultimately this would be a trade-off that passes complexity down to wallet developers and users. This gets especially hairy when we consider that some signature algorithms like SHRINCS have variable-size signatures. So we decided against this route, full explanation here |
|
after some experimenting with the union-based approach, i could not make it perform meaningfully better than a simple intrusive ref-counter which seemed much less error-prone. Experimental intrusive ref-counting code pushed to this branch. It achieves performance at or better than
The cost of course is the greater impl complexity, using a homebrewed pointer type to handle stack elements is risky. If you think the performance is worth it, i'll update this PR branch. EDIT: updated with additional benchmarks |
35d0834 to
8b9ef52
Compare
I started reading the proposal, and the branching inside I think it'd be better to split them into separate BIPs for stateful SHRINCS and stateless SHRINCS, and commit both as leaves in a taproot tree. Then which scheme runs is decided by the leaf you reveal, not by checking the signature mid-opcode eval. (I'd recommend this even if we end up increasing the script element size.) On the variable-size point from full explanation here, splitting actually makes it okayish. The stateless leaf is fixed-size, a fixed n-element read, no decisions. The stateful leaf is variable, and we can do like a self-delimiting read, read chunks into the verifier, which already has the length from an indicator byte in the first chunk, and stop once it has that many bytes capped at a max. (You could instead pad to a fixed n for the stateful leaf with empties to make the pop count constant, but that's a bit of a hack) I think this is a far smaller thing to reason about than multi-KB elements across the whole interpreter (it has a wider scope). I think this is ideally the same with the current version of the shrincs proposal?, both leaves under one output are still one address that can always spend, stateful or stateless. re: #36721 (comment) Nice benchmarks, thanks for the results. |
i should disambiguate here: the multiplexed OP_CHECKSIG defined in that BIP is designed to deploy new signature algorithms like SHRINCS, or maybe someday SQIsign/Falcon/whatever. That BIP doesn't know anything about the stateful vs stateless signing components in SHRINCS. It treats every signature scheme as a black box verification subroutine that takes a triple of byte strings in, and returns success/fail. SHRINCS is defined as one single unified signature scheme within that framework. I should also mention that BIP is presently being rewritten, to remove SHRINCS-specific language SHRINCS' verification subroutine does indeed branch based on the signature's leading 'indicator' byte - that is a hard requirement to achieve its design properties. But to the script interpreter, that branching is completely black-box. It is not part of script. If we chunked signatures into 520b elements though, and relied on the signature itself to tell us how many chunks to pop, we could not use SHRINCS (or any variable-size signature scheme, for that matter) as a black box anymore. Increasing the stack element size limit allows us to keep that black-box compatibility with any signature scheme up to the new size limit. Here is the current
We did consider a design where the stateful and stateless components are entirely separate schemes, whose keys can be stashed in disjoint tapscript leaves. However this would severely complicate scripting. Think about how you'd design a 2-of-3 multisig output, where each signer has two possible keys they may use, and we don't know which one they'll use until signing time. Every pubkey would need IF/ELSE branching, and every signature would need a true/false decision push (e.g. you sign stateless, i sign stateful, and vice versa, would use completely different pubkeys under this paradigm). |
Fold the two EvalScript declarations into a single one by defaulting the ScriptExecutionData argument, so a caller with no execution data to pass simply omits it instead of going through an overload wrapper. Callers that pass a ScriptError pointer must give a nullptr in this position, and the two fuzz targets that passed a bare nullptr drop the argument entirely. This is pure refactoring with no behaviour change.
The interpreter holds each stack item by value, so every opcode that duplicates or reorders items copies their contents. A future output type may soon raise the maximum stack element size well past today's 520 bytes, at which point a few weight units of script would be enough to drive megabytes of interpreter memory. Store the items as reference-counted objects instead: each element is materialized once per execution and shared from then on, and each gains a stable identity that later work can use as keys for caching. Every caller of the interpreter uses the new stack type. Opcode semantics unchanged.
Add unit tests for the interpreter's reference-counted stack: that duplicating and reordering stack items share a single element rather than copying it, and that an element is released once no stack slot holds it any more. No behaviour changes.
8b9ef52 to
40a419a
Compare
|
Fixed IWYU CI (and figured out how to run the CI on my own fork) |
Clearer, thanks. I think SHRINCS/shrincs-bip#76 approach is better, the leaf-version spec becomes a generic sig check, with each scheme defined in its own BIP. That makes the black-box boundary explicit, which is what I was missing.
Cool, the pubkey flag picks the scheme (e.g. SHRINCS vs BIP340), and within SHRINCS the indicator byte picks stateful vs stateless. From the interpreter's side, it's one indivisible unit; it never looks inside the sig. Makes sense.
Alternative that keeps black-box without raising the limit: the pubkey flag already tells you the scheme, so you can bound the max pop count up front (for SHRINCS). For the exact count, If we do raise the script element size: keeping the 1000-items stack limit means the total stack-data ceiling goes up by a lot. Do you plan to pair that with a lower max stack element count or a max stack bytes budget too?
Indeed, doesn't work for multisig on one pubkey. The two independent leaves in a tree will not play well.
Will await others to chime in and also follow the development. Not sure about https://github.com/SHRINCS/shrincs-bip/blob/4fe68e3a68fd58be6b0e19436ff6fb7a3357a291/leaf-version-0xC2.mediawiki#user-content-Relaxing_the_Max_Stack_Element_Size, still leaning towards the chunking idea. |
darosior
left a comment
There was a problem hiding this comment.
I believe the problem this PR is trying to solve is better addressed at the consensus rule level. This refactoring might still be desirable, but it should be motivated independently of a possible soft fork.
If a proposed consensus change introduces a DoS vector by lifting a limit, the first choice should be to introduce new bounds that make lifting this limit reasonable, not optimise the reference implementation to mitigate it. In this case, this seems clearly preferable to me:
- The current memory bound can be preserved by introducing a limit on the sum of the size of all stack elements.
- The computation bound can be preserved by restricting hashing operations from operating on elements larger than the current maximum stack element size (in the same fashion as the arithmetic opcodes are currently restricted from operating on elements larger than 4 bytes).
Furthermore, the cache approach here is brittle. It assumes a DoS attacker can’t evade the cache, which can’t be guaranteed in general when inputs are attacker-chosen 1. It does hold here, but only indirectly due to restrictions on scripting capabilities for large elements. Such a design would unnecessarily lock us into keeping these restrictions.
Footnotes
-
For instance, this is the reason why Bitcoin Core caches valid signatures but not invalid ones: there is an unbounded number of invalid signatures one can create to evade the cache. ↩
|
discussion seems spread out, but overall agreement with @darosior |
jrakibi
left a comment
There was a problem hiding this comment.
I was experimenting a bit with both changes in stage 1 (ref-counting) and stage 2 (hash caching), using some scripts. I think there are some script cases that neither stage addresses.
One example (assuming the stack limit is raised to 6kb) is a script like this:
<big_blob (6kb)> IFDUP VERIFY …
Both OP_IFDUP and OP_VERIFY scan the element until they find a nonzero byte, so an attacker can push a stack element with the nonzero byte last (5999 zero bytes + 0x01). This forces the interpreter to do 2 full scans of the same shared element for each IFDUP VERIFY pair.
Duplication and hashing cost only a single weight unit in tapscript, with no upper limit on how many times they can be executed, aside from implicit limits due to the 10,000 byte script size maximum.
AFAIK 10,000 byte script size limit you mention in the PR description only applies to legacy and segwit, it doesn't apply to tapscript, so an attacker could produce a script close to the max standard tx weight of 400,000 WU (MAX_STANDARD_TX_WEIGHT).
So the script becomes:
<stack_element (6kb)> [IFDUP VERIFY] (repeated 180000 times)
That's about 366k WU of witness data (180,000 * 2 bytes + 6kb stack bytes).
For a fair comparison, I also scaled your RMD160 script from the PR description up to the same ~366k WU. Since the 10000 byte script limit doesn't apply to tapscript, the worst case in your example could actually be worse than the 4284 RIPEMD160 evaluations you described.
I ran a benchmark on both the 520 and 6000 stack element limits. The results:
| Becnhmark | Element size | 104c7a0 | Stage1 (40a419a) | Stage 2 (1d64225) |
|---|---|---|---|---|
| VerifyDup3HashDropFull_ | 520 b | 204.1 ms | 191.8 ms | 14.5 ms (14x faster) |
| VerifyDup3HashDropFull_ | 6000 b | 1856.2 ms | 1832.3 ms | 13.7 ms (135x faster) |
| VerifyIfDupVerifyLast | 520 b | 83.3 ms | 68.4 ms | 68.6 ms (no change) |
| VerifyIfDupVerifyLast | 6000 b | 728.5 ms | 693.3 ms | 689.7 ms (no change) |
(Benchmark code on my branch if you wanna take a look jrakibi@9d58911, coming from a Rust background, I might be missing something in the C++ code)
For the repeated hashing case from the PR description, stage 2 makes a big difference: about 14x faster with 520 byte and 135× faster with 6000-byte elements, but the boolean scan gets no improvement from stage2, with the 6kb case still about 10x slower than the 520 byte case even after both stages. (Will open an issue on the SHRINCS repo since I have more stuff to share on that, but I guess boolean scanning is also something that needs to be addressed alongside hash caching and reference counting.)
I don't think we need be concerned with attacks that push identical elements, because such pushes must be paid for by the attacker in bandwidth and fees.
I believe that with a variant of the case I gave before, an attacker can create a UTXO whose tapscript always fails execution (eg. ends with OP_FALSE), and make nodes execute this script each time he tries to spend from it, without ever paying a fee for the spends. Nodes reject the spending tx, but he can submit it again (with a small change to dummy witness data to get a new wtxid) and the node re-runs full script validation each time.
I think this PR is useful to have, but am slightly leaning toward keeping the limit of 520 bytes and using chunking for PQ sig instead. Jonas suggestion here SHRINCS/shrincs-bip#3 (comment) makes more sense to me: for SHRINCS, we can always consume 12 chunks, so the number of elements popped doesn't depend on parsing untrusted data, and keep the size limit as it is. We never know if someone can come up with another opcode combination that isn't covered by the mitigations suggested so far (opcode restrictions, hash caching, ref-counting). The boolean scan above is one example that hash caching and ref-counting don't address.
|
@jrakibi weird timing, but I said pretty much this at the link above you edit: note that MAX_STANDARD_TX_WEIGHT isnt consensus, so your numbers are ~10x worse for a one-tx block |
|
@darosior Thanks for your review :)
This seems reasonable to me.
We did consider this option in our BIP, but restricting other opcodes from working on signatures could kill some use-cases. Consider a simple covenant, for instance, using But fair, if reducing impl complexity is the #1 goal, then restricting consensus might be preferable. Though as the below discussion shows, we may want to restrict other opcodes as well as hashing (e.g. duplication).
Yes true. If we are considering changes like OP_CAT that allow near-arbitrary mutation of large stack elements, the cache i propose in stage 2 would be useless. The design is tailored to today's script interpreter but if such changes are on the horizon then it would be the wrong approach. |
|
It's more about keeping our options open, and using the right tool for the job, than privileging implementation simplicity or saying OP_CAT is "on the horizon". Yes we probably want to restrict other opcodes, or preserve some limit on the size of each element (something like 10k bytes should give you an upper bound in the same ballpark as today, i think, but haven't measured). |
@instagibbs @jrakibi Nice finds, i completely missed this. The max script size thing is definitely my oversight, but it means optimization is even more important than i had believed. Your hashing benchmark demonstrates that nicely (thanks for testing!) As for i'm sure that particular case of
Chunking has its own issues. We would need to enforce a "standard chunking" mechanism (e.g. "endianness" of the chunks), and prevent non-deterministic chunking (e.g. If we were to go down the road of resource-limiting consensus rules (instead of the techniques in this PR) then my preference would be for rules like this:
@darosior suggested something similar above. |
|
🐙 This pull request conflicts with the target branch and needs rebase. |
|
Putting this in draft state until we resolve some open questions about the motivation of this PR. The general point of all feedback so far has been that improving the implementation performance is not the right way to go about handling a potential increase in max stack element size. Instead, it sounds like y'all would prefer a consensus-level ruleset which would make large stack elements more robust against abuse. To gather design feedback, i have started this thread on delving: https://delvingbitcoin.org/t/handling-pq-signatures-on-the-stack/3128 |
That seems a very fragile approach. Eg: is 6 bytes per hash, with a different prefix each time that should avoid any benefits from attempts at caching, necessitating input size limits on some or all of 2DUP, CAT and/or HASH160. If streaming hash opcodes (per elements tapscript) are available, then: should avoid any hash caching while only changing stack element order and bumping refcounts. |

Modifies the script interpreter to represent stack elements internally using smart pointers, making duplication memory-cheap, and giving us caching keys which are cheap and guaranteed unique by the compiler. First part of a 2-part project to improve script interpreter performance in preparation for PQ signatures.
No consensus changes - a pure performance improvement refactor.
Motivation
We presently have
MAX_SCRIPT_ELEMENT_SIZE = 520, but in the near future, motivated by the need for PQ signature schemes, we may want to introduce soft fork changes which increase the max stack element size for new output types well into the multi-kilobyte range. This may be perhaps as high as 10kb or more given the current landscape of PQ signature schemes' sizes.Ongoing related work:
This poses a new problem to today's implementations if deployed naively.
Today's Bitcoin script interpreter moves around raw mutable byte vectors to represent stack elements. When those elements are duplicated, the underlying byte vectors are deep-copied. When hash opcodes execute, they always invoke the corresponding hash function and fully ingest the top stack element. Duplication and hashing cost only a single weight unit in tapscript, with no upper limit on how many times they can be executed, aside from implicit limits due to the 10,000 byte script size maximum.
If we were to simply up the stack element size limit from 520b to 10kb, then we exacerbate an existing DoS vector on bitcoin nodes: Push a big (today 520b, maybe someday 10kb) stack element, then duplicate and hash it over and over. Worst case would be a script like this:
...with the
[...]part repeating up to the script size limit. RMD160 is used because it lacks hardware acceleration support and so performs significantly worse than even HASH256 or HASH160, making a more effective CPU attack.This costs the attacker only ~20000 weight units (10kb for the script, 10kb for the stack element), but forces all validators to evaluate OP_RIPEMD160 about 4284 times, each on the same 10kb input. That's about 672588 RMD160 compressions in software.
I ran a benchmark (not in this PR) using this style of script with 520b and 10kb script elements.
This PR
(idea credit: EthanHeilman)
To address this risk, we would want to implement a hash cache for all the hashing opcodes. However, to implement such a cache safely in consensus, we need extremely robust cache keys. A collision in the cache key would be a consensus bug because the cache would return the wrong hash for a given input. But we can't cryptographically hash the inputs to compute a cache key... that is the same work we are trying to avoid with the cache.
Instead we can kill two birds with two PRs.
Stage 1 reduces the asymmetric memory inflation attack allowed by OP_DUP et al. Stage 2 fixes the asymmetric CPU DoS attack. To be clear, neither stage fully prevents an attacker from uploading a series of large stack elements, and duplicating/hashing them. But we do force attackers to pay for those operations with fees and block space.
I have both stage 1 and 2 implemented locally and can show benchmarks to prove the effect of the cache, if desired. I could have submitted it all as one PR but both stages are atomic and could do well with separate review.