mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:47:36 +00:00
WIP: script: store interpreter stack elements as reference-counted objects #36721
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!36721
Loading…
Reference in a new issue
No description provided.
Delete branch "scriptvalptr-stage1"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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.
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.
A summary of reviews will appear here.
Conflicts
Reviewers, 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.
Earlier concerns remain unresolved; see the full report for their current assessments.
🔵 Suggestion · Shared vector elements add heap allocations on push paths
Small and numeric pushes and witness arguments gain allocation overhead, while repeated data pushes lose parser-buffer reuse, so duplication savings alone do not establish a general speedup.
Location:
src/script/interpreter.h:380(head).🔵 Suggestion · Boolean result elements allocate eagerly even when unused
During uncached verification, native Taproot key-path spends construct two pairs of Boolean elements that neither preliminary script uses.
Location:
src/script/interpreter.cpp:432(head).🔵 Suggestion · Benchmark comments misstate tapscript limits and push workloads
The comments confuse a chosen 10,000-byte workload with a tapscript consensus limit and incorrectly distinguish which push benchmarks materialize every element.
Location:
src/bench/verify_script.cpp:157(head).🔵 Suggestion · Oversized P2WSH witnesses allocate an owner per item before rejection
interpreter.cpp:1876 still makes one shared owner per P2WSH witness argument, including empty ones, before EvalScript rejects oversized stacks. Base needed no per-item allocation. Reaching this takes an invalid block with valid PoW, since default relay blocks it first.
Location:
src/script/interpreter.cpp:1873(head).Review coverage was incomplete.
Reviewed:
40a419af6325· Full review report · Previous reportspermalink
Wait, doesn't
elemTrueintroduce cross-core atomic contention inCCheckQueue?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_ptrexecuteslock xaddlon_M_use_count. When parallel script verification evaluates a valid block across 16+ worker threads, almost every standard transaction ends in a successfulCHECKSIGorEQUAL. 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_ptrdoubles heap allocations on the hot path. Moving avaltypeinto the stack is a 3-pointer transfer, whereasMakeStackElemallocates 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_DROPadds synchronization where no cross-thread sharing exists.🚧 At least one of the CI tasks failed.
Task
iwyu: https://github.com/bitcoin/bitcoin/actions/runs/41383997767/job/125213261218LLM reason (✨ experimental): CI failed because IWYU added a missing
<memory>include tosrc/script/sign.cpp, leaving a diff that the formatting/lint check rejects.Hints
Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:
Possibly due to a silent merge conflict (the changes in this pull request being
incompatible with the current code in the target branch). If so, make sure to rebase on the latest
commit of the target branch.
A sanitizer issue, which can only be found by compiling with the sanitizer and running the
affected test.
An intermittent issue.
Leave a comment here, if you need help tracking down a confusing failure.
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 (#36721 (comment)) 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
Good observation. I mitigated by making
elemTrueandelemFalseper-execution locals, so distinct script eval threads no longer contend with each other. https://github.com/bitcoin/bitcoin/pull/36721/commits/2405fe20bab4b4f7def9ecf8c3a2f8dc8e150fddYes, the smart pointer we use doesn't need to be atomically synchronized. I chose
shared_ptrbecause it was readily available instdand already in use elsewhere in the code. Coming from a Rust background, i would want to useRc(a reference counting pointer type with no cross-thread synchronization) for representingScriptStackElem. However i found no equivalent type in the C++ standard library.shared_ptris synchronized which we don't need here, it adds overhead.boost::intrusive_ptris 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?According to the
bench_bitcoinresults 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 isVerifyNestedIfScript, 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.
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.
@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
VerifyNestedIfScriptdue to the number of pushes, leading to a +38% slowdown on that benchmark, but we're talking about a difference of a few nanoseconds per push (on my machine). But that script doesn't seem like a good representative for an adversarial attack or for a common happy path. If an attacker wanted to waste CPU time, they'd use hashing opcodes, which are far slower than push opcodes likeOP_1, or of course checksig opcodes. If he wanted to consume memory, he'd use OP_DUP.run-to-run noise on my machine seems to be +/- 7%, so everything but
VerifyNestedIfScriptwas well within that.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
ScriptStackElemas a struct which embeds a union ofchar[127]andstruct { char* indirect; size_type capacity }. Any value smaller than 128 bytes would fit in the statically allocated array. Any value larger would go to the heap.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.
The contention was measured in
CCheckQueue(16 workers) against the static instance prior to62520cf. Moving them to locals eliminates the bus lock bouncing, but replaces it with two unconditional heap allocations on everyEvalScriptcall 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.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.
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.
I ran the
CCheckQueueSpeedPrevectorJobbenchmark on this branch and it doesn't seem to give any worse results on thanmaster. Could you please provide links or instructions for how to replicate your benchmark?The
VerifyNestedIfScriptbenchmark 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 inVerifyNestedIfScripti believe is coming from the additional allocations involved in pushing each of the 1000 stack elements (any elements, includingelemTrueandelemFalse).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.
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.
@ismaelsadeeq Benchmarks pushed. I added them as earlier commits so they can be tested with or without the
ScriptStackElemchanges.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
masteron these benchmarks.104c7a02scriptvalptr-stage1(8b9ef52a)scriptvalptr-stage1-refctr(ad6cef8b2)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
I started reading the proposal, and the branching inside
OP_CHECKSIGon whether the signature is stateful or stateless feels a bit icky; those are two different schemes, and bundling them into one leaf checksig is where some of the complexity comes from?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.
This way, no spender supplied count, the stop comes from the signature's own (verified) length, so a lie just fails, and the cap means a garbage indicator byte can at worst make you read n elements. Statically then "this opcode pops ≤n, known from the leaf".
(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: https://github.com/bitcoin/bitcoin/pull/36721#issuecomment-6624074329
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
shrincs_verifyreference code in case you're interested.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).
Fixed IWYU CI (and figured out how to run the CI on my own fork)
Clearer, thanks. I think https://github.com/SHRINCS/shrincs-bip/pull/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.
So scheme choice stays committed per key/leaf (the flag lives in the pubkey). With that rewrite reserving
0x01and moving SHRINCS out to its own BIP/flag, a scheme-flagged pubkey locks that spending path to that scheme, and only new outputs adopt future schemes. Is that the intended upgrade hook?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,
OP_CHECKSIGpops the pubkey and the first chunk, then lets the verifier read the indicator byte and say how many more chunks it needs, pops them, and verifies the concatenation. The interpreter never parses the sig itself, the verifier returns an opaque, bounded count, so it stays black-box; the signature just arrives as ≤520-byte pieces. (Inspired by https://github.com/SHRINCS/shrincs-bip/issues/3#issuecomment-4918125246.) And when you add a new flag the max can be adapted as well?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
github.com/SHRINCS/shrincs-bip@4fe68e3a68/leaf-version-0xC2.mediawiki (user-content-Relaxing_the_Max_Stack_Element_Size), still leaning towards the chunking idea.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:
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.
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
https://github.com/SHRINCS/shrincs-bip/issues/3#issuecomment-6858912363
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:
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 VERIFYpair.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:
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:
104c7a028840a419af63)(Benchmark code on my branch if you wanna take a look
github.com/jrakibi/bitcoin@9d589117cb, 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 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 https://github.com/SHRINCS/shrincs-bip/issues/3#issuecomment-4918125246 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
SIGHASH_ANYPREVOUT, and committing to the hash of a precomputed signature.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
IFDUPandVERIFY... I didn't expectCastToBoolcould consume so much CPU. That is genuinely surprising. I would say it is outside the scope of this PR (This PR doesn't try to optimize byte scanning), but is certainly well-within the scope of the overall plan that this PR is part of.i'm sure that particular case of
CastToBoolcould be addressed with implementation (e.g. more caching) or new consensus rules (requireOP_IFDUPto enforceMINIMALIFasOP_IFdoes today in tapscript). But i think the vein that you guys are poking at is that additional DoS vectors may skulk about the script interpreter if we increase the stack element size limit, and catching all of them is hard. (Another one that comes to mind isOP_EQUALwhich runsstd::equalon the top-two stack elements, which likely has similar performance asCastToBool).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.
<0xABCD> <0xEF>should not be treated the same as<0xAB> <0xCDEF>). Signers that handle pre-signed transactions from untrusted parties (e.g. lightning, ark, etc) would need to correctly follow these rules or else they may be vulnerable.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.
@ajtowns hashing small elements is not a concern. In fact my prototype cache impl (branch) ignores small elements completely, because the cache is more expensive than it's worth in that case. It relies on an assumption that large stack elements cannot be mutated, e.g. with OP_CAT