January 23, 2022
Top

Preparing to activate Taproot

Translation of a series of posts from Bitcoin Optech on the technical side of preparing for Taproot activation. Recommendations, code examples, links to tutorials and just what to expect upon activation. As well as the expected new features and the estimated time frame for their implementation.

List of topics:

  • Bech32m sending support
  • Does it make sense to use taproot for regular single signature transactions?
  • Taproot descriptors
  • P2WPKH to single-sig P2TR
  • Safety of funds on P2TR outputs before activation and a safe period after taproot activation
  • Learn taproot using it
  • Multisignature overview
    • Using multisig
    • Threshold signatures
  • Multisignature nonce values
  • Signature adapters
    • The magic of adapters
    • Multisignature adapters
  • PTLC (Point Time Locked Contracts)
    • Privacy issues with HTLC
    • PTLC solution
  • Lightning Network with taproot
    • PTLC on Lightning Network
    • P2TR channels
    • Time frame
  • Vault with taproot
  • Security schemes and recovery of access to funds
  • Signet testing
  • A protocol for signing universal messages is still needed
  • Linking Outputs
  • Is the collaboration option always needed?
  • Future changes in consensus
  • What happens upon activation?

Bech32m sending support

Starting at block 709 632 Bitcoin userswill be able to securely receive payments to taproot addresses. Given the level of user enthusiasm for the Taproot update and the five months it took wallet developers to implement support for it, we expect at least a few popular wallets to allow their users to generate taproot addresses, if not from the moment of activation, then as soon as possible. terms.

This means that ideally, to block 709 632, anyanother wallet or service sending bitcoins to custom addresses must allow sending to taproot addresses. Otherwise, it risks confusing and disappointing its users. Pay-to-Taproot (P2TR) addresses, according to the BIP350 specifications, use the bech32m encoding scheme, which is slightly different from the bech32 BIP173 algorithm used in segwit v0 for P2WPKH and P2WSH addresses. Bech32m uses a constant in the checksum function 0x2bc830a3 instead of 0x01used in bech32.

Changing this single constantprovides the ability to check the bech32m checksums, but the code still needs to use the original constant for the existing P2WPKH and P2WSH addresses. The code should decode the address without checking the checksum, determine whether it uses segwit v0 (bech32) or segwit v1 + (bech32m), and then check the checksum using the appropriate constant. See the bech32 reference implementations update pull request for C, C ++, JS, and Python for examples. If your code is already using the reference libraries, you can update them to the latest version from this repository, just note the slight changes in some of the APIs. BIP350 and reference implementations include test vectors that should be used in all bech32m implementations.

Though getting payments to taproot addresses before block 709 632 are insecure, dispatch shouldn't cause any problems for the sender. Bitcoin Core has supported relaying and mining transactions with taproot outputs since version 0.19 (released November 2019).

Does it make sense to use taproot for regular single signature transactions?

Using the transaction size calculator fromBitcoin Optech can be compared in size to different types of single-sig transactions. As you might expect, transactions with P2WPKH inputs and outputs are much smaller than transactions with P2PKH inputs and outputs, however - and this may be surprising - P2TR transactions are slightly larger than the equivalent P2WPKH transactions.

P2PKH (legacy) P2WPKH (segwit v0) P2TR (taproot / segwit v1)
Output 34 31 43
Input 148 68 57.5
2-in, 2-out tx 374 208.5 211.5

For single-sig wallets, early implementationspending taproot outputs may even seem counterproductive, but upon closer inspection, it becomes clear that using P2TR can have a number of benefits for both single-sig wallet users and the network as a whole.

  • Cheaper to spend: at the entry level of the transaction expendituresingle-sig P2TR UTXO costs 15% less than P2WPKH UTXO. In the simplest analysis, as in the table above, such a nuance is not revealed that the sender of the transaction does not choose which address he is asked to pay to, so if you stay on P2WPKH, and everyone else goes to P2TR, the actual typical size of your 2-in -2-out transactions will be 232.5 vBytes, while the size of transactions with P2TR on all inputs and outputs will still be only 211.5 vBytes.
  • Privacy: although usually the transition to a new script format forEarly adopters imply some loss of privacy; when switching to taproot, users get an immediate boost in privacy. Your transactions can look indistinguishable from transactions in new lightning channels, provide more efficient DLCs, more secure multisignatures, various "smart" schemes for recovering access to funds and opportunities for hundreds of other innovations. Using P2TR for single-sig transactions allows the wallet to also implement support for multisignatures, Tapscript, Lightning Network or other features without compromising the privacy of existing users. It doesn't matter if the UTXO was received in an old or new version of your software - both UTXO on-chains will look the same.
  • More convenient for [hardware] electronic signature devices: after the new "opening" of the attack by overpayment of the commission(fee overpayment attack), several ES hardware refused to sign transactions, unless each UTXO consumed in it is accompanied by metadata containing a copy of a significant part of the transaction in which this UTXO was created. This significantly increases the amount of worst-case processing performed by signers in the worst-case scenario, which is especially problematic for digital signage devices that use QR codes of a limited size as the main communication channel. Taproot removes the vulnerability underlying the fee overpayment attack, and therefore can significantly improve the performance of EDS devices.
  • More predictable commission rates: size of ECDSA signatures for P2PKH and P2WPKH UTXOmay vary. Since wallets need to select a transaction fee rate prior to generating a signature, most wallets simply assume the largest possible signature size and accept a small overpayment if the generated signature turns out to be smaller. For P2TR, the exact size of the signature is known in advance, which allows the wallet to reliably select the exact commission rate.
  • Full node help: the security of the Bitcoin system is largely builton the fact that a significant proportion of users verify each transaction confirmed by the network using their own full nodes. Schnorr signatures used in taproot allow for efficient batch verification, which roughly halves the number of CPU cycles a node spends verifying signatures while replenishing and processing previous blocks. Even if all the other items on this list didn't pique your interest, consider supporting taproot to make it somewhat easier for Bitcoin users to maintain full nodes.

Taproot descriptors

Output script descriptors provide forwallets are a common way to store the information you need to create addresses, efficiently scan outputs sending bitcoins to those addresses, and then spend funds from them. In addition, descriptors are quite compact and contain a basic checksum, which makes them convenient for backing up address information, copying this information between different wallets, or exchanging it between wallets that cooperate to provide multiple signatures.

Although descriptors are still used in verya small number of projects, these, together with their associated miniscript project, have the potential to dramatically improve interoperability between different wallets and tools. This will become increasingly important as more users actively take advantage of the taproot, whether in multi-signatures or consumable recovery schemes.

Before this happens, descriptors need toupdate to work with taproot. This was the subject of pull request # 22051 in Bitcoin Core. The syntax is designed in such a way as to fit in one descriptor template all the necessary information for spending both on the P2TR keypath and on the scriptpath. For a simple single-sig transaction, a descriptor like this is sufficient:

tr (<key>)

The same syntax can be used for multisignatures and threshold signatures. For example, Alice, Bob, and Carol combine their keys with MuSig and then pay out to tr (<combined_key>).

Somewhat counterintuitive, but the key specified in tr (<key>)will not be a key encoded into an address. Descriptor tr () follows the security recommendation from BIP341use an internal key, which is fixed in the tree of the non-consumable script. This eliminates the attack on users of naive key aggregation schemes (more advanced schemes, such as MuSig and MuSig2, are not susceptible to such attacks).

A new syntax has been added for the scriptpath flow to allow the contents of a binary tree to be specified. For example, {{B, C}, {D, E}} describes the following tree:

Internal key     /    /   / /   B C D E

The tree can be specified asthe optional second parameter of the descriptor template we used earlier. For example, if Alice wants to spend bitcoins on the keypath, but also wants to allow Bob, Carol, Dan, and Edmond to spend through the scriptpath that generates an audit path for her (but not an outside observer), Alice can use the following descriptor:

