<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by bitcoincashautist on Medium]]></title>
        <description><![CDATA[Stories by bitcoincashautist on Medium]]></description>
        <link>https://medium.com/@bitcoincashautist?source=rss-1113010c7f68------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*N-b0T4gvBKQzXzN-MtGXgA.png</url>
            <title>Stories by bitcoincashautist on Medium</title>
            <link>https://medium.com/@bitcoincashautist?source=rss-1113010c7f68------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 15:38:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bitcoincashautist/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How To Encode and Decode a Bitcoin Cash Cashaddress]]></title>
            <link>https://medium.com/@bitcoincashautist/how-to-encode-and-decode-a-bitcoin-cash-cashaddress-833293088742?source=rss-1113010c7f68------2</link>
            <guid isPermaLink="false">https://medium.com/p/833293088742</guid>
            <category><![CDATA[bitcoincash]]></category>
            <dc:creator><![CDATA[bitcoincashautist]]></dc:creator>
            <pubDate>Sat, 17 Sep 2022 08:08:39 GMT</pubDate>
            <atom:updated>2022-09-17T08:16:38.399Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been experimenting with Bitcoin Cash smart contracts and constructing transactions manually so had a need for an easy way to convert raw locking script to an address and back, so here’s a little howto.</p><p>Cashaddress specification can be found here: <a href="https://github.com/bitcoincashorg/bitcoincash.org/blob/master/spec/cashaddr.md">https://github.com/bitcoincashorg/bitcoincash.org/blob/master/spec/cashaddr.md</a></p><h3>Setup</h3><p>Download <a href="https://github.com/Electron-Cash/Electron-Cash/blob/master/electroncash/cashaddr.py">https://github.com/Electron-Cash/Electron-Cash/blob/master/electroncash/cashaddr.py</a> to some folder</p><p>Open a shell terminal in that same folder</p><h3>Encoding</h3><p>To <strong>encode</strong>, run this one-liner:</p><pre>python -c &#39;exec(open(&quot;cashaddr.py&quot;).read()); print(encode(&quot;bchtest&quot;,1,bytes.fromhex(&quot;beefbeefbeefbeefbeefbeefbeefbeefbeefbeef&quot;)))&#39;</pre><p>Output:</p><pre>pzlwl0h0hmhmama7a7lwl0h0hmhmama7auewyf5kev</pre><p>The “bchtest” is the address prefix, the number 1 is the address type (1 here it means 20-byte P2SH), and the “beef…beef” string is the hash of either a public key (P2PKH) or a redeem script (P2SH).</p><h3>Decoding</h3><p>To <strong>decode</strong>, run this one-liner:</p><pre>python -c &#39;exec(open(&quot;cashaddr.py&quot;).read()); ad=decode(&quot;bchtest:pzlwl0h0hmhmama7a7lwl0h0hmhmama7auewyf5kev&quot;); print(ad[0]); print(ad[1]); print(ad[2].hex())&#39;</pre><p>Output</p><pre>bchtest<br>1<br>beefbeefbeefbeefbeefbeefbeefbeefbeefbeef</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=833293088742" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluate Viability of Bitcoin Cash Transaction Format or ID Change]]></title>
            <link>https://medium.com/@bitcoincashautist/evaluate-viability-of-bitcoin-cash-transaction-format-or-id-change-b62c990aefcb?source=rss-1113010c7f68------2</link>
            <guid isPermaLink="false">https://medium.com/p/b62c990aefcb</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[bitcoincashautist]]></dc:creator>
            <pubDate>Fri, 29 Jul 2022 08:26:36 GMT</pubDate>
            <atom:updated>2022-07-29T10:17:26.254Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<h3>Summary</h3><p>Transaction format can be upgraded in a way which would have predictable costs and risks. Most of the known desired features from transaction format changes can be introduced in a way with better contained costs and risks.</p><p>Because there exists a knowable node-contained-cost alternative, there is a natural deterrent to changing the format: it would be a greater burden on the one who pushes for a change than it would be to adapt his change to the alternative approach.</p><h3>Current Situation</h3><h3>Transaction FORMAT</h3><p>Here we define FORMAT as specifying only the data sizes and data types, not the semantics of individual fields.</p><pre>* version, 4-byte uint<br>* input count, compact size integer<br>* transaction inputs<br>    * input0<br>        * previous output transaction hash, 32 raw bytes<br>        * previous output index, 4-byte uint<br>        * unlocking script length, compact size integer<br>        * unlocking script, variable number of raw bytes<br>        * sequence number, 4-byte uint<br>    * ...<br>    * inputN<br>* output count, compact size integer<br>* transaction outputs<br>    * output0<br>        * satoshi amount, 8-byte uint<br>        * locking script length, compact size integer<br>        * locking script, variable number of raw bytes<br>    * ...<br>    * outputN<br>* lock-time, 4-byte uint</pre><p>There was never a precedent for changing the above TX format.<br>There have been precedents only for changing semantics of some individual fields:</p><ul><li>version: BIP-0068</li><li>unlocking script: Script VM upgrades</li><li>sequence number: BIP-0068, BIP-0113</li><li>locking script: Script VM upgrades</li><li>lock time: BIP-0113</li></ul><p>The version field was never locked down using consensus, so an assumption that a transaction&#39;s FORMAT could be inferred only from its contents would not hold, not without a block height context. This could be changed by locking it down now, and then the assumption would hold only for never-before-seen version values.</p><h3>Transaction TYPE</h3><p>There are two main types:</p><ul><li>Coinbase;</li><li>Regular.</li></ul><p>The transaction version field is NOT used to indicate the main type. Instead, consensus verification uses simple heuristic [1] to infer the TX type: the first TX in a block is the coinbase TX, all others are regular.</p><p>Semantics of the previous output transaction hash and previous output index fields are inferred from the main type. For coinbase transactions it is locked down to constants: a 32-byte 0 for the hash, and 4-byte 0xFFFFFFFF for the index. For regular transactions it is a reference to some previous transaction&#39;s output.</p><p>With BIP-0068 [2], the regular type got divided into two sub-types:</p><ol><li>Interpret the inputs sequence number as sequence number;</li><li>Interpret the inputs sequence number as relative lock-times according to BIP-0068 [3] semantics.</li></ol><p>These two sub-types are commonly referred to as “v1” and “v2” transactions, and transaction version field is currently used by consensus only to distinguish the two sub-types. Any regular transaction with version &gt;= 2 is considered a v2 transaction, and others are considered v1.</p><p>There are no other consensus rules enforced over the version field, so on the blockchain there exist transaction with arbitrary data stored in the field. Without the context of the block height, some past transactions could be considered to be v2 even though v2 was not defined when they were mined.</p><p>Also note that the standardness network rule [4] requires version &gt;= 1 &amp;&amp; version &lt;= 2.</p><h3>Transaction ID</h3><p>It is used to build transactions cryptographic commitment scheme [5] and defined as the double SHA-256 digest of the whole transaction. It is a calculated field used for transactions Merkle tree, where transactions are leaf data and their TXIDs are leaf node hashes. Only the Merkle tree root node hash is written inside the block “raw” format, as commitment to all transactions in the block. The root node ID will also be a leaf ID (TXID) only if the block contains exactly one transaction, and that one transaction will then be a coinbase transaction. TXIDs of regular transactions will only appear in “raw” blocks when spent from, when referenced by an input of a newer transaction.</p><p>Even though most TXIDs of new transactions never get recorded into “raw” blocks, software processing transactions will still have to record TXIDs in local databases and caches.</p><p>To summarize, there are three things that define the transaction ID:</p><ul><li>The hashing algorithm: double SHA-256;</li><li>The size of the digest: 32 bytes;</li><li>The commitment preimage: whole “raw” transaction.</li></ul><p>There was never a precedent for changing any of the above.</p><h3>Costs and Risks of Change</h3><p>Changing the FORMAT in node software is something that could easily be done by competent programmers, this is not where the majority of cost would be. There may exist software which relies on node API to hand it verified “raw” transactions. Changing the FORMAT would have the same effect as changing the node API, and the cost would then spread to node-dependent software. We can draw a parallel between node software and the Linux kernel. The Bitcoin Cash “kernel” is what runs the peer-to-peer electronic cash system, as opposed to a single computer’s operating system. Even small changes there could have a cascade effect on the whole system, and everyone who depends on the system to conduct their business.</p><p>“We do not break userspace!” — Linus Torvalds</p><p>At least not without a very good reason. Change in transaction FORMAT or ID would affect all software that has to parse raw transactions, and the total cost would be the summed cost of upgrading all that software. The problem is not node software, or well known and open-source node-dependent software. We can evaluate that part of the cost, because it is known or, at least, knowable.</p><p>For the remainder we would have to expend large amounts of resources to communicate with and help migrate every known operator. Also, we would have to explore to get the lesser known ones, and it would be difficult to tell if we left any critical ones out. The cost of evaluation is itself a part of the total cost. We can visually illustrate this problem:</p><p>We can still expect to find, post upgrade, that someone had missed the memo. That is a difficult to assess risk for the Bitcoin Cash image and all Bitcoin Cash users who could be affected by a temporary disruption of services they rely on. With the breaking kind of change, a misstep in migration or risk assessment has the potential to result in catastrophic damage to the ecosystem that would be difficult to recover from.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/0*xKFUF3twR3LlRYGj.png" /></figure><p>To get the idea, here we list broad categories of systems that could be affected by a breaking change:</p><ul><li>block explorers,</li><li>blockchain API providers,</li><li>blockchain indexers,</li><li>exchanges,</li><li>payment processors,</li><li>wallet backends,</li><li>script debuggers,</li><li>smart contract compilers,</li><li>software libraries,</li><li>etc.</li></ul><p>This document merely highlights the nature of the costs and risks involved, and it could be used as a starting point of a process to solicit further input from potentially affected parties.</p><h3>Reasons for Change</h3><p>We can define two broad categories of rationales:</p><ol><li>Maintenance</li><li>New features</li></ol><p>Optimization is part of maintenance, and there were proposals to optimize the format. It was never really necessary because benefits would be some savings in node operating costs, where costs and risks would clearly outweigh the benefits.</p><p>Some catastrophic security flaw would be another, extreme, example of maintenance. In this scenario, fixing the flaw would be a matter of survival for the network, and if breaking the format or commitment scheme was the only way, then it would have to be done. Both transaction format and commitment scheme have been tested for almost 12 years, and we see it as unlikely that a severe security flaw would be discovered now.</p><p>There were considerations to increase precision of base units (fractional satoshis), which is presently not necessary. Only in the future, if the value of Bitcoin Cash would grow so much that it would be impractical to make small transactions, could it become a matter of great importance.</p><p>The cost of change at a later date would be greater because more software would be reliant on the fixed format and therefore affected. Would that be a good reason to upgrade the format now while the cost is smaller? That would be the case only if changing the format would be the only possible way to increase precision.</p><p>Similarly, there were considerations to permanently fix transaction malleability. This could be done by moving signatures from unlocking script into a dedicated transaction field. They would then be referenced from the unlocking script by signature opcodes, so signatures could sign inputs unlocking scripts, too. As we will see below, a new field can be added without changing the transaction format.</p><p>With new features, we must evaluate the costs vs benefits. The benefits will be contained to some subset of users who would use the feature. Maybe the feature would attract more users, in which case everyone would reap the benefits through increased value of Bitcoin Cash. Some kinds of features can have vaguely defined benefits because their value can come from enabled innovations beyond our control or knowledge, benefits could be speculative. Burden of proof for benefits is in proving at least some threshold level that would outweigh the costs.</p><p>How to set the threshold level when the costs are unknowable? It is impossible. We should instead strive to make the costs side of the scale knowable. If there is an alternative approach that has knowable costs and risks, then it is more likely that the alternative would stand a better chance of being implemented.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/0*JJqir80rPimQkZzK.png" /></figure><h3>Lowering The Cost of Future Change by Versioning Transaction FORMAT</h3><p>There would be value in paying off the technical debt by versioning transaction FORMAT, so any future upgrades that would prefer to change it would not have to take the whole burden of changing the format.</p><p>Old software does not expect the version field to have anything to do with the format of the TX it is being fed. First step would be locking the version field using consensus, so it could later be used to signal any future consensus rules that would come after the version lock. Just the version lock would not break old software so only new, version-aware, software would benefit from that.</p><p>It would still help with general preparedness for a future, breaking, change. From then onward, we could use part of the version field as an upgrade counter and match it 1-to-1 with applicable consensus specification. As a consequence:</p><ul><li>Any version value seen before the version lock would relate many-to-many with &quot;prehistorical&quot; consensus specifications, therefore be indeterminate. However, it would narrow it down to pre-lock era.</li><li>Post-lock, the counter part of the version field would be 1-to-1 with newer consensus specifications. We would have other bits free to allow us to have multiple kinds of TXes exist part of the same consensus specification, which would make the whole version field relate many-to-1 with consensus specifications.</li></ul><p>Alongside the counter, we could use a flag to signal whether an upgrade is breaking or non-breaking, e.g. when we increment the counter for a new HF, if it is non-breaking then we do not toggle the flag, and if it is, then we toggle the flag. Old version-aware software would know the old state of the flag so could know whether it can safely process counter+1 TXes even if it knows it can not fully understand them.</p><p>In that scenario, upgraded software could know what rules apply to the TX even without knowing the block height, but it still needs to be upgraded so that it could match the version with applicable consensus rules.</p><p>As the consensus upgrade counter part of the version field would be the most important and long-lived feature, the 4-byte* uint should be split into 16 bits for the counter, 1 bit for the breaking flag, and 8 bits for the type of transaction. The remainder* would be reserved for future use.</p><p>(*) Because the version field was never locked, and if we want to enable context-free transaction parsing, we would have to use only the not-seen-prior-to-lock numbers to encode the newVersion so the new version would have a range smaller than 4 bytes.</p><h3>An Alternative to Breaking Change</h3><p>Adding new fields to transactions is possible without breaking the format. There are two variable size fields where semantics have already been changed by upgrades, and are expected to be changed again in the future:</p><ul><li>unlocking script</li><li>locking script</li></ul><p>If the new fields are to be semantically attached to inputs or outputs, they can be inserted inside the related field as:</p><ul><li>unlocking script: [PFX_FIELDNAME &lt;fieldValue&gt;] &lt;realUnlockingScript&gt;, or</li><li>locking script: [PFX_FIELDNAME &lt;fieldValue&gt;] &lt;realLockingScript&gt;.</li></ul><p>The PFX_FIELDNAME would be a constant &quot;magic&quot; byte, <strong>P</strong>re<strong>F</strong>i<strong>X</strong> to the real locking script, and fieldValue the new field to be added. This approach was first proposed by Calin Culianu [6] as part of discussion of a specific upgrade. Consensus code would read the PFX byte and trigger required consensus code which would read the field and enforce required semantics over the field(s), and then pass the realLockingScript or realUnlockingScript to the Script VM.</p><p>The PFX_FIELDNAME could be decided to match a disabled Script opcode, in which case it would be a hard fork change:</p><ul><li>Unupgraded node software would fork the blockchain because, from the point of view of unupgraded software, such locking script will be seen as starting with a disabled opcode.</li><li>Unupgraded non-node software should already know how to deal with disabled opcodes found on the blockchain, so should not break when encountering them. From its point of view the PFX_FIELDNAME byte could be some new data push opcode followed by random data.</li></ul><p>It could be enveloped by a data push opcode followed by an OP_DROP, in which case it would be a soft-fork change:</p><ul><li>unlocking script: [OP_DATA_X PFX_FIELDNAME &lt;fieldValue&gt; OP_DROP] &lt;realLockingScript&gt;, or</li><li>locking script: [OP_DATA_X PFX_FIELDNAME &lt;fieldValue&gt; OP_DROP] &lt;realUnlockingScript&gt;.</li></ul><p>Because the push opcode depends on the length of data to be pushed, it would not be enough to look for a “magic” byte, here it would be more complex to detect because it would be magic pattern: any data push opcode that is followed by the magic PFX_FIELDNAME byte as first byte of the data, and followed by an OP_DROP after the data.</p><p>In this case all unupgraded software would interpret the prefix as a no-op and unupgraded nodes would continue to accept new transactions, even when unaware of any consensus rules applied to the no-op pattern.</p><p>The two above methods would extend inputs or outputs with new field(s). What if the new field would be independent of inputs or outputs? For that we would have to sacrifice one input or output to be a data carrier for the whole array, and use the version field to indicate that is the case. It would be exactly one input or output, and placed as the 1st output of a transaction.</p><p>In case of a field carrier input, it could be of the following format:</p><ul><li>previous output transaction hash: 0x00…01</li><li>previous output index: 0xFFFFFFFF</li><li>unlocking script length: to match</li><li>unlocking script: PFX_FIELDNAME &lt;N&gt;&lt;[element0][element1]...[elementN-1]</li><li>sequence number: 0x00000000</li></ul><p>Consensus would have to ignore the fact that the referenced output does not exists, so this is viable only as a hard-fork. There is precedent for this in coinbase inputs. Unupgraded node-dependent software would see this as an ordinary input so some risk would remain in that dependent software may want to query the node for the non-existent parent output. The node could provide a dummy output to address that, but we will see below that a carrier output is a better option.</p><p>In case of a field carrier output, it could be of the following format and it would require a hard-fork:</p><ul><li>satoshi amount: 0x0000000000000000</li><li>locking script length: to match</li><li>locking script: PFX_FIELDNAME &lt;N&gt;&lt;[element0][element1]...[elementN-1]&gt;</li></ul><p>Consensus would know that such output is unspendable and it would never have to be recorded in the UTXO database.</p><p>Soft-fork variant would be possible, too:</p><ul><li>satoshi amount: 0x0000000000000000</li><li>locking script length: to match</li><li>locking script: OP_RETURN OP_DATA_X PFX_FIELDNAME &lt;N&gt;&lt;[element0][element1]...[elementN-1]&gt;</li></ul><p>With the soft-fork variant, PFX_FIELDNAME would have to be chosen not to conflict with known OP_RETURN protocols.</p><p>Outputs have less overhead, 10 bytes for the hard-fork variant, and should be the preferred method. Nodes would naturally be aware that the output is a “magical” output. They would parse the locking script and populate the TX database and cache. The output itself, however, would never make it into the UTXO database because it is unspendable.</p><p>Unupgraded non-node software would see it as a real output starting with a disabled opcode, so should not break when encountering them.</p><h3>Conditions for Change</h3><p>Because there exists an alternative where the cost would be contained to node software, a proposal to change it by breaking it would have to demonstrate that:</p><ol><li>Benefits of the breaking change are significantly greater than the benefits of a non-breaking alternative or at least, any difference in benefits must make up for the difference in costs.</li><li>Majority of known stakeholders have been accounted for in cost estimation, as many as reasonably practicable.</li><li>Majority of known stakeholders have accepted to bear the cost, even knowing there is an alternative which would not require them to bear it.</li></ol><p>On the other hand, a non-breaking alternative would have to demonstrate that:</p><ol><li>Benefits are greater than the cost.</li><li>Node developers and miners are OK with the change.</li><li>Other stakeholders are not affected, unless they want to use the new feature.</li></ol><p>We can observe here that the burden of proof is much greater for a breaking, non-backwards-compatible change. It would have to involve the broad ecosystem, everyone who could have their software broken by the change. The coordination and consensus building effort would be a big meta cost shared by all, and there is no guarantee that the meta cost would be recouped by successful activation.</p><p>This is not a matter of soft forking vs hard forking, which are concepts that pertain solely to the nature of node consensus with no consideration for other software and services. Hard fork protocol upgrades are the preferred way for Bitcoin Cash. Most hard forks are backwards compatible with regards to dependent software and costs have been contained to nodes and miners. We can observe here that not all hard forks are the same. With the non-breaking type everyone can simply upgrade the node, and all their other software will continue to function. With the breaking type, everyone would have to update not just the node, but all their dependent software.</p><p>Note that presently there is one Bitcoin <strong>C</strong>as<strong>H</strong> <strong>I</strong>mprovement <strong>P</strong>roposal (CHIP) which proposes to roll out new features in a way that would break both the TX FORMAT and TX ID:</p><ul><li>CHIP-2021–01-PMv3: Version 3 Transaction Format [7]</li></ul><p>The CHIP owner has made a good start [8] in attempting to evaluate costs and risks, but because of nature of these costs and risks it is hard to estimate how much more work would be required to capture enough of them, or to even decide how much would be enough to be as-much-as-reasonably-practicable.</p><h3>Conclusion</h3><p>We have shown that not all hard forking upgrades are the same. There are hard-er forks, in that they would break node-dependent software. We have shown that the burden of proof for such a change is much greater than for a non-breaking change.</p><p>While not impossible, a proposal that attempts to make a breaking change will have to strongly demonstrate its superiority over a non-breaking alternative in the context of stakeholders.</p><p>As time goes on, and the network grows, there will be more reliant software. Therefore, the cost of breaking will grow with time so the likelihood of making new precedents and breaking what has never been broken is expected to only decrease with time.</p><p>—</p><p><em>(Bitcoin Cash Node technical bulletin, mirrored from gitlab [9], also published on read(dot)cash [10].)</em></p><p>—</p><p>Links</p><pre>[1] reference.cash/protocol/blockchain/block/transaction-ordering<br>[2] reference.cash/protocol/forks/bip-0068<br>[3] reference.cash/protocol/forks/bip-0068#specification<br>[4] reference.cash/protocol/blockchain/transaction-validation/network-level-validation-rules<br>[5] en.wikipedia.org/wiki/Commitment_scheme#Merkle_tree<br>[6] bitcoincashresearch.org/t/chip-2021-02-group-tokenization-for-bitcoin-cash/311/22<br>[7] github.com/bitjson/pmv3/commit/fbe89e0de877d773085c68a6d4e079bdb6ff63b0<br>[8] bitcoincashresearch.org/t/chip-2021-01-pmv3-version-3-transaction-format/265/48#consensus-validating-wallets-and-services-must-update-9<br>[9] gitlab.com/bitcoin-cash-node/announcements/-/blob/master/2021-12-23_evaluate_viability_of_transaction_format_or_id_change_EN.md<br>[10] read.cash/@bitcoincashnode/bchn-technical-bulletin-2021-12-23-3e65ca78</pre><p>—</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*0vsiP9qFBJVnPWST3Tr7qw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b62c990aefcb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Emulating OP_EVAL using Bitcoin Cash Native Introspection Opcodes (OP_UTXOBYTECODE)]]></title>
            <link>https://medium.com/@bitcoincashautist/emulating-op-eval-using-bitcoin-cash-native-introspection-opcodes-op-utxobytecode-957e4c49169f?source=rss-1113010c7f68------2</link>
            <guid isPermaLink="false">https://medium.com/p/957e4c49169f</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[bitcoincashautist]]></dc:creator>
            <pubDate>Sun, 17 Jul 2022 07:22:49 GMT</pubDate>
            <atom:updated>2022-07-20T14:03:18.871Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<p>The idea of OP_EVAL was presented by Gavin Andersen in BIP-0012[1] but never got implemented on a Bitcoin blockchain.</p><p>The idea behind OP_EVAL is this: allow an input to execute a stack item as Script VM bytecode. This would allow contract authors to hide code modules behind hashes, and those code modules never used would not have to be revealed when spending the UTXO.</p><p>Generalized construction like that is called a Merkelized Abstract Syntax Tree (MAST), and OP_EVAL would be a sufficient building primitive[2]:</p><blockquote>One way to implement the general MAST design is using a combination of OP_EVAL, OP_CAT, and OP_HASH256. However, that will suffer from the problems of OP_EVAL, including risks of indefinite program loop and inability to do static program analysis. A complicated implementation is required to fix these problems and is difficult to review.</blockquote><p>In the meantime, the first Bitcoin blockchain (blocks 0 to 478558) was forked and from there Bitcoin (BTC) and Bitcoin Cash (BCH) diverged in both their blockchain history and blockchain development.</p><p>With November 2021 soft-fork upgrade activation, Bitcoin (BTC) introduced Taproot which supports merkle branch constructions[3]:</p><blockquote><strong>Merkle branches</strong> let us only reveal the actually executed part of the script to the blockchain, as opposed to all possible ways a script can be executed. Among the various known mechanisms for implementing this, one where the Merkle tree becomes part of the script’s structure directly maximizes the space savings, so that approach is chosen.</blockquote><p>With May 2022 hard-fork upgrade activation, Bitcoin Cash (BCH) introduced native introspection opcodes[4] and here the OP_UTXOBYTECODE will be of use:</p><blockquote>Pop the top item from the stack as an input index (Script Number). Push the full locking bytecode of the Unspent Transaction Output (UTXO) spent by that input to the stack.</blockquote><p>It will let us load an additional code to be executed using another input, called “sidecar” input (term coined by Jason Dreyzehner), and then verify the code against the hash stored in the “main” input.</p><h4>Demo Contract</h4><p>The contract allows for two spending paths. It is a simple construction just to demonstrate the capability to emulate OP_EVAL using OP_UTXOBYTECODE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*IJBYyyFpcONc0MIZcA4N7Q.png" /></figure><ul><li>Example transaction using spending path “HA”, requiring a sidecar with P2PKH locking bytecode: 826763fd0ce418e0f0859c026d0498bf66af012bf78323fcf3557791d4510306 [5]</li><li>Example transaction using spending path “HB”, requiring a sidecar with P2SH locking bytecode: 72356114028064e36de76ae183c361e12cf22d525573556db64444290af72fc7 [6]</li></ul><p>The code to be executed is introduced through an input spending a dust amount UTXO prepared in advance of spending the “main” 0.1 UTXO. The “main” UTXO requires that some input in the TX spends the UTXO which has the “sidecar” code.</p><p>This is a simple hash structure that has only 2 leaf nodes and the root, so when spending using any of the 2 leaves, the hash of the other leaf node must be provided by the spender so the redeem script can verify the root hash. The code (“SA” or “SB”) of the other leaf is not revealed.</p><ul><li>The first transaction revealed 1 leaf, one that requires a P2PKH sidecar input, but it did not reveal the other leaf’s code.</li><li>The second transaction revealed the other leaf, one that requires a P2SH sidecar input, but it did not reveal the 1st transaction’s leaf.</li></ul><p>Anyone can spend using the P2SH path. To make things interesting I have again sent 0.1 to the contract, try and claim it. :) Edit: claimed[7] by TinosNitso[8].</p><p>Redeem script for the address (bitcoincash:pzgevd54q0cy3usffzxk00gphu77rdajdsp460cnt2 [9]) currently holding 0.1 BCH:</p><pre>OP_UTXOBYTECODE<br>711b8704f80c7b17082783be22b966251fd4df2feca36425b3e1b4c27776a8c9<br>OP_TOALTSTACK<br>OP_TOALTSTACK<br>OP_DUP<br>0<br>OP_EQUAL<br>OP_IF<br>OP_FROMALTSTACK<br>OP_HASH256<br>OP_ROT<br>OP_CAT<br>OP_HASH256<br>OP_FROMALTSTACK<br>OP_EQUAL<br>OP_SWAP<br>OP_ENDIF<br>1<br>OP_EQUAL<br>OP_IF<br>OP_FROMALTSTACK<br>OP_HASH256<br>OP_CAT<br>OP_HASH256<br>OP_FROMALTSTACK<br>OP_EQUAL<br>OP_ENDIF</pre><p>BitAuth IDE Scratchpad for the contract [10]</p><p>—</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*0vsiP9qFBJVnPWST3Tr7qw.png" /></figure><p>—</p><p>Links:</p><pre>[1] https://en.bitcoin.it/wiki/BIP_0012<br>[2] https://github.com/bitcoin/bips/blob/master/bip-0114.mediawiki#mast-structure<br>[3] https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#design<br>[4] https://gitlab.com/GeneralProtocols/research/chips/-/blob/master/CHIP-2021-02-Add-Native-Introspection-Opcodes.md<br>[5] https://explorer.bitcoinunlimited.info/tx/826763fd0ce418e0f0859c026d0498bf66af012bf78323fcf3557791d4510306<br>[6] https://explorer.bitcoinunlimited.info/tx/72356114028064e36de76ae183c361e12cf22d525573556db64444290af72fc7<br>[7] https://explorer.bitcoinunlimited.info/tx/260b5896d741a53322314fac403395fb4877b80b22cebced06841fcff8730580<br>[8] https://old.reddit.com/r/btc/comments/w11r7s/emulating_op_eval_using_bitcoin_cash_native/igi5msn/<br>[9] https://explorer.bitcoinunlimited.info/address/pzgevd54q0cy3usffzxk00gphu77rdajdsp460cnt2<br>[10] https://ide.bitauth.com/import-template/eJzNVW1v2zYQ_iuEsI9JTJESSQWBAddxlqAv8vzStZiHgC_HWYMtCRbdeCjy30tKspOsKIqiHzZ9Efnw7rnj3XPg5-iXRq9hK6PLaO1c3VwOBqpwcu_WF7raDrrDZhAAKF2hpSuq8tzBtt5IB-ef8EVncvF3U5XRWWSg0buiDlae0gOl3IJfLb2z24DxSOBxBTTR5efHs6gzD5uwlE6v72tpwrb3nHcomsrg3Jl7-Cqf3l8vp8j_bkfz25hhhA9xMlyVV_iASSwS0CZJBc8SKhOdqFRlMSUMDJXcqDQzJuOQUEY5YVxYyIwQLLWJ4ElmwfM8MXtOv5n8thy9eT-Z3d18DFHHt5Px6_ndr53leLRA3e_kSFK2KjvXf2d4tYocNG4VDf0hfpcvWu5vxfxehCP6Eg_1meXTAA8G6K6s9w511WuzwgfNJQMRK5tZrqhOpU44thbHGrhVRBmu0hiblFKqNBVWKZyllGXUGEJTHA-R5829Lnaolm6N1rJZB-IWn9dQmqL8qz3yaGc9Lwyca7lzqCgNHEIibXYzMADbPj0EB9D7oCDUFNv9ppVcb_jgVYi8MOtiE8h34GWoAfkkkK02m-ohoA-Fz8Zff7n4kL_6uJiM8-vJqkT-62uC_O05k1mcKN93MAnITHNBsSYAGdMxl1SZ1NqUUR0TS5QQUg_7uvE4VoLjxAqsuYo5FsT7KiBEZYyRNLYmMZZY0JKyhKSKQqwSTTj3MYXOhiGNRT56s5gvRuPXoS67qnJ9_V6cdV1cTruyHvUQFnc3pxvdzPK3J7InBYTlLD9qBj2XxjccT-Tz30fTNvTk3XUIFLr348F_JOrzaG2jdy8U0XUcDFL_ONCVgV7ABP9sM5hiijOMBWeUaSm54iAl04JzzUQan_AeZWLYZ1iTZv0sn2dT_tXEH2t6rMrTZJ8mutXW_2Qo_7vSDqPH8CTs67raOf9YXP4RvRrf3hNM8D1Ooz_Pok-wa9q3BT9-AWVOCaw=</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=957e4c49169f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bitcoin Cash Pay-to-Script-Hash (P2SH): Past, Present, and Future]]></title>
            <link>https://medium.com/@bitcoincashautist/bitcoin-cash-node-technical-bulletin-bitcoin-cash-pay-to-script-hash-p2sh-past-present-and-9f8c122acc18?source=rss-1113010c7f68------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f8c122acc18</guid>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[p2sh]]></category>
            <category><![CDATA[bitcoincash]]></category>
            <dc:creator><![CDATA[bitcoincashautist]]></dc:creator>
            <pubDate>Sun, 26 Jun 2022 11:07:58 GMT</pubDate>
            <atom:updated>2022-07-01T06:32:18.214Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<h3>Summary</h3><p>Creation of this document was prompted by recent discussion [1] on the Bitcoin Cash Research (BCR) forum regarding a potential upgrade of the long-used P2SH feature. The proposed upgrade would enable an additional BIP-0016 output template, one with a 32-byte hash, aimed at addressing a long standing cryptographic collision problem. We have taken the opportunity to create this comprehensive P2SH document, including complete details of our preferred solution to the collision problem.</p><p><strong>Contents:</strong></p><ol><li>Introduction to P2SH Feature</li><li>Technical Debt</li><li>Cryptographic Security Level</li><li>Preferred Upgrade</li><li>Post-quantum Cryptographic Security Level</li><li>Potential Future Upgrades</li><li>Pay-to-Public-Key-Hash (P2PKH) Outputs</li></ol><h3>1. Introduction to P2SH Feature</h3><p>The P2SH feature currently in use was introduced to Bitcoin in 2012 with BIP-0016 [2]. It was successfully activated on 2012–04–01 with block 173805 [3]. The upgrade had been deployed using the “soft-fork” covert upgrade mechanism. This meant that use of the feature by transactions had to be encoded as valid Script VM bytecode even from the point of view of non-upgraded node software. Therefore, the upgrade was disguised as a “hash-lock” [4] output with the following behavior:</p><ul><li>locking script:<br> OP_HASH160 OP_DATA_20 20-byte-value OP_EQUAL<br> (raw: a9 14 1122334455667788990011223344556677889900 87).</li></ul><p>Prior to BIP-0016 activation, a UTXO locked with that script could be unlocked by providing a value whose hash would match against the 20-byte-value in the locking script:</p><ul><li>unlocking script:<br> [push data N] ... [push data 2] [push data 1] &lt;push data 0&gt;.</li></ul><p>For example, an output with:</p><ul><li>locking script:<br> OP_HASH160 OP_DATA_20 0x994355199e516ff76c4fa4aab39337b9d84cf12b OP_EQUAL<br> (raw: a9 14 994355199e516ff76c4fa4aab39337b9d84cf12b 87)</li></ul><p>could have been unlocked with:</p><ul><li>unlocking script:<br> OP_DATA_1 0x61<br> (raw: 01 61).</li></ul><p>Script VM execution would pop the 0x61 value from top of the stack, hash it, compare it with the 20-byte hash value and leave true (0x01) as the top stack element, which would allow the prevout to be spent.</p><p>After BIP-0016, the above locking script became a “magical” bytecode pattern because of what happens next in upgraded software. In an upgraded node, the pattern works as before but also triggers additional execution:</p><ul><li>The true (0x01) resulting from OP_EQUAL is popped from the stack.</li><li>The input’s data 0 stack element is injected as code to be executed by the Script VM.</li></ul><p>As a consequence, the above unlocking script would fail to unlock the prevout because the 2nd run would leave an empty stack. The same output can currently be spent [5] using a slightly different input with</p><ul><li>unlocking script:<br> OP_1 OP_DATA_1 0x61<br> (raw: 51 01 61).</li></ul><p>The value 0x61 would first be validated against the hash and then executed in Script VM, where it would be interpreted as OP_NOP that has no effect on Script VM stack state. Therefore, input can be spent because only the 0x01 will remain on stack after both runs of Script VM are completed.</p><p>Non-upgraded nodes would see both input scripts as valid because they would see it as just some hashlock contract being spent from.</p><p>Note that at the time of P2SH deployment there was no “clean stack” [6] consensus rule. With the clean stack rule currently in force, a non-P2SH hash-lock contract would not be spendable because the “magical” execution would not trigger and therefore would not pop the top stack item. After the 1st and only run, the stack would be left “dirty”, and the “clean stack” rule would fail the transaction.</p><p>The stack element to be executed in the 2nd Script VM run got to be called “redeem script”, and because of network relay rules [69] it is practically the only way to execute arbitrary Script contracts.</p><p>The now familiar P2SH pattern is of the form:</p><ul><li>locking script:<br> OP_HASH160 OP_DATA_20 hash160(redeem_script) OP_EQUAL;</li><li>unlocking script:<br> [push data_N] ... [push data_1] [push data_0] &lt;push redeem_script&gt;.</li></ul><p>Note that the P2SH is rigidly defined by the exact locking script, with only the content of the 20 hash bytes being variable. For example, appending an OP_NOP to the locking script would turn it back into an ordinary hash-lock contract and only the 1st run would be executed. At the time of this writing we have found that there exists [70] exactly one output whose locking script is an extension of the P2SH pattern, and it was successfully spent [71] after BIP-0016 activation.</p><p>Even before BIP-0016 activation, there were some outputs that matched the P2SH pattern. Only one of them was spent before activation, and the rest have likely been made unspendable by the BIP-0016 upgrade since spending them would have to satisfy consensus rules not enforced when they were created. Total amount locked in those outputs was 0.044 BTC and they now also exist as BCH outputs. For information, attached [72] is a list of these outputs.</p><h3>2. Technical Debt</h3><p>Bitcoin Cash (BCH) blockchain is a direct descendant of the first Bitcoin blockchain, referring to blocks 0 to 478558, which were mined during the period 2009–01–03 to 2017–08–01. Using Bitcoin Cash user-activated hard-fork (UAHF) [7] consensus specification the blockchain was permanently split to two viable networks, each with their own version of block 478559. With that, Bitcoin Cash has inherited all technical debt created prior to the split. While some of it has been repaid in the meantime, there are still debts tied to the P2SH feature:</p><ol><li>Cryptographic security level is 80 bits against collision attack, which limits utility of the feature to a subset of possible uses — those that are not exposed to the attack;</li><li>Unnecessary overhead in transaction encoding, which makes every P2SH UTXO waste 2 bytes;</li><li>Mixing layers, resulting in redeem script size being limited by MAX_SCRIPT_ELEMENT_SIZE[8].</li></ol><p>Our main focus will be on debt 1., and at the end of the document we will discuss debts 2. and 3. as well.</p><h3>3. Cryptographic Security Level</h3><p>The 160-bit hash function (OP_HASH160) used for both P2PKH and P2SH Bitcoin addresses is a composite function of SHA-256 and RIPEMD-160, where RIPEMD-160 is the outer function: hash160(x) = ripemd160(sha256(x)).</p><p>Below we will discuss both security properties of the composite function itself, and adequacy of the choice of the function for Bitcoin Cash use-cases.</p><h3>3.1. Security Level of OP_HASH160 Function</h3><p>The inner, SHA-256, function is both preimage-resistant [9] and collision-resistant [10], but broken against length-extension attack [11], as summarized on this page [12].</p><p>The outer, RIPEMD-160, function is also broken against length-extension attack [13], and has a known theoretical weakness [14] against <strong>second</strong>-preimage attack:</p><blockquote><em>Our attack, like the earlier attack of Dean, probably has no practical impact on the security of any system currently relying upon a hash function such as SHA1, Whirlpool, or RIPEMD-160. This is true because the attack is always at least as expensive as collision search on the hash function, and because the difficulty of the attack grows quickly as the message gets shorter.</em></blockquote><p>Because SHA-256 is the inner function, it follows that the composite, HASH-160, function is both preimage and collision resistant [15]. To demonstrate why that is so, imagine replacing the outer function with a completely broken function, such as a linear function. Even if the intermediate hash of such composite is trivially revealed, a successful attack on the composite would still require breaking the inner function.</p><p>When it comes to length-extension resistance then both functions are broken, but the composite is resistant [16]. This is because the inner function’s output remains secret and obtaining it would require breaking preimage resistance of the outer function.</p><p>Our HASH-160 is therefore secure, meaning it currently has the full declared 160-bits of security against preimage and length-extension attacks, and 80-bits of security against collision attacks. Because of the generic birthday attack [17], the security against collision attack is halved even for ideal hash functions.</p><h3>3.2. Adequacy of OP_HASH160 Security Level</h3><p>Both P2PKH and P2SH addresses use HASH-160 to commit to a spending constraint without having to reveal it until time comes to spend from it. In case of P2PKH the address commits to a public key, and in case of P2SH it commits to a redeem script. The message that hashes to an address must therefore come from a set of valid public keys or redeem scripts, and finding any other message would be completely useless as it could not be used on Bitcoin Cash blockchain.</p><h4>3.2.1. Plausibility of a Preimage Attack</h4><p>With 160 bits of security, any attacker that would want to find a preimage of a specific hash would be faced with brute-forcing 160 bits which is infeasible, and well above the generally accepted “safe” security level [18] of 128 bits.</p><p>Attacking a larger set would reduce the required number of attempts. With a public ledger, the attacker has knowledge of all addresses that contain funds. If the set of such addresses would grow to a size of 4.29 billion (2³²), then the attacker would still need to brute-force 128 bits. To bring it down to 100 bits, which literature considers to be a “danger zone” (see section 4.4 here [19]), the attacker would need a target set of 2⁶⁰ addresses, which is a number with 18 zeroes. A successful attack against a set would at best yield a public key of some random address from the set and the attacker would still be facing the problem of cracking the public key, and that for an address with expected value practically 0 due to size of the target set.</p><p>We can conclude that 160-bits of security is adequate when attacker has no influence on how the target addresses are generated, which is the common case with Bitcoin Cash.</p><h4>3.2.2. Plausibility of a Collision Attack</h4><p>With a collision attack, the attacker does not target some existing address or even a set of all known addresses. Here any random collision will do, and both messages will be under control of the attacker. Even if someone else generates part of the message but the attacker has the final say by adding his data on top of another’s message before generating the hash, it still counts for the attack.</p><p>The distinction between a preimage attack and a collision attack is well described here [20]:</p><blockquote><em>A less-technical way to think about the difference between the collision attack and the SPA is how many degrees of freedom the attacker has. With an SPA, the attacker has one degree of freedom — their message. With a collision attack, the attacker has two degrees of freedom — both messages.</em></blockquote><blockquote><em>Whether Mallory uses a database size of 1, 100, or something else doesn’t matter for the attack classification — it’s a collision attack if she’s involved in creating the ultimate digest, it’s an SPA if she has to match a value someone else chose.</em></blockquote><p>Against the generic birthday attack, collision resistance of any hash function is half the declared preimage resistance. In other words, it would take 2⁸⁰ attempts on average to generate a colliding pair of messages when the message is hashed using HASH-160. Literature suggest [21] that the attack can be performed with constant memory, even when searching for a particular template of colliding messages [22]. Still, the attack against 80 bits is not trivial and would be expensive, on the order of magnitude of millions of US dollars. While such an attack is feasible, it would be exploitable for profit only in specific circumstances.</p><p>For most current Bitcoin Cash use-cases, having only 80 bits of security against collision attacks is not a problem because most users will be the sole owner of an address, with exclusive control over their address generation, and therefore not exposed to the attack. In other words, brute-forcing a colliding pair of P2PKH address keys or P2SH redeem scripts could only result in the same entity having two ways to spend from one randomly generated address. It would practically work as 1-of-2 multisig address where the one who generated it would hold both keys, and it would be an expensive address to generate.</p><blockquote>New to trading? Try <a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a">crypto trading bots</a> or <a href="https://medium.com/coinmonks/top-10-crypto-copy-trading-platforms-for-beginners-d0c37c7d698c">copy trading</a></blockquote><p>The problem arises when users are asked to pay into an address where someone else had control over address generation, such as P2SH multi-party multisig addresses and public-facing covenants. Feasibility of a collision attack makes it usable as part of a con executed in 3 stages:</p><ol><li>Collision attack: generate a colliding contract (redeem script) pair;</li><li>Social hacking set-up: release the address and only one of the two colliding contracts to some other party or parties and convince them to pay funds into the contract address;</li><li>Rug-pull: when the address has accumulated enough funds to pay for step 1 and have some profit, steal the funds from the address by using the other, secret, contract.</li></ol><p>For the con to work, the contract revealed to other parties must look innocent while also having a variable part suitable for manipulation by the attacker, one that can encode a whole 160-bit hash in order to make use of the constant-memory method by finding cycles. This does not just mean a continuous 160-bit block, it is much more broad — it means any degree of freedom which would let the attacker feed 160 bits of entropy of his choice into the final address. The other message can be anything that will allow only the attacker to spend from it.</p><p>This comment [23] sums it up well:</p><blockquote><em>If you are agreeing to lock up funds with somebody else, and they control what public key to use, you are susceptible to collision attacks.</em></blockquote><p>The above described collision attack vulnerability has been known since circa 2016 and recently it has been brought to attention [24] in context of Bitcoin Cash blockchain, because it has expanded its Script capabilities. Historically, Bitcoin contract language was not really used for anything more than multisig which was the main and probably only widespread case of “locking funds with somebody else”. As we will demonstrate below, even that use-case is exploitable in some con scenarios, and Bitcoin Cash is continuing to evolve Bitcoin Script language, with the latest upgrade (May 2022) bringing much more versatility to Script language:</p><ul><li>CHIP-2021–02: Native Introspection Opcodes [25] and</li><li>CHIP-2021–03: Bigger Script Integers [26].</li></ul><p>For example, one of the first applications demoed is a public crowdfunding assurance contract [27], but it is safe to assume there will be many more applications. Those uses could potentially attract enough users so that a con relying on the feasible P2SH collision would become attractive to adversaries. Seemingly legitimate contracts could intentionally be set-up as insecure in an elaborate con like what we will describe below.</p><p>We can conclude here that the HASH-160 function is not entirely adequate for use with the P2SH feature, not because of some weakness in the function, but due to design choice of the function’s output size. The output size of 160 bits makes a birthday attack feasible and there are already existing usage scenarios where it could be exploited, with more to come.</p><p>Bitcoin Core (disambiguation) has already closed the vulnerability by introducing BIP-0141 [28] (SegWit) which enables 256-bit commitments to redeem scripts (P2WSH [29]). The BIP in question was one of the main reasons for the 2017 UAHF split, so naturally Bitcoin Cash would have to close the vulnerability in some other way.</p><p>Thankfully, a much simpler way is available to Bitcoin Cash: expand the P2SH feature with the option to use a hash function that has a 256-bit output. There already exist 2 opcodes that call such a function as candidates for the “hardened”, 32-byte variant of the feature: P2SH32. Such a solution would not introduce new technical debts, and we will later state preference for a particular function and elaborate on the choice.</p><p><strong>Example Attack</strong></p><p>To better illustrate the attack, consider an adversary that creates a custody service which sets up 2-of-3 P2SH multisig addresses for their users. Any user of such service would control two keys, and the custodian (attacker) would control one. Note that there exist legitimate services that work just as described, enabling users to hold one of their two keys in cold storage and rely on the service to produce 2-of-3 signatures.</p><p>For the attack to be possible, user interface of the rogue service would have to first ask the user for their 2 public keys, and the adversary would add its key last to generate the multisig address, and then reveal their 3rd key to the user so the user could verify correctness of the contract. The user would likely think it is safe, because it would be the familiar multisig contract (redeem script) template which, if evaluated on its own, indeed works as advertised:</p><ul><li>Redeem script: OP_2 &lt;attacker&#39;s 33-byte pubkey&gt; &lt;user&#39;s 33-byte pubkey 1&gt; &lt;user&#39;s 33-byte pubkey 0&gt; OP_3 OP_CHECKMULTISIG;</li><li>Locking script: OP_HASH160 &lt;hash160(redeem_script)&gt; OP_EQUAL.</li></ul><p>Such an output could then be spent from using an input of the following form:</p><ul><li>Unlocking script: OP_0 &lt;user&#39;s signature&gt; &lt;user&#39;s other signature or attacker&#39;s signature&gt; &lt;redeem_script&gt;</li></ul><p>In our con scenario, when setting up the multisig address the attacker would have generated a redeem_script_steal, one that would hash to the exact same address and allow him to spend from the address by executing an entirely different script like:</p><ul><li>Redeem script: &lt;20-bytes&gt; OP_DROP OP_DUP OP_HASH160 OP_EQUALVERIFY OP_CHECKSIG.</li></ul><p>The script would be kept secret until stage 3. of the attack, the rug-pull. In the innocent-looking multisig script, his key would not really be a key, he would be using it as a variable part in his collision search. If the attacker expects users to call on the service to actually use the key from the innocent-looking script, then it would make stage 1. somewhat more expensive but still feasible.</p><p>The service could be operating legitimately for a long time, waiting for the right target or a set of targets. The attacker would not need to perform step 1. for all users, that would have an uncertain return-on-investment. He would first need to attract enough users and identify high-value targets, ones where they have enough funds to make a collision search worthwhile. The attacker could then ask his targets to move their funds into a new contract that would have the same 2 user keys, and the attacker could plausibly say he has to update his key for some internal security upgrade.</p><p>He would wait for his targets to move the funds, and then steal them all in one go and disappear.</p><p>There is a simple way users could protect themselves in this scenario: insist on having the last say in address generation. The service would have to provide their public key first, and the user would then generate two brand new keys for himself and use those to finalize the P2SH multisig address. The user would then be the one with the freedom to generate a collision, but in this scenario he is already the owner of the address so neither himself nor the service would be exposed.</p><p>Not all scenarios have such obvious mitigation, and some contracts may not have a way to work around the vulnerability at all or it will be too cumbersome for practical use, which will limit utility of the P2SH feature, and with that utility of Bitcoin Cash.</p><p>Similar example would be the same 2-of-3 multisig contract but set up so that 3 parties are supposed to each hold only a single key over some shared pool of funds. Here nobody should be trusted with adding the last key because it would give him a chance to perform a collision search. This can be mitigated using a pre-commitment scheme, like one described by Jason Dreyzehner [30]:</p><blockquote><em>Each participant generates their public key and shares the hash of that public key with the other participants. After receiving each other’s public key hash, the participants reveal their unhashed public keys. By verifying that each revealed public key matches the initially-shared hash, each participant can confirm that the other participants had already generated their public key before the reveal, making birthday attacks impossible.</em></blockquote><p>Here we can observe that, even for the ubiquitous mulitsig contract, the mitigation starts to take a toll on user experience as soon as funds are to be controlled by multiple parties.</p><p><strong>Applicability of a Collision Attack on Use-cases</strong></p><p>As we already discussed, any entity that has the last say in address generation would have the opportunity to exploit it. Multisig address generation happens only once, and from then on it is just used, so there is only the one opportunity for an attack and the risk can be mitigated by using an interactive key-exchange that ensures no party has a chance to “re-roll” the final address in a collision search.</p><p>However, there is a big class of contracts where the P2SH address may be updated on each contract spend and allow moving funds to a new address: self-mutating covenants that update some internal state when spent from. Here, address generation happens on every spend from the contract. Attack scenarios will depend on how they are set up. The contract may require authentication by a key or a set of keys, or it may be a public covenant where anyone could spend from it provided he updates the contract state as required. In either case, if the contract allows enough entropy to be fed into its internal state when used, then every update is an opportunity for a collision search and the risk of total fund loss will be there for as long as the contract lives.</p><p>Some examples of the above include:</p><ol><li>Contract that raise money from the public and make promises about how the funds will be spent. These are designed to ensure that the promise is kept, like releasing funds on fixed intervals. Collision-search for an alternative contract would allow the trustee to break out from self-imposed limitations.</li><li>Contracts that manage funds for an organization, allowing some keys to take only a limited amount of funds. These could be exposed to a collision-search by a rogue employee if the organization’s treasury would grow big enough.</li><li>Oracle-dependent contracts, where releasing the funds to some party in the contract is dependent on external data provided by an oracle. If it is possible to manipulate how the oracle is read from by the contract, then it may open an opportunity for a collision-search.</li><li>Covenants used to create bridges with other blockchains, which could end up locking a significant amount of funds and become attractive targets for adversaries.</li><li>DAO-like contracts, where anyone is free to interact with the funds locked inside of it while being allowed to update some internal state of the DAO. These would be exposed to a collision attack by anyone at any time, and a success would allow them to break out from the DAO and simply take all the funds.</li></ol><p>Above contracts would be extremely hard to audit because entropy for a collision may be obscurely snuck-in. It would be hard or even impossible to set-up those kinds of contracts in a way that would mitigate the risk. If the enclosing hash function for these contracts was secure against collision-attacks, then all of these problems would simply disappear.</p><h3>4. Preferred Upgrade</h3><p>The P2SH feature can be simply “hardened” by introducing another “magical” output pattern, one that uses a hash function with a 256-bit output. Current Script VM opcodes leave us with two possibilities:</p><ul><li>Locking script:<br> <strong>OP_SHA256</strong> OP_DATA_32 32-byte-value OP_EQUAL<br> (raw: <strong>a8</strong> 20 1122334455667788990011223344556677889900112233445566778899001122 87), or</li><li>Locking script:<br> <strong>OP_HASH256</strong> OP_DATA_32 32-byte-value OP_EQUAL<br> (raw: <strong>aa</strong> 20 1122334455667788990011223344556677889900112233445566778899001122 87).</li></ul><p>The OP_SHA256 is self-descriptive, and the OP_HASH256 is a composite hash just like OP_HASH160 but, instead of using RIPEMD-160 as the outer function, it is using the same SHA-256 function as the outer function:</p><ul><li>hash256(x) = sha256(sha256(x)).</li></ul><p>The composite is commonly referred to as “double-SHA256” and it is the same hash function used as the “main” hash [31] in Bitcoin design.</p><p>Either one would enable a 32-byte variant of the P2SH feature. The main differences between two functions are:</p><ul><li>CPU cost of evaluating the function.</li><li>Susceptibility to a length-extension attack.</li><li>Composite (double SHA-256) vs non-composite (single SHA-256) function structure.</li><li>Protocol consistency.</li></ul><p>We will discuss these differences and finally decide on a preferred hash function from among those already available.</p><h3>4.1. CPU Cost of Evaluating The Function</h3><p>The CPU cost depends on total bytes that pass through the SHA-256 function, and difference is made smaller with bigger redeem scripts. This is because the 2nd function call only needs to hash a fixed-size 32-byte message (output of the 1st call). For example, double hashing a 300-byte redeem script has 332 bytes pass through the hash function, while single hashing has 300 resulting in roughly 10% cost difference for the example script. For small scripts, the cost of a double function is double, but even so, it is small compared to the cost of verifying signatures and hashing the whole transaction for the transaction identifier.</p><h3>4.2. Susceptibility To a Length-extension Attack</h3><p>The single HASH-256 function is secure against preimage and collision attacks but completely broken when it comes to length-extension attacks. As we already discussed, the current P2SH feature uses a composite function that is secure against length-extension.</p><p>It could be argued [32] that the nature of P2SH feature is such that the length-extension attack is not applicable, because the message will be revealed on first spend from the contract and then anyone can trivially extend it anyway, regardless of the hash function used. While this is indeed generally true, there are other things to consider.</p><p>Using the double removes susceptibility to length-extension and makes the hash function close to a “random oracle” [33] which is an important assumption in commitment schemes devised to keep secrets safe until time comes to reveal them. We have found literature [34] exploring secure multi-party computations on Bitcoin, and the “hiding” property requires assumption of a random oracle:</p><blockquote><em>The binding property of this commitment follows from the collision-resistance of the hash function H, since to be able to open the commitment in two different ways a malicious sender would need to find collisions in H. </em><strong><em>For the hiding property we need to assume that H is a random oracle. We think that this is satisfactory since anyway the security of the Bitcoin PoWs relies on the random oracle assumption.</em></strong><em> Clearly, if H is a random oracle then no adversary can obtain any information about x if he does not learn s (which an honest C keeps private until the opening phase).</em></blockquote><blockquote><strong><em>Notice that use of single SHA-256 would be insecure here</em></strong><em>, because it is constructed using Merkle–Damgard transformation and therefore it is susceptible to the length extension attack [21]. It this attack </em><strong><em>an adversary which knows H(x) can compute a value H(x||y) for some string y controlled by him without the knowledge of the original value x. It could allow to completely compromise the lottery protocol</em></strong><em>, because the winner choosing function (described later) highly depends on the lengths of the secrets.</em></blockquote><p>The example is not directly applicable to P2SH but we use it to illustrate the kind of cryptographic schemes length-extension attack affects, and to support the statement that double SHA-256 is usable for making security claims in the random oracle model.</p><p>Susceptibility to a length-extension allows an adversary to extract some limited information from a target set of hashes even if their preimages are secret: check whether a preimage of one hash is a substring of a preimage belonging to some other hash in the set, and discover the extension while at it. By being able to extract information from known hashes with secret preimages, “unlinkability” property of known hashes is weakened [35].</p><p>Consider the P2PKH template embedded inside a reedem script:</p><ul><li>Locking script:<br> OP_HASH256 OP_DATA_32 redeem_script OP_EQUAL</li><li>Redeem script:<br> OP_DATA_33 pubkey OP_CHECKSIG</li><li>Unlocking script:<br> &lt;push signature&gt; &lt;push redeem_script&gt;.</li></ul><p>By appending a &lt;counter&gt; OP_DROP to the redeem script, one could have any number of distinct addresses, all spendable using the same key and expected to be indistinguishable from other P2SH addresses. However, because the &lt;counter&gt; is of sufficiently small size, and if SHA-256 was used instead of HASH-256, then an adversary could feasibly brute-force some set of known hashes and link addresses together even before they are first used. He would pick a hash from the set, test length-extensions up to some feasible N of bytes, then repeat the same with the next hash and so on until he checks the whole target set. Even if he does not find a match, he would still learn something about the set - that none of those hashes preimages are up-to-N-byte-suffix substrings of each other. If the hash function was a random oracle, then it would be impossible to extract any information and “hiding” property of the above address generation scheme could be proven to be sound.</p><p>While the double function may be usable as a random oracle in security claims like above, we have found literature [36] demonstrating that it is provably not generally indistinguishable from one, precisely because of the double construction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*p622QaKqOuiv7Dm3" /></figure><p>Note that a security proof in the “random oracle model” does not automatically make a cryptographic scheme secure because it is not complete. There are examples of intentionally broken schemes [37] designed to prove this point. However, it is the closest we can get to making plausible security assurances [38] when a complete proof cannot be constructed in the standard model [39]:</p><blockquote><em>Summary: proofs in the random oracle model are fine, but are never complete enough to cover a practical implementation: we know that any function we will use in lieu of the random oracle will not be a random oracle; so security relies on the fervent hope that the parts where the actual function is not a random oracle do not impact security. This justifies a bit of mistrust. Still, a proof in the random oracle model is much better than no proof at all.</em></blockquote><p>While use of the random oracle model has been somewhat controversial [40], it stood the test of time well, and we have found literature [41] that gives a good 20-year retrospective:</p><blockquote><em>In this retrospective we argue that there is no evidence that the need for the random oracle assumption in a proof indicates the presence of a real-world security weakness in the corresponding protocol. We give several examples of attempts to avoid random oracles that have led to protocols that have security weaknesses that were not present in the original ones whose proofs required random oracles.</em></blockquote><blockquote><em>If one is willing to use the random oracle model (and the analogous generic group model), then various security arguments are known for these two schemes. If one shuns these models, then no provable security result is known for them.</em></blockquote><p>Finally, both SHA-256 and double SHA-256 are flawed in some way when it comes to being used as a random oracle. The single has an obvious and generally exploitable length-extension vulnerability while the double has a more exotic property that only impacts a specific use in building hash chains.</p><p>In the context of making a decision about P2SH hash function, the benefit of using the double SHA-256 function over single would be the privacy aspect, that of all P2SH outputs being unlinkable. We are not aware of any current setups relying on this property (P2SH20 addresses are unlinkable just as well) so the benefit is speculative, and may or may not be reaped with future Bitcoin Cash contract setups.</p><h3>4.3. Composite vs Non-composite Function</h3><p>The composite structure also allows for the possibility of a contract proving existence of a known preimage of some target contract hash, without having to provide the contract’s redeem script. If the target contract is unspent and secret, then a first reveal of the intermediate hash would serve as one-time proof of knowledge of the preimage. The verifier contract could require a pre-commit step before reveal in order to prevent replay of the proof.</p><h3>4.4. Protocol Consistency</h3><p>P2SH32 will be the foundation of future UTXO contract developments, and double SHA-256 is already being used as the “main” hash that secures critical blockchain primitives, so we would want to avoid the risk of the unknown, of accidentally introducing a weakest link again when the objective of the upgrade is to strengthen the weakest link.</p><h3>4.5. Preferred Choice of Hash Function</h3><p>With all above said, in terms of hash functions already available, we would prefer an upgrade of the P2SH feature using <strong>OP_HASH256</strong>, by allowing an additional BIP-0016 pattern that would trigger redeem script execution:</p><ul><li>Locking script:<br> OP_HASH256 OP_DATA_32 redeem_script OP_EQUAL<br> (raw: aa 20 1122334455667788990011223344556677889900112233445566778899001122 87).</li></ul><p>The main trade-off for OP_HASH256 vs OP_SHA256 is stronger protocol consistency vs a micro-optimization, and speculative benefits add some secondary weight in favor of OP_HASH256.</p><p>BCHN has already started work on a proof of concept [42], to better assess impact of such an upgrade.</p><h4>Side Note: Other Hash Functions</h4><p>We have not considered other 256-bit-output hash functions such as BLAKE2s-256 [43] or SHA3–256 [44], both which are secure against preimage, collision, and length-extension attacks, and may also offer an increase in transaction validation performance. Using one of those would require either:</p><ul><li>upgrading the Script VM with a new opcode for the function or</li><li>moving redeem script authentication to the base layer and there using a hash function not available to the Script VM.</li></ul><p>Introducing a new hash function would be a bigger intervention than what is required to address the collision problem we set out to do. From security point of view and as far as we are aware: it would offer an improvement over our choice of double SHA-256 only in the exotic example of hash chains used as PoW mentioned above, and for which we cannot demonstrate any applicability to the P2SH feature. From performance point of view: it may offer a tempting improvement when viewed in isolation. The costs and benefits of a new hash function should be carefully evaluated, which is beyond scope of this document.</p><h3>4.6. Backwards Compatibility</h3><h4>4.6.1. Node Software</h4><p>Due to nature of the change the upgrade would technically be a soft-fork upgrade just like BIP-0016. However, with Bitcoin Cash it would be deployed as part of Bitcoin Cash upgrade schedule, that allows for clean upgrades using orderly hard-forks, which intentionally makes old node software obsolete. This pertains to node software only, the upgrade would be non-breaking when it comes to other software.</p><h4>4.6.2. Non-node Software</h4><p>Other applications will not require an immediate upgrade, meaning everyone can continue using Bitcoin Cash (BCH) as they are used to, no action required. Upgrading old applications or creating new ones will be on a voluntarily basis by those that want to access the upgraded feature, and at their own pace.</p><p>Some application like block explorers can choose not to upgrade their non-node software at all, resulting in P2SH32 being displayed as a generic “hashlock” contract. Opting to upgrade would mean more accurately displaying the contract address.</p><p>With recent Script VM upgrades however, we expect that many will be attracted to build and access products using the hardened, 32-byte variant of P2SH feature, and that such products will bring more utility to Bitcoin Cash.</p><p>Developing new Script applications will of course require updates to some libraries, transaction compilers, and other software which implements the Bitcoin Cash Script VM (e.g. Bitauth IDE).</p><p>Secure fund management setups relying on P2SH32 contracts may also require upgraded hardware wallet firmware, or even tailored custom firmware.</p><h4>4.6.3. Address Format</h4><p>Not all users will have a need to spend from P2SH contracts, but many may want to be able to send to them (example: crowdfunding contract [45]). To allow users to easily send Bitcoin Cash to contracts secured with a 32-byte hash, wallets and address handling tools should recognize one more address type. The current address standard [46] already supports encoding P2SH addresses up to 64 bytes, and a 32-byte P2SH address would look like:</p><p>bitcoincash:pvch8mmxy0rtfrlarg7ucrxxfzds5pamg73h7370aa87d80gyhqxq7fqng6m6.</p><p>It should be noted here that a key property of birthday-hardened P2SH use-cases is that they are likely to be interact with users through specialized web or local wallets anyway, and are unlikely to require direct depositing into contracts from common wallets. Therefore the usefulness of these use-cases, and by extension P2SH32 itself, is not dependent on widespread adoption of P2SH32 among common wallets and software.</p><h4>4.6.4. Historical Transactions</h4><p>As of time of this writing (block 742020) there exist both spent and unspent transaction outputs matching both OP_HASH256 and OP_SHA256 hashlock output patterns. Situation was similar at the time when BIP-0016 was proposed:</p><blockquote><em>These new rules should only be applied when validating transactions in blocks with timestamps &gt;= 1333238400 (Apr 1 2012) [1]. There are transactions earlier than 1333238400 in the block chain that fail these new validation rules. [2]. Older transactions must be validated under the old rules. (see the Backwards Compatibility section for details).</em></blockquote><p>The same would apply for activating either of the two 32-byte output patterns. For information, attached [47] is a list of all existing transaction outputs, both spent and unspent, which match those patterns.</p><p>Also, any unspent funds currently locked in outputs with the OP_HASH256 hashlock pattern would almost certainly be made unspendable (if not already) with the upgrade. As of time of this writing (block 742020) the total amount of such outputs is 0.00740026 BCH so currently this is not seen as a problem that would justify making exceptions to have them spendable under old rules.</p><h3>4.7. Interaction With Other Bitcoin Blockchains</h3><h4>4.7.1. Interaction With Bitcoin Core (BTC)</h4><p>Transactions on Bitcoin Core and its post-UAHF derivatives are not replayable on Bitcoin Cash, due to SIGHASH_FORKID bit required by UAHF specification [75].</p><p>However, due to Bitcoin Core post-UAHF “SegWit” soft-fork upgrade it may happen that funds accidentally get sent to “SegWit” P2WPKH nested in BIP16 P2SH [48] addresses, but on Bitcoin Cash (BCH) blockchain instead of on Bitcoin Core (BTC) blockchain:</p><pre>witness:      &lt;signature&gt; &lt;pubkey&gt;<br>scriptSig:    &lt;0 &lt;20-byte-key-hash&gt;&gt;<br>              (0x160014{20-byte-key-hash})<br>scriptPubKey: HASH160 &lt;20-byte-script-hash&gt; EQUAL<br>              (0xA914{20-byte-script-hash}87)</pre><p>Another variant is the P2WSH nested in BIP16 P2SH [49], affected all the same by what is discussed below.</p><p>Because Bitcoin Cash never implemented SegWit, the redeem script will be authenticated using the 1st Script VM run (hashlock) but the 2nd one (BIP-0016) will simply push an empty stack item and the 20-byte-key-hash. On Bitcoin Cash blockchain, the execution will end there, and with a “dirty” stack. On Bitcoin Core blockchain, a 3rd run (SegWit) would be executed to verify the signature against the witness, but on Bitcoin Cash that never happens since that soft-fork was never implemented.</p><p>On Bitcoin Cash, until introduction of clean stack rule with Bitcoin Cash 2018–11–15 upgrade [50], the “P2WPKH nested in BIP16 P2SH” was therefore an “anyone-can-spend” P2SH redeem script. With introduction of the clean stack rule, it was made unspendable. In the following upgrade (2019–05–15), an exception was made for the pattern in order to again allow recovery of those funds by miners [51].</p><p>With the 32-byte P2SH variant, no such exception is required, because P2SH32 does not exist on Bitcoin Core network, and its 32-byte P2WSH [52] variant uses a pattern distinct from what is proposed here.</p><h4>4.7.2. Interaction With Derivatives of Bitcoin Cash</h4><p>As discussed here [74], replays of some transactions sending unsplit funds to P2SH32 may be possible on derivatives of Bitcoin Cash. Users of P2SH32 should therefore be careful not to use unsplit funds. On those derivatives, funds sent to P2SH32 outputs would be free for the taking because there they would be seen as hashlock contracts. Miners could easily donate such funds to themselves because they could learn the unlocking preimage by looking at Bitcoin Cash blockchain. The P2SH32 pattern is not recognized as standard by other chains network rules, so those outputs could only be claimed by miners.</p><p>This is not seen as a problem which needs addressing by Bitcoin Cash network because those cases should be extremely rare since amount of unsplit funds only decreases with time. Besides, it is the responsibility of each network to safeguard their own users funds.</p><h3>5. Post-quantum Cryptographic Security Level</h3><p>It is currently understood that quantum computers could theoretically offer a quadratic speed-up in cracking hash function preimages using Grover’s algorithm [53], and cubic speed-up in finding hash collisions using Brassard-Høyer-Tapp algorithm [54]. It is also understood [55] that elliptic-curve cryptography would be the the first to go as it could be completely broken using Shor’s algorithm [56]. We summarize this in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*mLe7LjmGdzKsnIa0" /></figure><p>Note that these are theoretical lower bounds. Literature suggests [57] that, in a theoretical implementation, the cost of a quantum-computing attack might be more expensive than that:</p><blockquote><em>We showed that attacking SHA-256 requires approximately 2^{153.8} surface code cycles and that attacking SHA3–256 requires approximately 2^{146.5} surface code cycles. For both SHA-256 and SHA3–256 we found that the total cost when including the classical processing increases to approximately 2¹⁶⁶ basic operations.</em></blockquote><blockquote><em>Our estimates are by no means a lower bound, as they are based on a series of assumptions.</em></blockquote><p>Still, we can expect that in the advent of scalable quantum computing all Bitcoin Cash cryptographic primitives would have to be upgraded, but in what order and how to transition funds caught in old outputs?</p><p>Addresses that had their public key exposed would be easy targets since only cracking the public key would stay in the way of stealing the funds. Those may become vulnerable even before hash function preimage security level starts being in the “danger zone”, and even before Bitcoin networks react by implementing some quantum-hardening consensus rules.</p><p>What about addresses where the key was never exposed, would they be safe at rest? Assuming Bitcoin Cash would have P2SH32 enabled, our blockchain would have 3 address types, summarized below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*LfcAcetVXQmVoCNj" /></figure><p>We already demonstrated how a collision-attack would be a risk only for those who are being asked to pay into addresses generated by others <strong>after</strong> a collision attack becomes feasible, so a timely upgrade to “P2SH48” would address that in the same way that a P2SH32 upgrade addresses P2SH collision vulnerability against conventional computers.</p><p>If quantum-computing collision-attacks against 256-bit hash functions should ever become feasible, then all Bitcoin blockchains would have to upgrade more than just address hashes: transaction identifier hashes, Merkle-tree hashes, block hashes, and elliptic-curve signatures would all become insecure and an upgrade of the entire system would be required. For further reading, we have found some recent literature [58] discussing the impact on popular blockchains.</p><p>After a hypothetical and systematic quantum-proofing upgrade, there would still be unspent outputs locked using old methods. Here we will consider risks to those funds, left behind in old addresses. With 80-bits of preimage resistance, both 160-bit address types would theoretically be in the danger zone. We could conceive a quantum-computing attack that searches for any spendable pattern, which is an extension of Grover’s algorithm [59]:</p><ul><li>For P2PKH, that would mean finding any preimage that is a valid secp256k1 public key and then cracking the secret key.</li><li>For P2SH, that would mean finding any preimage which would allow the attacker to steal the funds using a contract template of his choice.</li></ul><p>We have not found much literature that explores possibility of breaking the address hash, one systematic analysis of Bitcoin primitives briefly considers [60] the possibility of breaking both the address hash and the underlying key.</p><p>With 128-bits of preimage-resistance against quantum computers, P2SH32 funds would still be safe at rest. Depending on the underlying contract, they could even be safe to use. This is because Bitcoin Cash introspection opcodes could be used to create hash-based P2SH contracts, where the spender could rely on time-locks and commitments to create quantum-resistant transactions. We can outline the contract here: require a valid signature from a key, and also require spending another input alongside — one that spends a prevout which reveals a pre-commitment to the signature and such that it is time-locked. This way, even if the key is revealed, the adversary could not immediately produce an alternative transaction since he would not have a matured pre-commitment output in his possession. He could produce one and wait, but by the time it matures, the real owner’s transaction will be buried under some blocks, and stealing the funds would require a chain re-org. Similar solutions [73] have already been proposed for Bitcoin Core (disambiguation) as potential soft-fork consensus rules that would implement a commit-delay-reveal spending pattern, with the goal of moving stranded funds to hypothetical quantum-secure contracts. With recent Bitcoin Cash Script developments, users will not have to wait for a consensus upgrade to secure their funds, as they will be able to encumber their outputs with custom contracts that could be designed to be quantum-secure. Those would not be as practical and these problems are in far-distant future, but in our view it is reassuring to know that with Introspection and P2SH32 upgrades, Bitcoin Cash network could already allow users to secure their funds for the long-term.</p><h3>6. Potential Future Upgrades</h3><p>We briefly mentioned two technical debts other than hash collision vulnerability, and here we will expand on them and consider some possibilities for repaying them.</p><h3>6.1. Transaction Encoding</h3><p>If Bitcoin had a hard-fork upgrade strategy, then the P2SH feature could have been rolled out differently and more efficiently, by implementing a dedicated opcode for the feature and using a single byte to encode its use instead of 3 that are required to disguise the feature as a hash-lock contract. Because it was rolled out as a soft-fork, every P2SH output now wastes 2 bytes in transaction encoding.</p><p>Recall the current P2SH pattern:</p><ul><li>locking script:<br> OP_HASH160 OP_DATA_20 hash160(redeem_script) OP_EQUAL;</li><li>unlocking script:<br> [push data_N] ... [push data_1] [push data_0] &lt;push redeem_script&gt;.</li></ul><p>Were it rolled out as a hard-fork, then it could have been rolled out with more efficient encoding:</p><ul><li>locking script:<br> OP_P2SH_20 hash160(redeem_script),</li><li>unlocking script:<br> [push data_N] ... [push data_1] [push data_0] &lt;push redeem_script&gt;,</li></ul><p>The OP_P2SH_20 would do it all at once: pop one item from the stack, hash it and push the result on the stack, push the next 20 bytes to the stack, execute an EQUALVERIFY internally and if it validates then execute the 2nd Script VM run.</p><p>The 2 bytes would not make a notable difference in network capacity and scaling, but the cost of shaving them off would have to be burdened by downstream applications, so we do not recommend any change to P2SH encoding and the above only illustrates the inherited technical debt.</p><h3>6.2. Mixing Layers</h3><p>Current specification (BIP-0016) relies on Script VM to authenticate the contract (redeem script) using a particular hash-lock output locking script pattern. The 2nd Script VM run happens only if the contract has both been authenticated AND if the output locking script matches the rigidly-specified P2SH pattern. Even slightly deviating from the pattern would turn it into an ordinary hash-lock contract, like:</p><ul><li>locking script:<br> OP_HASH160 OP_DATA_20 hash160(redeem_script) OP_EQUAL <strong>OP_0NOTEQUAL</strong>;</li><li>unlocking script:<br> &lt;push redeem_script&gt;.</li></ul><p>Here, the redeem_script does not have to be a valid Script VM bytecode because it will never be executed for the 2nd run, and any preimage will be able to unlock the output.</p><p>Because the P2SH locking script pattern is a rigidly-specified pattern, a validating node does not really need to parse it as Script for the 1st run. It can just use a simpler algorithm in-between executing input unlocking script and the output’s locking script. When evaluating an input, an optimized implementation could be doing this:</p><pre>// Execute only the input&#39;s unlocking script in order to populate<br>// the stack with unlocking data, so we can grab the redeem script<br>// from it later.<br>scriptvm.ClearStack();<br>scriptvm.EvalScript(input.unlocking_script);<br>if (scriptvm.error)<br>    fail();</pre><pre>// Check for P2SH &quot;magical&quot; pattern<br>if (prevout.locking_script.length == 23 &amp;&amp;<br>    prevout.locking_script[0] == OP_HASH160 &amp;&amp; // 0xa9<br>    prevout.locking_script[1] == OP_DATA_20 &amp;&amp;) // 0x14<br>    prevout.locking_script[22] == OP_EQUAL) { // 0x87<br>        // P2SH VM state &quot;hack&quot;<br>        real_script = scriptvm.stack.top();<br>        scriptvm.stack.pop();<br>        if (scriptvm.stack.count() == 0)<br>            fail();<br>        if (hash160(real_script) != prevout.locking_script.substr(2,21))<br>            fail();<br>}<br>else<br>    real_script = prevout.locking_script;</pre><pre>// Executes either the redeem script or the &quot;bare&quot; locking script.<br>scriptvm.EvalScript(real_script);<br>if (scriptvm.error)<br>    fail();<br>if (scriptvm.stack.top() != 1 || scriptvm.stack.count() != 1)<br>    fail();</pre><p>The BIP-0016 specification has the contract authentication (matching the hash) done by Script VM, but it does not have to be. It could just as well be verified by the base transaction validation layer without the Script VM. The base layer already modifies the initial Script VM state by popping a stack element. That sets up the Script VM to execute the 2nd run of the redeem script, starting from the “hacked” VM state. Instead of this limited state hack, the base layer could handle the first validation step without the overhead of the Script VM.</p><p>Inputs use a small subset of Script VM operations (push-only [61]) so we could instead use an input pre-processor to obtain only the value of interest (redeem script). That would let us authenticate the script and remove the last input’s push without having to instantiate the Script VM at all, and the P2SH feature could be self-contained and agnostic of the language that will execute the bytecode it authenticates. In that scenario, we would have to call on EvalScript only once, and we would feed it the complete script: EvalScript(input.unlocking_script || output.locking_script).</p><p>Because of current specification’s soft-fork backwards-compatibility [62] clause, an optimized implementation would still have to pretend the redeem script is a stack element. This has for consequence that the redeem script is more limited in size than a “bare” output script, because it is limited by the MAX_SCRIPT_ELEMENT_SIZE[63].</p><p>Still, we could have a simpler validation algorithm, compatible with the current specification:</p><pre>// Self-contained P2SH authentication<br>if (prevout.locking_script.length == 23 &amp;&amp;<br>    prevout.locking_script[0] == OP_HASH160 &amp;&amp; // 0xa9<br>    prevout.locking_script[1] == OP_DATA_20 &amp;&amp; // 0x14<br>    prevout.locking_script[22] == OP_EQUAL) { // 0x87<br>        real_script = input.getRedeemScript(); // find the last unlocking script data push and get its data<br>        input.removeRedeemScript(); // remove the last data push and its data from input.unlocking_script<br>        if (len(real_script) &gt; MAX_SCRIPT_ELEMENT_SIZE)<br>            fail();<br>        if (hash160(real_script) != prevout.locking_script.substr(2, 21))<br>            fail();<br>}<br>else<br>    real_script = prevout.locking_script;</pre><pre>// Execute full script at once, be it a P2SH or a &quot;bare&quot; output.<br>scriptvm.EvalScript(real_script + input.unlocking_script); // byte concatenation<br>if (scriptvm.error)<br>    fail();<br>if (scriptvm.stack.top() != 1 || scriptvm.stack.count() != 1)<br>    fail();</pre><p>This would untangle the P2SH feature from Script VM as much as possible within bounds of the current specification, which implementations are free to do at their discretion.</p><p>Through a hard-fork upgrade, the length limit could be set to some other value, independent of the stack element size limit. Increasing this and other Script VM limits is being discussed [64] but here we are not ready to recommend changing the limit. The script length is a DoS vector and the limit should be increased only after a careful analysis, which is outside scope of this document.</p><p>Similarly, the input and output transaction format could be optimized using the non-breaking PreFiX [65] method to entirely separate the feature from Script VM, by giving dedicated input and output fields to the redeem script and its hash, similar to what was explored by Andrew Stone (Bitcoin Unlimited) and labeled “closure hash” [66]. Such an upgrade would be subject to a cost-benefit analysis, maybe part of a broader transaction format update, which is also outside scope of this document.</p><h3>7. Pay-to-Public-Key-Hash (P2PKH) Outputs</h3><p>The P2PKH locking script pattern does not rely on a VM state “hack” like P2SH. It uses a single Script VM run to both authenticate the public key and verify its signature. It is not a standalone feature but a regular use of the Script language, in “bare” output script form. As such, it would require only a relay policy upgrade to allow for a 32-byte variant (let us call it “P2PKH32”):</p><ul><li>Locking script:<br> OP_DUP OP_HASH256 OP_DATA_32 pubkey-hash-32 OP_EQUALVERIFY OP_CHECKSIG</li><li>Unlocking script:<br> &lt;push signature&gt; &lt;push pubkey&gt;</li></ul><p>Such an upgrade would not really be necessary, because an equivalent could be implemented as redeem script and hidden “inside” the P2SH32 hash, call it a pay-to-public-key-script-hash (P2PKSH) address, like so:</p><ul><li>Locking script:<br> OP_HASH256 OP_DATA_32 redeem_script OP_EQUAL</li><li>Redeem script:<br> OP_DATA_33 pubkey OP_CHECKSIG</li><li>Unlocking script:<br> &lt;push signature&gt; &lt;push redeem_script&gt;.</li></ul><p>Either way, wallets would have to process a list of keys and compute a 32-byte hash and address corresponding to each key, but address generation would be slightly different. Total size of prevout + input would be the same in either case:</p><ul><li>P2PKH32 address (37 bytes):<br> 0x76aa20 || hash256(pubkey) || 0x88ac</li><li>P2PKSH32 address (35 bytes):<br> 0xaa20 || hash256(0x21 || pubkey || 0xac) || 0x87</li></ul><p>Spending input script would also be slightly different:</p><ul><li>P2PKH32 spend (66 + 34 bytes):<br> &lt;push signature&gt; &lt;push pubkey&gt;</li><li>P2PKSH32 spend (66 + 36 bytes):<br> &lt;push signature&gt; &lt;push (0x21 || pubkey || 0xac)&gt;</li></ul><p>Note: || indicates byte concatenation.</p><p>Both would require support by applications such as wallets, and both would have the same transaction (input+output) size. The P2PKSH32 option has some advantage in that it would make the address relatively smaller and in that it would make all 32-byte outputs indistinguishable from each other.</p><p>—</p><p><em>(Bitcoin Cash Node technical bulletin, mirrored from gitlab [67], also published on read(dot)cash [68].)</em></p><p>—</p><pre>[1] https://bitcoincashresearch.org/t/p2sh32-a-long-term-solution-for-80-bit-p2sh-collision-attacks/750<br>[2] https://github.com/bitcoin/bips/blob/master/bip-0016.mediawiki<br>[3] https://explorer.bitcoinunlimited.info/block-height/173805<br>[4] https://en.bitcoin.it/wiki/Hashlock<br>[5] https://blockchair.com/bitcoin-cash/transaction/11ac4602f988dd3415ef01d65263ede861410173be628fbb47a065cc0867e19e<br>[6] https://documentation.cash/protocol/forks/hf-20181115#clean-stack<br>[7] https://documentation.cash/protocol/forks/bch-uahf<br>[8] https://gitlab.com/bitcoin-cash-node/bitcoin-cash-node/-/blob/master/src/script/script.h#L23<br>[9] https://en.wikipedia.org/wiki/Preimage_attack<br>[10] https://en.wikipedia.org/wiki/Collision_attack<br>[11] https://en.wikipedia.org/wiki/Length_extension_attack<br>[12] https://en.wikipedia.org/wiki/Hash_function_security_summary<br>[13] https://blog.skullsecurity.org/2012/everything-you-need-to-know-about-hash-length-extension-attacks<br>[14] https://www.schneier.com/wp-content/uploads/2016/02/paper-preimages.pdf<br>[15] https://crypto.stackexchange.com/questions/96461/composition-of-cryptographic-hash-functions/96470#96470<br>[16] https://crypto.stackexchange.com/questions/84481/is-mac-double-hashing-enough-to-prevent-length-extension-attacks/84483#84483<br>[17] https://en.wikipedia.org/wiki/Birthday_attack<br>[18] https://en.wikipedia.org/wiki/Security_level#Typical_levels<br>[19] https://eprint.iacr.org/2019/1492.pdf<br>[20] https://bitcoin.stackexchange.com/questions/88556/is-this-a-collision-attack-or-a-2nd-preimage-attack<br>[21] https://www.cs.umd.edu/~jkatz/imc/hash-erratum.pdf<br>[22] https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2016-January/012204.html<br>[23] https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2016-January/012234.html<br>[24] https://bitcoincashresearch.org/t/p2sh32-a-long-term-solution-for-80-bit-p2sh-collision-attacks/750<br>[25] https://gitlab.com/GeneralProtocols/research/chips/-/blob/master/CHIP-2021-02-Add-Native-Introspection-Opcodes.md<br>[26] https://gitlab.com/GeneralProtocols/research/chips/-/blob/master/CHIP-2021-02-Bigger-Script-Integers.md<br>[27] https://bitcoincashresearch.org/t/p2sh-assurance-contract/720<br>[28] https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki<br>[29] https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WSH<br>[30] https://gitlab.com/bitcoin-cash-node/announcements/-/merge_requests/52#note_972949731<br>[31] https://documentation.cash/protocol/blockchain/hash#sha-256<br>[32] https://bitcoincashresearch.org/t/p2sh32-a-long-term-solution-for-80-bit-p2sh-collision-attacks/750#using-op_sha256-rather-than-op_hash256-3<br>[33] https://en.wikipedia.org/wiki/Random_oracle<br>[34] https://eprint.iacr.org/2013/784.pdf<br>[35] https://crypto.stackexchange.com/questions/33663/unlinkability-of-merkle-damg%c3%a5rd-hash-function-resultshttps://crypto.stackexchange.com/questions/33663/unlinkability-of-merkle-damg%c3%a5rd-hash-function-results<br>[36] https://eprint.iacr.org/2013/382.pdf<br>[37] https://blog.cryptographyengineering.com/2020/01/05/what-is-the-random-oracle-model-and-why-should-you-care-part-5/<br>[38] https://crypto.stackexchange.com/questions/879/what-is-the-random-oracle-model-and-why-is-it-controversial/880#880<br>[39] https://en.wikipedia.org/wiki/Standard_model_(cryptography)<br>[40] https://link.springer.com/chapter/10.1007/978-3-030-63287-8_12<br>[41] https://eprint.iacr.org/2015/140.pdf<br>[42] https://gitlab.com/bitcoin-cash-node/bitcoin-cash-node/-/merge_requests/1556<br>[43] https://en.wikipedia.org/wiki/BLAKE_(hash_function)#BLAKE2<br>[44] https://en.wikipedia.org/wiki/SHA-3#Comparison_of_SHA_functions<br>[45] https://bitcoincashresearch.org/t/p2sh-assurance-contract/720<br>[46] https://github.com/bitcoincashorg/bitcoincash.org/blob/master/spec/cashaddr.md#version-byte<br>[47] https://gitlab.com/0353F40E/announcements/-/blob/p2sh-data/attachments/2022-06-09_bitcoin_cash_pay_to_script_hash_p2sh_past_present_and_future/p2sh_data_EN.md<br>[48] https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#p2wpkh-nested-in-bip16-p2sh<br>[49] https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#p2wsh-nested-in-bip16-p2sh<br>[50] https://documentation.cash/protocol/forks/hf-20181115#clean-stack<br>[51] https://documentation.cash/protocol/forks/hf-20190515#allow-segwit-recovery<br>[52] https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#p2wsh<br>[53] https://en.wikipedia.org/wiki/Grover%27s_algorithm<br>[54] https://en.wikipedia.org/wiki/BHT_algorithm<br>[55] https://www.researchgate.net/figure/Comparison-of-conventional-and-quantum-security-levels-of-typical-ciphers-12_tbl1_332863808<br>[56] https://en.wikipedia.org/wiki/Shor&#39;s_algorithm<br>[57] https://www.cs.sfu.ca/~meamy/Papers/breakingsha.pdf<br>[58] https://eprint.iacr.org/2022/026.pdf<br>[59] https://en.wikipedia.org/wiki/Grover%27s_algorithm#Multiple_matching_entries<br>[60] https://link.springer.com/chapter/10.1007/978-3-319-45741-3_11#Sec19<br>[61] https://documentation.cash/protocol/forks/hf-20181115#push-only<br>[62] https://github.com/bitcoin/bips/blob/master/bip-0016.mediawiki#520byte_limitation_on_serialized_script_size<br>[63] https://gitlab.com/bitcoin-cash-node/bitcoin-cash-node/-/blob/master/src/script/script.h#L23<br>[64] https://bitcoincashresearch.org/t/chip-2021-05-targeted-virtual-machine-limits/437<br>[65] https://gitlab.com/bitcoin-cash-node/announcements/-/blob/master/2021-12-23_evaluate_viability_of_transaction_format_or_id_change_EN.md#an-alternative-to-breaking-change<br>[66] https://docs.google.com/document/d/1X-yrqBJNj6oGPku49krZqTMGNNEWnUJBRFjX7fJXvTs/edit#heading=h.5m05gajyo69u<br>[67] https://gitlab.com/bitcoin-cash-node/announcements/-/blob/master/2022-06-09_bitcoin_cash_pay_to_script_hash_p2sh_past_present_and_future_EN.md#bitcoin-cash-node-technical-bulletin<br>[68] https://read.cash/@bitcoincashnode/bchn-technical-bulletin-2022-06-09-d76f7a1c<br>[69] https://documentation.cash/protocol/blockchain/transaction/locking-script#standard-scripts<br>[70] https://explorer.bitcoinunlimited.info/tx/587f949b39e4590e40ed2a1e06c9cfb3ae4b73a18f7261251e6e68a4a2d41896<br>[71] https://explorer.bitcoinunlimited.info/tx/106f5e8263b7051e2528d25047f75808a82f3d838589e357c54738beff0fa384<br>[72] https://gitlab.com/0353F40E/announcements/-/blob/p2sh-data/attachments/2022-06-09_bitcoin_cash_pay_to_script_hash_p2sh_past_present_and_future/p2sh_data_EN.md<br>[73] https://eprint.iacr.org/2018/213.pdf<br>[74] https://bitcoincashresearch.org/t/p2sh32-a-long-term-solution-for-80-bit-p2sh-collision-attacks/750/3<br>[75] https://documentation.cash/protocol/forks/bch-uahf#req-6-2-mandatory-signature-shift-via-hash-type</pre><p>—</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*0vsiP9qFBJVnPWST3Tr7qw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f8c122acc18" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>