tr (<a_key>, {{pk (<b_key>), pk (<c_key>)}, {pk (<d_key>), pk (<e_key>)})

The above options are all that is required toиспользования дескрипторов для taproot, однако в пулл-реквесте #22051 перечисляется также ряд отсутствующих опций, которые можно было бы добавить, чтобы дескрипторы лучше и полнее описывали ожидаемые пользовательские политики расходования:

  • Keypath invalidation: некоторые пользователи могут захотеть запретить расходование по keypath, оставив только вариант scriptpath. Сейчас это можно сделать, используя в качестве первого параметра tr () non-consumable key, but it would be nice to allow wallets to store this preference in the descriptor itself and calculate the non-consumable keypath without compromising privacy.
  • Tapscript multisig: for legacy and segwit v0 standards, descriptors multi () and sortedmulti () support opcode OP_CHECKMULTISIG... To allow batch validation in taproot, scripted multisignatures in tapscript are handled slightly differently, so today descriptors tr () you have to specify any required multisig opcodes through a script raw ()... It would be nice to get updated versions of the scripts multi () and sortedmulti () for tapscript.
  • MuSig based multi-signatures: in the example above, we described how Alice, Bob, and Carol manually aggregated their keys to use the descriptor tr ()... Ideally, it would be nice to have a function that would allow them to specify something like tr (musig (<a_key>, <b_key>, <c_key>))so that they can save all the original key information and use it to populate the fields in the PSBT used to coordinate signing.
  • Timelock, hashlock and pointlock:blocking by time, by hash and by point onelliptical curve - These powerful constructs used in the Lightning Network, DLC, CoinSwap and many other protocols can currently only be described using the function raw ()... Adding their support directly todescriptors are possible, but it may be that support is provided through the descriptor sibling miniscript project instead. The integration of miniscript into Bitcoin Core is still in progress, but we expect these innovations to spread to other wallets in the future, as has already happened with PSBT and descriptors.

Wallets do not need to implement descriptors to start using taproot, but those who do will create a better foundation for using the more advanced taproot functionality later on.

P2WPKH to single-sig P2TR

For wallets that already support receiving and spending segwit v0 P2WPKH outputs, upgrading to segwit v1 P2TR for single-sig transactions should be fairly straightforward. The main steps look like this:

  • Use the new way to get the key: you don't need to change your BIP32 hierarchicaldeterministic (HD) code and users do not need to generate new seeds. [1] However, it is highly recommended to use the new acquisition path for public P2TR keys (as defined in BIP86). Ignoring this recommendation opens up opportunities for attack, and they can be implemented if you use the same keys for ECDSA and Schnorr signatures.
  • Set up your public key by its hash: although technically it is not required for single-sig,especially if all your keys come from a randomly generated BIP32 seed, BIP341 recommends committing the key to a non-consumable scripthash tree. It is no more complicated than the elliptic curve addition operation, which adds the public key to the point on the curve corresponding to the hash of that key. Following this recommendation will allow you to use the same code when adding descriptor support tr () or if you later decide to add support for scriptless multisignatures (Scriptless Scripts PDF).
  • Create addresses and track them: use bech32m to create addresses. Payments will be sent to scriptPubKey OP_1 <tweaked_pubkey>... You can scan transactions to the script address using any method that you used to scan segwit v0 addresses, like P2WPKH.
  • Create an expense transaction: all but witness fields for taproot are the same as for P2WPKH, so there is no need to worry about changes in transaction serialization.
  • Create a signature message: this is a commit, a commit, data from a transactionspending. Most of the data is the same as what is being signed for a P2WPKH transaction, but the order of the fields is changed, plus a few additional elements are signed. Implementing this essentially boils down to serializing and hashing various data, so the code should be easy to write.
  • Sign the hash of the signature message: there are different ways to create Schnorr signatures.Better not reinvent the wheel, but use a function from a trusted library that you trust. But if for some reason you cannot do this, BIP340 provides an algorithm that should be quite simple to implement, having the necessary primitives to create ECDSA signatures. After receiving the signature, enter it in the witness data for your login and send the transaction.

Before activating taproot on block 709 632, the code can betest in testnet, public default signet or private regtest mode of Bitcoin Core. When adding taproot support to an open source wallet, we recommend that you share links to relevant pull requests on the Taproot Uses and Bech32 adoption pages of the Bitcoin Wiki so that other developers can learn from your code.

Safety of funds on P2TR outputs before activation and a safe period after taproot activation

Implement taproot support in wallets andservices, it is quite appropriate and correct in advance, so that everything is ready for the activation block. However, you should not generate any P2TR addresses before block 709 632, as this could result in a loss of money by the service and its users.

The reason is that prior to block 709 632, any funds sent to the P2TR output could be spent anyone... In this case, the money will be absolutely unprotected. But starting with the activation block, thousands of full nodes will begin to apply the BIP341 and BIP342 rules (and also BIP340).

If there was a 100% guarantee thatSince the blockchain will not be reorganized, it would be safe to start generating addresses for P2TR as soon as the last block appears before the taproot (709 631). But there is reason to be worried about possible reorganizations - not only accidental, but specifically aimed at making money from premature P2TR payments.

Imagine a large number of peoplewho want to be among the first to receive P2TR payments. They naively send themselves a small amount as soon as they see block 709 631. [2] These payments will be protected at block 709 632, however they can be easily stolen by any miner who creates an alternative to block 709 631. If the total value of bitcoins sent to P2TR is large enough, then it may be justified to try to mine two blocks instead of one (more in the topic Fee Sniping on Bitcoin Optech).

For this reason, we do not recommend generatingaddresses for P2TR until you are sure that the risk of reorganization is no longer relevant. We consider the 144 block period (about one day) after activation to be conservative enough to minimize risks without unduly delaying services and users from using taproot.

In a nutshell:

  • 709,631: The last block in which anyone can spend the funds sent to the P2TR output.
  • 709 632: The first block in which P2TRs can only be spent if they meet BIP341 and BIP342 rules.
  • 709 776: the end of a reasonably safe waiting period, from which wallets and services can provide their users with bech32m addresses to receive P2TR outputs.

However, nothing described here overridesthe above recommendations on the soonest implementation of payments to bech32m addresses. If someone requests a payment to a P2TR address prior to what you consider to be a safe deadline, then that is their risk, not the sender's.

Learn taproot using it

About two years ago James Chiang and ElichaiTurkel has created an open source repository of Jupyter documents for the Bitcoin Optech series of workshops to educate developers on taproot technology. Workshops in San Francisco, New York and London received positive reviews, but later travel restrictions prevented new face-to-face workshops.

Since posting these Jupyter docstaproot has undergone several changes. But at the same time, taproot support was added to Bitcoin Core, which allowed the repository to remove dependence on a separate custom branch of Bitcoin Core. Developer Elle Mouton has kindly updated the repository with all of these changes, making it again a great way to quickly get hands-on with taproot algorithms and datatypes.

The repository documents are divided into four sections:

  • Section 0 helps you set up your environment, explains the basics of elliptic cryptography and the tagged hashes used in BIP 340, 341, and 342.
  • Section 1 guides you through the Schnorr signature creation process. Once you've mastered this, you will learn how to create multisignatures using the MuSig protocol.
  • Section 2 gives experience with all aspects of taproot.It starts with the principles of segwit v0 transactions and then helps you create and dispatch the first segwit v1 (taproot) transactions. By applying the knowledge from section 1, you can create and send a taproot output using MuSig. This introduces the concept of key customization and shows you how taproot allows a public key to be used to commit data. Now that you can create commits, you will learn about tapscript (s) - how they differ from legacy Bitcoin scripts and segwit v0 scripts, and how to bind to the tapscript (s) tree. Finally, the last short file introduces Huffman coding for creating optimal script trees.
  • AT section 3 an additional exercise oncreating a taproot exit that modifies signature requirements as the output remains unspent, which allows for efficient use of output under normal circumstances, but also provides a reliable way to regain access to funds in the event of a problem.

The repository contains many exercises forprogramming that is relatively simple, but ensures that you really understand the material presented. The author of this text, not god knows what a coder, coped with the passage in six hours and regretted only that he had not done it earlier.

Multisignature overview

In the last 1000 blocks as of the momentof writing this part, 11% of all transaction inputs contained a multisignature opcode. The two biggest and most immediate benefits of taproot will emerge if many of the users and services creating such transactions move from opcodes to scriptless multisig.

The first big benefit would be to reducethe size of the transaction. Script-based multisignatures are larger the more keys and signatures are required for them, while multisignatures themselves have a consistently small size. The least effective multisig script policy (1-of-2) requires more space than a multisig policy, which can involve thousands of signers. This reduction in size provides a direct reduction in fees for multisig users and an indirect one for all users in that the same volume of transaction confirmation demand can be satisfied using less block space.

</p>

The second important advantage is the increaseprivacy. Every use of the multisig script is explicitly and definitely recorded on the blockchain, where observers can use these records to formulate educated guesses about the wallet history and current balance of individual users. For example, looking at block 692,039, we can not only distinguish multisig and single-sig transactions from each other, but also draw some reasonable conclusions based on the set sizes and thresholds for multisig scripts.

</p>

For comparison, a third party based on onlyblockchain data cannot infer that the sender used a multisignature. When multisig is used for keypath spending, it is indistinguishable from spending through single-sig transactions. If all single-sig and multisig transactions in the block above are transferred to P2TR transactions of expenditure by keypath, then only a few exotic expenditures will be distinguishable due to their scripts (and those in the most ideal scenario could be implemented via keypath).

</p>

Using multisig

We are aware of three Schnorr-based multisignature schemes designed specifically for Bitcoin, all from the MuSig family:

  • MuSig (also called MuSig1) is fairly simple to implement, but requires three rounds of communication in the signing process.
  • MuSig2, also easy to implement.Eliminates one round of communication and allows you to combine another round with key exchange. This allows for a signing process somewhat similar to what we use today with script-based multi-signatures. This requires additional data storage and great care to ensure that your software or device cannot be tricked into replaying part of the signing session. We'll look at the trade-offs that arise in more detail in the next section.
  • MuSig-DN (Deterministic Nonce), which is much more difficult to implement. Communication between participants here cannot be combined with key exchange, but this scheme is invulnerable to a session replay attack.

All signers must agree among themselvesthe protocol being used, so there can be a network effect where many implementations decide to use the same protocol. MuSig's proponents speculate that this will be MuSig2 due to its inherent combination of relative simplicity and high utility.

There is an open source and actively developeda pull request to the libsecp256k1-zkp project to add MuSig2 support. We expect the basic multisignature workflow for most programs to look something like this:

  1. Each member's wallet generates BIP32 xpub,which they share with the rest of the participants using an exit script handle or some other method (similar to how it is usually implemented now for multisignature scripts).
  2. Then any of the wallets can generatea generic, aggregated public key by merging your pubkey at a specific BIP32 depth with a pubkey at the same depth from all other wallets in the multisignature set. This aggregated public key can be used to receive P2TR payments.
  3. When one of the wallets wants to spend funds,it uses a PSBT-based process similar to what it would use with scripted multisignature, but now requires two rounds of communication between signers. In the first round, the initiator creates an unsigned transaction and includes a pair of randomly generated nonces. It is imperative that nonces are not obtained in a completely deterministic manner that would result in the same nonce being reused for a different signature. The initiator sends PSBT with two nonces to other wallets.
  4. Other wallets receive the PSBT, add their random nonce pairs to it, and send it to other wallets or to a general coordinator who works on behalf of the wallets in a trustless manner.
  5. When all wallets receive all nonce pairs, theycombine them into one nonce value. Again, the coordinator can do this for the signers. Then all wallets add partial signatures to their PSBT versions and send PSBT to the rest of the wallets or to the coordinator. The partial signatures are then combined to create the final signature and the transaction is broadcast.

Threshold signatures

The MuSig family of multisignature schemes itselfallows only n-of-n signatures to be generated - each party providing its own key for the consolidated public key must also submit a partial signature to create a shared final. This works great as a direct replacement for some of the uses of today's multisig scripts - such as spending 2-of-2 outlets of Lightning Network funding - but is a departure from other popular policies, such as the 2-of-3 multisign script used by many exchanges.

Several developers work with schemasthreshold signatures that would provide k-of-n scenarios with the same efficiency and privacy benefits as multisignatures, but until they are available, a simple trick can be used.

In many cases of application of threshold schemesit is known in advance which participants are most likely to provide their signature. For example, in a 2-of-3 situation, it might be known that typically Alice and Bob jointly sign transactions, while Carol only provides the signature if one of the other participants is unavailable. In these circumstances, primary keys may use multisignature for keypath taproot flow (e.g. between Alice and Bob), and secondary outputs (Alice and Carol or Bob and Carol) may use multisignature with opcode OP_CHECKSIG in separate branches of the tapscript tree (s).

In the usual case, such a scheme will provide the sameefficiency and privacy as a single-sig or multisig transaction. In special cases, spending still works as expected and remains more efficient and private than publishing your multisig script parameters to the blockchain.

While users wanting minimal commissionsand maximum privacy may eventually move to pure threshold signature schemes, the scheme described above can also be used in the future, since it provides the auditor (if he knows the public keys of all participants) on-chain proof of which corresponding private keys were used to sign ...

Multisignature nonce values

In this part, we'll look at what we have learned may be the biggest challenge to securely implementing multisignature support: the need to avoid nonce reuse.

To verify your Bitcoin signature, youfill out the well-known equation with a signature, a signed message (such as a transaction), your public key, and your public nonce. You can balance this equation only if you know your private key and the private form of the nonce. So anyone who sees a balanced equation like this can conclude that this message and the public key are valid.

Motivation to include signatures in the equation andthe message is obvious. The public key replaces your private key. But what is a public nonce for? Without the nonce, all other values ​​would be known except for your private key, which means that this only unknown is calculated at the level of basic algebra. But algebra cannot solve an equation for two unknowns, so the closed form of nonce serves to keep the private key secret. And just as a public key replaces a private key in the signature equation, a nonce public form replaces its private form.

Nonce values ​​in this context are not easy numbers used oncebut the numbers that must used strictly once.If you use the same nonce in two different signatures, these two signature equations can be combined into one, the nonce can be deduced from it, and, again, the only remaining unknown is the private key. If you use a simple (non-hardened) BIP32 key retrieval, which is likely to be preferred by almost all multisignature wallets, then disclosing one private key means disclosing all other private keys along the same BIP32 path (and possibly other paths too ). That is, if a multi-signature wallet received bitcoins for a hundred different addresses, then reusing a single nonce would compromise all of these addresses.

Single-sig wallets or those that usescripted multisig can avoid reusing nonces with a simple trick - making the nonce dependent on the message being signed. Any change to the message changes the nonce and thus prevents reuse.

But in multi-signatures, use this technique.will not work. They require each signer to submit not only a partial signature, but also a partial public nonce. These partial public nonces are combined to create an aggregated public nonce that is included in the message being signed.

This means that it is not safe to use one andthe same partial nonce more than once, even within the same transaction. If, when you sign the second time, one of your co-signers changed their partial nonce (which changes the aggregated nonce), then your second partial signature will actually sign the other message. This exposes your private key. Since it is impossible for each party to make their private nonce depend on the partial public nonces of all other parties, there is no easy way to avoid reusing the nonce in multi-signatures.

At first glance, it doesn't seem like muchproblem. You can simply ask signers to generate a new random nonce each time they need to sign something. But in practice, it turns out to be not so easy to ensure the desired result. Since at least 2012, people have found bugs in wallets that lead to the loss of bitcoins and that depend on the generation of random nonces.

But even if the wallet does generatehigh quality random nonces, it must ensure that each nonce is not used more than once. And that can be a non-trivial task. Imagine a MuSig2 compatible cold wallet or (hardware) e-signature device that generates a large number of nonces on first launch. This wallet or device will then need to ensure that none of these nonces are ever used with more than one partial signature. It sounds simple - increase the counter each time you use a nonce - but it can be a real problem when you start to work out all the options for an accidental failure of a program or device, not to mention external and possibly malicious interference.

Possibly the easiest way for a walletto reduce the risk of reusing nonce is to store them for as little time as possible. Long-term storage of nonces not only creates many opportunities for things to go wrong, but also requires them to be written to persistent media that can be copied and restored or otherwise brought into an unexpected state. Another possible way to use MuSig2 is to generate a nonce on request only, for example when receiving a PSBT. Nonce can be stored in volatile memory for the short time during which they are needed, and automatically destroyed (excluding reuse) in several variants of unforeseen events, such as a software failure or power outage.

However, cryptographers working on thisthe problem seems to be very concerned about the lack of a reliable way to prevent nonce reuse in the original MuSig (MuSig1) and MuSig2 protocol. MuSig-DN (Deterministic Nonce) offers a solution, but complex and slow (in the alpha implementation on a 2.9 GHz Intel i7 it takes almost a second to create a proof of nonce; it is not known how long this operation might take on a 16 MHz digital signature device with a much less advanced processor ).

Our recommendation to everyone who implementsMultiple signatures on your service: It might make sense for you to go to the # secp256k1 IRC channel or another place where Bitcoin cryptographers communicate and ask for advice on a planned solution before making any major investment of time or resources.

Signature adapters

Imagine someone offering to donate1,000 BTC for a specific charitable cause, if anyone can guess his favorite and very large number. A simple way for the donor to do this is to create an unsigned 1000 BTC spending transaction, and then publish an encrypted copy of his signature to this transaction, the decryption key of which will be that favorite and very large number.

In theory, anyone who guesses the hidden numbercan decrypt the signature and broadcast the charity transaction. But if the donor uses a standard encryption scheme such as AES, then before decryption, there is no easy way for third parties to verify that the encrypted signature is indeed valid for this transaction. Anyone who wants to spend efforts and resources to find a hidden number is forced to trust the honesty and conscientiousness of the donor (so far only assumed).

Let's expand on this problem a bit.Alice and Bob, third parties, want to gamble on whether the signature will be decrypted by anyone or not. Perhaps they could ask the author for a signature hash and use it as a hash in the HTLC function, but again, this requires trusting the alleged donor to act honestly. Even if the signature is ultimately revealed, the donor can sabotage Alice and Bob's contract by providing them with the wrong hash.

The magic of adapters

Signature adapters (signature adapters), often referred to as adapter signatures (by signatures-adapters), these and manyother problems that are relevant today for systems built on the basis of Bitcoin. While they can be used with ECDSA, Bitcoin's current signature scheme, it is much easier to use adapters - privately and at no cost - in conjunction with the BIP340 implementation of Schnorr's schemes for the taproot. Let's see how the above example changes when using adapters.

As before, the donor prepares the transaction for1000 BTC. He signs the transaction in almost the usual way, with the only difference that, in fact, he generates his nonce in two parts: a real random nonce, which he will always keep secret, and his favorite large number, which will initially be kept secret, but that can be safely disclosed to other people. The donor generates a valid signature using both of these values ​​- adding them together as if they were one nonce.

BIP340 signatures use nonce in two forms: numerical representation (called scalar), which is usually known only to the author of the signature, and how point on an elliptic curve (EC) that is published to provide verification.

The donor takes the comment part of hisvalid signature, commitment, and subtracts the hidden scalar from it. This makes the signature incomplete (and therefore invalid), but allows the donor to share a (invalid) signature commit, a (valid) EC point for a full nonce, and a (valid) point for a hidden number. Together, these three pieces of information make up signature adapter.

Using a variation of the signature verification algorithmBIP340, anyone can verify the validity of the signature provided by the adapter by simply substituting the hidden scalar back into the (now invalid) signature commit. This can be verified even without knowing the hidden number itself. That is, now users can try to guess the value of the hidden scalar and be sure that the correctly guessed value will allow them to receive a signature and send a transaction.

Like everyone else who got the signature adapterdonor, Alice and Bob now have a copy of the dot on the EC for the hidden number. Like everyone else, they don't know a real scalar. But, as we remember, all that the donor did in order to turn his valid signature into invalid was to subtract the hidden number from the commit of his signature, while retaining, however, the binding of the signature to the dot on the EC for the hidden number. Alice can just as easily create an invalid signature without being bound to a scalar she doesn't know, but with a dot on the EC that she knows. It does this by creating its own pair of nonce values, using the closed form of nonce when creating its (invalid) signature, but with a binding to the aggregated value of the open form of its nonce and a dot on the EC from the donor's signature adapter. This creates a signature adapter for the transaction that pays Bob. If Bob recognizes the scalar, he can convert that adapter into a valid signature and send the transaction, winning the bet.

But how does Bob know the winning number?Will he have to wait for whoever guesses him to release a press release? No. Let me remind you again that the signature adapter published by the donor is their valid signature minus a scalar. When the hidden number is found and someone sends a 1000 BTC transaction, they must publish the original (valid) signature. Bob, upon seeing this transaction, can take this (valid) signature commit and subtract the (invalid) original adapter signature commit from it to get a scalar. It then uses this scalar to convert Alice's adapter to a valid signature.

Multisignature adapters

The previous subsection shows how the individualusers change the way they create their signatures to get their adapters. This is the same method that parties can use when creating a multisignature. This is extremely useful because many signing adapter scenarios will require two users to collaborate.

For example, when Alice and Bob from the example above dobet, they can start with a deposit in the script, which can only be spent by providing a multi-signature between them. Alice can then create her partial signature in the form of a signature adapter; if Bob discovers the hidden number, he can convert Alice's adapter to her valid partial signature, then add his partial signature and create a complete signature that costs money.

This gives the signature adapters all the sameadvantages that multisig in general: they look and take up as much space as a regular single-sig signature, minimizing fees and maximizing privacy and fungibility.

PTLC (Point Time Locked Contracts)

There are several ways to use adaptersBitcoin signatures, but one option with immediate benefits would be PTLC (Point Time Locked Contract), which could replace the HTLC (Hash Time Locked Contract) that has been used for many years. This will bring several benefits, but it also presents some challenges. To understand both kinds of contracts, let's start with a simplified example of using HTLC; the example below can be applied to off-chain lightning payments, on-chain coinswap payments, or hybrid on-chain / off-chain systems such as the Lightning Loop - it is this flexibility that makes HTLCs so widespread.

Alice wants to pay Carol by sending the payment viaBob, whom neither Alice nor Carol want to trust. Carol generates a random preimage and hashes it using the SHA256 algorithm. Carol passes the hash to Alice and keeps the prototype secret. Alice initiates a payment to Bob, which he can claim by presenting a signature for his public key plus a preimage; or 10 blocks later, Alice can return the transaction to herself by submitting a signature for her public key. This is how the description of this policy in the Minsc language looks like:

(pk ($ bob) && sha256 ($ preimage)) || (pk ($ alice) && older (10))

Now Bob can initiate a payment to Carol for the same amount (possibly minus commissions) with an almost identical script, only with updated parties and a shorter time to return.

(pk ($ carol) && sha256 ($ preimage)) || (pk ($ bob) && older (5))

Now Carol candemand payment from Bob to his address by submitting a prototype; this reveals the prototype to Bob and allows him to demand payment to himself from Alice, also within five blocks.

Privacy issues with HTLC

If the scripts from the example above are published on-chain,reusing the same hash and preimage immediately makes it clear that A pays C through B. It is somewhat less obvious that this is also a problem for off-chain routing protocols such as the Lightning Network. If we imagine a longer routing path, where one person controls several segments of this path, he can see the reuse of the same hash and preimage, and from this determine that some nodes are routing nodes, which increases the likelihood that other nodes are either by senders or recipients. This is part of the connectivity challenge - arguably the Lightning Network's biggest privacy challenge today.

</p>

Although multipath payments are partiallymitigate other aspects of the LN connectivity problem - such as the ability to bind by payment amount - that can exacerbate the hash connectivity problem by giving routing nodes more ability to track hash correlation.

Another problem with HTLC today isthat any scripts written to the blockchain are clearly different from regular spending scripts. This helps observers identify patterns of use and possibly make effective assumptions about information specific to individual users.

PTLC solution

In the previous Minsc scripts, we had a function,which returned true only if a predefined value was passed to it (preimage). The signature adapter is similar in that it can be converted to a valid signature only if the found value is passed to the function (scalar). Ignoring multisig for now allows us to convert the above HTLC scripts to the following PTLCs:

(pk ($ bob) && pk ($ alice_adaptor)) || (pk ($ alice) && older (10))
(pk ($ carol) && pk ($ bob_adaptor)) || (pk ($ bob) && older (5))

In a nutshell, Carol gives Alice a point on EK for herhidden scalar, Alice uses it with a public key of her choice and creates a signature adapter that she passes to Bob. Bob can use the same public key point of his choice and creates an adapter that Carol passes on. Carol exposes the scalar, converting Bob's adapter to a valid signature, and claims Bob's coins. Bob reconstructs a scalar from a valid signature, allowing him to convert Alice's adapter to his own valid signature, and claims her coins.

This solves the problem of connectivity viablockchain surveillance because all anyone sees on the blockchain is a group of valid signatures for individual public keys. Third parties cannot know about the use of the adapters, much less what scalar these adapters were based on.

However, the above procedure does not interfere withthe observing nodes involved in routing tie payments together. If all payments are based on the same scalar, then they are related to each other in the same way as if they were using hashlock and preimage. This can be fixed by having each routing node use its own scalar and then, after the payment has passed, delete the corresponding point. Let's revisit our example with this in mind:

As before, Carol gives Alice a point for herscalar, but this time Alice also asks for Bob's point. Alice, using the aggregation of both points, Carol and Bob, creates an adapter that she gives to Bob. Bob knows his point, so he can subtract it from the adapter he got from Alice. Using the received point (which Bob does not know, this is the point Alice originally received from Carol), Bob creates an adapter that Carol passes on. Carol knows the scalar for this last point, and converts Bob's adapter to a valid signature. As before, Bob reconstructs Carol's scalar from her signature and uses it and his own scalar to convert Alice's adapter to a valid signature.

On two legs of this path, Alice → Bob andBob → Carol, different points on EC and scalars were used, excluding the possibility of linking (associating) payments with each other. This can be extended to a longer path - like the one we looked at in the HTLC example - and see how it improves privacy:

</p>

As mentioned in the previous section, Schnorr schemas make it easy to create adapters for multisig. In the case of standard PTLCs, this allows us to shorten our on-chain scripts to:

pk ($ bob_with_alice_adaptor) || (pk ($ alice) && older (10))
pk ($ carol_with_bob_adaptor) || (pk ($ bob) && older (5))

With taproot, the left branch can be used likekeypath, the path to the key, and the right one as tapleaf, the leaf of the taproot tree. With successful payment routing, Bob and Carol will be able to complete the settlement of their portions of the on-chain without further interaction with their counterparties, making this routed payment indistinguishable from single-sig payments, regular multisig payments, and jointly resolved contracts. It also minimizes block space usage. When one of the return conditions is activated, the method is still quite efficient and quite confidential - pk (x) && older (n) indistinguishable from degrading multisig, enforced hodling and many other possible scripts.

Lightning Network with taproot

This part was written by ZmnSCPxj, ​​the developer of the Lightning Network protocol. In it, the author discusses two privacy features provided by taproot for the Lightning Network:

  • PTLC to LN,
  • P2TR channels.

PTLC on Lightning Network

PTLC allows you to implement many functions, the most important of which for LN, as mentioned in the previous part, is decorrelation of payments without the need to randomize routes.[3] Each node on a single-path or multipath route can be assigned a scalar that is used to fine-tune each PTLC forwarded, providing payment decorrelation so that individual transfers no longer leak a unique identifier for each LN payment.

PTLC - this is not a panacea against all privacy concerns. If the observer sees a forward (forwarded) payment with a specific timelock and amount, and shortly thereafter, the second observer sees a forward payment with smaller timelock and slightly less sum, then very likelythat these forwarded payments belong to the same payment path, even if they cannot be correlated using a unique identifying hash. However, PTLCs do provide:

  • Increased uncertainty in analysis results. The reliability of the probabilities available to the observer is now lower, which means that the information obtained in this way is of much less value.
  • Much greater decorrelation in multipath payments.The paths will not have a strong correlation with each other in timelock and amount, and if LN succeeds, there must be enough payments so that the time correlation does not give a reliable result either.
  • No cost increase over HTLC (possibly even cost savings thanks to multisig efficiency).

Basically, the pre-taproot channel can be updatedbefore PTLC support without having to close and reopen the channel. Existing channels can host PTLC by creating an off-chain transaction that consumes the existing non-taproot output to the taproot output containing the PTLC. This means that adding support for PTLC over LN does not require any cost from node operators and no hardware upgrades from their peers.

However, for actual use of PTLC each forward node on the route from the sender torecipient must support PTLC. This means that real PTLC support may not come until a sufficient number of nodes have been updated. They do not need to use the same protocol (there can be several PTLC protocols), but they should all support any of the PTLC protocols. The need to support multiple PTLC protocols will further complicate LN support and development, so I hope there won't be too many of them (ideally, of course, one).

P2TR channels

One of the solutions to improve the decorrelation between the base layer and the LN was unpublished (private) channels that did not transmit information about their existence to the network.

Unfortunately, every LN channel requires collaboration between two signers, and before taproot is activated, every 2-of-2 script in Bitcoin open encoded.LN is the most active 2-of-2 multisig user, so any blockchain explorer can show that this is an LN channel closing transaction. The funds can then be tracked, and if they are directed to a different P2WSH outlet, it will most likely be another unpublished channel. Thus, even unpublished channels can be identified on-chain after they are closed, with some level of false positives, of course.

Taproot, using Schnorr circuits, allows n-of-nsignatures look exactly like 1-of-1. After some processing, even k-of-n (threshold) signatures will look the same as 1-of-1 (and n-of-n). Then we can offer an option in which the LN channel is provided P2TR UTXO - P2TR channel - which increases the level onchain privacy for unpublished ("private") channels. [4]

This is a (rather small) privacy boostbenefits the published channels too. Published channels are only disseminated over the network as long as they are open, so an attempt to search for published channels will not return any results for preexisting and closed channels. If the observer wants to have data about every published channel that has ever existed, he must store all this data himself and cannot rely on any "archive" node.

In addition, taproot spending on keypath "weighs" 40% less (38.5 vBytes) than P2WSH payments used in LN. Unfortunately, you cannot upgrade an existing pre-taproot channel to P2TR... Existing channels use P2WSH with a 2-of-2 scheme and will have to be closed to switch to P2TR.

In theory outpoint, the channel starting point specified by the transactionfunding concerns only two nodes using this channel. The other nodes on the network do not bother about what the channel provides between any two nodes. However, published channels are distributed over the Lightning gossip network. When a node receives data about such a published channel, it checks against a full Bitcoin node of its choice, verifying that the funding outpoint channel exists and, more importantly, has a correct address... Address verification complicates the spam mechanismdistribution of information about the channel; it is necessary to deposit real funds into the contract recorded in the blockchain so that information about the channel spreads over the LN gossip network. Thus, in practice, even P2TR channels require some remote compatibility; otherwise, senders will ignore these routing channels because they cannot confirm their existence.

Time frame

I think that the best way to set indicativethe time frame for the implementation of functions in a distributed FOSS (Free and Open-Source Software) project is to take as a basis the previous functions and how long it took to implement them. [5]

The last important function in my opinion issimilar in scale to PTLC in LN, it is a bilateral (dual) financing of the channel. Lisa Neigut created an initial proposal for a bilateral funding protocol at BOLT # 524, but the first bilateral funding channel on the mainnet was opened nearly two and a half years later. Bilateral funding only requires compatibility with your direct peers. While PTLC over LN requires compatibility with all routing nodes on the selected routes, including the destination, so I find it justifiable to multiply the time it takes to implement this feature by 1.5 due to the added complexity. As a result, we get an approximate 3 years and 9 months from the date of the proposal of a specific PTLC protocol.

As for P2TR channels, it should be noted thatthat while this is a “only” interaction between two direct peers, they also provide fewer benefits. So I expect this task to be of lower priority. Assuming that most developers will prioritize PTLC over LN, then I expect P2TR channels to start working by the time the basic SIGHASH_ANYPREVOUT or other ways to implement the Decker-Russell-Osuntokun (Eltoo) proposal are available.

Vault with taproot

The author of this part - Antoine poinsot, developer Revault.

The Bitcoin vault (eng.vault, safe) is a type of contract that requires two consecutive transactions to spend money from the wallet. Many such protocols have been proposed (unilateral and multilateral, with or without covenants), so here we focus on what they have in common.

Unlike batching payments,when multiple payments are made in a single on-chain transaction, multiple transactions are used in a vault to make a single payment. First transaction, unvault, pays either:

  1. a set of public keys after a relative timelock (timelock), or
  2. one public key without any timelocks.

The first spending option is the main one, which is expected to be used with hotter keys. The second option for spending allows cancel transaction.

So the vault concept goes somewhatgoes against the taproot's idea that most contracts provide for a "happy path" in which all parties cooperate through a signature (and the challenge path usually contains temporary locks). Rather, the opposite is true. For a transaction spending it is necessary to use a taproot script, since it is limited by the relative timelock [6], while the transaction canceling theoretically it can be performed through key spending.

Since multi-sided vaults in practicealready require a lot of interactivity, in theory they could benefit from the interactive multilateral and threshold signature schemes made possible by the BIP340, such as MuSig2. However, these schemes pose new security challenges. Since vault protocols are primarily intended for use with cold storage, design choices are more conservative here and it is likely that vault will be the last to use these new technologies.

Switching to taproot will also provide a vaultsome privacy and efficiency gains through the use of Merkle branches and shorter BIP340 signatures (especially for multilateral transactions). For example, unvault an exit script in a multilateral setup with 6 "cold" and 3 "active" keys (with a threshold of 2) can be represented as a taproot with a depth of 2 and with leaves:

  • <X> CSV DROP <active key 1> CHECKSIG <active key 2> CHECKSIGADD 2 EQUAL
  • <X> CSV DROP <active key 2> CHECKSIG <active key 3> CHECKSIGADD 2 EQUAL
  • <X> CSV DROP <active key 3> CHECKSIG <active key 1> CHECKSIGADD 2 EQUAL
  • <cold key 1> CHECKSIG <cold key 2> CHECKSIGADD <cold key 3> CHECKSIGADD <cold key 4> CHECKSIGADD <cold key 5> CHECKSIGADD <cold key 6> CHECKSIGADD 6 EQUAL

In taproot, only the leaf used to spend the output needs to be expanded, so the transaction weight is significantly less than for the equivalent P2WSH script:

IF   6 <cold key 1> <cold key 2> <cold key 3> <cold key 4> <cold key 5> <cold key 6> 6 CHECKMULTISIG ELSE   <X> CSV DROP   2 <active key 1> <active key 2> <active key 3> 3 CHECKMULTISIG ENDIF

Although the branch of the payment revocation in case of a successfulspending can be hidden (when using the multisignature threshold, its existence and the number of participants is also hidden), the increase in privacy is minimal, since the vault usage pattern will be easily discernible on-chain.

Finally, vault protocols like mostpre-signed transaction protocols will greatly benefit from further proposed taproot-based upgrades such as BIP118's SIGHASH_ANYPREVOUT. Although requiring additional precautions and tweaking the protocol, ANYPREVOUT and ANYPREVOUTANYSCRIPT will allow you to implement rebindable signatures canceling, which can greatly reduce the required level of interactivity and allow storage with a 0 (1) signature. This is especially interesting for emergency signatures in the Revault protocol, as it will greatly reduce the DoS surface of attacks. With a signature in the output ANYPREVOUTANYSCRIPT, you are actually creating a covenant by constraininghow the transaction of spending these coins can create its outputs. Even more customizable hashes of future signatures will allow for even more flexible constraints.

Security schemes and recovery of access to funds

In this section, we'll look at several other recovery and asset protection schemes that will be positively impacted by switching to taproot.

  • Simple 2-of-3: as mentioned in the previous section,The combination of multisig and scripting costs can easily be used to create a 2-of-3 spend policy that typically has the same on-chain efficiency as single-sig spend and provides much more privacy than current P2SH and P2WSH multisignatures. In non-standard cases, it is still quite efficient and confidential. Therefore taproot is great for enhancing the security of a single signature wallet to a multi-party signature policy. We expect future methods for threshold signatures to further improve handling of 2-of-3 and other k-of-n cases.
  • Degrading a multisignature: one of the exercises in the Optech Taproot Workshopallows you to experiment with creating a taproot script that can be spent any time with three keys, or after three days with two of the original keys, or after ten days with just one of the original keys. (The exercise also uses recovery keys, but we'll cover that separately in the next section.) The ability to customize the time and key parameters provides a flexible and powerful model for disaster recovery of access to funds. For example, imagine that you would normally spend funds using a combination from laptop, mobile phone and separate electronic signature device. In case one of these devices becomes unavailable, a month later it will be possible to dispose of these funds using two devices from the initial list. If two devices become unavailable, then after six months only one of these devices can be used to dispose of funds. Normally, when using all three devices, your on-chain script is as efficient and private as possible. In other cases, it is slightly less efficient, but it can still be quite private (your script and its tree depth will be similar to the parameters used in many other contracts).
  • Social recovery of backups and security schemes: the example above protects perfectly if an attackerwill steal one of your devices, but what if two devices are stolen? Plus, if you use a wallet frequently, are you willing and willing to wait a month after losing your device before you can spend money on it again? Taproot makes it easy, cheap and private to add a social element to your recovery schemes. In addition to the scripts from the previous example, you can also allow immediate spending of your bitcoins on two of your devices plus the signatures of two of your friends or family members. Or spending immediately with just one of your keys and the signatures of five people you trust. (A similar non-“social” version of this setup would be simply to use extra devices or seeds stored in various relatively secure locations.)
  • Combination of temporal and social thresholds for inheritance: by combining the above methods, you canAllow someone or a group of people to recover funds in the event of your sudden death or disability. For example, you can let your lawyer or any three of your five most trusted relatives spend your coins if they haven't moved in six months. If you usually operate your bitcoins anyway for a six-month period, then such an inheritance setup does not require additional on-chain costs while you are alive, and is completely hidden from outside observers. You can even keep your transactions private from your lawyer and family as long as you have a secure way of giving them the extended public key (xpub) from the wallet after you die. Please note that giving your heirs the ability to spend your bitcoins is in itself does not mean that they will be able to do it legally. We encourage anyone planning to inherit their bitcoins to read Pamela Morgan's Cryptoasset Inheritance Planning (physical book and DRM eBook or DRM free eBook) and use this information when discussing details with a local inheritance planning expert.
  • Determination of device compromise: an idea proposed even before the taproot was invented,is to put a key that controls a certain amount of bitcoins on all the devices you are interested in as a way of determining that a device has been compromised. If the amount is large enough, then the attacker is likely to withdraw it immediately, rather than waiting to use their illegal access in a longer-term attack that could cause you more overall damage. The problem with this approach is that you want to do the proposed amount. large enough to lure an attacker into an immediate withdrawal, but it is even more burdensome to allocate a sufficient amount to each of the devices - it would be preferable to allocate the required amount only once. However, if you put the same key on each of the devices, then the consumption of the total bitcoins will not show which of the devices was compromised. Taproot makes it easy to install a separate key on each device with a different scriptpath. Any of these keys will be able to spend funds from one common address, but due to the uniqueness of the key, this will clearly show which of the devices was compromised.

Signet testing

Although up to block 709 632 it is safe to usetaproot is not allowed on the main network, it can be tested even before activation on the testnet or signet testnet. Compared to creating a local test network in the Bitcoin Core test mode, as is done in the Bitcoin Optech tutorial, using testnet or signet makes it easier to test how your service interacts with other people's wallets.

In this section we will get and spend taprootsignet transaction using the built-in Bitcoin Core wallet. You will probably need to adapt these instructions to test ingestion and spending between your wallet and Bitcoin Core.

While it is technically possible to receive and sendtaproot transactions using the built-in Bitcoin Core 22.0 wallet, we recommend using the pull request build of Bitcoin Core # 22364 instead, which makes taproot the default option for descriptor wallets. After building, run signet:

$ bitcoind -signet -daemon

When using signet for the first time, you will needsync her blockchain. Today it includes about 200 MB of data and can be fully synchronized in just a minute. You can track synchronization progress using RPC call getblockchaininfo... After syncing, create a descriptor wallet:

$ bitcoin-cli -signet -named createwallet wallet_name = p4tr descriptors = true load_on_startup = true {   "name": "p4tr",   "warning": "Wallet is an experimental descriptor wallet" }

Now you can create a bech32m address:

$ bitcoin-cli -named -signet getnewaddress address_type = bech32m tb1p6h5fuzmnvpdthf5shf0qqjzwy7wsqc5rhmgq2ks9xrak4ry6mtrscsqvzp

With this address you can request funds fromtap signet. Then you will need to wait for confirmation, which takes about the same amount of time as on the main network (usually up to 30 minutes, but sometimes longer). If you take a look at the transaction, you will see the P2TR script you have created.

$ bitcoin-cli -signet getrawtransaction688f8c792a7b3d9cb46b95bfa5b10fe458617b758fe4100c5a1b9536bedae4cd true | jq .vout [0] {   "value": 0.001,   "n": 0,   "scriptPubKey": {     "asm": "1 d5e89e0b73605abba690ba5e00484e279d006283bed0055a0530fb6a8c9adac7",     "hex": "5120d5e89e0b73605abba690ba5e00484e279d006283bed0055a0530fb6a8c9adac7",     "address": "tb1p6h5fuzmnvpdthf5shf0qqjzwy7wsqc5rhmgq2ks9xrak4ry6mtrscsqvzp",     "type": "witness_v1_taproot"   } }

Then you can create a second bech32m address and send funds to it to check spending.

$ bitcoin-cli -named -signet getnewaddressaddress_type = bech32m tb1p53qvqxja52ge4a7dlcng6qsqggdd85fydxs4f5s3s4ndd2yrn6ns0r6uhx $ bitcoin-cli -named -signet sendtoaddress address = tb1p53qvqxja52ge4a7dlcng6qsqggdd85fydxs4f5s3s4ndd2yrn6ns0r6uhx amount = 0.00099 24083fdac05edc9dbe0bb836272601c8893e705a2b046f97193550a30d880a0c

At this expense, we can look at one ofinputs and see that its witness-field contains nothing but one 64-byte signature. This weighs less vBytes than the witness that would be required to consume P2WPKH or any other old type of script.

$ bitcoin-cli -signet getrawtransaction24083fdac05edc9dbe0bb836272601c8893e705a2b046f97193550a30d880a0c true | jq .vin [0] {   "txid": "bd6dbd2271a95bce8a806288a751a33fc4cf2c336e52a5b98a5ded432229b6f8",   "vout": 0,   "scriptSig": {     "asm": "",     "hex": ""   },   "txinwitness": [     "2a926abbc29fba46e0ba9bca45e1e747486dec748df1e07ee8d887e2532eb48e0b0bff511005eeccfe770c0c1bf880d0d06cb42861212832c5f01f7e6c40c3ce"   ],   "sequence": 4294967294 }

After playing around a bit with these commands, you should be expected to receive and spend funds without any problems using taproot and any of the signet-enabled wallets.

A protocol for signing universal messages is still needed

More than four years since segwit activationback there was no generally accepted way to create signed text messages for bech32 or bech32m addresses. Perhaps this means that widespread adoption of message signing support does not appear to be very important to users or developers, or more work would be devoted to it. However, there is an impression of some regression in bitcoin wallets since the days when everyone used classic standard addresses and could easily exchange signed messages.

Generic signmessage solution failed, notbeing implemented even in Bitcoin Core, despite periodic updates to the documentation of its protocol, BIP322. Regardless, we know of no better alternative and therefore BIP322 should still be considered the preferred choice for any developer looking to add support for universal signed messages to their P2TR wallet.

When implemented, generic signmessagewill allow you to sign messages for P2TR outputs, be it one-way, multilateral, or using any of the tapscript scripts. This will also provide backward compatibility with all legacy and bech32 addresses, as well as compatibility with all types of changes planned for the near future (some of which we will discuss below). Applications with access to the full UTXO set (for example, through a full node) can also use BIP322 to create and verify reserve proofs, providing evidence that the signer is in control of a specific amount of bitcoins at a given point in time.

It should be very easy to implement support for generating universal signed messages. The BIP322 provides a technique called virtual transactions... The first virtual transaction is created asdeliberately invalid through an attempt to spend a non-existent previous transaction (with a txid consisting of zeros). This first transaction is sent to the address (script) that the user wants to sign and contains a hash commit for the desired message. The second transaction spends the output of the first transaction, and if the signatures and other data for this expenditure can be a valid transaction, then the message is considered signed (although the second virtual transaction still cannot be included in the blockchain because it wastes outputs from an invalid previous transaction).

Verifying Universal Signed Messages for many wallets can be significantly more difficult. To be able to fully check any BIP322 message, you need to implementpretty much all of the Bitcoin consensus rules. Most wallets do not, so BIP322 allows them to return an "inconclusive" state when they cannot fully validate the script. In practice, and especially given the incentive in taproot to spend on keypath, this can be rare. Any wallet that implements only a few of the most popular types of scripts will be able to verify signed messages for 99% of all UTXOs.

Support for generic signmessage, genericsigned messages would be a useful addition to Bitcoin. Although we cannot ignore the lack of attention to this topic in the past few years, I would like to note that for wallet developers, support for generic signmessage, even in experimental mode, is an easy way to return users to a feature that they have been deprived of for several years. If you are a developer working on an implementation of BIP322 or related reserve proofs, or perhaps a service manager who finds such features useful, feel free to write at [email protected] to coordinate efforts.

Linking Outputs

After activating taproot, users will startreceive payments on P2TR outputs. Later, they will spend these outputs. In some cases, they will make payments to outputs other than P2TR, but they will still receive change on the new P2TR output.

</p>

An expert or algorithm observing suchtransaction, it is easy to make a reasonable conclusion that the P2TR output in it is the change output belonging to the user himself, which means that the other output belongs to the payee. This is not guaranteed to be the case, but is the most likely explanation.

Some argue that many of the benefitsThe privacy taproot should not be taken lightly yet due to this likely temporary decline in privacy during the transition to P2TR wallets. Many experts called this conclusion unjustified and excessive. We join the opinion of the latter and can also offer several additional counterarguments against criticism in this direction:

  • Other metadata: transactions can contain other metadata,showing which outputs are intended for receiving change, and which are payment. One of the most worrisome factors today is the percentage of address reuse, which significantly reduces the level of privacy for both the sender and the recipient of such transactions. And since this problem has persisted for quite some time, it seems unreasonable not to support wallets and services for significant privacy improvements and best available practices.
  • Mapping script outputs: built-in Bitcoin Core wallet by defaultuses a segwit output for change if any of the payment outputs is also a segwit. Otherwise, it uses the default change address type. For example, when paying on a P2PKH outlet, the P2PKH outlet can be used for change; P2WPKH output always uses P2WPKH change output. Once taproot is activated, Bitcoin Core will opportunistically use P2TR outputs for change if one of the spending outputs of this transaction is P2TR. This can minimize any increase in the ability to identify transition gates.
  • Updates request: with P2TR we have, regardless of the requirements forsecurity, for the first time in the history of Bitcoin, it became possible for everyone to use one type of exit scripts, as well as often use indistinguishable transaction inputs, which significantly increases the level of privacy. If you want to see a significant increase in Bitcoin's privacy sooner, you can ask the users and services you are paying to support taproot (and stop reusing addresses, if applicable). If both you and the recipients of your payments upgrade, it will be more difficult to determine the change outlets, plus we will get all the other great benefits of taproot in the area of ​​transaction privacy.

Is the collaboration option always needed?

Gregory Maxwell's original taproot proposal included an interesting contract-building principle:

“It almost always happens that interesting scriptshave a top-level logical branch that allows contract execution only with signatures from all parties. Other branches will only be used in cases where a member opts out of interaction. Strictly speaking, I believe that any a contract with a fixed and finite set of participants can and should be represented as an OR between N-of-N and any more complex contract you may wish to represent. "

Since then, experts have discussed the universality of this principle, with two possible exceptions known to us related to time blocks:

  • User self-control by means of network consensus: some people used temporary locks,timelocks to avoid spending your own bitcoins for a certain amount of time. The temporary blocking requirement appears to imply that more than one signature is required, however several criticisms have been voiced:
    • Someone who is seriously desperate to spend their locked bitcoins may take out a loan - perhaps secured by some other asset - which undermines the usefulness of such a contract with oneself.
    • In addition to the timelock along the script path(scriptpath), the user can allow the keypath to be spent between his own key and the key of a third party, which provides the signature only after the temporary lock expires. This is not only more efficient, but also allows for more flexible policies, such as allowing the user to sell any forkcoins they receive or interact with a third party that will allow them to spend the coins before their deadline in the event of major life changes or price increases.
  • Vaults: as Antoine Poinsot wrote above, vaults alsoTemporal locks are widely used to protect funds, which seems to "go against the taproot's idea that most contracts provide for a 'happy path' in which all participants collaborate through a signature." Others have argued that there is no scenario in which the vault user would not want to be able to escape the terms of such a contract by spending the keypath, and that since it costs nothing to add the appropriate parameter to the contract, it would be strictly better to enable such an option.

The argument against always providingthe keypath expense option seems to be that there are cases in which even all co-signers do not fully trust themselves. However, they are willing to trust other people - the economic full node operators who enforce Bitcoin's consensus rules - to enforce spending limits instead of the signers themselves.

The counter-argument is that at leastin theory, you can provide the same level of security by creating a keypath flow between regular signers and all these economic full node operators. As a practical matter, there is probably a subset or alternative set of these node operators that can be added to the multisig set for your key expense and which will enforce the desired policy if available (if not, you have nothing to lose, since you can still use the scriptpath flow).

Theory is theory, but for developers we recommendspend some extra time considering adding keypath flow to taproot-based contracts, even if you don't initially think it is necessary.

Future changes in consensus

While taproot nears activation on the block709 632, we can already start looking forward to some of the consensus changes that the developers have already mentioned about the desire to implement "on top" of the taproot.

  • Aggregation of signatures for different inputs: Schnorr schemes allow owners of multiple pairspublic and private keys create a single signature, confirming that the holders of all those keys acted together to create this signature. With a future consensus change, this could allow a transaction to contain a single signature confirming that the holders of all UTXOs spent in that transaction have authorized the spending. This will save about 16 vB per keypath after the first login, providing significant savings for consolidated and coinjoin transactions. This can make spending through coinjoin cheaper than conventional single transactions, creating a mild incentive for more private practices.
  • SIGHASH_ANYPREVOUT: each regular Bitcoin transaction includes oneor multiple inputs, and each of these inputs refers to the output of the previous transaction through its txid. Such links tell full verifying nodes - like Bitcoin Core - how much money can be spent in this transaction and what conditions must be met in order to confirm that the spending has been authorized. All methods of generating signatures for Bitcoin transactions, both with and without a taproot, either bind to the txid of previous outputs, or not bind to previous outputs at all. This is a problem for multi-user protocols that do not want to use an exact predefined series of transactions. If any user can skip a certain transaction or change any details of any transaction other than its witness data, this will change the txid of any subsequent transaction. Changing the txid invalidates all signatures previously generated for subsequent transactions. This forces off-chain protocols to implement mechanisms (such as the LN penalty) to penalize any user submitting an older transaction. SIGHASH_ANYPREVOUT can fix this problem by allowing the signature to skip binding to the txid of the previous output. Depending on the other flags used, it will still refer to other data about the previous exit and transaction (such as the amount and script), but which txid was used for the previous transaction will no longer matter. This will allow for the implementation of the eltoo layer for the Lightning Network, and some improvements in the vaults protocols and other contracts.
  • Delegation and generalization: after creating a script (taproot or someotherwise) you have almost no opportunity to delegate to additional people the right to spend funds from this script, except for transferring your private key to them, which can be very dangerous when using BIP32 wallets. In addition, taproot can be made more accessible for users who want to use keypath costs plus very few script-based conditions. Several methods have been proposed to improve and develop taproot:
    • Graftroot: proposed shortly after the idea was postedtaproot, graftroot provides additional functionality to anyone who can taproot the keypath. Instead of spending funds directly, keypath senders could instead sign a script describing the new spending conditions, delegating the right to spend them to anyone who can fulfill the requirements of the script. The signature, script, and any other data required to satisfy the requirements of the script will be provided in the expense transaction. Thus, keypath signers can delegate an unlimited number of scripts without generating any on-chain data until actual consumption occurs.
    • Generalized taproot (g'root): a few months later, Anthony Towns suggesteda way to use public key points to fulfill several different spending conditions without the need for a MAST-like construct. Design generalized taproot (g'root) "potentially more effective forcases where the basic taproot assumption is not met. " It also "offers an easy way to build a soft fork-safe cross-entry aggregation system."
    • Entroot: later synthesis of graftroot and g'root,simplifying many scenarios and making them more bandwidth efficient. It can support delegation of signatures from anyone who can satisfy the requirements of any of the entroot branches, not just those who can create an expense on the top-level keypath.
  • New and old opcodes: the taproot soft fork includes tapscript support, which provides an improved way of adding new opcodes to Bitcoin, opcodes OP_SUCCESSx... Like OP_NOPx (no operation) added early in the history of Bitcoin, OP_SUCCESSx are intended to be replaced with opcodes that do not always return success. Some proposed new opcodes include:
    • Restoring old opcodes: a number of opcodes for math and stringsoperations was shut down in 2010 out of concerns about potential vulnerabilities. Many developers would like to return support for these opcodes after security checks and (in some cases) possibly extend them to handle larger numbers.
    • OP_CAT: one of the previously disabled opcodes,deserves special mention. As researchers have since discovered, OP_CAT itself opens up opportunities for a wide variety of interesting actions in Bitcoin, but it can also be combined with other new opcodes.
    • OP_TAPLEAF_UPDATE_VERIFY: Anthony Townes' proposed opcode OP_TLUVas stated in the Bitcoin Optech mailing list,allows you to create covenants and is especially effective and useful when used with the keypath and scriptpath capabilities of taproot. It can be used to implement joinpools, vaults, and other security and privacy enhancements. It can also pair well with OP_CHECKTEMPLATEVERIFY.

All these ideas for today are only onstage of the proposal. None of them are guaranteed to be successful. Researchers and developers must first bring each proposal to a sufficiently mature state, then users will determine if adding each of these features is worth the effort of changing Bitcoin's consensus rules.

What happens upon activation?

The taproot should be activated as early as Sunday November 14th, at block 709 632. We know what's going to happen and we also know about several possible failure scenarios.

The best and most likely option is that allgoes well. Ordinary users shouldn't be able to see what is happening at all. Only those who closely monitor their nodes or are trying to create taproot transactions are likely to notice the change. At block 709 631, virtually all full nodes we know of will apply the same consensus rules. On the next block, nodes with a client Bitcoin Core 0.21.1, 22.0, or related versions will begin to apply additional taproot rules that are not provided for in earlier versions of the software.

This carries the risk that earlier andlater versions of software clients will accept different blocks as valid. This happened with the activation of the BIP66 soft fork in 2015, which led to a blockchain split over 6 blocks and several shorter splits. Significant engineering efforts have been made to prevent a recurrence of this scenario. With a taproot, something like this can only happen if the miner deliberately mines a block that is not valid for the taproot, or if he has disabled security measures hard-coded in Bitcoin Core or other client software of Bitcoin nodes.

In particular, to create a blockchain split,the miner will need to create or accept a transaction spending bitcoins from the taproot (segwit v1) exit without following the taproot rules. If the miner does this, he will lose at least 6.25 BTC (over $ 400K as of Thursday 11 November) if the economic consensus of the Bitcoin node operators rejects the invalid taproot blocks.

Until the incorrect block appears, we cannotsay for sure how these node operators will behave - nodes can function completely private - but indirect indicators indicate that more than 50% of node operators use versions of Bitcoin Core with taproot support. This seems to be more than enough to ensure that any block that is not valid according to the taproot will be rejected by the network.

Although very unlikely, a short-term blockchain split is theoretically possible. It should be possible to track this in services such as ForkMonitor.info or using a PRC call getchaintips to Bitcoin Core.If this happens, light clients can get false confirmations. Although in theory the number of such confirmations can reach six, as was the case when the blockchain was split in 2015, this would mean that miners lost almost $ 2.5 million on this (compared to ~ $ 50 thousand in 2015). We can hope that with such a strong financial incentive, miners will indeed enforce the taproot rules they had signaled they were ready for six months earlier.

In almost any case of temporary failure,As we can imagine, a simple but effective response would be to increase the transaction confirmation limit. If you usually wait 6 confirmations before accepting a payment, this threshold can be temporarily increased to 30 - for several hours until the problem is resolved or it becomes clear that an even higher limit of confirmations is required.

For users and services that are completelyare convinced that the economic consensus of full node operators will enforce the taproot rules, an even simpler solution will be to receive data only on those transactions that have been confirmed in Bitcoin Core version 0.21.1 and higher (or a compatible alternative implementation of the node).

Bitcoin Optech and BitNovosti expecttaproot activation will go smoothly, but we urge exchanges and anyone else who will be accepting significant amounts around block 709 632 to either upgrade their node or be prepared to temporarily raise the limit on confirmations at the first sign of a problem.

Notes

1.When Electrum upgraded to segwit v0, the developers required everyone who wanted to get bech32 addresses to generate new seed phrases. While not technically required, it allowed the Electrum authors to implement a few new features into their custom seed method. One of these functions was the ability to use the seed version number to determine which scripts it should be used with. This allows you to safely drop support for outdated scripts (for example, in the future, there may be a version of Electrum that no longer supports receiving transactions to legacy P2PKH addresses).

Around the same time the developersWith Electrum deploying seed versioning, Bitcoin Core developers began using exit script descriptors - including to address the same issue: to safely remove support for legacy scripts. The table below compares the versioned Electrum seed and Bitcoin Core descriptors with the method undefined scripts (implicit scripts) previously used by both wallets and still widely used in most other wallets today.

Script management Initial backup Introducing new scripts Scanning (bandwidth / CPU cost) Obsolete scripts
Undefined scripts (e.g. BIP44) Seed phrase Automatically (no user action required) It is necessary to iterate over the list of all supported scripts O (n) There is no way to warn users that they are using unsupported scripts
Certain scripts (versioned seed) Seed phrase (includes version bits) The user must create a new seed; funds are either split into two separate wallets, or the user has to transfer them from the old wallet to the new one Only one script template needs to be checked, O (1) Users are warned about unsupported scripts
Certain scripts (descriptors) Seed phrase and descriptor User must save new descriptor Only really used script templates need to be checked, O (n); for a new wallet n = 1 Users are warned about unsupported scripts

2.Users who want to receive a P2TR payment in the first taproot block need to generate an address that they will not share with anyone, and then create a transaction to that address with nLockTime set to 709 631. This transaction can be transferred to the network, as soon as block 709 631 is received. The nLockTime option ensures that the transaction is not included in any block until 709 632, from which the taproot rules take effect. Exercising with new script types and custom block times can be risky if you don't know exactly what you are doing, so please be careful. ↩

3. Senders can randomize payment routes and create very convoluted payment paths in an attempt to obfuscate the HTLC correlation analysis, but this has its drawbacks:

      • Twisty payment paths are more expensive and less reliable (more nodes need to be paid and more nodes must successfully redirect the payment to reach its destination).
      • The tortuous payment paths are longer, which means the sender is reporting the payment more the number of nodes, increasing the likelihood that the observing node will be among them. So winding payment paths aren't necessarily the best way to boost your privacy.

4.When talking about unpublished channels, remember that it takes two to tango, and if the unpublished channel is closed, then one participant (say, an LN service provider) uses the remaining funds to published channel, then the blockchain explorer can assume that the source of these funds, with some probability, was a closed unpublished channel. ↩

5.Yes, details are important, but also not particularly: from a sufficiently high viewing angle, unexpected difficulties with some aspects of development and their unexpected absence with other aspects more or less balance each other, and as a result, each new function is released approximately within some average time frame. If we want to give accurate estimate, and not rough and optimistic, then should use methods to avoid planning errors. Therefore, it makes sense to take as a basis the previous similar implemented function and deliberately ignore some small details, looking only at how long it took to implement this feature. ↩

6. If known in advance, you can pre-sign the transaction expense with a specific nSequence, but then you don'tan alternative way of spending with "active" keys is needed. In addition, usually at the moment of receiving the coins, the user does not know exactly how he is going to spend them. ↩

</p>
Facebook Notice for EU! You need to login to view and post FB Comments!