diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000000..732da86f7a
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1 @@
+*.mediawiki linguist-detectable
diff --git a/.github/workflows/github-action-checks.yml b/.github/workflows/github-action-checks.yml
new file mode 100644
index 0000000000..ad76317f96
--- /dev/null
+++ b/.github/workflows/github-action-checks.yml
@@ -0,0 +1,31 @@
+name: GitHub Actions Check
+run-name: ${{ github.actor }} Checks 🚀
+on: [push, pull_request]
+jobs:
+ Link-Format-Checks:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - run: scripts/link-format-chk.sh
+ Build-Table-Checks:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - run: scripts/buildtable.pl >/tmp/table.mediawiki || exit 1
+ Diff-Checks:
+ name: "Diff Checks (fails until number assignment)"
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ fetch-depth: 2
+ - run: scripts/diffcheck.sh
+ Typo-Checks:
+ name: "Typo Checks"
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout Actions Repository
+ uses: actions/checkout@v4
+
+ - name: Check spelling
+ uses: crate-ci/typos@master
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000000..d939d2a572
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,6 @@
+bip-0174/coinjoin-workflow.aux
+bip-0174/coinjoin-workflow.log
+bip-0174/coinjoin-workflow.pdf
+bip-0174/multisig-workflow.aux
+bip-0174/multisig-workflow.log
+bip-0174/multisig-workflow.pdf
diff --git a/.typos.toml b/.typos.toml
new file mode 100644
index 0000000000..15d831fa1e
--- /dev/null
+++ b/.typos.toml
@@ -0,0 +1,44 @@
+[default]
+extend-ignore-re = [
+ # NOTE: use here for regex patterns
+ "xpub.*",
+ "xprv.*",
+ "3.*", # address
+ "5.*", # address
+ "private_key .*",
+ "privkey .*",
+ "tt.*", # tags
+ "code.*", # tags
+ "\\w*", # prefix for tags
+ "OP_SUCCESSx|\\d+",
+ "pay.*",
+ "ser.*",
+ "prefix.*",
+ "value: .*",
+]
+
+[default.extend-words]
+# NOTE: use here for false-positives
+anc = "anc"
+PSBT = "PSBT"
+ser = "ser"
+# Names
+Atack = "Atack"
+Meni = "Meni"
+Ono = "Ono"
+
+[files]
+extend-exclude = [
+ "/*/*.csv",
+ "/*.d*",
+ "/*/*.d*",
+ "/*/*.go",
+ "/*/*.json",
+ "/*/*/*.json",
+ "/*/*.mod",
+ "/*/*.proto",
+ "/*/*.py",
+ "scripts",
+ "/*/*.s*",
+ "/*/*.t*",
+]
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000000..df6d947a5a
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,12 @@
+# Contributing Guidelines
+
+Apart from following [BIP 2](./bip-0002.mediawiki),
+we do CI checks to ensure that the proposed BIPs do not have common typos.
+These checks are done using [`typos`](https://github.com/crate-ci/typos).
+To check for typos locally,
+install [`typos`](https://github.com/crate-ci/typos)
+and then run in the root directory:
+
+```bash
+typos
+```
diff --git a/README.mediawiki b/README.mediawiki
index 7fb4174410..7950e107d8 100644
--- a/README.mediawiki
+++ b/README.mediawiki
@@ -1,383 +1,1292 @@
-People wishing to submit BIPs, first should propose their idea or document to the mailing list. After discussion they should email Greg Maxwell <gmaxwell@gmail.com>. After copy-editing and acceptance, it will be published here.
+People wishing to submit BIPs, first should propose their idea or document to the [https://groups.google.com/g/bitcoindev bitcoindev@googlegroups.com] mailing list (do not assign a number - read BIP 2 for the full process). After discussion, please open a PR. After copy-editing and acceptance, it will be published here.
We are fairly liberal with approving BIPs, and try not to be too involved in decision making on behalf of the community. The exception is in very rare cases of dispute resolution when a decision is contentious and cannot be agreed upon. In those cases, the conservative option will always be preferred.
-Having a BIP here does not make it a formally accepted standard until its status becomes Active. For a BIP to become Active requires the mutual consent of the community.
+Having a BIP here does not make it a formally accepted standard until its status becomes Final or Active.
Those proposing changes should consider that ultimately consent may rest with the consensus of the Bitcoin users (see also: [https://en.bitcoin.it/wiki/Economic_majority economic majority]).
{| class="wikitable sortable" style="width: auto; text-align: center; font-size: smaller; table-layout: fixed;"
!Number
+!Layer
!Title
!Owner
!Type
!Status
-|- style="background-color: #cfffcf"
+|- style="background-color: #ffcfcf"
| [[bip-0001.mediawiki|1]]
+|
| BIP Purpose and Guidelines
| Amir Taaki
-| Standard
+| Process
+| Replaced
+|- style="background-color: #cfffcf"
+| [[bip-0002.mediawiki|2]]
+|
+| BIP process, revised
+| Luke Dashjr
+| Process
| Active
|-
+| [[bip-0008.mediawiki|8]]
+|
+| Version bits with lock-in by height
+| Shaolin Fry, Luke Dashjr
+| Informational
+| Draft
+|- style="background-color: #cfffcf"
| [[bip-0009.mediawiki|9]]
+|
| Version bits with timeout and delay
| Pieter Wuille, Peter Todd, Greg Maxwell, Rusty Russell
| Informational
-| Draft
-|-
+| Final
+|- style="background-color: #ffcfcf"
| [[bip-0010.mediawiki|10]]
+| Applications
| Multi-Sig Transaction Distribution
| Alan Reiner
| Informational
| Withdrawn
|- style="background-color: #cfffcf"
| [[bip-0011.mediawiki|11]]
+| Applications
| M-of-N Standard Transactions
| Gavin Andresen
| Standard
-| Accepted
+| Final
|- style="background-color: #ffcfcf"
| [[bip-0012.mediawiki|12]]
+| Consensus (soft fork)
| OP_EVAL
| Gavin Andresen
| Standard
| Withdrawn
|- style="background-color: #cfffcf"
| [[bip-0013.mediawiki|13]]
+| Applications
| Address Format for pay-to-script-hash
| Gavin Andresen
| Standard
| Final
|- style="background-color: #cfffcf"
| [[bip-0014.mediawiki|14]]
+| Peer Services
| Protocol Version and User Agent
| Amir Taaki, Patrick Strateman
| Standard
-| Accepted
-|- style="background-color: #ffcfcf"
+| Final
+|-
| [[bip-0015.mediawiki|15]]
+| Applications
| Aliases
| Amir Taaki
| Standard
| Deferred
|- style="background-color: #cfffcf"
| [[bip-0016.mediawiki|16]]
-| Pay To Script Hash
+| Consensus (soft fork)
+| Pay to Script Hash
| Gavin Andresen
| Standard
| Final
|- style="background-color: #ffcfcf"
| [[bip-0017.mediawiki|17]]
+| Consensus (soft fork)
| OP_CHECKHASHVERIFY (CHV)
| Luke Dashjr
| Standard
| Withdrawn
-|-
+|- style="background-color: #ffffcf"
| [[bip-0018.mediawiki|18]]
+| Consensus (soft fork)
| hashScriptCheck
| Luke Dashjr
| Standard
-| Draft
-|-
+| Proposed
+|- style="background-color: #ffcfcf"
| [[bip-0019.mediawiki|19]]
+| Applications
| M-of-N Standard Transactions (Low SigOp)
| Luke Dashjr
| Standard
-| Draft
+| Rejected
|- style="background-color: #ffcfcf"
| [[bip-0020.mediawiki|20]]
+| Applications
| URI Scheme
| Luke Dashjr
| Standard
| Replaced
|- style="background-color: #cfffcf"
| [[bip-0021.mediawiki|21]]
+| Applications
| URI Scheme
| Nils Schneider, Matt Corallo
| Standard
-| Accepted
+| Final
|- style="background-color: #cfffcf"
| [[bip-0022.mediawiki|22]]
+| API/RPC
| getblocktemplate - Fundamentals
| Luke Dashjr
| Standard
-| Accepted
+| Final
|- style="background-color: #cfffcf"
| [[bip-0023.mediawiki|23]]
+| API/RPC
| getblocktemplate - Pooled Mining
| Luke Dashjr
| Standard
-| Accepted
+| Final
|- style="background-color: #cfffcf"
| [[bip-0030.mediawiki|30]]
+| Consensus (soft fork)
| Duplicate transactions
| Pieter Wuille
| Standard
| Final
|- style="background-color: #cfffcf"
| [[bip-0031.mediawiki|31]]
+| Peer Services
| Pong message
| Mike Hearn
| Standard
-| Accepted
+| Final
|- style="background-color: #cfffcf"
| [[bip-0032.mediawiki|32]]
+| Applications
| Hierarchical Deterministic Wallets
| Pieter Wuille
| Informational
-| Accepted
-|-
+| Final
+|- style="background-color: #ffcfcf"
| [[bip-0033.mediawiki|33]]
+| Peer Services
| Stratized Nodes
| Amir Taaki
| Standard
-| Draft
+| Rejected
|- style="background-color: #cfffcf"
| [[bip-0034.mediawiki|34]]
-| Block v2, Height in coinbase
+| Consensus (soft fork)
+| Block v2, Height in Coinbase
| Gavin Andresen
| Standard
-| Accepted
+| Final
|- style="background-color: #cfffcf"
| [[bip-0035.mediawiki|35]]
+| Peer Services
| mempool message
| Jeff Garzik
| Standard
-| Accepted
-|-
+| Final
+|- style="background-color: #ffcfcf"
| [[bip-0036.mediawiki|36]]
+| Peer Services
| Custom Services
| Stefan Thomas
| Standard
-| Draft
+| Rejected
|- style="background-color: #cfffcf"
| [[bip-0037.mediawiki|37]]
-| Bloom filtering
-| Mike Hearn and Matt Corallo
+| Peer Services
+| Connection Bloom filtering
+| Mike Hearn, Matt Corallo
| Standard
-| Accepted
+| Final
|-
| [[bip-0038.mediawiki|38]]
+| Applications
| Passphrase-protected private key
-| Mike Caldwell
+| Mike Caldwell, Aaron Voisine
| Standard
| Draft
-|-
+|- style="background-color: #cfffcf"
| [[bip-0039.mediawiki|39]]
+| Applications
| Mnemonic code for generating deterministic keys
-| Slush
+| Marek Palatinus, Pavol Rusnak, Aaron Voisine, Sean Bowe
| Standard
-| Draft
+| Final
|-
| 40
+| API/RPC
| Stratum wire protocol
-| Slush
+| Marek Palatinus
| Standard
| BIP number allocated
|-
| 41
+| API/RPC
| Stratum mining protocol
-| Slush
+| Marek Palatinus
| Standard
| BIP number allocated
-|-
+|- style="background-color: #cfffcf"
| [[bip-0042.mediawiki|42]]
+| Consensus (soft fork)
| A finite monetary supply for Bitcoin
| Pieter Wuille
| Standard
-| Draft
-|-
+| Final
+|- style="background-color: #cfffcf"
| [[bip-0043.mediawiki|43]]
+| Applications
| Purpose Field for Deterministic Wallets
-| Slush
+| Marek Palatinus, Pavol Rusnak
| Standard
-| Draft
-|-
+| Final
+|- style="background-color: #cfffcf"
| [[bip-0044.mediawiki|44]]
+| Applications
| Multi-Account Hierarchy for Deterministic Wallets
-| Slush
+| Marek Palatinus, Pavol Rusnak
| Standard
-| Draft
-|-
+| Final
+|- style="background-color: #ffffcf"
| [[bip-0045.mediawiki|45]]
+| Applications
| Structure for Deterministic P2SH Multisignature Wallets
-| Manuel Araoz
+| Manuel Araoz, Ryan X. Charles, Matias Alejo Garcia
| Standard
-| Draft
+| Proposed
|-
+| [[bip-0046.mediawiki|46]]
+| Applications
+| Address Scheme for Timelocked Fidelity Bonds
+| Chris Belcher, Thebora Kompanioni
+| Standard
+| Draft
+|- style="background-color: #cfffcf"
| [[bip-0047.mediawiki|47]]
+| Applications
| Reusable Payment Codes for Hierarchical Deterministic Wallets
| Justus Ranvier
| Informational
-| Draft
-|-
+| Final
+|- style="background-color: #ffffcf"
+| [[bip-0048.mediawiki|48]]
+| Applications
+| Multi-Script Hierarchy for Multi-Sig Wallets
+| Fontaine
+| Standard
+| Proposed
+|- style="background-color: #cfffcf"
+| [[bip-0049.mediawiki|49]]
+| Applications
+| Derivation scheme for P2WPKH-nested-in-P2SH based accounts
+| Daniel Weigl
+| Standard
+| Final
+|- style="background-color: #cfffcf"
| [[bip-0050.mediawiki|50]]
+|
| March 2013 Chain Fork Post-Mortem
| Gavin Andresen
| Informational
+| Final
+|-
+| [[bip-0052.mediawiki|52]]
+| Consensus (hard fork)
+| Durable, Low Energy Bitcoin PoW
+| Michael Dubrovsky, Bogdan Penkovsky
+| Standard
| Draft
|-
| [[bip-0060.mediawiki|60]]
+| Peer Services
| Fixed Length "version" Message (Relay-Transactions Field)
| Amir Taaki
| Standard
| Draft
-|-
+|- style="background-color: #cfffcf"
| [[bip-0061.mediawiki|61]]
-| "reject" P2P message
+| Peer Services
+| Reject P2P message
| Gavin Andresen
| Standard
| Final
-|-
+|- style="background-color: #ffcfcf"
| [[bip-0062.mediawiki|62]]
+| Consensus (soft fork)
| Dealing with malleability
| Pieter Wuille
| Standard
| Withdrawn
|-
| 63
+| Applications
| Stealth Addresses
| Peter Todd
| Standard
| BIP number allocated
-|-
+|- style="background-color: #ffcfcf"
| [[bip-0064.mediawiki|64]]
-| getutxos message
+| Peer Services
+| getutxo message
| Mike Hearn
| Standard
-| Draft
-|-
+| Obsolete
+|- style="background-color: #cfffcf"
| [[bip-0065.mediawiki|65]]
+| Consensus (soft fork)
| OP_CHECKLOCKTIMEVERIFY
| Peter Todd
| Standard
-| Draft
-|-
+| Final
+|- style="background-color: #cfffcf"
| [[bip-0066.mediawiki|66]]
+| Consensus (soft fork)
| Strict DER signatures
| Pieter Wuille
| Standard
-| Draft
-|-
+| Final
+|- style="background-color: #ffffcf"
| [[bip-0067.mediawiki|67]]
-| Deterministic P2SH multi-signature addresses
-| Thomas Kerin
+| Applications
+| Deterministic Pay-to-script-hash multi-signature addresses through public key sorting
+| Thomas Kerin, Jean-Pierre Rupp, Ruben de Vries
| Standard
-| Draft
-|-
+| Proposed
+|- style="background-color: #cfffcf"
| [[bip-0068.mediawiki|68]]
-| Relative lock-time through consensus-enforced sequence numbers
-| Mark Friedenbach, BtcDrak and Nicolas Dorier
+| Consensus (soft fork)
+| Relative lock-time using consensus-enforced sequence numbers
+| Mark Friedenbach, BtcDrak, Nicolas Dorier, kinoshitajona
| Standard
-| Draft
-|-
+| Final
+|- style="background-color: #ffffcf"
| [[bip-0069.mediawiki|69]]
+| Applications
| Lexicographical Indexing of Transaction Inputs and Outputs
| Kristov Atlas
-| Standard
-| Draft
-|-
+| Informational
+| Proposed
+|- style="background-color: #cfffcf"
| [[bip-0070.mediawiki|70]]
-| Payment protocol
-| Gavin Andresen
+| Applications
+| Payment Protocol
+| Gavin Andresen, Mike Hearn
| Standard
| Final
-|-
+|- style="background-color: #cfffcf"
| [[bip-0071.mediawiki|71]]
-| Payment protocol MIME types
+| Applications
+| Payment Protocol MIME types
| Gavin Andresen
| Standard
| Final
-|-
+|- style="background-color: #cfffcf"
| [[bip-0072.mediawiki|72]]
-| Payment protocol URIs
+| Applications
+| bitcoin: uri extensions for Payment Protocol
| Gavin Andresen
| Standard
| Final
-|-
+|- style="background-color: #cfffcf"
| [[bip-0073.mediawiki|73]]
-| Use "Accept" header with Payment Request URLs
+| Applications
+| Use "Accept" header for response type negotiation with Payment Request URLs
| Stephen Pair
| Standard
+| Final
+|- style="background-color: #ffcfcf"
+| [[bip-0074.mediawiki|74]]
+| Applications
+| Allow zero value OP_RETURN in Payment Protocol
+| Toby Padilla
+| Standard
+| Rejected
+|- style="background-color: #cfffcf"
+| [[bip-0075.mediawiki|75]]
+| Applications
+| Out of Band Address Exchange using Payment Protocol Encryption
+| Justin Newton, Matt David, Aaron Voisine, James MacWhyte
+| Standard
+| Final
+|-
+| [[bip-0078.mediawiki|78]]
+| Applications
+| A Simple Payjoin Proposal
+| Nicolas Dorier
+| Standard
| Draft
+|- style="background-color: #ffcfcf"
+| [[bip-0079.mediawiki|79]]
+| Applications
+| Bustapay :: a practical coinjoin protocol
+| Ryan Havar
+| Informational
+| Replaced
|-
-| [[bip-0099.mediawiki|99]]
-| Motivation and deployment of consensus rule changes
-| Jorge Timón
-| Informational | Process
+| [[bip-0080.mediawiki|80]]
+|
+| Hierarchy for Non-Colored Voting Pool Deterministic Multisig Wallets
+| Justus Ranvier, Jimmy Song
+| Informational
+| Deferred
+|-
+| [[bip-0081.mediawiki|81]]
+|
+| Hierarchy for Colored Voting Pool Deterministic Multisig Wallets
+| Justus Ranvier, Jimmy Song
+| Informational
+| Deferred
+|- style="background-color: #ffcfcf"
+| [[bip-0083.mediawiki|83]]
+| Applications
+| Dynamic Hierarchical Deterministic Key Trees
+| Eric Lombrozo
+| Standard
+| Rejected
+|- style="background-color: #cfffcf"
+| [[bip-0084.mediawiki|84]]
+| Applications
+| Derivation scheme for P2WPKH based accounts
+| Pavol Rusnak
+| Standard
+| Final
+|- style="background-color: #cfffcf"
+| [[bip-0085.mediawiki|85]]
+| Applications
+| Deterministic Entropy From BIP32 Keychains
+| Ethan Kosakovsky, Aneesh Karve
+| Informational
+| Final
+|- style="background-color: #cfffcf"
+| [[bip-0086.mediawiki|86]]
+| Applications
+| Key Derivation for Single Key P2TR Outputs
+| Ava Chow
+| Standard
+| Final
+|- style="background-color: #ffffcf"
+| [[bip-0087.mediawiki|87]]
+| Applications
+| Hierarchy for Deterministic Multisig Wallets
+| Robert Spigler
+| Standard
+| Proposed
+|- style="background-color: #ffffcf"
+| [[bip-0088.mediawiki|88]]
+| Applications
+| Hierarchical Deterministic Path Templates
+| Dmitry Petukhov
+| Informational
+| Proposed
+|- style="background-color: #cfffcf"
+| [[bip-0090.mediawiki|90]]
+|
+| Buried Deployments
+| Suhas Daftuar
+| Informational
+| Final
+|- style="background-color: #cfffcf"
+| [[bip-0091.mediawiki|91]]
+| Consensus (soft fork)
+| Reduced threshold Segwit MASF
+| James Hilliard
+| Standard
+| Final
+|-
+| [[bip-0093.mediawiki|93]]
+| Applications
+| codex32: Checksummed SSSS-aware BIP32 seeds
+| Leon Olsson Curr, Pearlwort Sneed, Andrew Poelstra
+| Informational
+| Draft
+|-
+| [[bip-0094.mediawiki|94]]
+| Applications
+| Testnet 4
+| Fabian Jahr
+| Standard
| Draft
|-
+| [[bip-0098.mediawiki|98]]
+| Consensus (soft fork)
+| Fast Merkle Trees
+| Mark Friedenbach, Kalle Alm, BtcDrak
+| Standard
+| Draft
+|- style="background-color: #ffcfcf"
+| [[bip-0099.mediawiki|99]]
+|
+| Motivation and deployment of consensus rule changes ([soft/hard]forks)
+| Jorge Timón
+| Informational
+| Rejected
+|- style="background-color: #ffcfcf"
+| [[bip-0100.mediawiki|100]]
+| Consensus (hard fork)
+| Dynamic maximum block size by miner vote
+| Jeff Garzik, Tom Harding, Dagur Valberg Johannsson
+| Standard
+| Rejected
+|- style="background-color: #ffcfcf"
| [[bip-0101.mediawiki|101]]
+| Consensus (hard fork)
| Increase maximum block size
| Gavin Andresen
| Standard
-| Draft
-|-
+| Withdrawn
+|- style="background-color: #ffcfcf"
| [[bip-0102.mediawiki|102]]
+| Consensus (hard fork)
| Block size increase to 2MB
| Jeff Garzik
| Standard
-| Draft
-|-
+| Rejected
+|- style="background-color: #ffcfcf"
| [[bip-0103.mediawiki|103]]
+| Consensus (hard fork)
| Block size following technological growth
| Pieter Wuille
| Standard
-| Draft
-|-
+| Withdrawn
+|- style="background-color: #ffcfcf"
+| [[bip-0104.mediawiki|104]]
+| Consensus (hard fork)
+| 'Block75' - Max block size like difficulty
+| t.khan
+| Standard
+| Rejected
+|- style="background-color: #ffcfcf"
| [[bip-0105.mediawiki|105]]
+| Consensus (hard fork)
| Consensus based block size retargeting algorithm
| BtcDrak
| Standard
-| Draft
-|-
+| Rejected
+|- style="background-color: #ffcfcf"
| [[bip-0106.mediawiki|106]]
+| Consensus (hard fork)
| Dynamically Controlled Bitcoin Block Size Max Cap
| Upal Chakraborty
| Standard
-| Draft
-|-
+| Rejected
+|- style="background-color: #ffcfcf"
+| [[bip-0107.mediawiki|107]]
+| Consensus (hard fork)
+| Dynamic limit on the block size
+| Washington Y. Sanchez
+| Standard
+| Rejected
+|- style="background-color: #ffcfcf"
+| [[bip-0109.mediawiki|109]]
+| Consensus (hard fork)
+| Two million byte size limit with sigop and sighash limits
+| Gavin Andresen
+| Standard
+| Rejected
+|- style="background-color: #ffffcf"
| [[bip-0111.mediawiki|111]]
+| Peer Services
| NODE_BLOOM service bit
-| Matt Corallo and Peter Todd
+| Matt Corallo, Peter Todd
| Standard
-| Draft
-|-
+| Proposed
+|- style="background-color: #cfffcf"
| [[bip-0112.mediawiki|112]]
+| Consensus (soft fork)
| CHECKSEQUENCEVERIFY
-| BtcDrak and Mark Friedenbach
+| BtcDrak, Mark Friedenbach, Eric Lombrozo
| Standard
-| Draft
-|-
+| Final
+|- style="background-color: #cfffcf"
| [[bip-0113.mediawiki|113]]
+| Consensus (soft fork)
| Median time-past as endpoint for lock-time calculations
-| Thomas Kerin and Mark Friedenbach
+| Thomas Kerin, Mark Friedenbach
+| Standard
+| Final
+|- style="background-color: #ffcfcf"
+| [[bip-0114.mediawiki|114]]
+| Consensus (soft fork)
+| Merkelized Abstract Syntax Tree
+| Johnson Lau
+| Standard
+| Rejected
+|- style="background-color: #ffcfcf"
+| [[bip-0115.mediawiki|115]]
+| Consensus (soft fork)
+| Generic anti-replay protection using Script
+| Luke Dashjr
+| Standard
+| Rejected
+|-
+| [[bip-0116.mediawiki|116]]
+| Consensus (soft fork)
+| MERKLEBRANCHVERIFY
+| Mark Friedenbach, Kalle Alm, BtcDrak
+| Standard
+| Draft
+|-
+| [[bip-0117.mediawiki|117]]
+| Consensus (soft fork)
+| Tail Call Execution Semantics
+| Mark Friedenbach, Kalle Alm, BtcDrak
| Standard
| Draft
|-
+| [[bip-0118.mediawiki|118]]
+| Consensus (soft fork)
+| SIGHASH_ANYPREVOUT for Taproot Scripts
+| Christian Decker, Anthony Towns
+| Standard
+| Draft
+|-
+| [[bip-0119.mediawiki|119]]
+| Consensus (soft fork)
+| CHECKTEMPLATEVERIFY
+| Jeremy Rubin
+| Standard
+| Draft
+|- style="background-color: #ffcfcf"
| [[bip-0120.mediawiki|120]]
+| Applications
| Proof of Payment
| Kalle Rosenbaum
| Standard
-| Draft
-|-
+| Withdrawn
+|- style="background-color: #ffcfcf"
| [[bip-0121.mediawiki|121]]
+| Applications
| Proof of Payment URI scheme
| Kalle Rosenbaum
| Standard
-| Draft
+| Withdrawn
|-
+| [[bip-0122.mediawiki|122]]
+| Applications
+| URI scheme for Blockchain references / exploration
+| Marco Pontello
+| Standard
+| Draft
+|- style="background-color: #cfffcf"
| [[bip-0123.mediawiki|123]]
+|
| BIP Classification
| Eric Lombrozo
+| Process
+| Active
+|- style="background-color: #ffcfcf"
+| [[bip-0124.mediawiki|124]]
+| Applications
+| Hierarchical Deterministic Script Templates
+| Eric Lombrozo, William Swanson
+| Informational
+| Rejected
+|- style="background-color: #cfffcf"
+| [[bip-0125.mediawiki|125]]
+| Applications
+| Opt-in Full Replace-by-Fee Signaling
+| David A. Harding, Peter Todd
+| Standard
+| Final
+|-
+| [[bip-0126.mediawiki|126]]
+|
+| Best Practices for Heterogeneous Input Script Transactions
+| Kristov Atlas
| Informational
| Draft
|-
+| [[bip-0127.mediawiki|127]]
+| Applications
+| Simple Proof-of-Reserves Transactions
+| Steven Roose
+| Standard
+| Draft
+|- style="background-color: #ffffcf"
+| [[bip-0129.mediawiki|129]]
+| Applications
+| Bitcoin Secure Multisig Setup (BSMS)
+| Hugo Nguyen, Peter Gray, Marko Bencun, Aaron Chen, Rodolfo Novak
+| Standard
+| Proposed
+|- style="background-color: #cfffcf"
| [[bip-0130.mediawiki|130]]
-| sendheaders message
+| Peer Services
+| sendheaders message
| Suhas Daftuar
| Standard
+| Final
+|- style="background-color: #ffcfcf"
+| [[bip-0131.mediawiki|131]]
+| Consensus (hard fork)
+| "Coalescing Transaction" Specification (wildcard inputs)
+| Chris Priest
+| Standard
+| Rejected
+|- style="background-color: #ffcfcf"
+| [[bip-0132.mediawiki|132]]
+|
+| Committee-based BIP Acceptance Process
+| Andy Chase
+| Process
+| Withdrawn
+|- style="background-color: #cfffcf"
+| [[bip-0133.mediawiki|133]]
+| Peer Services
+| feefilter message
+| Alex Morcos
+| Standard
+| Final
+|- style="background-color: #ffcfcf"
+| [[bip-0134.mediawiki|134]]
+| Consensus (hard fork)
+| Flexible Transactions
+| Tom Zander
+| Standard
+| Rejected
+|- style="background-color: #ffcfcf"
+| [[bip-0135.mediawiki|135]]
+|
+| Generalized version bits voting
+| Sancho Panza
+| Informational
+| Rejected
+|-
+| [[bip-0136.mediawiki|136]]
+| Applications
+| Bech32 Encoded Tx Position References
+| Велеслав, Jonas Schnelli, Daniel Pape
+| Informational
+| Draft
+|- style="background-color: #cfffcf"
+| [[bip-0137.mediawiki|137]]
+| Applications
+| Signatures of Messages using Private Keys
+| Christopher Gilliard
+| Standard
+| Final
+|- style="background-color: #ffcfcf"
+| [[bip-0140.mediawiki|140]]
+| Consensus (soft fork)
+| Normalized TXID
+| Christian Decker
+| Standard
+| Rejected
+|- style="background-color: #cfffcf"
+| [[bip-0141.mediawiki|141]]
+| Consensus (soft fork)
+| Segregated Witness (Consensus layer)
+| Eric Lombrozo, Johnson Lau, Pieter Wuille
+| Standard
+| Final
+|- style="background-color: #ffcfcf"
+| [[bip-0142.mediawiki|142]]
+| Applications
+| Address Format for Segregated Witness
+| Johnson Lau
+| Standard
+| Withdrawn
+|- style="background-color: #cfffcf"
+| [[bip-0143.mediawiki|143]]
+| Consensus (soft fork)
+| Transaction Signature Verification for Version 0 Witness Program
+| Johnson Lau, Pieter Wuille
+| Standard
+| Final
+|- style="background-color: #cfffcf"
+| [[bip-0144.mediawiki|144]]
+| Peer Services
+| Segregated Witness (Peer Services)
+| Eric Lombrozo, Pieter Wuille
+| Standard
+| Final
+|- style="background-color: #cfffcf"
+| [[bip-0145.mediawiki|145]]
+| API/RPC
+| getblocktemplate Updates for Segregated Witness
+| Luke Dashjr
+| Standard
+| Final
+|- style="background-color: #ffcfcf"
+| [[bip-0146.mediawiki|146]]
+| Consensus (soft fork)
+| Dealing with signature encoding malleability
+| Johnson Lau, Pieter Wuille
+| Standard
+| Withdrawn
+|- style="background-color: #cfffcf"
+| [[bip-0147.mediawiki|147]]
+| Consensus (soft fork)
+| Dealing with dummy stack element malleability
+| Johnson Lau
+| Standard
+| Final
+|- style="background-color: #cfffcf"
+| [[bip-0148.mediawiki|148]]
+| Consensus (soft fork)
+| Mandatory activation of segwit deployment
+| Shaolin Fry
+| Standard
+| Final
+|- style="background-color: #ffcfcf"
+| [[bip-0149.mediawiki|149]]
+| Consensus (soft fork)
+| Segregated Witness (second deployment)
+| Shaolin Fry
+| Standard
+| Withdrawn
+|-
+| [[bip-0150.mediawiki|150]]
+| Peer Services
+| Peer Authentication
+| Jonas Schnelli
+| Standard
+| Deferred
+|- style="background-color: #ffcfcf"
+| [[bip-0151.mediawiki|151]]
+| Peer Services
+| Peer-to-Peer Communication Encryption
+| Jonas Schnelli
+| Standard
+| Replaced
+|- style="background-color: #cfffcf"
+| [[bip-0152.mediawiki|152]]
+| Peer Services
+| Compact Block Relay
+| Matt Corallo
+| Standard
+| Final
+|- style="background-color: #ffcfcf"
+| [[bip-0154.mediawiki|154]]
+| Peer Services
+| Rate Limiting via peer specified challenges
+| Karl-Johan Alm
+| Standard
+| Withdrawn
+|-
+| [[bip-0155.mediawiki|155]]
+| Peer Services
+| addrv2 message
+| Wladimir J. van der Laan
+| Standard
+| Draft
+|- style="background-color: #ffcfcf"
+| [[bip-0156.mediawiki|156]]
+| Peer Services
+| Dandelion - Privacy Enhancing Routing
+| Brad Denby, Andrew Miller, Giulia Fanti, Surya Bakshi, Shaileshh Bojja Venkatakrishnan, Pramod Viswanath
+| Standard
+| Rejected
+|-
+| [[bip-0157.mediawiki|157]]
+| Peer Services
+| Client Side Block Filtering
+| Olaoluwa Osuntokun, Alex Akselrod, Jim Posen
+| Standard
+| Draft
+|-
+| [[bip-0158.mediawiki|158]]
+| Peer Services
+| Compact Block Filters for Light Clients
+| Olaoluwa Osuntokun, Alex Akselrod
+| Standard
+| Draft
+|- style="background-color: #cfffcf"
+| [[bip-0159.mediawiki|159]]
+| Peer Services
+| NODE_NETWORK_LIMITED service bit
+| Jonas Schnelli
+| Standard
+| Final
+|- style="background-color: #ffcfcf"
+| [[bip-0171.mediawiki|171]]
+| Applications
+| Currency/exchange rate information API
+| Luke Dashjr
+| Standard
+| Rejected
+|- style="background-color: #cfffcf"
+| [[bip-0173.mediawiki|173]]
+| Applications
+| Base32 address format for native v0-16 witness outputs
+| Pieter Wuille, Greg Maxwell
+| Informational
+| Final
+|- style="background-color: #cfffcf"
+| [[bip-0174.mediawiki|174]]
+| Applications
+| Partially Signed Bitcoin Transaction Format
+| Ava Chow
+| Standard
+| Final
+|- style="background-color: #ffcfcf"
+| [[bip-0175.mediawiki|175]]
+| Applications
+| Pay to Contract Protocol
+| Omar Shibli, Nicholas Gregory
+| Informational
+| Rejected
+|-
+| [[bip-0176.mediawiki|176]]
+|
+| Bits Denomination
+| Jimmy Song
+| Informational
+| Draft
+|-
+| [[bip-0178.mediawiki|178]]
+| Applications
+| Version Extended WIF
+| Karl-Johan Alm
+| Standard
+| Draft
+|-
+| [[bip-0179.mediawiki|179]]
+|
+| Name for payment recipient identifiers
+| Emil Engler, Luke Dashjr
+| Informational
+| Draft
+|- style="background-color: #ffcfcf"
+| [[bip-0180.mediawiki|180]]
+| Peer Services
+| Block size/weight fraud proof
+| Luke Dashjr
+| Standard
+| Rejected
+|-
+| [[bip-0197.mediawiki|197]]
+| Applications
+| Hashed Time-Locked Collateral Contract
+| Matthew Black, Tony Cai
+| Standard
+| Draft
+|-
+| [[bip-0199.mediawiki|199]]
+| Applications
+| Hashed Time-Locked Contract transactions
+| Sean Bowe, Daira Hopwood
+| Standard
+| Draft
+|-
+| [[bip-0300.mediawiki|300]]
+| Consensus (soft fork)
+| Hashrate Escrows (Consensus layer)
+| Paul Sztorc, CryptAxe
+| Standard
+| Draft
+|-
+| [[bip-0301.mediawiki|301]]
+| Consensus (soft fork)
+| Blind Merged Mining (Consensus layer)
+| Paul Sztorc, CryptAxe
+| Standard
+| Draft
+|-
+| [[bip-0310.mediawiki|310]]
+| Applications
+| Stratum protocol extensions
+| Pavel Moravec, Jan Čapek
+| Informational
+| Draft
+|-
+| [[bip-0320.mediawiki|320]]
+|
+| nVersion bits for general purpose use
+| BtcDrak
+| Standard
+| Draft
+|-
+| [[bip-0322.mediawiki|322]]
+| Applications
+| Generic Signed Message Format
+| Karl-Johan Alm
+| Standard
+| Draft
+|- style="background-color: #cfffcf"
+| [[bip-0324.mediawiki|324]]
+| Peer Services
+| Version 2 P2P Encrypted Transport Protocol
+| Dhruv Mehta, Tim Ruffing, Jonas Schnelli, Pieter Wuille
+| Standard
+| Final
+|- style="background-color: #ffffcf"
+| [[bip-0325.mediawiki|325]]
+| Applications
+| Signet
+| Karl-Johan Alm, Anthony Towns
+| Standard
+| Proposed
+|-
+| [[bip-0326.mediawiki|326]]
+| Applications
+| Anti-fee-sniping in taproot transactions
+| Chris Belcher
+| Informational
+| Draft
+|- style="background-color: #cfffcf"
+| [[bip-0327.mediawiki|327]]
+|
+| MuSig2 for BIP340-compatible Multi-Signatures
+| Jonas Nick, Tim Ruffing, Elliott Jin
+| Informational
+| Active
+|-
+| [[bip-0328.mediawiki|328]]
+| Applications
+| Derivation Scheme for MuSig2 Aggregate Keys
+| Ava Chow
+| Informational
+| Draft
+|-
+| [[bip-0329.mediawiki|329]]
+| Applications
+| Wallet Labels Export Format
+| Craig Raw
+| Informational
+| Draft
+|-
+| [[bip-0330.mediawiki|330]]
+| Peer Services
+| Transaction announcements reconciliation
+| Gleb Naumenko, Pieter Wuille
+| Standard
+| Draft
+|-
+| [[bip-0331.mediawiki|331]]
+| Peer Services
+| Ancestor Package Relay
+| Gloria Zhao
+| Standard
+| Draft
+|-
+| [[bip-0337.mediawiki|337]]
+| API/RPC
+| Compressed Transactions
+| Tom Briar
+| Standard
+| Draft
+|- style="background-color: #ffcfcf"
+| [[bip-0338.mediawiki|338]]
+| Peer Services
+| Disable transaction relay message
+| Suhas Daftuar
+| Standard
+| Withdrawn
+|- style="background-color: #cfffcf"
+| [[bip-0339.mediawiki|339]]
+| Peer Services
+| WTXID-based transaction relay
+| Suhas Daftuar
+| Standard
+| Final
+|- style="background-color: #cfffcf"
+| [[bip-0340.mediawiki|340]]
+|
+| Schnorr Signatures for secp256k1
+| Pieter Wuille, Jonas Nick, Tim Ruffing
+| Standard
+| Final
+|- style="background-color: #cfffcf"
+| [[bip-0341.mediawiki|341]]
+| Consensus (soft fork)
+| Taproot: SegWit version 1 spending rules
+| Pieter Wuille, Jonas Nick, Anthony Towns
+| Standard
+| Final
+|- style="background-color: #cfffcf"
+| [[bip-0342.mediawiki|342]]
+| Consensus (soft fork)
+| Validation of Taproot Scripts
+| Pieter Wuille, Jonas Nick, Anthony Towns
+| Standard
+| Final
+|- style="background-color: #cfffcf"
+| [[bip-0343.mediawiki|343]]
+| Consensus (soft fork)
+| Mandatory activation of taproot deployment
+| Shinobius, Michael Folkson
+| Standard
+| Final
+|-
+| [[bip-0345.mediawiki|345]]
+| Consensus (soft fork)
+| OP_VAULT
+| James O'Beirne, Greg Sanders
+| Standard
+| Draft
+|-
+| [[bip-0347.mediawiki|347]]
+| Consensus (soft fork)
+| OP_CAT in Tapscript
+| Ethan Heilman, Armin Sabouri
+| Standard
+| Draft
+|-
+| [[bip-0348.md|348]]
+| Consensus (soft fork)
+| CHECKSIGFROMSTACK
+| Brandon Black, Jeremy Rubin
+| Standard
+| Draft
+|-
+| [[bip-0349.md|349]]
+| Consensus (soft fork)
+| OP_INTERNALKEY
+| Brandon Black, Jeremy Rubin
+| Standard
+| Draft
+|- style="background-color: #cfffcf"
+| [[bip-0350.mediawiki|350]]
+| Applications
+| Bech32m format for v1+ witness addresses
+| Pieter Wuille
+| Standard
+| Final
+|-
+| [[bip-0351.mediawiki|351]]
+| Applications
+| Private Payments
+| Alfred Hodler, Clark Moody
+| Informational
+| Draft
+|- style="background-color: #ffffcf"
+| [[bip-0352.mediawiki|352]]
+| Applications
+| Silent Payments
+| josibake, Ruben Somsen
+| Standard
+| Proposed
+|-
+| [[bip-0353.mediawiki|353]]
+| Applications
+| DNS Payment Instructions
+| Matt Corallo, Bastien Teinturier
+| Standard
+| Draft
+|- style="background-color: #cfffcf"
+| [[bip-0370.mediawiki|370]]
+| Applications
+| PSBT Version 2
+| Ava Chow
+| Standard
+| Final
+|- style="background-color: #cfffcf"
+| [[bip-0371.mediawiki|371]]
+| Applications
+| Taproot Fields for PSBT
+| Ava Chow
+| Standard
+| Final
+|-
+| [[bip-0372.mediawiki|372]]
+| Applications
+| Pay-to-contract tweak fields for PSBT
+| Maxim Orlovsky
+| Standard
+| Draft
+|-
+| [[bip-0373.mediawiki|373]]
+| Applications
+| MuSig2 PSBT Fields
+| Ava Chow
+| Standard
+| Draft
+|-
+| [[bip-0374.mediawiki|374]]
+| Applications
+| Discrete Log Equality Proofs
+| Andrew Toth, Ruben Somsen, Sebastian Falbesoner
+| Standard
+| Draft
+|-
+| [[bip-0379.md|379]]
+| Applications
+| Miniscript
+| Pieter Wuille, Andrew Poelstra, Sanket Kanjalkar, Antoine Poinsot, Ava Chow
+| Informational
+| Draft
+|- style="background-color: #cfffcf"
+| [[bip-0380.mediawiki|380]]
+| Applications
+| Output Script Descriptors General Operation
+| Pieter Wuille, Ava Chow
+| Informational
+| Final
+|- style="background-color: #cfffcf"
+| [[bip-0381.mediawiki|381]]
+| Applications
+| Non-Segwit Output Script Descriptors
+| Pieter Wuille, Ava Chow
+| Informational
+| Final
+|- style="background-color: #cfffcf"
+| [[bip-0382.mediawiki|382]]
+| Applications
+| Segwit Output Script Descriptors
+| Pieter Wuille, Ava Chow
+| Informational
+| Final
+|- style="background-color: #cfffcf"
+| [[bip-0383.mediawiki|383]]
+| Applications
+| Multisig Output Script Descriptors
+| Pieter Wuille, Ava Chow
+| Informational
+| Final
+|- style="background-color: #cfffcf"
+| [[bip-0384.mediawiki|384]]
+| Applications
+| combo() Output Script Descriptors
+| Pieter Wuille, Ava Chow
+| Informational
+| Final
+|- style="background-color: #cfffcf"
+| [[bip-0385.mediawiki|385]]
+| Applications
+| raw() and addr() Output Script Descriptors
+| Pieter Wuille, Ava Chow
+| Informational
+| Final
+|- style="background-color: #cfffcf"
+| [[bip-0386.mediawiki|386]]
+| Applications
+| tr() Output Script Descriptors
+| Pieter Wuille, Ava Chow
+| Informational
+| Final
+|- style="background-color: #cfffcf"
+| [[bip-0387.mediawiki|387]]
+| Applications
+| Tapscript Multisig Output Script Descriptors
+| Pieter Wuille, Ava Chow
+| Informational
+| Final
+|- style="background-color: #ffffcf"
+| [[bip-0388.mediawiki|388]]
+| Applications
+| Wallet Policies for Descriptor Wallets
+| Salvatore Ingala
+| Standard
+| Proposed
+|-
+| [[bip-0389.mediawiki|389]]
+| Applications
+| Multipath Descriptor Key Expressions
+| Ava Chow
+| Informational
+| Draft
+|-
+| [[bip-0390.mediawiki|390]]
+| Applications
+| musig() Descriptor Key Expression
+| Ava Chow
+| Informational
+| Draft
+|-
+| [[bip-0431.mediawiki|431]]
+| Applications
+| Topology Restrictions for Pinning
+| Gloria Zhao
+| Informational
| Draft
|}
diff --git a/bip-0001.mediawiki b/bip-0001.mediawiki
index 7af25cde84..7067f64b30 100644
--- a/bip-0001.mediawiki
+++ b/bip-0001.mediawiki
@@ -1,9 +1,13 @@
BIP: 1
Title: BIP Purpose and Guidelines
- Status: Active
- Type: Standards Track
- Created: 2011-08-19
+ Author: Amir Taaki
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0001
+ Status: Replaced
+ Type: Process
+ Created: 2011-09-19
+ Superseded-By: 2
==What is a BIP?==
@@ -13,6 +17,7 @@ BIP stands for Bitcoin Improvement Proposal. A BIP is a design document providin
We intend BIPs to be the primary mechanisms for proposing new features, for collecting community input on an issue, and for documenting the design decisions that have gone into Bitcoin. The BIP author is responsible for building consensus within the community and documenting dissenting opinions.
Because the BIPs are maintained as text files in a versioned repository, their revision history is the historical record of the feature proposal.
+
==BIP Types==
There are three kinds of BIP:
@@ -23,30 +28,26 @@ There are three kinds of BIP:
==BIP Work Flow==
-The BIP editors assign BIP numbers and change their status. Please send all BIP-related email to the BIP editor, which is listed under [[#BIP_Editors|BIP Editors]] below. Also see [[#BIP_Editor_Responsibilities__Workflow|BIP Editor Responsibilities & Workflow]].
+The BIP process begins with a new idea for Bitcoin. Each potential BIP must have a champion -- someone who writes the BIP using the style and format described below, shepherds the discussions in the appropriate forums, and attempts to build community consensus around the idea. The BIP champion (a.k.a. Author) should first attempt to ascertain whether the idea is BIP-able. Posting to the [https://lists.linuxfoundation.org/mailman/listinfo/bitcoin-dev bitcoin-dev@lists.linuxfoundation.org] mailing list (and maybe the [https://bitcointalk.org/index.php?board=6.0 Development & Technical Discussion] forum) is the best way to go about this.
-Authors MUST NOT self assign numbers, but should use an alias such as "bip-johndoe-infinitebitcoins" which includes the author's name/nick and the BIP subject.
+Vetting an idea publicly before going as far as writing a BIP is meant to save both the potential author and the wider community time. Many ideas have been brought forward for changing Bitcoin that have been rejected for various reasons. Asking the Bitcoin community first if an idea is original helps prevent too much time being spent on something that is guaranteed to be rejected based on prior discussions (searching the internet does not always do the trick). It also helps to make sure the idea is applicable to the entire community and not just the author. Just because an idea sounds good to the author does not mean it will work for most people in most areas where Bitcoin is used. Small enhancements or patches often don't need standardisation between multiple projects; these don't need a BIP and should be injected into the relevant Bitcoin development work flow with a patch submission to the applicable Bitcoin issue tracker.
-The BIP process begins with a new idea for Bitcoin. It is highly recommended that a single BIP contain a single key proposal or new idea. Small enhancements or patches often don't need a BIP and can be injected into the Bitcoin development work flow with a patch submission to the Bitcoin issue tracker. The more focused the BIP, the more successful it tends to be. The BIP editor reserves the right to reject BIP proposals if they appear too unfocused or too broad. If in doubt, split your BIP into several well-focused ones.
+Once the champion has asked the Bitcoin community as to whether an idea has any chance of acceptance, a draft BIP should be presented to the [https://lists.linuxfoundation.org/mailman/listinfo/bitcoin-dev bitcoin-dev] mailing list. This gives the author a chance to flesh out the draft BIP to make it properly formatted, of high quality, and to address additional concerns about the proposal. Following a discussion, the proposal should be sent to the bitcoin-dev list and the BIP editor with the draft BIP. This draft must be written in BIP style as described below, else it will be sent back without further regard until proper formatting rules are followed.
-Each BIP must have a champion -- someone who writes the BIP using the style and format described below, shepherds the discussions in the appropriate forums, and attempts to build community consensus around the idea. The BIP champion (a.k.a. Author) should first attempt to ascertain whether the idea is BIP-able. Posting to the [https://lists.linuxfoundation.org/mailman/listinfo/bitcoin-dev bitcoin-dev] mailing list (and maybe the [https://bitcointalk.org/index.php?board=6.0 Development&Technical Discussion] forum) is the best way to go about this.
+BIP authors are responsible for collecting community feedback on both the initial idea and the BIP before submitting it for review. However, wherever possible, long open-ended discussions on public mailing lists should be avoided. Strategies to keep the discussions efficient include: setting up a separate SIG mailing list for the topic, having the BIP author accept private comments in the early design phases, setting up a wiki page or git repository, etc. BIP authors should use their discretion here.
-Vetting an idea publicly before going as far as writing a BIP is meant to save the potential author time. Many ideas have been brought forward for changing Bitcoin that have been rejected for various reasons. Asking the Bitcoin community first if an idea is original helps prevent too much time being spent on something that is guaranteed to be rejected based on prior discussions (searching the internet does not always do the trick). It also helps to make sure the idea is applicable to the entire community and not just the author. Just because an idea sounds good to the author does not mean it will work for most people in most areas where Bitcoin is used.
+It is highly recommended that a single BIP contain a single key proposal or new idea. The more focused the BIP, the more successful it tends to be. If in doubt, split your BIP into several well-focused ones.
-Once the champion has asked the Bitcoin community as to whether an idea has any chance of acceptance, a draft BIP should be presented to [https://lists.linuxfoundation.org/mailman/listinfo/bitcoin-dev bitcoin-dev@lists.linuxfoundation.org]. This gives the author a chance to flesh out the draft BIP to make properly formatted, of high quality, and to address initial concerns about the proposal.
+The BIP editors assign BIP numbers and change their status. Please send all BIP-related email to the BIP editor, which is listed under [[#BIP_Editors|BIP Editors]] below. Also see [[#BIP_Editor_Responsibilities__Workflow|BIP Editor Responsibilities & Workflow]]. The BIP editor reserves the right to reject BIP proposals if they appear too unfocused or too broad.
-Following a discussion, the proposal should be sent to the Bitcoin-dev list and the BIP editor with the draft BIP. This draft must be written in BIP style as described below, else it will be sent back without further regard until proper formatting rules are followed.
+Authors MUST NOT self assign BIP numbers, but should use an alias such as "bip-johndoe-infinitebitcoins" which includes the author's name/nick and the BIP subject.
-If the BIP editor approves, he will assign the BIP a number, label it as Standards Track, Informational, or Process, give it status "Draft", and add it to the git repository. The BIP editor will not unreasonably deny a BIP. Reasons for denying BIP status include duplication of effort, being technically unsound, not providing proper motivation or addressing backwards compatibility, or not in keeping with the Bitcoin philosophy.
+If the BIP editor approves, he will assign the BIP a number, label it as Standards Track, Informational, or Process, give it status "Draft", and add it to the BIPs git repository. The BIP editor will not unreasonably deny a BIP. Reasons for denying BIP status include duplication of effort, disregard for formatting rules, being too unfocused or too broad, being technically unsound, not providing proper motivation or addressing backwards compatibility, or not in keeping with the Bitcoin philosophy. For a BIP to be accepted it must meet certain minimum criteria. It must be a clear and complete description of the proposed enhancement. The enhancement must represent a net improvement. The proposed implementation, if applicable, must be solid and must not complicate the protocol unduly.
The BIP author may update the Draft as necessary in the git repository. Updates to drafts may also be submitted by the author as pull requests.
Standards Track BIPs consist of two parts, a design document and a reference implementation. The BIP should be reviewed and accepted before a reference implementation is begun, unless a reference implementation will aid people in studying the BIP. Standards Track BIPs must include an implementation -- in the form of code, a patch, or a URL to same -- before it can be considered Final.
-BIP authors are responsible for collecting community feedback on a BIP before submitting it for review. However, wherever possible, long open-ended discussions on public mailing lists should be avoided. Strategies to keep the discussions efficient include: setting up a separate SIG mailing list for the topic, having the BIP author accept private comments in the early design phases, setting up a wiki page or git repository, etc. BIP authors should use their discretion here.
-
-For a BIP to be accepted it must meet certain minimum criteria. It must be a clear and complete description of the proposed enhancement. The enhancement must represent a net improvement. The proposed implementation, if applicable, must be solid and must not complicate the protocol unduly.
-
Once a BIP has been accepted, the reference implementation must be completed. When the reference implementation is complete and accepted by the community, the status will be changed to "Final".
A BIP can also be assigned status "Deferred". The BIP author or editor can assign the BIP this status when no progress is being made on the BIP. Once a BIP is deferred, the BIP editor can re-assign it to draft status.
@@ -87,9 +88,9 @@ Each BIP should have the following parts:
==BIP Formats and Templates==
-BIPs should be written in mediawiki or markdown format. Image files should be included in a subdirectory for that BIP.
+BIPs should be written in mediawiki or markdown format.
-==BIP Header Preamble==
+===BIP Header Preamble===
Each BIP must begin with an RFC 822 style header preamble. The headers must appear in the following order. Headers marked with "*" are optional and are described below. All other headers are required.
@@ -131,9 +132,10 @@ The Created header records the date that the BIP was assigned a number, while Po
BIPs may have a Requires header, indicating the BIP numbers that this BIP depends on.
BIPs may also have a Superseded-By header indicating that a BIP has been rendered obsolete by a later document; the value is the number of the BIP that replaces the current document. The newer BIP must have a Replaces header containing the number of the BIP that it rendered obsolete.
-Auxiliary Files
-BIPs may include auxiliary files such as diagrams. Such files must be named BIP-XXXX-Y.ext, where "XXXX" is the BIP number, "Y" is a serial number (starting at 1), and "ext" is replaced by the actual file extension (e.g. "png").
+===Auxiliary Files===
+
+BIPs may include auxiliary files such as diagrams. Image files should be included in a subdirectory for that BIP. Auxiliary files must be named BIP-XXXX-Y.ext, where "XXXX" is the BIP number, "Y" is a serial number (starting at 1), and "ext" is replaced by the actual file extension (e.g. "png").
==Transferring BIP Ownership==
@@ -143,11 +145,11 @@ If you are interested in assuming ownership of a BIP, send a message asking to t
==BIP Editors==
-The current BIP editor is Gregory Maxwell who can be contacted at [[mailto:gmaxwell@gmail.com|gmaxwell@gmail.com]].
+The current BIP editor is Luke Dashjr who can be contacted at [[mailto:luke_bipeditor@dashjr.org|luke_bipeditor@dashjr.org]].
==BIP Editor Responsibilities & Workflow==
-A BIP editor must subscribe to the Bitcoin development mailing list. All BIP-related correspondence should be sent (or CC'd) to gmaxwell@gmail.com.
+The BIP editor subscribes to the Bitcoin development mailing list. All BIP-related correspondence should be sent (or CC'd) to luke_bipeditor@dashjr.org.
For each new BIP that comes in an editor does the following:
@@ -167,11 +169,9 @@ The BIP editor will:
* List the BIP in [[README.mediawiki]]
-* Send email back to the BIP author with next steps (post to bitcoin mailing list).
-
-Many BIPs are written and maintained by developers with write access to the Bitcoin codebase. The BIP editors monitor BIP changes, and correct any structure, grammar, spelling, or markup mistakes we see.
+* Send email back to the BIP author with next steps (post to bitcoin-dev mailing list).
-The editors don't pass judgement on BIPs. We merely do the administrative & editorial part. Except for times like this, there's relatively low volume.
+The BIP editors are intended to fulfill administrative and editorial responsibilities. The BIP editors monitor BIP changes, and correct any structure, grammar, spelling, or markup mistakes we see.
==History==
@@ -179,4 +179,6 @@ This document was derived heavily from Python's PEP-0001. In many places text wa
==Changelog==
-10 Oct 2015 - Added clarifications about sumission process and BIP number assignment.
+10 Oct 2015 - Added clarifications about submission process and BIP number assignment.
+
+01 Jan 2016 - Clarified early stages of BIP idea championing, collecting community feedback, etc.
diff --git a/bip-0002.mediawiki b/bip-0002.mediawiki
new file mode 100644
index 0000000000..291a0b1d9a
--- /dev/null
+++ b/bip-0002.mediawiki
@@ -0,0 +1,424 @@
+
+ BIP: 2
+ Title: BIP process, revised
+ Author: Luke Dashjr
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0002
+ Status: Active
+ Type: Process
+ Created: 2016-02-03
+ License: BSD-2-Clause
+ OPL
+ Replaces: 1
+
+
+==Abstract==
+
+A Bitcoin Improvement Proposal (BIP) is a design document providing information to the Bitcoin community, or describing a new feature for Bitcoin or its processes or environment. The BIP should provide a concise technical specification of the feature and a rationale for the feature.
+
+We intend BIPs to be the primary mechanisms for proposing new features, for collecting community input on an issue, and for documenting the design decisions that have gone into Bitcoin. The BIP author is responsible for building consensus within the community and documenting dissenting opinions.
+
+Because the BIPs are maintained as text files in a versioned repository, their revision history is the historical record of the feature proposal.
+
+This particular BIP replaces BIP 1 with a more well-defined and clear process.
+
+==Copyright==
+
+This BIP is dual-licensed under the Open Publication License and BSD 2-clause license.
+
+==BIP workflow==
+
+The BIP process begins with a new idea for Bitcoin. Each potential BIP must have a champion -- someone who writes the BIP using the style and format described below, shepherds the discussions in the appropriate forums, and attempts to build community consensus around the idea. The BIP champion (a.k.a. Author) should first attempt to ascertain whether the idea is BIP-able.
+Small enhancements or patches to a particular piece of software often don't require standardisation between multiple projects; these don't need a BIP and should be injected into the relevant project-specific development workflow with a patch submission to the applicable issue tracker.
+Additionally, many ideas have been brought forward for changing Bitcoin that have been rejected for various reasons.
+The first step should be to search past discussions to see if an idea has been considered before, and if so, what issues arose in its progression.
+After investigating past work, the best way to proceed is by posting about the new idea to the [https://groups.google.com/g/bitcoindev Bitcoin development mailing list].
+
+Vetting an idea publicly before going as far as writing a BIP is meant to save both the potential author and the wider community time.
+Asking the Bitcoin community first if an idea is original helps prevent too much time being spent on something that is guaranteed to be rejected based on prior discussions (searching the internet does not always do the trick).
+It also helps to make sure the idea is applicable to the entire community and not just the author. Just because an idea sounds good to the author does not mean it will work for most people in most areas where Bitcoin is used.
+
+Once the champion has asked the Bitcoin community as to whether an idea has any chance of acceptance, a draft BIP should be presented to the [https://groups.google.com/g/bitcoindev Bitcoin development mailing list].
+This gives the author a chance to flesh out the draft BIP to make it properly formatted, of high quality, and to address additional concerns about the proposal.
+Following a discussion, the proposal should be submitted to the [https://github.com/bitcoin/bips BIPs git repository] as a pull request.
+This draft must be written in BIP style as described below, and named with an alias such as "bip-johndoe-infinitebitcoins" until an editor has assigned it a BIP number (authors MUST NOT self-assign BIP numbers).
+
+BIP authors are responsible for collecting community feedback on both the initial idea and the BIP before submitting it for review. However, wherever possible, long open-ended discussions on public mailing lists should be avoided. Strategies to keep the discussions efficient include: setting up a separate SIG mailing list for the topic, having the BIP author accept private comments in the early design phases, setting up a wiki page or git repository, etc. BIP authors should use their discretion here.
+
+It is highly recommended that a single BIP contain a single key proposal or new idea. The more focused the BIP, the more successful it tends to be. If in doubt, split your BIP into several well-focused ones.
+
+When the BIP draft is complete, a BIP editor will assign the BIP a number, label it as Standards Track, Informational, or Process, and merge the pull request to the BIPs git repository.
+The BIP editors will not unreasonably reject a BIP.
+Reasons for rejecting BIPs include duplication of effort, disregard for formatting rules, being too unfocused or too broad, being technically unsound, not providing proper motivation or addressing backwards compatibility, or not in keeping with the Bitcoin philosophy.
+For a BIP to be accepted it must meet certain minimum criteria.
+It must be a clear and complete description of the proposed enhancement.
+The enhancement must represent a net improvement.
+The proposed implementation, if applicable, must be solid and must not complicate the protocol unduly.
+
+The BIP author may update the draft as necessary in the git repository. Updates to drafts should also be submitted by the author as pull requests.
+
+===Transferring BIP Ownership===
+
+It occasionally becomes necessary to transfer ownership of BIPs to a new champion. In general, we'd like to retain the original author as a co-author of the transferred BIP, but that's really up to the original author. A good reason to transfer ownership is because the original author no longer has the time or interest in updating it or following through with the BIP process, or has fallen off the face of the 'net (i.e. is unreachable or not responding to email). A bad reason to transfer ownership is because you don't agree with the direction of the BIP. We try to build consensus around a BIP, but if that's not possible, you can always submit a competing BIP.
+
+If you are interested in assuming ownership of a BIP, send a message asking to take over, addressed to both the original author and the BIP editors. If the original author doesn't respond to email in a timely manner, the BIP editors will make a unilateral decision (it's not like such decisions can't be reversed :).
+
+===BIP Editors===
+
+The current BIP editors are:
+
+* Bryan Bishop ([[mailto:kanzure@gmail.com|kanzure@gmail.com]])
+* Jon Atack ([[mailto:jon@atack.com|jon@atack.com]])
+* Luke Dashjr ([[mailto:luke_bipeditor@dashjr.org|luke_bipeditor@dashjr.org]])
+* Mark "Murch" Erhardt ([[mailto:murch@murch.one|murch@murch.one]])
+* Olaoluwa Osuntokun ([[mailto:laolu32@gmail.com|laolu32@gmail.com]])
+* Ruben Somsen ([[mailto:rsomsen@gmail.com|rsomsen@gmail.com]])
+
+===BIP Editor Responsibilities & Workflow===
+
+The BIP editors subscribe to the Bitcoin development mailing list.
+Off-list BIP-related correspondence should be sent (or CC'd) to the BIP editors.
+
+For each new BIP that comes in an editor does the following:
+
+* Read the BIP to check if it is ready: sound and complete. The ideas must make technical sense, even if they don't seem likely to be accepted.
+* The title should accurately describe the content.
+* The BIP draft must have been sent to the Bitcoin development mailing list for discussion.
+* Motivation and backward compatibility (when applicable) must be addressed.
+* The defined Layer header must be correctly assigned for the given specification.
+* Licensing terms must be acceptable for BIPs.
+
+If the BIP isn't ready, the editor will send it back to the author for revision, with specific instructions.
+
+Once the BIP is ready for the repository it should be submitted as a "pull request" to the [https://github.com/bitcoin/bips BIPs git repository] where it may get further feedback.
+
+The BIP editor will:
+
+* Assign a BIP number in the pull request.
+
+* Merge the pull request when it is ready.
+
+* List the BIP in [[README.mediawiki]]
+
+The BIP editors are intended to fulfill administrative and editorial responsibilities. The BIP editors monitor BIP changes, and update BIP headers as appropriate.
+
+BIP editors may also, at their option, unilaterally make and merge strictly-editorial changes to BIPs, such as correcting misspellings, fixing broken links, etc.
+
+==BIP format and structure==
+
+===Specification===
+
+BIPs should be written in mediawiki or markdown format.
+
+Each BIP should have the following parts:
+
+* Preamble -- Headers containing metadata about the BIP ([[#BIP header preamble|see below]]).
+
+* Abstract -- A short (~200 word) description of the technical issue being addressed.
+
+* Copyright -- The BIP must be explicitly licensed under acceptable copyright terms ([[#BIP licensing|see below]]).
+
+* Specification -- The technical specification should describe the syntax and semantics of any new feature. The specification should be detailed enough to allow competing, interoperable implementations for any of the current Bitcoin platforms.
+
+* Motivation -- The motivation is critical for BIPs that want to change the Bitcoin protocol. It should clearly explain why the existing protocol is inadequate to address the problem that the BIP solves.
+
+* Rationale -- The rationale fleshes out the specification by describing what motivated the design and why particular design decisions were made. It should describe alternate designs that were considered and related work. The rationale should provide evidence of consensus within the community and discuss important objections or concerns raised during discussion.
+
+* Backwards compatibility -- All BIPs that introduce backwards incompatibilities must include a section describing these incompatibilities and their severity. The BIP must explain how the author proposes to deal with these incompatibilities.
+
+* Reference implementation -- The reference implementation must be completed before any BIP is given status "Final", but it need not be completed before the BIP is accepted. It is better to finish the specification and rationale first and reach consensus on it before writing code. The final implementation must include test code and documentation appropriate for the Bitcoin protocol.
+
+====BIP header preamble====
+
+Each BIP must begin with an RFC 822 style header preamble. The headers must appear in the following order. Headers marked with "*" are optional and are described below. All other headers are required.
+
+
+
+The Layer header (only for Standards Track BIPs) documents which layer of Bitcoin the BIP applies to.
+See [[bip-0123.mediawiki|BIP 123]] for definitions of the various BIP layers. Activation of this BIP implies activation of BIP 123.
+
+The Author header lists the names and email addresses of all the authors/owners of the BIP.
+The format of the Author header value must be
+
+ Random J. User
+
+If there are multiple authors, each should be on a separate line following RFC 2822 continuation line conventions.
+
+While a BIP is in private discussions (usually during the initial Draft phase), a Discussions-To header will indicate the mailing list or URL where the BIP is being discussed. No Discussions-To header is necessary if the BIP is being discussed privately with the author, or on the bitcoin email mailing lists.
+
+The Type header specifies the type of BIP: Standards Track, Informational, or Process.
+
+The Created header records the date that the BIP was assigned a number, while Post-History is used to record when new versions of the BIP are posted to bitcoin mailing lists.
+Dates should be in yyyy-mm-dd format, e.g. 2001-08-14.
+Post-History is permitted to be a link to a specific thread in a mailing list archive.
+
+BIPs may have a Requires header, indicating the BIP numbers that this BIP depends on.
+
+BIPs may also have a Superseded-By header indicating that a BIP has been rendered obsolete by a later document; the value is the number of the BIP that replaces the current document. The newer BIP must have a Replaces header containing the number of the BIP that it rendered obsolete.
+
+====Auxiliary Files====
+
+BIPs may include auxiliary files such as diagrams. Auxiliary files should be included in a subdirectory for that BIP, or must be named BIP-XXXX-Y.ext, where "XXXX" is the BIP number, "Y" is a serial number (starting at 1), and "ext" is replaced by the actual file extension (e.g. "png").
+
+==BIP types==
+
+There are three kinds of BIP:
+
+* A Standards Track BIP describes any change that affects most or all Bitcoin implementations, such as a change to the network protocol, a change in block or transaction validity rules, or any change or addition that affects the interoperability of applications using Bitcoin. Standards Track BIPs consist of two parts, a design document and a reference implementation.
+* An Informational BIP describes a Bitcoin design issue, or provides general guidelines or information to the Bitcoin community, but does not propose a new feature. Informational BIPs do not necessarily represent a Bitcoin community consensus or recommendation, so users and implementors are free to ignore Informational BIPs or follow their advice.
+* A Process BIP describes a process surrounding Bitcoin, or proposes a change to (or an event in) a process. Process BIPs are like Standards Track BIPs but apply to areas other than the Bitcoin protocol itself. They may propose an implementation, but not to Bitcoin's codebase; they often require community consensus; unlike Informational BIPs, they are more than recommendations, and users are typically not free to ignore them. Examples include procedures, guidelines, changes to the decision-making process, and changes to the tools or environment used in Bitcoin development. Any meta-BIP is also considered a Process BIP.
+
+==BIP status field==
+
+===Specification===
+
+The typical paths of the status of BIPs are as follows:
+
+
+
+Champions of a BIP may decide on their own to change the status between Draft, Deferred, or Withdrawn.
+A BIP editor may also change the status to Deferred when no progress is being made on the BIP.
+
+A BIP may only change status from Draft (or Rejected) to Proposed, when the author deems it is complete, has a working implementation (where applicable), and has community plans to progress it to the Final status.
+
+BIPs should be changed from Draft or Proposed status, to Rejected status, upon request by any person, if they have not made progress in three years. Such a BIP may be changed to Draft status if the champion provides revisions that meaningfully address public criticism of the proposal, or to Proposed status if it meets the criteria required as described in the previous paragraph.
+
+A Proposed BIP may progress to Final only when specific criteria reflecting real-world adoption has occurred. This is different for each BIP depending on the nature of its proposed changes, which will be expanded on below. Evaluation of this status change should be objectively verifiable, and/or be discussed on the development mailing list.
+
+When a Final BIP is no longer relevant, its status may be changed to Replaced or Obsolete (which is equivalent to Replaced). This change must also be objectively verifiable and/or discussed.
+
+A process BIP may change status from Draft to Active when it achieves rough consensus on the mailing list. Such a proposal is said to have rough consensus if it has been open to discussion on the development mailing list for at least one month, and no person maintains any unaddressed substantiated objections to it. Addressed or obstructive objections may be ignored/overruled by general agreement that they have been sufficiently addressed, but clear reasoning must be given in such circumstances.
+
+====Progression to Final status====
+
+A soft-fork BIP strictly requires a clear miner majority expressed by blockchain voting (eg, using BIP 9). In addition, if the economy seems willing to make a "no confidence" hard-fork (such as a change in proof-of-work algorithm), the soft-fork does not become Final for as long as such a hard-fork might have majority support, or at most three months. Soft-fork BIPs may also set additional requirements for their adoption. Because of the possibility of changes to miner dynamics, especially in light of delegated voting (mining pools), it is highly recommended that a supermajority vote around 95% be required by the BIP itself, unless rationale is given for a lower threshold.
+
+A hard-fork BIP requires adoption from the entire Bitcoin economy, particularly including those selling desirable goods and services in exchange for bitcoin payments, as well as Bitcoin holders who wish to spend or would spend their bitcoins (including selling for other currencies) differently in the event of such a hard-fork. Adoption must be expressed by de facto usage of the hard-fork in practice (ie, not merely expressing public support, although that is a good step to establish agreement before adoption of the BIP). This economic adoption cannot be established merely by a super-majority, except by literally forcing the minority to accept the hard-fork (whether this is viable or not is outside the scope of this document).
+
+Peer services BIPs should be observed to be adopted by at least 1% of public listening nodes for one month.
+
+API/RPC and application layer BIPs must be implemented by at least two independent and compatible software applications.
+
+Software authors are encouraged to publish summaries of what BIPs their software supports to aid in verification of status changes. Good examples of this at the time of writing this BIP, can be observed in [https://github.com/bitcoin/bitcoin/blob/master/doc/bips.md Bitcoin Core's doc/bips.md file] as well as [https://github.com/bitcoin-wallet/bitcoin-wallet/blob/master/wallet/README.specs.md Bitcoin Wallet for Android's wallet/README.specs.md file].
+
+These criteria are considered objective ways to observe the de facto adoption of the BIP, and are not to be used as reasons to oppose or reject a BIP. Should a BIP become actually and unambiguously adopted despite not meeting the criteria outlined here, it should still be updated to Final status.
+
+===Rationale===
+
+Why is this necessary at all?
+
+* BIP 1 defines an ambiguous criteria for the Status field of BIPs, which is often a source of confusion. As a result, many BIPs with significant real-world use have been left as Draft or Proposed status longer than appropriate. By giving objective criteria to judge the progression of BIPs, this proposal aims to help keep the Status accurate and up-to-date.
+
+How is the entire Bitcoin economy defined by people selling goods/services and holders?
+
+* For Bitcoin to function as a currency, it must be accepted as payment. Bitcoins have no value if you cannot acquire anything in exchange for them. If everyone accepting such payments requires a particular set of consensus rules, "bitcoins" are de facto defined by that set of rules - this is already the case today. If those consensus rules are expected to broaden (as with a hard-fork), those merchants need to accept payments made under the new set of rules, or they will reject "bitcoins" as invalid. Holders are relevant to the degree in that they choose the merchants they wish to spend their bitcoins with, and could also as a whole decide to sell under one set of consensus rules or the other, thus flooding the market with bitcoins and crashing the price.
+
+Why aren't included in the economy?
+
+* Some entities may, to some degree, also be involved in offering goods and/or services in exchange for bitcoins, thus in that capacity (but not their capacity as ) be involved in the economy.
+* Miners are not included in the economy, because they merely *rely on* others to sell/spend their otherwise-worthless mined produce. Therefore, they must accept everyone else's direction in deciding the consensus rules.
+* Exchanges are not included in the economy, because they merely provide services of connecting the merchants and users who wish to trade. Even if all exchanges were to defect from Bitcoin, those merchants and users can always trade directly and/or establish their own exchanges.
+* Developers are not included in the economy, since they merely write code, and it is up to others to decide to use that code or not.
+
+But they're doing something important and have invested a lot in Bitcoin! Shouldn't they be included in such an important decision?
+
+* This BIP does not aim to address what "should" be the basis of decisions. Such a statement, no matter how perfect in its justification, would be futile without some way to force others to use it. The BIP process does not aim to be a kind of forceful "governance" of Bitcoin, merely to provide a collaborative repository for proposing and providing information on standards, which people may voluntarily adopt or not. It can only hope to achieve accuracy in regard to the "Status" field by striving to reflect the reality of *how things actually are*, rather than *how they should be*.
+
+What if a single merchant wishes to block a hard-fork?
+
+* This BIP addresses only the progression of the BIP Status field, not the deployment of the hard-fork (or any other change) itself.
+* Regardless, one shop cannot operate in a vacuum: if they are indeed alone, they will soon find themselves no longer selling in exchange for bitcoin payments, as nobody else would exist willing to use the previous blockchain to pay them. If they are no longer selling, they cease to meet the criteria herein which enables their veto.
+
+How about a small number of merchants (maybe only two) who sell products to each other?
+
+* In this scenario, it would seem the previous Bitcoin is alive and working, and that the hard-fork has failed. How to resolve such a split is outside the scope of this BIP.
+
+How can economic agreement veto a soft-fork?
+
+* The group of miners is determined by the consensus rules for the dynamic-membership multi-party signature (for Bitcoin, the proof-of-work algorithm), which can be modified with a hard-fork. Thus, if the same conditions required to modify this group are met in opposition to a soft-fork, the miner majority supporting the soft-fork is effectively void because the economy can decide to replace them with another group of would-be miners who do not support the soft-fork.
+
+What happens if the economy decides to hard-fork away from a controversial soft-fork, more than three months later?
+
+* The controversial soft-fork, in this circumstance, changes from Final to Replaced status to reflect the nature of the hard-fork replacing the previous (final) soft-fork.
+
+What is the ideal percentage of listening nodes needed to adopt peer services proposals?
+
+* This is unknown, and set rather arbitrarily at this time. For a random selection of peers to have at least one other peer implementing the extension, 13% or more would be necessary, but nodes could continue to scan the network for such peers with perhaps some reasonable success. Furthermore, service bits exist to help identification upfront.
+
+Why is it necessary for at least two software projects to release an implementation of API/RPC and application layer BIPs, before they become Final?
+
+* If there is only one implementation of a specification, there is no other program for which a standard interface is used with or needed.
+* Even if there are only two projects rather than more, some standard coordination between them exists.
+
+What if a BIP is proposed that only makes sense for a single specific project?
+
+* The BIP process exists for standardisation between independent projects. If something only affects one project, it should be done through that project's own internal processes, and never be proposed as a BIP in the first place.
+
+==BIP comments==
+
+===Specification===
+
+Each BIP should, in its preamble, link to a public wiki page with a summary tone of the comments on that page.
+Reviewers of the BIP who consider themselves qualified, should post their own comments on this wiki page.
+The comments page should generally only be used to post final comments for a completed BIP.
+If a BIP is not yet completed, reviewers should instead post on the applicable development mailing list thread to allow the BIP author(s) to address any concerns or problems pointed out by the review.
+
+Some BIPs receive exposure outside the development community prior to completion, and other BIPs might not be completed at all. To avoid a situation where critical BIP reviews may go unnoticed during this period, reviewers may, at their option, still post their review on the comments page, provided they first post it to the mailing list and plan to later remove or revise it as applicable based on the completed version. Such revisions should be made by editing the previous review and updating the timestamp. Reviews made prior to the complete version may be removed if they are no longer applicable and have not been updated in a timely manner (eg, within one month).
+
+Pages must be named after the full BIP number (eg, "BIP 0001") and placed in the "Comments" namespace.
+For example, the link for BIP 1 will be https://github.com/bitcoin/bips/wiki/Comments:BIP-0001 .
+
+Comments posted to this wiki should use the following format:
+
+ --,
+
+BIPs may also choose to list a second forum for BIP comments, in addition to the BIPs wiki.
+In this case, the second forum's URI should be listed below the primary wiki's URI.
+
+After some time, the BIP itself may be updated with a summary tone of the comments.
+Summary tones may be chosen from the following, but this BIP does not intend to cover all possible nuances and other summaries may be used as needed:
+
+* No comments yet.
+* Unanimously Recommended for implementation
+* Unanimously Discourage for implementation
+* Mostly Recommended for implementation, with some Discouragement
+* Mostly Discouraged for implementation, with some Recommendation
+
+For example, the preamble to BIP 1 might be updated to include the line:
+
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0001
+ https://some-other-wiki.org/BIP_1_Comments
+
+These fields must follow the "Discussions-To" header defined in BIP 1 (if that header is not present, it should follow the position where it would be present; generally this is immediately above the Status header).
+
+To avoid doubt: comments and status are unrelated metrics to judge a BIP, and neither should be directly influencing the other.
+
+===Rationale===
+
+What is the purpose of BIP comments?
+
+* Various BIPs have been adopted (the criteria required for "Final" Status) despite being considered generally inadvisable. Some presently regard BIPs as a "good idea" simply by virtue of them being assigned a BIP number. Due to the low barrier of entry for submission of new BIPs, it seems advisable for a way for reviewers to express their opinions on them in a way that is consumable to the public without needing to review the entire development discussion.
+
+Will BIP comments be censored or limited to particular participants/"experts"?
+
+* Participants should freely refrain from commenting outside of their area of knowledge or expertise. However, comments should not be censored, and participation should be open to the public.
+
+==BIP licensing==
+
+===Specification===
+
+New BIPs may be accepted with the following licenses. Each new BIP must identify at least one acceptable license in its preamble. The License header in the preamble must be placed after the Created header. Each license must be referenced by their respective abbreviation given below.
+
+For example, a preamble might include the following License header:
+
+ License: BSD-2-Clause
+ GNU-All-Permissive
+
+In this case, the BIP text is fully licensed under both the OSI-approved BSD 2-clause license as well as the GNU All-Permissive License, and anyone may modify and redistribute the text provided they comply with the terms of *either* license. In other words, the license list is an "OR choice", not an "AND also" requirement.
+
+It is also possible to license source code differently from the BIP text. An optional License-Code header is placed after the License header. Again, each license must be referenced by their respective abbreviation given below.
+
+For example, a preamble specifying the optional License-Code header might look like:
+
+ License: BSD-2-Clause
+ GNU-All-Permissive
+ License-Code: GPL-2.0+
+
+In this case, the code in the BIP is not available under the BSD or All-Permissive licenses, but only under the terms of the GNU General Public License (GPL), version 2 or newer.
+If the code were to be available under *only* version 2 exactly, the "+" symbol should be removed from the license abbreviation.
+For a later version (eg, GPL 3.0), you would increase the version number (and retain or remove the "+" depending on intent).
+
+ License-Code: GPL-2.0 # This refers to GPL v2.0 *only*, no later license versions are acceptable.
+ License-Code: GPL-2.0+ # This refers to GPL v2.0 *or later*.
+ License-Code: GPL-3.0 # This refers to GPL v3.0 *only*, no later license versions are acceptable.
+ License-Code: GPL-3.0+ # This refers to GPL v3.0 *or later*.
+
+In the event that the licensing for the text or code is too complicated to express with a simple list of alternatives, the list should instead be replaced with the single term "Complex". In all cases, details of the licensing terms must be provided in the Copyright section of the BIP.
+
+BIPs are not required to be *exclusively* licensed under approved terms, and may also be licensed under unacceptable licenses *in addition to* at least one acceptable license.
+In this case, only the acceptable license(s) should be listed in the License and License-Code headers.
+
+====Recommended licenses====
+
+* BSD-2-Clause: [https://opensource.org/licenses/BSD-2-Clause OSI-approved BSD 2-clause license]
+* BSD-3-Clause: [https://opensource.org/licenses/BSD-3-Clause OSI-approved BSD 3-clause license]
+* CC0-1.0: [https://creativecommons.org/publicdomain/zero/1.0/ Creative Commons CC0 1.0 Universal]
+* GNU-All-Permissive: [https://www.gnu.org/prep/maintain/html_node/License-Notices-for-Other-Files.html GNU All-Permissive License]
+
+In addition, it is recommended that literal code included in the BIP be dual-licensed under the same license terms as the project it modifies. For example, literal code intended for Bitcoin Core would ideally be dual-licensed under the MIT license terms as well as one of the above with the rest of the BIP text.
+
+====Not recommended, but acceptable licenses====
+
+* Apache-2.0: [https://www.apache.org/licenses/LICENSE-2.0 Apache License, version 2.0]
+* BSL-1.0: [https://www.boost.org/LICENSE_1_0.txt Boost Software License, version 1.0]
+* CC-BY-4.0: [https://creativecommons.org/licenses/by/4.0/ Creative Commons Attribution 4.0 International]
+* CC-BY-SA-4.0: [https://creativecommons.org/licenses/by-sa/4.0/ Creative Commons Attribution-ShareAlike 4.0 International]
+* MIT: [https://opensource.org/licenses/MIT Expat/MIT/X11 license]
+* AGPL-3.0+: [https://www.gnu.org/licenses/agpl-3.0.en.html GNU Affero General Public License (AGPL), version 3 or newer]
+* FDL-1.3: [https://www.gnu.org/licenses/fdl-1.3.en.html GNU Free Documentation License, version 1.3]
+* GPL-2.0+: [https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html GNU General Public License (GPL), version 2 or newer]
+* LGPL-2.1+: [https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html GNU Lesser General Public License (LGPL), version 2.1 or newer]
+
+====Not acceptable licenses====
+
+All licenses not explicitly included in the above lists are not acceptable terms for a Bitcoin Improvement Proposal unless a later BIP extends this one to add them.
+However, BIPs predating the acceptance of this BIP were allowed under other terms, and should use these abbreviation when no other license is granted:
+
+* OPL: [https://opencontent.org/openpub/ Open Publication License, version 1.0]
+* PD: Released into the public domain
+
+===Rationale===
+
+BIP 1 allowed the Open Publication License or releasing into the public domain; was this insufficient?
+
+* The OPL is generally regarded as obsolete, and not a license suitable for new publications.
+* Many are unfamiliar with the OPL terms, and may just prefer to use the public domain rather than license under uncertain terms.
+* The OPL license terms allowed for the author to prevent publication and derived works, which was widely considered inappropriate for Bitcoin standards.
+* Public domain is not universally recognised as a legitimate action, thus it is inadvisable.
+
+Why are there software licenses included?
+
+* Some BIPs, especially consensus layer, may include literal code in the BIP itself which may not be available under the exact license terms of the BIP.
+* Despite this, not all software licenses would be acceptable for content included in BIPs.
+
+Why is Public Domain no longer acceptable for new BIPs?
+
+* In some jurisdictions, public domain is not recognised as a legitimate legal action, leaving the BIP simply copyrighted with no redistribution or modification allowed at all.
+
+==Changes from BIP 1==
+
+* Acceptable licenses are entirely rechosen, allowing a wide variety of open licenses, while prohibiting the problematic older choices.
+* Accepted Status has been renamed to Proposed.
+* An implementation is now required (when applicable) before BIPs can proceed to Proposed Status.
+* BIP Comments are newly introduced.
+* The License preamble headers have been added.
+* The Layer header is included from BIP 123.
+* Non-image auxiliary files are permitted in the bip-XXXX subdirectory.
+* Email addresses are now required for authors.
+* The Post-History header may be provided as a link instead of a simple date.
+* The Resolution header has been dropped, as it is not applicable to a decentralised system where no authority exists to make final decisions.
+
+==See Also==
+
+* [[bip-0001.mediawiki|BIP 1: BIP Purpose and Guidelines]]
+* [[bip-0123.mediawiki|BIP 123: BIP Classification]]
+* [https://tools.ietf.org/html/rfc7282 RFC 7282: On Consensus and Humming in the IETF]
diff --git a/bip-0002/process.png b/bip-0002/process.png
new file mode 100644
index 0000000000..b532799011
Binary files /dev/null and b/bip-0002/process.png differ
diff --git a/bip-0002/process.svg b/bip-0002/process.svg
new file mode 100644
index 0000000000..7bfbe7a53e
--- /dev/null
+++ b/bip-0002/process.svg
@@ -0,0 +1,53 @@
+
diff --git a/bip-0008.mediawiki b/bip-0008.mediawiki
new file mode 100644
index 0000000000..d357401827
--- /dev/null
+++ b/bip-0008.mediawiki
@@ -0,0 +1,280 @@
+
+ BIP: 8
+ Title: Version bits with lock-in by height
+ Author: Shaolin Fry
+ Luke Dashjr
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0008
+ Status: Draft
+ Type: Informational
+ Created: 2017-02-01
+ License: BSD-3-Clause
+ CC0-1.0
+
+
+==Abstract==
+
+This document specifies an alternative to [[bip-0009.mediawiki|BIP9]] that corrects for a number of perceived mistakes.
+Block heights are used for start and timeout rather than POSIX timestamps.
+It additionally introduces an activation parameter that can guarantee activation of backward-compatible changes (further called "soft forks").
+
+The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.
+
+==Motivation==
+
+BIP9 introduced a mechanism for doing parallel soft forking deployments based on repurposing the block nVersion field. Activation is dependent on near unanimous hashrate signalling which may be impractical and result in veto by a small minority of non-signalling hashrate. Super majority hashrate based activation triggers allow for accelerated activation where the majority hash power enforces the new rules in lieu of full nodes upgrading. Since all consensus rules are ultimately enforced by full nodes, eventually any new soft fork will be enforced by the economy. This proposal combines these two aspects to provide optional flag day activation after a reasonable time, as well as for accelerated activation by majority of hash rate before the flag date.
+
+Due to using timestamps rather than block heights, it was found to be a risk that a sudden loss of significant hashrate could interfere with a late activation.
+
+Block time is somewhat unreliable and may be intentionally or unintentionally inaccurate, so thresholds based on block time are not ideal. Secondly, BIP9 specified triggers based on the first retarget after a given time, which is non-intuitive. Since each new block must increase the height by one, thresholds based on block height are much more reliable and intuitive and can be calculated exactly for difficulty retarget.
+
+==Specification==
+
+===Parameters===
+
+Each soft fork deployment is specified by the following per-chain parameters (further elaborated below):
+
+# The '''name''' specifies a very brief description of the soft fork, reasonable for use as an identifier.
+# The '''bit''' determines which bit in the nVersion field of the block is to be used to signal the soft fork lock-in and activation. It is chosen from the set {0,1,2,...,28}.
+# The '''startheight''' specifies the height of the first block at which the bit gains its meaning.
+# The '''timeoutheight''' specifies a block height at which the miner signalling ends. Once this height has been reached, if the soft fork has not yet locked in (excluding this block's bit state), the deployment is considered failed on all descendants of the block.
+# The '''threshold''' specifies the minimum number of block per retarget period which indicate lock-in of the soft fork during the subsequent period.
+# The '''minimum_activation_height''' specifies the height of the first block at which the soft fork is allowed to become active.
+# The '''lockinontimeout''' boolean if set to true, blocks are required to signal in the final period, ensuring the soft fork has locked in by timeoutheight.
+
+===Selection guidelines===
+
+The following guidelines are suggested for selecting these parameters for a soft fork:
+
+# '''name''' should be selected such that no two softforks, concurrent or otherwise, ever use the same name. For deployments described in a single BIP, it is recommended to use the name "bipN" where N is the appropriate BIP number.
+# '''bit''' should be selected such that no two concurrent softforks use the same bit. The bit chosen should not overlap with active usage (legitimately or otherwise) for other purposes.
+# '''startheight''' should be set to some block height in the future. If '''minimum_activation_height''' is not going to be set, then '''startheight''' should be set to a height when a majority of economic activity is expected to have upgraded to software including the activation parameters. Some allowance should be made for potential release delays. If '''minimum_activation_height''' is going to be set, then '''startheight''' can be set to be soon after software with parameters is expected to be released. This shifts the time for upgrading from before signaling begins to during the LOCKED_IN state.
+# '''timeoutheight''' should be set to a block height when it is considered reasonable to expect the entire economy to have upgraded by, probably at least 1 year, or 52416 blocks (26 retarget intervals) after '''startheight'''.
+# '''threshold''' should be 1815 blocks (90% of 2016), or 1512 (75%) for testnet.
+# '''minimum_activation_height''' should be set to several retarget periods in the future if the '''startheight''' is to be very soon after software with parameters is expected to be released. '''minimum_activation_height''' should be set to a height when a majority of economic activity is expected to have upgraded to software including the activation parameters. This allows more time to be spent in the LOCKED_IN state so that nodes can upgrade. This may be set to 0 to have the LOCKED_IN state be a single retarget period.
+# '''lockinontimeout''' should be set to true for any softfork that is expected or found to have political opposition from a non-negligible percent of miners. (It can be set after the initial deployment, but cannot be cleared once set.)
+
+A later deployment using the same bit is possible as long as the startheight is after the previous one's
+timeoutheight or activation, but it is discouraged until necessary, and even then recommended to have a pause in between to detect buggy software.
+
+'''startheight''', '''timeoutheight''', and '''minimum_activation_height''' must be an exact multiple of 2016 (ie, at a retarget boundary), and '''timeoutheight''' must be at least 4032 blocks (2 retarget intervals) after '''startheight'''.
+
+===States===
+
+With each block and soft fork, we associate a deployment state. The possible states are:
+
+# '''DEFINED''' is the first state that each soft fork starts out as. The genesis block is by definition in this state for each deployment.
+# '''STARTED''' for blocks at or beyond the startheight.
+# '''MUST_SIGNAL''' for one retarget period prior to the timeout, if LOCKED_IN was not reached and '''lockinontimeout''' is true.
+# '''LOCKED_IN''' for at least one retarget period after the first retarget period with STARTED (or MUST_SIGNAL) blocks of which at least threshold have the associated bit set in nVersion. A soft fork remains in LOCKED_IN until at least '''minimum_activation_height''' is reached.
+# '''ACTIVE''' for all blocks after the LOCKED_IN state.
+# '''FAILED''' for all blocks after the timeoutheight if LOCKED_IN is not reached.
+
+===Bit flags===
+
+The nVersion block header field is to be interpreted as a 32-bit little-endian integer (as present), and bits are selected within this integer as values (1 << N) where N is the bit number.
+
+Blocks in the STARTED state get an nVersion whose bit position bit is set to 1. The top 3 bits of such blocks must be
+001, so the range of actually possible nVersion values is [0x20000000...0x3FFFFFFF], inclusive.
+
+Due to the constraints set by BIP 34, BIP 66 and BIP 65, we only have 0x7FFFFFFB possible nVersion values available.
+This restricts us to at most 30 independent deployments. By restricting the top 3 bits to 001 we get 29 out of those
+for the purposes of this proposal, and support two future upgrades for different mechanisms (top bits 010 and 011).
+When a block nVersion does not have top bits 001, it is treated as if all
+bits are 0 for the purposes of deployments.
+
+Miners should continue setting the bit in LOCKED_IN phase so uptake is visible, though this has no effect on consensus rules.
+
+===New consensus rules===
+
+The new consensus rules for each soft fork are enforced for each block that has ACTIVE state.
+
+During the MUST_SIGNAL phase, if '''(2016 - threshold)''' blocks in the retarget period have already failed to signal, any further blocks that fail to signal are invalid.
+
+===State transitions===
+
+
+
+Note that when '''lockinontimeout''' is true, the LOCKED_IN state will be reached no later than at a height of '''timeoutheight'''.
+Regardless of the value of '''lockinontimeout''', if LOCKED_IN is reached, ACTIVE will be reached either one retarget period later, or at '''minimum_activation_height''', whichever comes later.
+
+The genesis block has state DEFINED for each deployment, by definition.
+
+ State GetStateForBlock(block) {
+ if (block.height == 0) {
+ return DEFINED;
+ }
+
+All blocks within a retarget period have the same state. This means that if
+floor(block1.height / 2016) = floor(block2.height / 2016), they are guaranteed to have the same state for every
+deployment.
+
+ if ((block.height % 2016) != 0) {
+ return GetStateForBlock(block.parent);
+ }
+
+Otherwise, the next state depends on the previous state:
+
+ switch (GetStateForBlock(GetAncestorAtHeight(block, block.height - 2016))) {
+
+We remain in the initial state until we reach the start block height.
+
+ case DEFINED:
+ if (block.height >= startheight) {
+ return STARTED;
+ }
+ return DEFINED;
+
+After a period in the STARTED state, we tally the bits set,
+and transition to LOCKED_IN if a sufficient number of blocks in the past period set the deployment bit in their
+version numbers.
+If the threshold hasn't been met, lockinontimeout is true, and we are at the last period before the timeout, then we transition to MUST_SIGNAL.
+If the threshold hasn't been met and we reach the timeout, we transition directly to FAILED.
+
+Note that a block's state never depends on its own nVersion; only on that of its ancestors.
+
+ case STARTED:
+ int count = 0;
+ walk = block;
+ for (i = 0; i < 2016; i++) {
+ walk = walk.parent;
+ if (walk.nVersion & 0xE0000000 == 0x20000000 && (walk.nVersion >> bit) & 1 == 1) {
+ ++count;
+ }
+ }
+ if (count >= threshold) {
+ return LOCKED_IN;
+ } else if (lockinontimeout && block.height + 2016 >= timeoutheight) {
+ return MUST_SIGNAL;
+ } else if (block.height >= timeoutheight) {
+ return FAILED;
+ }
+ return STARTED;
+
+If we have finished a period of MUST_SIGNAL, we transition directly to LOCKED_IN.
+
+ case MUST_SIGNAL:
+ return LOCKED_IN;
+
+After at least one retarget period of LOCKED_IN, we automatically transition to ACTIVE if the minimum activation height is reached. Otherwise LOCKED_IN continues.
+
+ case LOCKED_IN:
+ if (block.height >= minimum_activation_height) {
+ return ACTIVE;
+ } else {
+ return LOCKED_IN;
+ }
+
+And ACTIVE and FAILED are terminal states, which a deployment stays in once they're reached.
+
+ case ACTIVE:
+ return ACTIVE;
+
+ case FAILED:
+ return FAILED;
+ }
+ }
+
+'''Implementation'''
+It should be noted that the states are maintained along block chain
+branches, but may need recomputation when a reorganization happens.
+
+Given that the state for a specific block/deployment combination is completely determined by its ancestry before the
+current retarget period (i.e. up to and including its ancestor with height block.height - 1 - (block.height % 2016)),
+it is possible to implement the mechanism above efficiently and safely by caching the resulting state of every multiple-of-2016
+block, indexed by its parent.
+
+===Mandatory signalling===
+
+Blocks received while in the MUST_SIGNAL phase must be checked to ensure that they signal as required. For example:
+
+ if (GetStateForBlock(block) == MUST_SIGNAL) {
+ int nonsignal = 0;
+ walk = block;
+ while (true) {
+ if ((walk.nVersion & 0xE0000000) != 0x20000000 || ((walk.nVersion >> bit) & 1) != 1) {
+ ++nonsignal;
+ if (nonsignal > 2016 - threshold) {
+ return state.Invalid(BlockValidationResult::RECENT_CONSENSUS_CHANGE, "bad-version-bip8-must-signal");
+ }
+ }
+ if (walk.nHeight % 2016 == 0) {
+ // checked every block in this retarget period
+ break;
+ }
+ walk = walk.parent;
+ }
+ }
+
+Implementations should be careful not to ban peers that send blocks that are invalid due to not signalling (or blocks that build on those blocks), as that would allow an incompatible chain that is only briefly longer than the compliant chain to cause a split of the p2p network. If that occurred, nodes that have not set ''lockinontimeout'' may not see new blocks in the compliant chain, and thus not reorg to it at the point when it has more work, and would thus not be following the valid chain with the most work.
+
+Implementations with ''lockinontimeout'' set to true may potentially follow a lower work chain than nodes with ''lockinontimeout'' set to false for an extended period. In order for this not to result in a net split nodes with ''lockinontimeout'' set to true, those nodes may need to preferentially connect to each other. Deployments proposing that implementations set ''lockinontimeout'' to true should either use parameters that do not risk there being a higher work alternative chain, or specify a mechanism for implementations that support the deployment to preferentially peer with each other.
+
+===Warning mechanism===
+
+To support upgrade warnings, an extra "unknown upgrade" is tracked, using the "implicit bit" mask = (block.nVersion & ~expectedVersion) != 0. Mask will be non-zero whenever an unexpected bit is set in nVersion. Whenever LOCKED_IN for the unknown upgrade is detected, the software should warn loudly about the upcoming soft fork. It should warn even more loudly after the next retarget period (when the unknown upgrade is in the ACTIVE state).
+
+===getblocktemplate changes===
+
+The template request Object is extended to include a new item:
+
+{| class="wikitable"
+!colspan=4| template request
+|-
+! Key !! Required !! Type !! Description
+|-
+| rules || No || Array of Strings || list of supported softfork deployments, by name
+|}
+
+The template Object is also extended:
+
+{| class="wikitable"
+!colspan=4| template
+|-
+! Key !! Required !! Type !! Description
+|-
+| rules || Yes || Array of Strings || list of softfork deployments, by name, that are active state
+|-
+| vbavailable || Yes || Object || set of pending, supported softfork deployments; each uses the softfork name as the key, and the softfork bit as its value
+|-
+| vbrequired || No || Number || bit mask of softfork deployment version bits the server requires enabled in submissions
+|}
+
+The "version" key of the template is retained, and used to indicate the server's preference of deployments.
+If versionbits is being used, "version" MUST be within the versionbits range of [0x20000000...0x3FFFFFFF].
+Miners MAY clear or set bits in the block version WITHOUT any special "mutable" key, provided they are listed among the template's "vbavailable" and (when clearing is desired) NOT included as a bit in "vbrequired".
+Servers MUST set bits in "vbrequired" for deployments in MUST_SIGNAL state, to ensure blocks produced are valid.
+
+Softfork deployment names listed in "rules" or as keys in "vbavailable" may be prefixed by a '!' character.
+Without this prefix, GBT clients may assume the rule will not impact usage of the template as-is; typical examples of this would be when previously valid transactions cease to be valid, such as BIPs 16, 65, 66, 68, 112, and 113.
+If a client does not understand a rule without the prefix, it may use it unmodified for mining.
+On the other hand, when this prefix is used, it indicates a more subtle change to the block structure or generation transaction; examples of this would be BIP 34 (because it modifies coinbase construction) and 141 (since it modifies the txid hashing and adds a commitment to the generation transaction).
+A client that does not understand a rule prefixed by '!' must not attempt to process the template, and must not attempt to use it for mining even unmodified.
+
+=== Reference implementation ===
+
+https://github.com/bitcoin/bitcoin/compare/master...luke-jr:bip8
+
+==Contrasted with BIP 9==
+
+* The '''lockinontimeout''' flag is added, providing a way to guarantee transition to LOCKED_IN.
+* Block heights are used for the deployment monotonic clock, rather than median-time-past.
+
+==Backwards compatibility==
+
+BIP8 and BIP9 deployments should not share concurrent active deployment bits. Nodes that only implement BIP9 will not activate a BIP8 soft fork if hashpower threshold is not reached by '''timeoutheight''', however, those nodes will still accept the blocks generated by activated nodes.
+
+==Deployments==
+
+A living list of deployment proposals can be found [[bip-0008/assignments.mediawiki|here]].
+
+==References==
+
+[[bip-0009.mediawiki|BIP9]]
+
+[https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2017-February/013643.html Mailing list discussion]
+
+==Copyright==
+
+This document is dual licensed as BSD 3-clause, and Creative Commons CC0 1.0 Universal.
+
diff --git a/bip-0008/assignments.mediawiki b/bip-0008/assignments.mediawiki
new file mode 100644
index 0000000000..c18751b69c
--- /dev/null
+++ b/bip-0008/assignments.mediawiki
@@ -0,0 +1,6 @@
+==Deployments==
+
+List of deployments.
+
+State can be defined, active, failed. Dates are in UTC.
+
diff --git a/bip-0008/states.dot b/bip-0008/states.dot
new file mode 100644
index 0000000000..8615978769
--- /dev/null
+++ b/bip-0008/states.dot
@@ -0,0 +1,35 @@
+digraph {
+ rankdir=TD;
+
+ node [style="rounded,filled,bold", shape=box, fixedsize=true, width=1.5, fontname="Arial"];
+
+ edge [weight = 100];
+ "DEFINED" -> "STARTED" [label="height >= start_height"];
+ "STARTED" -> "MUST_SIGNAL" [label="height + 2016 >= timeoutheight AND lockinontimeout"];
+ "STARTED" -> "FAILED" [label="height >= timeoutheight\nAND\nNOT lockinontimeout"];
+ "LOCKED_IN" -> "ACTIVE" [label="height >= minimum_activation_height"];
+ "LOCKED_IN":se -> "LOCKED_IN":ne [label="height < minimum_activation_height"];
+ "MUST_SIGNAL" -> "LOCKED_IN" [label="always"];
+
+ edge [weight = 1];
+ "STARTED" -> "LOCKED_IN" [label="height < timeoutheight\nAND\nthreshold reached"];
+
+ "FAILED" -> "LOCKED_IN" [style=invis];
+
+ "DEFINED":sw -> "DEFINED":nw;
+ "STARTED":sw -> "STARTED":nw;
+ "ACTIVE":sw -> "ACTIVE":nw;
+ "FAILED":sw -> "FAILED":nw;
+
+ "STARTED" [fillcolor="#a0a0ff"];
+ "MUST_SIGNAL" [fillcolor="#a0a0ff"];
+ "LOCKED_IN" [fillcolor="#ffffa0"];
+ "ACTIVE" [fillcolor="#a0ffa0"];
+ "FAILED" [fillcolor="#ffa0a0"];
+
+ { rank=same; "STARTED" "MUST_SIGNAL" }
+ { rank=same; "FAILED" "LOCKED_IN" }
+ { rank=sink; "ACTIVE" }
+}
+
+
diff --git a/bip-0008/states.png b/bip-0008/states.png
new file mode 100644
index 0000000000..f15efdbc17
Binary files /dev/null and b/bip-0008/states.png differ
diff --git a/bip-0008/states.svg b/bip-0008/states.svg
new file mode 100644
index 0000000000..63fe634d8e
--- /dev/null
+++ b/bip-0008/states.svg
@@ -0,0 +1,126 @@
+
+
+
+
+
diff --git a/bip-0009.mediawiki b/bip-0009.mediawiki
index b160810f06..1883562dba 100644
--- a/bip-0009.mediawiki
+++ b/bip-0009.mediawiki
@@ -1,10 +1,16 @@
BIP: 9
Title: Version bits with timeout and delay
- Author: Pieter Wuille , Peter Todd , Greg Maxwell , Rusty Russell
- Status: Draft
- Type: Informational Track
+ Author: Pieter Wuille
+ Peter Todd
+ Greg Maxwell
+ Rusty Russell
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0009
+ Status: Final
+ Type: Informational
Created: 2015-10-04
+ License: PD
==Abstract==
@@ -13,137 +19,193 @@ This document specifies a proposed change to the semantics of the 'version' fiel
==Motivation==
-BIP 34 introduced a mechanism for doing soft-forking changes without a predefined flag timestamp (or flag block height), instead relying on measuring miner support indicated by a higher version number in block headers. As it relies on comparing version numbers as integers however, it only supports one single change being rolled out at once, requiring coordination between proposals, and does not allow for permanent rejection: as long as one soft fork is not fully rolled out, no future one can be scheduled.
+[[bip-0034.mediawiki|BIP 34]] introduced a mechanism for doing soft-forking changes without a predefined flag timestamp (or flag block height), instead relying on measuring miner support indicated by a higher version number in block headers. As it relies on comparing version numbers as integers however, it only supports one single change being rolled out at once, requiring coordination between proposals, and does not allow for permanent rejection: as long as one soft fork is not fully rolled out, no future one can be scheduled.
-In addition, BIP 34 made the integer comparison (nVersion >= 2) a consensus rule after its 95% threshold was reached, removing 231+2 values from the set of valid version numbers (all negative numbers, as nVersion is interpreted as a signed integer, as well as 0 and 1). This indicates another downside this approach: every upgrade permanently restricts the set of allowed nVersion field values. This approach was later reused in BIP 66, which further removed nVersion = 2 as valid option. As will be shown further, this is unnecessary.
+In addition, BIP 34 made the integer comparison (nVersion >= 2) a consensus rule after its 95% threshold was reached, removing 231+2 values from the set of valid version numbers (all negative numbers, as nVersion is interpreted as a signed integer, as well as 0 and 1). This indicates another downside this approach: every upgrade permanently restricts the set of allowed nVersion field values. This approach was later reused in [[bip-0066.mediawiki|BIP 66]] and [[bip-0065.mediawiki|BIP 65]], which further removed nVersions 2 and 3 as valid options. As will be shown further, this is unnecessary.
==Specification==
-===Mechanism===
+Each soft fork deployment is specified by the following per-chain parameters (further elaborated below):
-'''Bit flags'''
-We are permitting several independent soft forks to be deployed in parallel. For each, a bit B is chosen from the set {0,1,2,...,28}, which is not currently in use for any other ongoing soft fork. Miners signal intent to enforce the new rules associated with the proposed soft fork by setting bit 1B in nVersion to 1 in their blocks.
+# The '''name''' specifies a very brief description of the soft fork, reasonable for use as an identifier. For deployments described in a single BIP, it is recommended to use the name "bipN" where N is the appropriate BIP number.
+# The '''bit''' determines which bit in the nVersion field of the block is to be used to signal the soft fork lock-in and activation. It is chosen from the set {0,1,2,...,28}.
+# The '''starttime''' specifies a minimum median time past of a block at which the bit gains its meaning.
+# The '''timeout''' specifies a time at which the deployment is considered failed. If the median time past of a block >= timeout and the soft fork has not yet locked in (including this block's bit state), the deployment is considered failed on all descendants of the block.
-'''High bits'''
-The highest 3 bits are set to 001, so the range of actually possible nVersion values is [0x20000000...0x3FFFFFFF], inclusive. This leaves two future upgrades for different mechanisms (top bits 010 and 011), while complying to the constraints set by BIP34 and BIP66. Having more than 29 available bits for parallel soft forks does not add anything anyway, as the (nVersion >= 3) requirement already makes that impossible.
+===Selection guidelines===
-'''States'''
-With every softfork proposal we associate a state BState, which begins
-at ''defined'', and can be ''locked-in'', ''activated'',
-or ''failed''. Transitions are considered after each
-retarget period.
+The following guidelines are suggested for selecting these parameters for a soft fork:
-'''Soft Fork Support'''
-Software which supports the change should begin by setting B in all blocks
-mined until it is resolved.
+# '''name''' should be selected such that no two softforks, concurrent or otherwise, ever use the same name.
+# '''bit''' should be selected such that no two concurrent softforks use the same bit.
+# '''starttime''' should be set to some date in the future, approximately one month after a software release date including the soft fork. This allows for some release delays, while preventing triggers as a result of parties running pre-release software.
+# '''timeout''' should be 1 year (31536000 seconds) after starttime.
- if (BState != activated && BState != failed) {
- SetBInBlock();
- }
+A later deployment using the same bit is possible as long as the starttime is after the previous one's
+timeout or activation, but it is discouraged until necessary, and even then recommended to have a pause in between to detect buggy software.
+
+===States===
+
+With each block and soft fork, we associate a deployment state. The possible states are:
+
+# '''DEFINED''' is the first state that each soft fork starts out as. The genesis block is by definition in this state for each deployment.
+# '''STARTED''' for blocks past the starttime.
+# '''LOCKED_IN''' for one retarget period after the first retarget period with STARTED blocks of which at least threshold have the associated bit set in nVersion.
+# '''ACTIVE''' for all blocks after the LOCKED_IN retarget period.
+# '''FAILED''' for one retarget period past the timeout time, if LOCKED_IN was not reached.
+
+===Bit flags===
+
+The nVersion block header field is to be interpreted as a 32-bit little-endian integer (as present), and bits are selected within this integer as values (1 << N) where N is the bit number.
+
+Blocks in the STARTED state get an nVersion whose bit position bit is set to 1. The top 3 bits of such blocks must be
+001, so the range of actually possible nVersion values is [0x20000000...0x3FFFFFFF], inclusive.
+
+Due to the constraints set by BIP 34, BIP 66 and BIP 65, we only have 0x7FFFFFFB possible nVersion values available.
+This restricts us to at most 30 independent deployments. By restricting the top 3 bits to 001 we get 29 out of those
+for the purposes of this proposal, and support two future upgrades for different mechanisms (top bits 010 and 011).
+When a block nVersion does not have top bits 001, it is treated as if all
+bits are 0 for the purposes of deployments.
+
+Miners should continue setting the bit in LOCKED_IN phase so uptake is visible, though this has no effect on
+consensus rules.
+
+===New consensus rules===
-'''Success: Lock-in Threshold'''
-If bit B is set in 1916 (1512 on testnet) or
-more of the 2016 blocks within a retarget period, it is considered
-''locked-in''. Miners should continue setting bit B, so uptake is
-visible.
+The new consensus rules for each soft fork are enforced for each block that has ACTIVE state.
- if (NextBlockHeight % 2016 == 0) {
- if (BState == defined && Previous2016BlocksCountB() >= 1916) {
- BState = locked-in;
- BActiveHeight = NextBlockHeight + 2016;
+===State transitions===
+
+
+
+The genesis block has state DEFINED for each deployment, by definition.
+
+ State GetStateForBlock(block) {
+ if (block.height == 0) {
+ return DEFINED;
+ }
+
+All blocks within a retarget period have the same state. This means that if
+floor(block1.height / 2016) = floor(block2.height / 2016), they are guaranteed to have the same state for every
+deployment.
+
+ if ((block.height % 2016) != 0) {
+ return GetStateForBlock(block.parent);
+ }
+
+Otherwise, the next state depends on the previous state:
+
+ switch (GetStateForBlock(GetAncestorAtHeight(block, block.height - 2016))) {
+
+We remain in the initial state until either we pass the start time or the timeout. GetMedianTimePast in the code below
+refers to the median nTime of a block and its 10 predecessors. The expression GetMedianTimePast(block.parent) is
+referred to as MTP in the diagram above, and is treated as a monotonic clock defined by the chain.
+
+ case DEFINED:
+ if (GetMedianTimePast(block.parent) >= timeout) {
+ return FAILED;
+ }
+ if (GetMedianTimePast(block.parent) >= starttime) {
+ return STARTED;
+ }
+ return DEFINED;
+
+After a period in the STARTED state, if we're past the timeout, we switch to FAILED. If not, we tally the bits set,
+and transition to LOCKED_IN if a sufficient number of blocks in the past period set the deployment bit in their
+version numbers. The threshold is ≥1916 blocks (95% of 2016), or ≥1512 for testnet (75% of 2016).
+The transition to FAILED takes precedence, as otherwise an ambiguity can arise.
+There could be two non-overlapping deployments on the same bit, where the first one transitions to LOCKED_IN while the
+other one simultaneously transitions to STARTED, which would mean both would demand setting the bit.
+
+Note that a block's state never depends on its own nVersion; only on that of its ancestors.
+
+ case STARTED:
+ if (GetMedianTimePast(block.parent) >= timeout) {
+ return FAILED;
+ }
+ int count = 0;
+ walk = block;
+ for (i = 0; i < 2016; i++) {
+ walk = walk.parent;
+ if (walk.nVersion & 0xE0000000 == 0x20000000 && (walk.nVersion >> bit) & 1 == 1) {
+ count++;
+ }
+ }
+ if (count >= threshold) {
+ return LOCKED_IN;
+ }
+ return STARTED;
+
+After a retarget period of LOCKED_IN, we automatically transition to ACTIVE.
+
+ case LOCKED_IN:
+ return ACTIVE;
+
+And ACTIVE and FAILED are terminal states, which a deployment stays in once they're reached.
+
+ case ACTIVE:
+ return ACTIVE;
+
+ case FAILED:
+ return FAILED;
}
}
-'''Success: Activation Delay'''
-The consensus rules related to ''locked-in'' soft fork will be enforced in
-the second retarget period; ie. there is a one retarget period in
-which the remaining 5% can upgrade. At the that activation block and
-after, miners should stop setting bit B, which may be reused for a different soft fork.
-
- if (BState == locked-in && NextBlockHeight == BActiveHeight) {
- BState = activated;
- ApplyRulesForBFromNextBlock();
- /* B can be reused, immediately */
- }
-
-'''Failure: Timeout'''
-A soft fork proposal should include a ''timeout''. This is measured
-as the beginning of a calendar year as per this table (suggest
-adding three to the current calendar year when drafting the soft fork proposal):
-
-{|
-! Timeout Year
-! >= Seconds
-! Timeout Year
-! >= Seconds
-|-
-|2018
-|1514764800
-|2026
-|1767225600
-|-
-|2019
-|1546300800
-|2027
-|1798761600
+'''Implementation'''
+It should be noted that the states are maintained along block chain
+branches, but may need recomputation when a reorganization happens.
+
+Given that the state for a specific block/deployment combination is completely determined by its ancestry before the
+current retarget period (i.e. up to and including its ancestor with height block.height - 1 - (block.height % 2016)),
+it is possible to implement the mechanism above efficiently and safely by caching the resulting state of every multiple-of-2016
+block, indexed by its parent.
+
+===Warning mechanism===
+
+To support upgrade warnings, an extra "unknown upgrade" is tracked, using the "implicit bit" mask = (block.nVersion & ~expectedVersion) != 0. Mask will be non-zero whenever an unexpected bit is set in nVersion. Whenever LOCKED_IN for the unknown upgrade is detected, the software should warn loudly about the upcoming soft fork. It should warn even more loudly after the next retarget period (when the unknown upgrade is in the ACTIVE state).
+
+===getblocktemplate changes===
+
+The template request Object is extended to include a new item:
+
+{| class="wikitable"
+!colspan=4| template request
|-
-|2020
-|1577836800
-|2028
-|1830297600
+! Key !! Required !! Type !! Description
|-
-|2021
-|1609459200
-|2029
-|1861920000
+| rules || No || Array of Strings || list of supported softfork deployments, by name
+|}
+
+The template Object is also extended:
+
+{| class="wikitable"
+!colspan=4| template
|-
-|2022
-|1640995200
-|2030
-|1893456000
+! Key !! Required !! Type !! Description
|-
-|2023
-|1672531200
-|2031
-|1924992000
+| rules || Yes || Array of Strings || list of softfork deployments, by name, that are active state
|-
-|2024
-|1704067200
-|2032
-|1956528000
+| vbavailable || Yes || Object || set of pending, supported softfork deployments; each uses the softfork name as the key, and the softfork bit as its value
|-
-|2025
-|1735689600
-|2033
-|1988150400
+| vbrequired || No || Number || bit mask of softfork deployment version bits the server requires enabled in submissions
|}
-If the soft fork still not ''locked-in'' and the
-GetMedianTimePast() of a block following a retarget period is at or
-past this timeout, miners should cease setting this bit.
-
- if (NextBlockHeight % 2016 == 0) {
- if (BState == defined && GetMedianTimePast(nextblock) >= BFinalYear) {
- BState = failed;
- }
- }
-
-After another retarget period (to allow detection of buggy miners),
-the bit may be reused.
+The "version" key of the template is retained, and used to indicate the server's preference of deployments.
+If versionbits is being used, "version" MUST be within the versionbits range of [0x20000000...0x3FFFFFFF].
+Miners MAY clear or set bits in the block version WITHOUT any special "mutable" key, provided they are listed among the template's "vbavailable" and (when clearing is desired) NOT included as a bit in "vbrequired".
-'''Warning system'''
-To support upgrade warnings, an extra "unknown upgrade" is tracked, using the "implicit bit" mask = (block.nVersion & ~expectedVersion) != 0. Mask will be non-zero whenever an unexpected bit is set in nVersion. Whenever lock-in for the unknown upgrade is detected, the software should warn loudly about the upcoming soft fork. It should warn even more loudly after the next retarget period.
+Softfork deployment names listed in "rules" or as keys in "vbavailable" may be prefixed by a '!' character.
+Without this prefix, GBT clients may assume the rule will not impact usage of the template as-is; typical examples of this would be when previously valid transactions cease to be valid, such as BIPs [[bip-0016.mediawiki|16]], [[bip-0065.mediawiki|65]], [[bip-0066.mediawiki|66]], [[bip-0068.mediawiki|68]], [[bip-0112.mediawiki|112]], and [[bip-0113.mediawiki|113]].
+If a client does not understand a rule without the prefix, it may use it unmodified for mining.
+On the other hand, when this prefix is used, it indicates a more subtle change to the block structure or generation transaction; examples of this would be [[bip-0034.mediawiki|BIP 34]] (because it modifies coinbase construction) and [[bip-0141.mediawiki|141]] (since it modifies the txid hashing and adds a commitment to the generation transaction).
+A client that does not understand a rule prefixed by '!' must not attempt to process the template, and must not attempt to use it for mining even unmodified.
-'''Forks'''
-It should be noted that the states are maintained along block chain
-branches, but may need recomputation when a reorganization happens.
-
-===Support for future changes===
+==Support for future changes==
The mechanism described above is very generic, and variations are possible for future soft forks. Here are some ideas that can be taken into account.
'''Modified thresholds'''
-The 95% threshold (based on in BIP 34) does not have to be maintained for eternity, but changes should take the effect on the warning system into account. In particular, having a lock-in threshold that is incompatible with the one used for the warning system may have long-term effects, as the warning system cannot rely on a permanently detectable condition anymore.
+The 1916 threshold (based on BIP 34's 95%) does not have to be maintained for eternity, but changes should take the effect on the warning system into account. In particular, having a lock-in threshold that is incompatible with the one used for the warning system may have long-term effects, as the warning system cannot rely on a permanently detectable condition anymore.
'''Conflicting soft forks'''
At some point, two mutually exclusive soft forks may be proposed. The naive way to deal with this is to never create software that implements both, but that is making a bet that at least one side is guaranteed to lose. Better would be to encode "soft fork X cannot be locked-in" as consensus rule for the conflicting soft fork - allowing software that supports both, but can never trigger conflicting changes.
@@ -155,7 +217,7 @@ Soft forks right now are typically treated as booleans: they go from an inactive
The failure timeout allows eventual reuse of bits even if a soft fork was
never activated, so it's clear that the new use of the bit refers to a
-new BIP. It's deliberately very course grained, to take into account
+new BIP. It's deliberately very coarse-grained, to take into account
reasonable development and deployment delays. There are unlikely to be
enough failed proposals to cause a bit shortage.
@@ -163,6 +225,10 @@ The fallow period at the conclusion of a soft fork attempt allows some
detection of buggy clients, and allows time for warnings and software
upgrades for successful soft forks.
+==Deployments==
+
+A living list of deployment proposals can be found [[bip-0009/assignments.mediawiki|here]].
+
==Copyright==
This document is placed in the public domain.
diff --git a/bip-0009/assignments.mediawiki b/bip-0009/assignments.mediawiki
new file mode 100644
index 0000000000..c6a8f0027e
--- /dev/null
+++ b/bip-0009/assignments.mediawiki
@@ -0,0 +1,37 @@
+==Deployments==
+
+List of proposed deployments.
+
+State can be defined, active, failed. Dates are in UTC.
+
+{| class="wikitable sortable"
+! Name
+! Bit
+! Mainnet Start
+! Mainnet Expire
+! Mainnet State
+! Testnet Start
+! Testnet Expire
+! Testnet State
+! BIPs
+|-
+| csv
+| 0
+| 2016-05-01 00:00:00
+| 2017-05-01 00:00:00
+| active since #419328
+| 2016-03-01 00:00:00
+| 2017-05-01 00:00:00
+| active since #770112
+| [[/bip-0068.mediawiki|68]], [[/bip-0112.mediawiki|112]], [[/bip-0113.mediawiki|113]]
+|-
+| segwit
+| 1
+| 2016-11-15 00:00:00
+| 2017-11-15 00:00:00
+| active since #481824
+| 2016-05-01 00:00:00
+| 2017-05-01 00:00:00
+| active since #834624
+| [[/bip-0141.mediawiki|141]], [[/bip-0143.mediawiki|143]], [[/bip-0147.mediawiki|147]]
+|}
diff --git a/bip-0009/states.gv b/bip-0009/states.gv
new file mode 100644
index 0000000000..9dc95c56e3
--- /dev/null
+++ b/bip-0009/states.gv
@@ -0,0 +1,22 @@
+/* There are many ways to compile this, but one of them is:
+ *
+ * $ dot -Tpng states.gv -o states.png
+ */
+digraph {
+ /* States. */
+ DEFINED; FAILED; STARTED; LOCKED_IN; ACTIVE;
+
+ /* Relationships between states, labeled where applicable. */
+ DEFINED -> DEFINED;
+ DEFINED -> FAILED [label = "timeout ≤ MTP"];
+ DEFINED -> STARTED [label = "starttime ≤ MTP < timeout"];
+ FAILED -> FAILED;
+ STARTED -> STARTED;
+ STARTED -> FAILED [label = "timeout ≤ MTP"];
+ STARTED -> LOCKED_IN [label = "(MTP < timeout) AND (threshold reached)"];
+ LOCKED_IN -> ACTIVE [label = "Always"];
+ ACTIVE -> ACTIVE;
+
+ /* Visualization hack to unclutter output. */
+ nodesep = 1.2;
+}
diff --git a/bip-0009/states.png b/bip-0009/states.png
new file mode 100644
index 0000000000..2048ed870d
Binary files /dev/null and b/bip-0009/states.png differ
diff --git a/bip-0010.mediawiki b/bip-0010.mediawiki
index 4307f3e42a..289e3b041a 100644
--- a/bip-0010.mediawiki
+++ b/bip-0010.mediawiki
@@ -1,8 +1,11 @@
BIP: 10
+ Layer: Applications
Title: Multi-Sig Transaction Distribution
- Author: Alan Reiner
- Status: Withdrawn
+ Author: Alan Reiner
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0010
+ Status: Withdrawn
Type: Informational
Created: 2011-10-28
@@ -90,10 +93,10 @@ The following is an example TxDP from Armory, produced while running on the test
In this transaction, there are two inputs, one of 150 BTC and the other of 12 BTC. This transaction combines 162 BTC to create two outputs, one of 160 BTC, one 1.9995 BTC, and a tx fee of 0.0005. In this TxDP, both inputs have been signed, and thus could broadcast immediately.
-The style of communication is taken directly from PGP/GPG, which uses blocks of ASCII like this to communicate encrypted messages and signatures. This serialization is compact, and will be interpretted the same in all character encodings. It can be copied inline into an email, or saved in a text file. The advantage over the analogous PGP encoding is that there are some human readable elements to it, for users that wish to examine the TxDP packet manually, instead of requiring a program to parse the core elements of the TxDP.
+The style of communication is taken directly from PGP/GPG, which uses blocks of ASCII like this to communicate encrypted messages and signatures. This serialization is compact, and will be interpreted the same in all character encodings. It can be copied inline into an email, or saved in a text file. The advantage over the analogous PGP encoding is that there are some human readable elements to it, for users that wish to examine the TxDP packet manually, instead of requiring a program to parse the core elements of the TxDP.
A party receiving this TxDP can simply add their signature to the appropriate _TXINPUT_ line. If that is the last signature required, they can broadcast it themselves. Any software that implements this standard should be able to combine multiple TxDPs into a single TxDP. However, even without the programmatic support, a user could manually combine them by copying the appropriate _TXSIGS_ lines between serializations, though it is not the recommended method for combining TxDPs.
== Reference Implementation ==
-This proposal was implemented and tested in the older versions of ''Armory'' Bitcoin software for use in offline-wallet transaction signing (as a 1-of-1 transaction). Implementation can be found in https://github.com/etotheipi/BitcoinArmory/blob/v0.91-beta/armoryengine/Transaction.py under the class PyTxDistProposal. However, as of verion 0.92 released in July 2014, Armory no longer uses this proposal for offline wallet transaction signing and has moved on to a new format.
+This proposal was implemented and tested in the older versions of ''Armory'' Bitcoin software for use in offline-wallet transaction signing (as a 1-of-1 transaction). Implementation can be found in https://github.com/etotheipi/BitcoinArmory/blob/v0.91-beta/armoryengine/Transaction.py under the class PyTxDistProposal. However, as of version 0.92 released in July 2014, Armory no longer uses this proposal for offline wallet transaction signing and has moved on to a new format.
diff --git a/bip-0011.mediawiki b/bip-0011.mediawiki
index 2499ac0376..7e9e1f6842 100644
--- a/bip-0011.mediawiki
+++ b/bip-0011.mediawiki
@@ -1,8 +1,11 @@
BIP: 11
+ Layer: Applications
Title: M-of-N Standard Transactions
Author: Gavin Andresen
- Status: Accepted
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0011
+ Status: Final
Type: Standards Track
Created: 2011-10-18
Post-History: 2011-10-02
@@ -20,7 +23,7 @@ A couple of motivating use cases:
* A wallet secured by a "wallet protection service" (WPS). 2-of-2 signatures required transactions will be used, with one signature coming from the (possibly compromised) computer with the wallet and the second signature coming from the WPS. When sending protected bitcoins, the user's bitcoin client will contact the WPS with the proposed transaction and it can then contact the user for confirmation that they initiated the transaction and that the transaction details are correct. Details for how clients and WPS's communicate are outside the scope of this BIP. Side note: customers should insist that their wallet protection service provide them with copies of the private key(s) used to secure their wallets that they can safely store off-line, so that their coins can be spent even if the WPS goes out of business.
-* Three-party escrow (buyer, seller and trusted dispute agent). 2-of-3 signatures required transactions will be used. The buyer and seller and agent will each provide a public key, and the buyer will then send coins into a 2-of-3 CHECKMULTISIG transaction and send the seller and the agent the transaction id. The seller will fulfill their obligation and then ask the buyer to co-sign a transaction ( already signed by seller ) that sends the tied-up coins to him (seller). If the buyer and seller cannot agree, then the agent can, with the cooperation of either buyer or seller, decide what happens to the tied-up coins. Details of how buyer, seller, and agent communicate to gather signatures or public keys are outside the scope of this BIP.
+* Three-party escrow (buyer, seller, and trusted dispute agent). 2-of-3 signatures required transactions will be used. The buyer and seller and agent will each provide a public key, and the buyer will then send coins into a 2-of-3 CHECKMULTISIG transaction and send the seller and the agent the transaction id. The seller will fulfill their obligation and then ask the buyer to co-sign a transaction ( already signed by seller ) that sends the tied-up coins to him (seller). If the buyer and seller cannot agree, then the agent can, with the cooperation of either buyer or seller, decide what happens to the tied-up coins. Details of how buyer, seller, and agent communicate to gather signatures or public keys are outside the scope of this BIP.
==Specification==
@@ -35,7 +38,7 @@ OP_CHECKMULTISIG transactions are redeemed using a standard scriptSig:
(OP_0 is required because of a bug in OP_CHECKMULTISIG; it pops one too many items off the execution stack, so a dummy value must be placed on the stack).
-The current Satoshi bitcoin client does not relay or mine transactions with scriptSigs larger than 200 bytes; to accomodate 3-signature transactions, this will be increased to 500 bytes.
+The current Satoshi bitcoin client does not relay or mine transactions with scriptSigs larger than 200 bytes; to accommodate 3-signature transactions, this will be increased to 500 bytes.
==Rationale==
@@ -51,7 +54,7 @@ A weaker argument is OP_CHECKMULTISIG should not be used because it pops one too
OP_CHECKMULTISIG is already supported by old clients and miners as a non-standard transaction type.
-https://github.com/gavinandresen/bitcoin-git/tree/op_eval
+https://github.com/gavinandresen/bitcoin-git/tree/77f21f1583deb89bf3fffe80fe9b181fedb1dd60
== Post History ==
diff --git a/bip-0012.mediawiki b/bip-0012.mediawiki
index ee2fda6b8c..bd3d88c9b4 100644
--- a/bip-0012.mediawiki
+++ b/bip-0012.mediawiki
@@ -1,7 +1,10 @@
BIP: 12
+ Layer: Consensus (soft fork)
Title: OP_EVAL
Author: Gavin Andresen
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0012
Status: Withdrawn
Type: Standards Track
Created: 2011-10-18
@@ -40,11 +43,11 @@ OP_EVAL allows the receiver of bitcoins to specify how they can be spent when th
If ''serialized script'' is a large or complicated multi-signature script, then the burden of paying for it (in increased transaction fees due to more signature operations or transaction size) is shifted from the sender to the receiver.
-The main objection to OP_EVAL is that it adds complexity, and complexity is the enemy of security. Also, evaluating data as code has a long record of being a source of security vulnerabilties.
+The main objection to OP_EVAL is that it adds complexity, and complexity is the enemy of security. Also, evaluating data as code has a long record of being a source of security vulnerabilities.
That same argument can be applied to the existing Bitcoin 'scripting' system; scriptPubKeys are transmit as data across the network and are then interpreted by every bitcoin implementation. OP_EVAL just moves the data that will be interpreted. It is debatable whether or not the entire idea of putting a little interpreted expression evaluation language at the core of Bitcoin was brilliant or stupid, but the existence of OP_EVAL does not make the expression language less secure.
-There is a 1-confirmation attack on old clients that interepret OP_EVAL as a no-op, but it is expensive and difficult in practice. The attack is:
+There is a 1-confirmation attack on old clients that interpret OP_EVAL as a no-op, but it is expensive and difficult in practice. The attack is:
# Attacker creates an OP_EVAL transaction that is valid as seen by old clients, but invalid for new clients.
# Attacker also creates a standard transaction that spends the OP_EVAL transaction, and pays the victim.
@@ -72,7 +75,7 @@ Example of a transaction that must fail for both old and new miners/clients:
==Reference Implementation==
-https://github.com/gavinandresen/bitcoin-git/tree/op_eval
+https://github.com/gavinandresen/bitcoin-git/tree/77f21f1583deb89bf3fffe80fe9b181fedb1dd60
==See Also==
diff --git a/bip-0013.mediawiki b/bip-0013.mediawiki
index a537d16a29..70be90d38d 100644
--- a/bip-0013.mediawiki
+++ b/bip-0013.mediawiki
@@ -1,7 +1,10 @@
BIP: 13
+ Layer: Applications
Title: Address Format for pay-to-script-hash
Author: Gavin Andresen
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0013
Status: Final
Type: Standards Track
Created: 2011-10-18
@@ -11,7 +14,7 @@
This BIP describes a new type of Bitcoin address to support arbitrarily complex transactions. Complexity in this context is defined as what information is needed by the recipient to respend the received coins, in contrast to needing a single ECDSA private key as in current implementations of Bitcoin.
-In essence, an address encoded under this proposal represents the encoded hash of a [[script]], rather than the encoded hash of an ECDSA public key.
+In essence, an address encoded under this proposal represents the encoded hash of a [https://en.bitcoin.it/wiki/Script script], rather than the encoded hash of an ECDSA public key.
==Motivation==
@@ -19,7 +22,7 @@ Enable "end-to-end" secure wallets and payments to fund escrow transactions or o
==Specification==
-The new bitcoin address type is constructed in the same manner as existing bitcoin addresses (see [[Base58Check encoding]]):
+The new bitcoin address type is constructed in the same manner as existing bitcoin addresses (see [https://en.bitcoin.it/Base58Check_encoding Base58Check encoding]):
base58-encode: [one-byte version][20-byte hash][4-byte checksum]
@@ -47,7 +50,7 @@ This proposal is not backwards compatible, but it fails gracefully-- if an older
==Reference Implementation==
-See base58.cpp1/base58.h at https://github.com/bitcoin/bitcoin/src
+See base58.cpp/base58.h at https://github.com/bitcoin/bitcoin/tree/master/src
==See Also==
diff --git a/bip-0014.mediawiki b/bip-0014.mediawiki
index 111eb78bed..fded42036a 100644
--- a/bip-0014.mediawiki
+++ b/bip-0014.mediawiki
@@ -1,9 +1,12 @@
BIP: 14
- Title: BIP Protocol Version and User Agent
+ Layer: Peer Services
+ Title: Protocol Version and User Agent
Author: Amir Taaki
Patrick Strateman
- Status: Accepted
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0014
+ Status: Final
Type: Standards Track
Created: 2011-11-10
Post-History: 2011-11-02
@@ -25,7 +28,7 @@ Version bumping can also introduce incompatibilities and fracture the network. I
By using a protocol version, we set all implementations on the network to a common standard. Everybody is able to agree within their confines what is protocol and what is implementation-dependent. A user agent string is offered as a 'vanity-plate' for clients to distinguish themselves in the network.
-Separation of the network protocol from the implemention, and forming development of said protocol by means of a mutual consensus among participants, has the democratic disadvantage when agreement is hard to reach on contentious issues. To mitigate this issue, strong communication channels and fast release schedules are needed, and are outside the scope of this document (concerning a process-BIP type).
+Separation of the network protocol from the implementation, and forming development of said protocol by means of a mutual consensus among participants, has the democratic disadvantage when agreement is hard to reach on contentious issues. To mitigate this issue, strong communication channels and fast release schedules are needed, and are outside the scope of this document (concerning a process-BIP type).
User agents provide extra tracking information that is useful for keeping tabs on network data such as client implementations used or common architectures/operating-systems. In the rare case they may even provide an emergency method of shunning faulty clients that threaten network health- although this is strongly unrecommended and extremely bad form. The user agent does not provide a method for clients to work around and behave differently to different implementations, as this will lead to protocol fracturing.
diff --git a/bip-0015.mediawiki b/bip-0015.mediawiki
index c08498f16b..635fb7fabe 100644
--- a/bip-0015.mediawiki
+++ b/bip-0015.mediawiki
@@ -1,7 +1,10 @@
BIP: 15
- Title: BIP Aliases
+ Layer: Applications
+ Title: Aliases
Author: Amir Taaki
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0015
Status: Deferred
Type: Standards Track
Created: 2011-12-10
@@ -33,7 +36,7 @@ Their FirstBits alias becomes:
It is enough information to be given the FirstBits alias ''1brmlab''. When someone wishes to make a purchase, without FirstBits, they either have to type out their address laboriously by hand, scan their QR code (which requires a mobile handset that this author does not own) or find their address on the internet to copy and paste into the client to send bitcoins. FirstBits alleviates this impracticality by providing an easy method to make payments.
-Together with [[vanitygen|Vanitygen (vanity generator)]], it becomes possible to create memorable unique named addresses. Addresses that are meaningful, rather than an odd assemblage of letters and numbers but add context to the destination.
+Together with Vanitygen (vanity generator), it becomes possible to create memorable unique named addresses. Addresses that are meaningful, rather than an odd assemblage of letters and numbers but add context to the destination.
However FirstBits has its own problems. One is that the possible aliases one is able to generate is limited by the available computing power available. It may not be feasible to generate a complete or precise alias that is wanted- only approximates may be possible. It is also computationally resource intensive which means a large expenditure of power for generating unique aliases in the future, and may not scale up to the level of individuals at home or participants with hand-held devices in an environment of ubiquitous computing.
@@ -205,7 +208,7 @@ NameResolutionService::~NameResolutionService()
void NameResolutionService::ExplodeHandle(const string& strHandle, string& strNickname, string& strDomain)
{
- // split address at @ furthrest to the right
+ // split address at @ furthest to the right
size_t nPosAtsym = strHandle.rfind('@');
strNickname = strHandle.substr(0, nPosAtsym);
strDomain = strHandle.substr(nPosAtsym + 1, strHandle.size());
@@ -345,7 +348,7 @@ By using DNS lookups, the MITM problem with IP transactions could be mitigated b
=== Namecoin ID ===
-This proposal uses the Namecoin blockchain to associate an alias with a bitcoin address. Bitcoin queries a namecoin node. This retreives the structured data containing the bitcoin address(es) associated with this alias.
+This proposal uses the Namecoin blockchain to associate an alias with a bitcoin address. Bitcoin queries a namecoin node. This retrieves the structured data containing the bitcoin address(es) associated with this alias.
Using a decentralised domain name system like Namecoin, means no external server or entity needs to be trusted unlike the other proposals listed here. This indicates a system with the advantage of having a high availability and ease of entry (no restrictions for users to create aliases).
@@ -398,4 +401,4 @@ Any text can be put into the brackets, allowing merchants to adapt it to all the
New features can be added later to support uncovered cases.
-See the specification of [http://dot-bit.org/Namespace:Identity Namecoin ID] for more informations.
+See the specification of [http://dot-bit.org/Namespace:Identity Namecoin ID] for more information.
diff --git a/bip-0016.mediawiki b/bip-0016.mediawiki
index 0a539fc294..abc27d6610 100644
--- a/bip-0016.mediawiki
+++ b/bip-0016.mediawiki
@@ -1,7 +1,10 @@
BIP: 16
+ Layer: Consensus (soft fork)
Title: Pay to Script Hash
Author: Gavin Andresen
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0016
Status: Final
Type: Standards Track
Created: 2012-01-03
@@ -37,7 +40,7 @@ The rules for validating these outpoints when relaying transactions or consideri
# Normal validation is done: an initial stack is created from the signatures and {serialized script}, and the hash of the script is computed and validation fails immediately if it does not match the hash in the outpoint.
# {serialized script} is popped off the initial stack, and the transaction is validated again using the popped stack and the deserialized script as the scriptPubKey.
-These new rules should only be applied when validating transactions in blocks with timestamps >= 1333238400 (Apr 1 2012) [https://github.com/bitcoin/bitcoin/commit/8f188ece3c82c4cf5d52a3363e7643c23169c0ff Remove -bip16 and -paytoscripthashtime command-line arguments]. There are transaction earlier than 13333238400 in the block chain that fail these new validation rules. [http://blockexplorer.com/tx/6a26d2ecb67f27d1fa5524763b49029d7106e91e3cc05743073461a719776192 Transaction 6a26d2ecb67f27d1fa5524763b49029d7106e91e3cc05743073461a719776192]. Older transactions must be validated under the old rules. (see the Backwards Compatibility section for details).
+These new rules should only be applied when validating transactions in blocks with timestamps >= 1333238400 (Apr 1 2012) [https://github.com/bitcoin/bitcoin/commit/8f188ece3c82c4cf5d52a3363e7643c23169c0ff Remove -bip16 and -paytoscripthashtime command-line arguments]. There are transactions earlier than 1333238400 in the block chain that fail these new validation rules. [https://web.archive.org/web/20141122040355/http://blockexplorer.com/tx/6a26d2ecb67f27d1fa5524763b49029d7106e91e3cc05743073461a719776192 Transaction 6a26d2ecb67f27d1fa5524763b49029d7106e91e3cc05743073461a719776192]. Older transactions must be validated under the old rules. (see the Backwards Compatibility section for details).
For example, the scriptPubKey and corresponding scriptSig for a one-signature-required transaction is:
@@ -98,7 +101,7 @@ If a majority of hashing power does not support the new validation rules, then r
===520-byte limitation on serialized script size===
-As a consequence of the requirement for backwards compatiblity the serialized script is itself subject to the same rules as any other PUSHDATA operation, including the rule that no data greater than 520 bytes may be pushed to the stack. Thus is it not possible to spend a P2SH output if the redemption script it refers to is >520 bytes in length. For instance while the OP_CHECKMULTISIG opcode can itself accept up to 20 pubkeys, with 33-byte compressed pubkeys it is only possible to spend a P2SH output requiring a maximum of 15 pubkeys to redeem: 3 bytes + 15 pubkeys * 34 bytes/pubkey = 513 bytes.
+As a consequence of the requirement for backwards compatibility the serialized script is itself subject to the same rules as any other PUSHDATA operation, including the rule that no data greater than 520 bytes may be pushed to the stack. Thus it is not possible to spend a P2SH output if the redemption script it refers to is >520 bytes in length. For instance while the OP_CHECKMULTISIG opcode can itself accept up to 20 pubkeys, with 33-byte compressed pubkeys it is only possible to spend a P2SH output requiring a maximum of 15 pubkeys to redeem: 3 bytes + 15 pubkeys * 34 bytes/pubkey = 513 bytes.
==Reference Implementation==
diff --git a/bip-0016/qa.mediawiki b/bip-0016/qa.mediawiki
index 6a8a08dc43..1edf28e5b9 100644
--- a/bip-0016/qa.mediawiki
+++ b/bip-0016/qa.mediawiki
@@ -1,4 +1,4 @@
-This page is a Quality Assurance test plan for [[BIP 16]]. If you see a test missing, please add it.
+This page is a Quality Assurance test plan for [[../bip-0016.mediawiki|BIP 16]]. If you see a test missing, please add it.
If you can help test, please edit this page to sign-off on it.
{| class="wikitable"
diff --git a/bip-0017.mediawiki b/bip-0017.mediawiki
index 44011d5790..aeb8764486 100644
--- a/bip-0017.mediawiki
+++ b/bip-0017.mediawiki
@@ -1,16 +1,24 @@
==Abstract==
This BIP describes a new opcode (OP_CHECKHASHVERIFY) for the Bitcoin scripting system, and a new 'standard' transaction type that uses it to enables the receiver of bitcoins to specify the transaction type needed to re-spend them.
+==Copyright==
+
+This BIP is licensed under the BSD 2-clause license.
+
==Motivation==
The purpose of pay-to-script-hash is to move the responsibility for supplying the conditions to redeem a transaction from the sender of the funds to the redeemer.
@@ -78,7 +86,7 @@ Avoiding a block-chain split by malicious pay-to-script transactions requires ca
* A pay-to-script-hash transaction that is invalid for new clients/miners but valid for old clients/miners.
-To gracefully upgrade and ensure no long-lasting block-chain split occurs, more than 50% of miners must support full validation of the new transaction type and must switch from the old validation rules to the new rules at the same time.
+To gracefully upgrade and ensure no long-lasting block-chain split occurs, more than 50% of miners must support full validation of the new transaction type and must switch from the old validation rules to the new rules at the same time.
To judge whether or not more than 50% of hashing power supports this BIP, miners are asked to upgrade their software and put the string "p2sh/CHV" in the input of the coinbase transaction for blocks that they create.
diff --git a/bip-0018.mediawiki b/bip-0018.mediawiki
index 023b2bfbc5..a82ab44140 100644
--- a/bip-0018.mediawiki
+++ b/bip-0018.mediawiki
@@ -1,16 +1,24 @@
==Abstract==
This BIP modifies the basic format of transaction inputs and outputs, replacing the current scriptSig and scriptPubKey (scripts executed to validate a transaction) with new contents: dataSig, scriptCheck, and hashScriptCheck.
+==Copyright==
+
+This BIP is licensed under the BSD 2-clause license.
+
==Motivation==
The purpose of pay-to-script-hash is to move the responsibility for supplying the conditions to redeem a transaction from the sender of the funds to the redeemer.
diff --git a/bip-0019.mediawiki b/bip-0019.mediawiki
index 7784e084a8..32179ea1c1 100644
--- a/bip-0019.mediawiki
+++ b/bip-0019.mediawiki
@@ -1,16 +1,24 @@
==Abstract==
This BIP proposes M-of-N-signatures required transactions as a new 'standard' transaction type using the existing scripting system without significant modifications.
+==Copyright==
+
+This BIP is licensed under the BSD 2-clause license.
+
==Motivation==
Enable secured wallets, escrow transactions, and other use cases where redeeming funds requires more than a single signature.
@@ -38,7 +46,7 @@ But only for n less than or equal to 3.
These transactions are redeemed using a standard scriptSig:
...signatures...
-The current Satoshi bitcoin client does not relay or mine transactions with scriptSigs larger than 200 bytes; to accomodate 3-signature transactions, this will be increased to 500 bytes.
+The current Satoshi bitcoin client does not relay or mine transactions with scriptSigs larger than 200 bytes; to accommodate 3-signature transactions, this will be increased to 500 bytes.
===Templates===
scriptPubKey:
diff --git a/bip-0020.mediawiki b/bip-0020.mediawiki
index fad634b76d..fc3c0eaaee 100644
--- a/bip-0020.mediawiki
+++ b/bip-0020.mediawiki
@@ -1,10 +1,14 @@
BIP: 20
+ Layer: Applications
Title: URI Scheme
Author: Luke Dashjr
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0020
Status: Replaced
Type: Standards Track
Created: 2011-01-10
+ License: BSD-2-Clause
BIP 0020 is based off an earlier document by Nils Schneider. '''And has been replaced by BIP 0021'''
@@ -12,6 +16,9 @@ BIP 0020 is based off an earlier document by Nils Schneider. '''And has been rep
==Abstract==
This BIP proposes a URI scheme for making Bitcoin payments.
+==Copyright==
+This BIP is licensed under the BSD 2-clause license.
+
==Motivation==
The purpose of this URI scheme is to enable users to easily make payments by simply clicking links on webpages or scanning QR Codes.
diff --git a/bip-0021.mediawiki b/bip-0021.mediawiki
index 270692646a..9fa4823256 100644
--- a/bip-0021.mediawiki
+++ b/bip-0021.mediawiki
@@ -1,9 +1,12 @@
BIP: 21
+ Layer: Applications
Title: URI Scheme
Author: Nils Schneider
Matt Corallo
- Status: Accepted
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0021
+ Status: Final
Type: Standards Track
Created: 2012-01-29
@@ -34,7 +37,7 @@ Elements of the query component may contain characters outside the valid range.
=== ABNF grammar ===
-(See also [[#Simpler syntax|a simpler representation of syntax]])
+(See also [[#simpler-syntax|a simpler representation of syntax]])
bitcoinurn = "bitcoin:" bitcoinaddress [ "?" bitcoinparams ]
bitcoinaddress = *base58
@@ -55,11 +58,9 @@ The scheme component ("bitcoin:") is case-insensitive, and implementations must
*label: Label for that address (e.g. name of receiver)
*address: bitcoin address
*message: message that describes the transaction to the user ([[#Examples|see examples below]])
-*size: amount of base bitcoin units ([[#Transfer amount/size|see below]])
-*paycode: payment code (BIP-47)
*(others): optional, for future extensions
-==== Transfer amount/size ====
+==== Transfer amount ====
If an amount is provided, it MUST be specified in decimal BTC.
All amounts MUST contain no commas and use a period (.) as the separating character to separate whole numbers and decimal fractions.
@@ -68,11 +69,6 @@ I.e. amount=50.00 or amount=50 is treated as 50 BTC, and amount=50,000.00 is inv
Bitcoin clients MAY display the amount in any format that is not intended to deceive the user.
They SHOULD choose a format that is foremost least confusing, and only after that most reasonable given the amount requested.
For example, so long as the majority of users work in BTC units, values should always be displayed in BTC by default, even if mBTC or TBC would otherwise be a more logical interpretation of the amount.
-
-==== Payment code ====
-
-If a URI provides a payment code, and if the client supports BIP-47, then the resulting transaction SHOULD construct a transaction per BIP-47 instead of using the address provided in the URI.
-
== Rationale ==
===Payment identifiers, not person identifiers===
@@ -124,10 +120,6 @@ Some future version that has variables which are (currently) not understood but
Characters must be URI encoded properly.
-== Reference Implementations ==
-=== Bitcoin clients ===
-* Bitcoin-Qt supports the old version of Bitcoin URIs (ie without the req- prefix), with Windows and KDE integration as of commit 70f55355e29c8e45b607e782c5d76609d23cc858.
-
-==References==
+== Reference Implementation ==
-* [[bip-0047.mediawiki|BIP47 - Reusable Payment Codes for Hierarchical Deterministic Wallets]]
+Bitcoin-Qt supports the old version of Bitcoin URIs (ie without the req- prefix), with Windows and KDE integration as of commit 70f55355e29c8e45b607e782c5d76609d23cc858.
diff --git a/bip-0022.mediawiki b/bip-0022.mediawiki
index b39f957333..45ebacf874 100644
--- a/bip-0022.mediawiki
+++ b/bip-0022.mediawiki
@@ -1,10 +1,14 @@
==Abstract==
@@ -12,6 +16,10 @@
This BIP describes a new JSON-RPC method for "smart" Bitcoin miners and proxies.
Instead of sending a simple block header for hashing, the entire block structure is sent, and left to the miner to (optionally) customize and assemble.
+==Copyright==
+
+This BIP is licensed under the BSD 2-clause license.
+
==Specification==
===Block Template Request===
@@ -26,9 +34,9 @@ Block template creation can be influenced by various parameters:
|-
! Key !! Required !! Type !! Description
|-
-| capabilities || {{No}} || Array of Strings || SHOULD contain a list of the following, to indicate client-side support: [[#Optional: Long Polling|"longpoll"]], "coinbasetxn", "coinbasevalue", [[bip-0023.mediawiki#Block Proposal|"proposal"]], [[bip-0023.mediawiki#Logical Services|"serverlist"]], "workid", and any of the [[bip-0023.mediawiki#Mutations|mutations]]
+| capabilities || No || Array of Strings || SHOULD contain a list of the following, to indicate client-side support: [[#Optional: Long Polling|"longpoll"]], "coinbasetxn", "coinbasevalue", [[bip-0023.mediawiki#Block Proposal|"proposal"]], [[bip-0023.mediawiki#Logical Services|"serverlist"]], "workid", and any of the [[bip-0023.mediawiki#Mutations|mutations]]
|-
-| mode || {{No}} || String || MUST be "template" or omitted
+| mode || No || String || MUST be "template" or omitted
|}
getblocktemplate MUST return a JSON Object containing the following keys:
@@ -37,29 +45,29 @@ getblocktemplate MUST return a JSON Object containing the following keys:
|-
! Key !! Required !! Type !! Description
|-
-| bits || {{Yes}} || String || the compressed difficulty in hexadecimal
+| bits || Yes || String || the compressed difficulty in hexadecimal
|-
-| curtime || {{Yes}} || Number || the current time as seen by the server (recommended for block time) - note this is not necessarily the system clock, and must fall within the mintime/maxtime rules
+| curtime || Yes || Number || the current time as seen by the server (recommended for block time) - note this is not necessarily the system clock, and must fall within the mintime/maxtime rules
|-
-| height || {{Yes}} || Number || the height of the block we are looking for
+| height || Yes || Number || the height of the block we are looking for
|-
-| previousblockhash || {{Yes}} || String || the hash of the previous block, in big-endian hexadecimal
+| previousblockhash || Yes || String || the hash of the previous block, in big-endian hexadecimal
|-
-| sigoplimit || {{No}} || Number || number of sigops allowed in blocks
+| sigoplimit || No || Number || number of sigops allowed in blocks
|-
-| sizelimit || {{No}} || Number || number of bytes allowed in blocks
+| sizelimit || No || Number || number of bytes allowed in blocks
|-
-| transactions || {{Yes|Should}} || Array of Objects || Objects containing [[#Transactions Object Format|information for Bitcoin transactions]] (excluding coinbase)
+| transactions || Should || Array of Objects || Objects containing [[#Transactions Object Format|information for Bitcoin transactions]] (excluding coinbase)
|-
-| version || {{Yes}} || Number || always 1 or 2 (at least for bitcoin) - clients MUST understand the implications of the version they use (eg, comply with [[bip-0034.mediawiki|BIP 0034]] for version 2)
+| version || Yes || Number || always 1 or 2 (at least for bitcoin) - clients MUST understand the implications of the version they use (eg, comply with [[bip-0034.mediawiki|BIP 0034]] for version 2)
|-
-| coinbaseaux || {{No}} || Object || data that SHOULD be included in the coinbase's scriptSig content. Only the values (hexadecimal byte-for-byte) in this Object should be included, not the keys. This does not include the block height, which is required to be included in the scriptSig by [[bip-0034.mediawiki|BIP 0034]]. It is advisable to encode values inside "PUSH" opcodes, so as to not inadvertently expend SIGOPs (which are counted toward limits, despite not being executed).
+| coinbaseaux || No || Object || data that SHOULD be included in the coinbase's scriptSig content. Only the values (hexadecimal byte-for-byte) in this Object should be included, not the keys. This does not include the block height, which is required to be included in the scriptSig by [[bip-0034.mediawiki|BIP 0034]]. It is advisable to encode values inside "PUSH" opcodes, so as to not inadvertently expend SIGOPs (which are counted toward limits, despite not being executed).
|-
-| coinbasetxn || {{Patch|this or ↓}} || Object || [[#Transactions Object Format|information for coinbase transaction]]
+| coinbasetxn || this or ↓ || Object || [[#Transactions Object Format|information for coinbase transaction]]
|-
-| coinbasevalue || {{Patch|this or ↑}} || Number || total funds available for the coinbase (in Satoshis)
+| coinbasevalue || this or ↑ || Number || total funds available for the coinbase (in Satoshis)
|-
-| workid || {{No}} || String || if provided, this value must be returned with results (see [[#Block Submission|Block Submission]])
+| workid || No || String || if provided, this value must be returned with results (see [[#Block Submission|Block Submission]])
|}
==== Transactions Object Format ====
diff --git a/bip-0023.mediawiki b/bip-0023.mediawiki
index a53b00bf8d..4974a3a351 100644
--- a/bip-0023.mediawiki
+++ b/bip-0023.mediawiki
@@ -1,19 +1,27 @@
BIP: 23
+ Layer: API/RPC
Title: getblocktemplate - Pooled Mining
Author: Luke Dashjr
- Status: Accepted
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0023
+ Status: Final
Type: Standards Track
Created: 2012-02-28
+ License: BSD-2-Clause
==Abstract==
This BIP describes extensions to the getblocktemplate JSON-RPC call to enhance pooled mining.
+==Copyright==
+
+This BIP is licensed under the BSD 2-clause license.
+
==Specification==
-Note that all sections of this specification are optional extensions on top of [[BIP 0022|BIP 22]].
+Note that all sections of this specification are optional extensions on top of [[bip-0022.mediawiki|BIP 22]].
===Summary Support Levels===
diff --git a/bip-0030.mediawiki b/bip-0030.mediawiki
index 135d30062d..b653ba6415 100644
--- a/bip-0030.mediawiki
+++ b/bip-0030.mediawiki
@@ -1,14 +1,22 @@
==Abstract==
-This document gives a specification for dealing with duplicate transactions in the block chain, in an attempt to solve certain problems the reference implementations has with them.
+This document gives a specification for dealing with duplicate transactions in the block chain, in an attempt to solve certain problems the reference implementation has with them.
+
+==Copyright==
+
+This BIP is licensed under the 2-clause BSD license.
==Motivation==
So far, the Bitcoin reference implementation always assumed duplicate transactions (transactions with the same identifier) didn't exist. This is not true; in particular coinbases are easy to duplicate, and by building on duplicate coinbases, duplicate normal transactions are possible as well. Recently, an attack that exploits the reference implementation's dealing with duplicate transactions was described and demonstrated. It allows reverting fully-confirmed transactions to a single confirmation, making them vulnerable to become unspendable entirely. Another attack is possible that allows forking the block chain for a subset of the network.
diff --git a/bip-0031.mediawiki b/bip-0031.mediawiki
index 8adcd2955c..7f4cec45ef 100644
--- a/bip-0031.mediawiki
+++ b/bip-0031.mediawiki
@@ -1,8 +1,11 @@
diff --git a/bip-0032.mediawiki b/bip-0032.mediawiki
index 28541f5406..0e6df24042 100644
--- a/bip-0032.mediawiki
+++ b/bip-0032.mediawiki
@@ -3,14 +3,20 @@ RECENT CHANGES:
* (30 Apr 2013) Switched from multiplication by IL to addition of IL (faster, easier implementation)
* (25 May 2013) Added test vectors
* (15 Jan 2014) Rename keys with index ≥ 0x80000000 to hardened keys, and add explicit conversion functions.
+* (24 Feb 2017) Added test vectors for hardened derivation with leading zeros
+* (4 Nov 2020) Added new test vectors for hardened derivation with leading zeros
==Abstract==
@@ -19,7 +25,11 @@ This document describes hierarchical deterministic wallets (or "HD Wallets"): wa
The specification is intended to set a standard for deterministic wallets that can be interchanged between different clients. Although the wallets described here have many features, not all are required by supporting clients.
-The specification consists of two parts. In a first part, a system for deriving a tree of keypairs from a single seed is presented. The second part demonstrates how to build a wallet structure on top of such a tree.
+The specification consists of two parts. In the first part, a system for deriving a tree of keypairs from a single seed is presented. The second part demonstrates how to build a wallet structure on top of such a tree.
+
+==Copyright==
+
+This BIP is licensed under the 2-clause BSD license.
==Motivation==
@@ -27,7 +37,7 @@ The Bitcoin reference client uses randomly generated keys. In order to avoid the
Deterministic wallets do not require such frequent backups, and elliptic curve mathematics permit schemes where one can calculate the public keys without revealing the private keys. This permits for example a webshop business to let its webserver generate fresh addresses (public key hashes) for each order or for each customer, without giving the webserver access to the corresponding private keys (which are required for spending the received funds).
-However, deterministic wallets typically consist of a single "chain" of keypairs. The fact that there is only one chain means that sharing a wallet happens on an all-or-nothing basis. However, in some cases one only wants some (public) keys to be shared and recoverable. In the example of a webshop, the webserver does not need access to all public keys of the merchant's wallet; only to those addresses which are used to receive customer's payments, and not for example the change addresses that are generated when the merchant spends money. Hierarchical deterministic wallets allow such selective sharing by supporting multiple keypair chains, derived from a single root.
+However, deterministic wallets typically consist of a single "chain" of keypairs. The fact that there is only one chain means that sharing a wallet happens on an all-or-nothing basis. However, in some cases one only wants some (public) keys to be shared and recoverable. In the example of a webshop, the webserver does not need access to all public keys of the merchant's wallet; only to those addresses which are used to receive customers' payments, and not for example the change addresses that are generated when the merchant spends money. Hierarchical deterministic wallets allow such selective sharing by supporting multiple keypair chains, derived from a single root.
==Specification: Key derivation==
@@ -94,7 +104,7 @@ The function N((k, c)) → (K, c) computes the extended public key correspond
To compute the public child key of a parent private key:
* N(CKDpriv((kpar, cpar), i)) (works always).
* CKDpub(N(kpar, cpar), i) (works only for non-hardened child keys).
-The fact that they are equivalent is what makes non-hardened keys useful (one can derive child public keys of a given parent key without knowing any private key), and also what distinguishes them from hardened keys. The reason for not always using non-hardened keys (which are more useful) is security; see further for more information.
+The fact that they are equivalent is what makes non-hardened keys useful (one can derive child public keys of a given parent key without knowing any private key), and also what distinguishes them from hardened keys. The reason for not always using non-hardened keys (which are more useful) is security; see further below for more information.
====Public parent key → private child key====
@@ -109,11 +119,11 @@ To shorten notation, we will write CKDpriv(CKDpriv(CKDpriv(m,3H),2),5
* N(m/aH/b/c) = N(m/aH/b)/c = N(m/aH)/b/c.
However, N(m/aH) cannot be rewritten as N(m)/aH, as the latter is not possible.
-Each leaf node in the tree corresponds to an actual key, while the internal nodes correspond to the collections of keys that descend from them. The chain codes of the leaf nodes are ignored, and only their embedded private or public key is relevant. Because of this construction, knowing an extended private key allows reconstruction of all descendant private keys and public keys, and knowing an extended public keys allows reconstruction of all descendant non-hardened public keys.
+Each leaf node in the tree corresponds to an actual key, while the internal nodes correspond to the collections of keys that descend from them. The chain codes of the leaf nodes are ignored, and only their embedded private or public key is relevant. Because of this construction, knowing an extended private key allows reconstruction of all descendant private keys and public keys, and knowing an extended public key allows reconstruction of all descendant non-hardened public keys.
===Key identifiers===
-Extended keys can be identified by the Hash160 (RIPEMD160 after SHA256) of the serialized ECSDA public key K, ignoring the chain code. This corresponds exactly to the data used in traditional Bitcoin addresses. It is not advised to represent this data in base58 format though, as it may be interpreted as an address that way (and wallet software is not required to accept payment to the chain key itself).
+Extended keys can be identified by the Hash160 (RIPEMD160 after SHA256) of the serialized ECDSA public key K, ignoring the chain code. This corresponds exactly to the data used in traditional Bitcoin addresses. It is not advised to represent this data in base58 format though, as it may be interpreted as an address that way (and wallet software is not required to accept payment to the chain key itself).
The first 32 bits of the identifier are called the key fingerprint.
@@ -141,13 +151,13 @@ The total number of possible extended keypairs is almost 2512, but th
* Calculate I = HMAC-SHA512(Key = "Bitcoin seed", Data = S)
* Split I into two 32-byte sequences, IL and IR.
* Use parse256(IL) as master secret key, and IR as master chain code.
-In case IL is 0 or ≥n, the master key is invalid.
+In case parse256(IL) is 0 or parse256(IL) ≥ n, the master key is invalid.
==Specification: Wallet structure==
-The previous sections specified key trees and their nodes. The next step is imposing a wallet structure on this tree. The layout defined in this section is a default only, though clients are encouraged to mimick it for compatibility, even if not all features are supported.
+The previous sections specified key trees and their nodes. The next step is imposing a wallet structure on this tree. The layout defined in this section is a default only, though clients are encouraged to mimic it for compatibility, even if not all features are supported.
===The default wallet layout===
@@ -174,7 +184,7 @@ When a business has several independent offices, they can all use wallets derive
====Recurrent business-to-business transactions: N(m/iH/0)====
In case two business partners often transfer money, one can use the extended public key for the external chain of a specific account (M/i h/0) as a sort of "super address", allowing frequent transactions that cannot (easily) be associated, but without needing to request a new address for each payment.
-Such a mechanism could also be used by mining pool operators as variable payout address.
+Such a mechanism could also be used by mining pool operators as a variable payout address.
====Unsecure money receiver: N(m/iH/0)====
@@ -191,7 +201,7 @@ In addition to the expectations from the EC public-key cryptography itself:
the intended security properties of this standard are:
* Given a child extended private key (ki,ci) and the integer i, an attacker cannot find the parent private key kpar more efficiently than a 2256 brute force of HMAC-SHA512.
* Given any number (2 ≤ N ≤ 232-1) of (index, extended private key) tuples (ij,(kij,cij)), with distinct ij's, determining whether they are derived from a common parent extended private key (i.e., whether there exists a (kpar,cpar) such that for each j in (0..N-1) CKDpriv((kpar,cpar),ij)=(kij,cij)), cannot be done more efficiently than a 2256 brute force of HMAC-SHA512.
-Note however that the following properties does not exist:
+Note however that the following properties do not exist:
* Given a parent extended public key (Kpar,cpar) and a child public key (Ki), it is hard to find i.
* Given a parent extended public key (Kpar,cpar) and a non-hardened child private key (ki), it is hard to find kpar.
@@ -202,7 +212,7 @@ Private and public keys must be kept safe as usual. Leaking a private key means
Somewhat more care must be taken regarding extended keys, as these correspond to an entire (sub)tree of keys.
One weakness that may not be immediately obvious, is that knowledge of a parent extended public key plus any non-hardened private key descending from it is equivalent to knowing the parent extended private key (and thus every private and public key descending from it). This means that extended public keys must be treated more carefully than regular public keys.
-It is also the reason for the existence of hardened keys, and why they are used for the account level in the tree. This way, a leak of account-specific (or below) private key never risks compromising the master or other accounts.
+It is also the reason for the existence of hardened keys, and why they are used for the account level in the tree. This way, a leak of account-specific (or below) private keys never risks compromising the master or other accounts.
==Test Vectors==
@@ -251,34 +261,57 @@ Seed (hex): fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c
** ext pub: xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt
** ext prv: xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j
-==Implementations==
-
-Two Python implementations exist:
-
-PyCoin (https://github.com/richardkiss/pycoin) is a suite of utilities for dealing with Bitcoin that includes BIP0032 wallet features. BIP32Utils (https://github.com/jmcorgan/bip32utils) is a library and command line interface specifically focused on BIP0032 wallets and scripting.
-
-A Java implementation is available at https://github.com/bitsofproof/supernode/blob/1.1/api/src/main/java/com/bitsofproof/supernode/api/ExtendedKey.java
-
-A C++ implementation is available at https://github.com/CodeShark/CoinClasses/tree/master/tests/hdwallets
-
-An Objective-C implementation is available at https://github.com/oleganza/CoreBitcoin/blob/master/CoreBitcoin/BTCKeychain.h
+===Test vector 3===
-A Ruby implementation is available at https://github.com/GemHQ/money-tree
+These vectors test for the retention of leading zeros. See [https://github.com/bitpay/bitcore-lib/issues/47 bitpay/bitcore-lib#47] and [https://github.com/iancoleman/bip39/issues/58 iancoleman/bip39#58] for more information.
-Two Go implementations exist:
-
-hdkeychain (https://github.com/conformal/btcutil/tree/master/hdkeychain) provides an API for bitcoin hierarchical deterministic extended keys (BIP0032). Go HD Wallet (https://github.com/WeMeetAgain/go-hdwallet).
-
-Two JavaScript implementations exist: available at https://github.com/sarchar/brainwallet.github.com/tree/bip32 and https://github.com/bitpay/bitcore
+Seed (hex): 4b381541583be4423346c643850da4b320e46a87ae3d2a4e6da11eba819cd4acba45d239319ac14f863b8d5ab5a0d0c64d2e8a1e7d1457df2e5a3c51c73235be
+* Chain m
+** ext pub: xpub661MyMwAqRbcEZVB4dScxMAdx6d4nFc9nvyvH3v4gJL378CSRZiYmhRoP7mBy6gSPSCYk6SzXPTf3ND1cZAceL7SfJ1Z3GC8vBgp2epUt13
+** ext prv: xprv9s21ZrQH143K25QhxbucbDDuQ4naNntJRi4KUfWT7xo4EKsHt2QJDu7KXp1A3u7Bi1j8ph3EGsZ9Xvz9dGuVrtHHs7pXeTzjuxBrCmmhgC6
+* Chain m/0H
+** ext pub: xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y
+** ext prv: xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L
-A PHP implemetation is available at https://github.com/Bit-Wasp/bitcoin-lib-php
+===Test vector 4===
-A C# implementation is available at https://github.com/NicolasDorier/NBitcoin (ExtKey, ExtPubKey)
+These vectors test for the retention of leading zeros. See [https://github.com/btcsuite/btcutil/issues/172 btcsuite/btcutil#172] for more information.
-A Haskell implementation is available at https://github.com/haskoin/haskoin together with a CLI interface at https://github.com/np/hx
+Seed (hex): 3ddd5602285899a946114506157c7997e5444528f3003f6134712147db19b678
+* Chain m
+** ext pub: xpub661MyMwAqRbcGczjuMoRm6dXaLDEhW1u34gKenbeYqAix21mdUKJyuyu5F1rzYGVxyL6tmgBUAEPrEz92mBXjByMRiJdba9wpnN37RLLAXa
+** ext prv: xprv9s21ZrQH143K48vGoLGRPxgo2JNkJ3J3fqkirQC2zVdk5Dgd5w14S7fRDyHH4dWNHUgkvsvNDCkvAwcSHNAQwhwgNMgZhLtQC63zxwhQmRv
+* Chain m/0H
+** ext pub: xpub69AUMk3qDBi3uW1sXgjCmVjJ2G6WQoYSnNHyzkmdCHEhSZ4tBok37xfFEqHd2AddP56Tqp4o56AePAgCjYdvpW2PU2jbUPFKsav5ut6Ch1m
+** ext prv: xprv9vB7xEWwNp9kh1wQRfCCQMnZUEG21LpbR9NPCNN1dwhiZkjjeGRnaALmPXCX7SgjFTiCTT6bXes17boXtjq3xLpcDjzEuGLQBM5ohqkao9G
+* Chain m/0H/1H
+** ext pub: xpub6BJA1jSqiukeaesWfxe6sNK9CCGaujFFSJLomWHprUL9DePQ4JDkM5d88n49sMGJxrhpjazuXYWdMf17C9T5XnxkopaeS7jGk1GyyVziaMt
+** ext prv: xprv9xJocDuwtYCMNAo3Zw76WENQeAS6WGXQ55RCy7tDJ8oALr4FWkuVoHJeHVAcAqiZLE7Je3vZJHxspZdFHfnBEjHqU5hG1Jaj32dVoS6XLT1
+
+===Test vector 5===
+
+These vectors test that invalid extended keys are recognized as invalid.
+
+* xpub661MyMwAqRbcEYS8w7XLSVeEsBXy79zSzH1J8vCdxAZningWLdN3zgtU6LBpB85b3D2yc8sfvZU521AAwdZafEz7mnzBBsz4wKY5fTtTQBm (pubkey version / prvkey mismatch)
+* xprv9s21ZrQH143K24Mfq5zL5MhWK9hUhhGbd45hLXo2Pq2oqzMMo63oStZzFGTQQD3dC4H2D5GBj7vWvSQaaBv5cxi9gafk7NF3pnBju6dwKvH (prvkey version / pubkey mismatch)
+* xpub661MyMwAqRbcEYS8w7XLSVeEsBXy79zSzH1J8vCdxAZningWLdN3zgtU6Txnt3siSujt9RCVYsx4qHZGc62TG4McvMGcAUjeuwZdduYEvFn (invalid pubkey prefix 04)
+* xprv9s21ZrQH143K24Mfq5zL5MhWK9hUhhGbd45hLXo2Pq2oqzMMo63oStZzFGpWnsj83BHtEy5Zt8CcDr1UiRXuWCmTQLxEK9vbz5gPstX92JQ (invalid prvkey prefix 04)
+* xpub661MyMwAqRbcEYS8w7XLSVeEsBXy79zSzH1J8vCdxAZningWLdN3zgtU6N8ZMMXctdiCjxTNq964yKkwrkBJJwpzZS4HS2fxvyYUA4q2Xe4 (invalid pubkey prefix 01)
+* xprv9s21ZrQH143K24Mfq5zL5MhWK9hUhhGbd45hLXo2Pq2oqzMMo63oStZzFAzHGBP2UuGCqWLTAPLcMtD9y5gkZ6Eq3Rjuahrv17fEQ3Qen6J (invalid prvkey prefix 01)
+* xprv9s2SPatNQ9Vc6GTbVMFPFo7jsaZySyzk7L8n2uqKXJen3KUmvQNTuLh3fhZMBoG3G4ZW1N2kZuHEPY53qmbZzCHshoQnNf4GvELZfqTUrcv (zero depth with non-zero parent fingerprint)
+* xpub661no6RGEX3uJkY4bNnPcw4URcQTrSibUZ4NqJEw5eBkv7ovTwgiT91XX27VbEXGENhYRCf7hyEbWrR3FewATdCEebj6znwMfQkhRYHRLpJ (zero depth with non-zero parent fingerprint)
+* xprv9s21ZrQH4r4TsiLvyLXqM9P7k1K3EYhA1kkD6xuquB5i39AU8KF42acDyL3qsDbU9NmZn6MsGSUYZEsuoePmjzsB3eFKSUEh3Gu1N3cqVUN (zero depth with non-zero index)
+* xpub661MyMwAuDcm6CRQ5N4qiHKrJ39Xe1R1NyfouMKTTWcguwVcfrZJaNvhpebzGerh7gucBvzEQWRugZDuDXjNDRmXzSZe4c7mnTK97pTvGS8 (zero depth with non-zero index)
+* DMwo58pR1QLEFihHiXPVykYB6fJmsTeHvyTp7hRThAtCX8CvYzgPcn8XnmdfHGMQzT7ayAmfo4z3gY5KfbrZWZ6St24UVf2Qgo6oujFktLHdHY4 (unknown extended key version)
+* DMwo58pR1QLEFihHiXPVykYB6fJmsTeHvyTp7hRThAtCX8CvYzgPcn8XnmdfHPmHJiEDXkTiJTVV9rHEBUem2mwVbbNfvT2MTcAqj3nesx8uBf9 (unknown extended key version)
+* xprv9s21ZrQH143K24Mfq5zL5MhWK9hUhhGbd45hLXo2Pq2oqzMMo63oStZzF93Y5wvzdUayhgkkFoicQZcP3y52uPPxFnfoLZB21Teqt1VvEHx (private key 0 not in 1..n-1)
+* xprv9s21ZrQH143K24Mfq5zL5MhWK9hUhhGbd45hLXo2Pq2oqzMMo63oStZzFAzHGBP2UuGCqWLTAPLcMtD5SDKr24z3aiUvKr9bJpdrcLg1y3G (private key n not in 1..n-1)
+* xpub661MyMwAqRbcEYS8w7XLSVeEsBXy79zSzH1J8vCdxAZningWLdN3zgtU6Q5JXayek4PRsn35jii4veMimro1xefsM58PgBMrvdYre8QyULY (invalid pubkey 020000000000000000000000000000000000000000000000000000000000000007)
+* xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHL (invalid checksum)
==Acknowledgements==
* Gregory Maxwell for the original idea of type-2 deterministic wallets, and many discussions about it.
* Alan Reiner for the implementation of this scheme in Armory, and the suggestions that followed from that.
+* Eric Lombrozo for reviewing and revising this BIP.
* Mike Caldwell for the version bytes to obtain human-recognizable Base58 strings.
diff --git a/bip-0033.mediawiki b/bip-0033.mediawiki
index 6768e19802..2c1a86fb3e 100644
--- a/bip-0033.mediawiki
+++ b/bip-0033.mediawiki
@@ -1,8 +1,11 @@
@@ -19,7 +22,7 @@ Bitcoin blocks and transactions are versioned binary structures. Both currently
==Specification==
# Treat transactions with a version greater than 1 as non-standard (official Satoshi client will not mine or relay them).
-# Add height as the first item in the coinbase transaction's scriptSig, and increase block version to 2. The format of the height is "serialized CScript" -- first byte is number of bytes in the number (will be 0x03 on main net for the next 300 or so years), following bytes are little-endian representation of the number. Height is the height of the mined block in the block chain, where the genesis block is height zero (0).
+# Add height as the first item in the coinbase transaction's scriptSig, and increase block version to 2. The format of the height is "minimally encoded serialized CScript" -- first byte is number of bytes in the number (will be 0x03 on main net for the next 150 or so years with 223-1 blocks), following bytes are little-endian representation of the number (including a sign bit). Height is the height of the mined block in the block chain, where the genesis block is height zero (0).
# 75% rule: If 750 of the last 1,000 blocks are version 2 or greater, reject invalid version 2 blocks. (testnet3: 51 of last 100)
# 95% rule ("Point of no return"): If 950 of the last 1,000 blocks are version 2 or greater, reject all version 1 blocks. (testnet3: 75 of last 100)
diff --git a/bip-0035.mediawiki b/bip-0035.mediawiki
index cdadd1d72a..eccd381559 100644
--- a/bip-0035.mediawiki
+++ b/bip-0035.mediawiki
@@ -1,8 +1,11 @@
@@ -13,7 +16,7 @@ Make a network node's transaction memory pool accessible via a new "mempool" mes
==Motivation==
-Several use cases make it desireable to expose a network node's transaction memory pool:
+Several use cases make it desirable to expose a network node's transaction memory pool:
# SPV clients, wishing to obtain zero-confirmation transactions sent or received.
# Miners, to avoid missing lucrative fees, downloading existing network transactions after a restart.
# Remote network diagnostics.
diff --git a/bip-0036.mediawiki b/bip-0036.mediawiki
index 9c61fdb6d8..b3393b045e 100644
--- a/bip-0036.mediawiki
+++ b/bip-0036.mediawiki
@@ -1,10 +1,14 @@
BIP: 38
+ Layer: Applications
Title: Passphrase-protected private key
- Authors: Mike Caldwell
- Aaron Voisine
+ Author: Mike Caldwell
+ Aaron Voisine
+ Comments-Summary: Unanimously Discourage for implementation
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0038
Status: Draft (Some confusion applies: The announcements for this never made it to the list, so it hasn't had public discussion)
Type: Standards Track
Created: 2012-11-20
+ License: PD
==Abstract==
@@ -32,10 +36,10 @@ Password and passphrase-protected private keys enable new practical use cases fo
This proposal is hereby placed in the public domain.
==Rationale==
-:'''''User story:''' As a Bitcoin user who uses paper wallets, I would like the ability to add encryption, so that my Bitcoin paper storage can be two factor: something I have plus something I know.''
-:'''''User story:''' As a Bitcoin user who would like to pay a person or a company with a private key, I do not want to worry that any part of the communication path may result in the interception of the key and theft of my funds. I would prefer to offer an encrypted private key, and then follow it up with the password using a different communication channel (e.g. a phone call or SMS).''
-:'''''User story:''' (EC-multiplied keys) As a user of physical bitcoins, I would like a third party to be able to create password-protected Bitcoin private keys for me, without them knowing the password, so I can benefit from the physical bitcoin without the issuer having access to the private key. I would like to be able to choose a password whose minimum length and required format does not preclude me from memorizing it or engraving it on my physical bitcoin, without exposing me to an undue risk of password cracking and/or theft by the manufacturer of the item.''
-:'''''User story:''' (EC multiplied keys) As a user of paper wallets, I would like the ability to generate a large number of Bitcoin addresses protected by the same password, while enjoying a high degree of security (highly expensive scrypt parameters), but without having to incur the scrypt delay for each address I generate.
+:'' '''User story:''' As a Bitcoin user who uses paper wallets, I would like the ability to add encryption, so that my Bitcoin paper storage can be two factor: something I have plus something I know.''
+:'' '''User story:''' As a Bitcoin user who would like to pay a person or a company with a private key, I do not want to worry that any part of the communication path may result in the interception of the key and theft of my funds. I would prefer to offer an encrypted private key, and then follow it up with the password using a different communication channel (e.g. a phone call or SMS).''
+:'' '''User story:''' (EC-multiplied keys) As a user of physical bitcoins, I would like a third party to be able to create password-protected Bitcoin private keys for me, without them knowing the password, so I can benefit from the physical bitcoin without the issuer having access to the private key. I would like to be able to choose a password whose minimum length and required format does not preclude me from memorizing it or engraving it on my physical bitcoin, without exposing me to an undue risk of password cracking and/or theft by the manufacturer of the item.''
+:'' '''User story:''' (EC-multiplied keys) As a user of paper wallets, I would like the ability to generate a large number of Bitcoin addresses protected by the same password, while enjoying a high degree of security (highly expensive scrypt parameters), but without having to incur the scrypt delay for each address I generate.''
==Specification==
This proposal makes use of the following functions and definitions:
@@ -43,12 +47,12 @@ This proposal makes use of the following functions and definitions:
*'''AES256Encrypt, AES256Decrypt''': the simple form of the well-known AES block cipher without consideration for initialization vectors or block chaining. Each of these functions takes a 256-bit key and 16 bytes of input, and deterministically yields 16 bytes of output.
*'''SHA256''', a well-known hashing algorithm that takes an arbitrary number of bytes as input and deterministically yields a 32-byte hash.
*'''scrypt''': A well-known key derivation algorithm. It takes the following parameters: (string) password, (string) salt, (int) n, (int) r, (int) p, (int) length, and deterministically yields an array of bytes whose length is equal to the length parameter.
-*'''ECMultiply''': Multiplication of an elliptic curve point by a scalar integer with respect to the [[secp256k1]] elliptic curve.
-*'''G, N''': Constants defined as part of the [[secp256k1]] elliptic curve. G is an elliptic curve point, and N is a large positive integer.
-*'''[[Base58Check]]''': a method for encoding arrays of bytes using 58 alphanumeric characters commonly used in the Bitcoin ecosystem.
+*'''ECMultiply''': Multiplication of an elliptic curve point by a scalar integer with respect to the secp256k1 elliptic curve.
+*'''G, N''': Constants defined as part of the secp256k1 elliptic curve. G is an elliptic curve point, and N is a large positive integer.
+*'''Base58Check''': a method for encoding arrays of bytes using 58 alphanumeric characters commonly used in the Bitcoin ecosystem.
===Prefix===
-It is proposed that the resulting Base58Check-encoded string start with a '6'. The number '6' is intended to represent, from the perspective of the user, "a private key that needs something else to be usable" - an umbrella definition that could be understood in the future to include keys participating in multisig transactions, and was chosen with deference to the existing prefix '5' most commonly observed in [[Wallet Import Format]] which denotes an unencrypted private key.
+It is proposed that the resulting Base58Check-encoded string start with a '6'. The number '6' is intended to represent, from the perspective of the user, "a private key that needs something else to be usable" - an umbrella definition that could be understood in the future to include keys participating in multisig transactions, and was chosen with deference to the existing prefix '5' most commonly observed in Wallet Import Format which denotes an unencrypted private key.
It is proposed that the second character ought to give a hint as to what is needed as a second factor, and for an encrypted key requiring a passphrase, the uppercase letter P is proposed.
@@ -60,9 +64,9 @@ To keep the size of the encrypted key down, no initialization vectors (IVs) are
* How the user sees it: 58 characters always starting with '6P'
** Visual cues are present in the third character for visually identifying the EC-multiply and compress flag.
* Count of payload bytes (beyond prefix): 37
-** 1 byte (''flagbyte''):
+** 1 byte (''flagbyte''):
*** the most significant two bits are set as follows to preserve the visibility of the compression flag in the prefix, as well as to keep the payload within the range of allowable values that keep the "6P" prefix intact. For non-EC-multiplied keys, the bits are 11. For EC-multiplied keys, the bits are 00.
-*** the bit with value 0x20 when set indicates the key should be converted to a bitcoin address using the compressed public key format.
+*** the bit with value 0x20 when set indicates the key should be converted to a base58check encoded P2PKH bitcoin address using the DER compressed public key format. When not set, it should be a base58check encoded P2PKH bitcoin address using the DER uncompressed public key format.
*** the bits with values 0x10 and 0x08 are reserved for a future specification that contemplates using multisig as a way to combine the factors such that parties in possession of the separate factors can independently sign a proposed transaction without requiring that any party possess both factors. These bits must be 0 to comply with this version of the specification.
*** the bit with value 0x04 indicates whether a lot and sequence number are encoded into the first factor, and activates special behavior for including them in the decryption process. This applies to EC-multiplied keys only. Must be 0 for non-EC-multiplied keys.
*** remaining bits are reserved for future use and must all be 0 to comply with this version of the specification.
@@ -71,10 +75,10 @@ To keep the size of the encrypted key down, no initialization vectors (IVs) are
**16 bytes: lasthalf: An AES-encrypted key material record (contents depend on whether EC multiplication is used)
* Range in base58check encoding for non-EC-multiplied keys without compression (prefix 6PR):
** Minimum value: 6PRHv1jg1ytiE4kT2QtrUz8gEjMQghZDWg1FuxjdYDzjUkcJeGdFj9q9Vi (based on 01 42 C0 plus thirty-six 00's)
-** Maximum value: 6PRWdmoT1ZursVcr5NiD14p5bHrKVGPG7yeEoEeRb8FVaqYSHnZTLEbYsU (based on 01 42 C0 plus thirty-six FF's)
+** Maximum value: 6PRWdmoT1ZursVcr5NiD14p5bHrKVGPG7yeEoEeRb8FVaqYSHnZTLEbYsU (based on 01 42 C0 plus thirty-six FF's)
* Range in base58check encoding for non-EC-multiplied keys with compression (prefix 6PY):
** Minimum value: 6PYJxKpVnkXUsnZAfD2B5ZsZafJYNp4ezQQeCjs39494qUUXLnXijLx6LG (based on 01 42 E0 plus thirty-six 00's)
-** Maximum value: 6PYXg5tGnLYdXDRZiAqXbeYxwDoTBNthbi3d61mqBxPpwZQezJTvQHsCnk (based on 01 42 E0 plus thirty-six FF's)
+** Maximum value: 6PYXg5tGnLYdXDRZiAqXbeYxwDoTBNthbi3d61mqBxPpwZQezJTvQHsCnk (based on 01 42 E0 plus thirty-six FF's)
* Range in base58check encoding for EC-multiplied keys without compression (prefix 6Pf):
** Minimum value: 6PfKzduKZXAFXWMtJ19Vg9cSvbFg4va6U8p2VWzSjtHQCCLk3JSBpUvfpf (based on 01 43 00 plus thirty-six 00's)
** Maximum value: 6PfYiPy6Z7BQAwEHLxxrCEHrH9kasVQ95ST1NnuEnnYAJHGsgpNPQ9dTHc (based on 01 43 00 plus thirty-six FF's)
@@ -166,7 +170,7 @@ To recalculate the address:
# Derive ''passfactor'' using scrypt with ''ownerentropy'' and the user's passphrase and use it to recompute ''passpoint''
# Derive decryption key for ''pointb'' using scrypt with ''passpoint'', ''addresshash'', and ''ownerentropy''
# Decrypt ''encryptedpointb'' to yield ''pointb''
-# ECMultiply ''pointb'' by ''passfactor''. Use the resulting EC point as a public key and hash it into ''address'' using either compressed or uncompressed public key methodology as specifid in ''flagbyte''.
+# ECMultiply ''pointb'' by ''passfactor''. Use the resulting EC point as a public key and hash it into ''address'' using either compressed or uncompressed public key methodology as specified in ''flagbyte''.
=====Decryption=====
# Collect encrypted private key and passphrase from user.
@@ -180,7 +184,7 @@ To recalculate the address:
# Hash the Bitcoin address, and verify that ''addresshash'' from the encrypted private key record matches the hash. If not, report that the passphrase entry was incorrect.
==Backwards compatibility==
-Backwards compatibility is minimally applicable since this is a new standard that at most extends [[Wallet Import Format]]. It is assumed that an entry point for private key data may also accept existing formats of private keys (such as hexadecimal and [[Wallet Import Format]]); this draft uses a key format that cannot be mistaken for any existing one and preserves auto-detection capabilities.
+Backwards compatibility is minimally applicable since this is a new standard that at most extends Wallet Import Format. It is assumed that an entry point for private key data may also accept existing formats of private keys (such as hexadecimal and Wallet Import Format); this draft uses a key format that cannot be mistaken for any existing one and preserves auto-detection capabilities.
==Suggestions for implementers of proposal with alt-chains==
If this proposal is accepted into alt-chains, it is requested that the unused flag bytes not be used for denoting that the key belongs to an alt-chain.
@@ -205,8 +209,7 @@ The preliminary values of 16384, 8, and 8 are hoped to offer the following prope
==Reference implementation==
Added to alpha version of Casascius Bitcoin Address Utility for Windows available at:
-* via https: https://casascius.com/btcaddress-alpha.zip
-* at github: https://github.com/casascius/Bitcoin-Address-Utility
+* https://github.com/casascius/Bitcoin-Address-Utility
Click "Tools" then "PPEC Keygen" (provisional name)
@@ -269,7 +272,7 @@ Test 2:
Test 1:
*Passphrase: MOLON LABE
-*Passphrase code: passphraseaB8feaLQDENqCgr4gKZpmf4VoaT6qdjJNJiv7fsKvjqavcJxvuR1hy25aTu5sX
+*Passphrase code: passphraseaB8feaLQDENqCgr4gKZpmf4VoaT6qdjJNJiv7fsKvjqavcJxvuR1hy25aTu5sX
*Encrypted key: 6PgNBNNzDkKdhkT6uJntUXwwzQV8Rr2tZcbkDcuC9DZRsS6AtHts4Ypo1j
*Bitcoin address: 1Jscj8ALrYu2y9TD8NrpvDBugPedmbj4Yh
*Unencrypted private key (WIF): 5JLdxTtcTHcfYcmJsNVy1v2PMDx432JPoYcBTVVRHpPaxUrdtf8
@@ -277,9 +280,9 @@ Test 1:
*Confirmation code: cfrm38V8aXBn7JWA1ESmFMUn6erxeBGZGAxJPY4e36S9QWkzZKtaVqLNMgnifETYw7BPwWC9aPD
*Lot/Sequence: 263183/1
-Test 2:
+Test 2:
*Passphrase (all letters are Greek - test UTF-8 compatibility with this): ΜΟΛΩΝ ΛΑΒΕ
-*Passphrase code: passphrased3z9rQJHSyBkNBwTRPkUGNVEVrUAcfAXDyRU1V28ie6hNFbqDwbFBvsTK7yWVK
+*Passphrase code: passphrased3z9rQJHSyBkNBwTRPkUGNVEVrUAcfAXDyRU1V28ie6hNFbqDwbFBvsTK7yWVK
*Encrypted private key: 6PgGWtx25kUg8QWvwuJAgorN6k9FbE25rv5dMRwu5SKMnfpfVe5mar2ngH
*Bitcoin address: 1Lurmih3KruL4xDB5FmHof38yawNtP9oGf
*Unencrypted private key (WIF): 5KMKKuUmAkiNbA3DazMQiLfDq47qs8MAEThm4yL8R2PhV1ov33D
diff --git a/bip-0039.mediawiki b/bip-0039.mediawiki
index da59124cc2..bfbb9db95c 100644
--- a/bip-0039.mediawiki
+++ b/bip-0039.mediawiki
@@ -1,12 +1,15 @@
- BIP: BIP-0039
- Title: Mnemonic code for generating deterministic keys
- Authors: Marek Palatinus
- Pavol Rusnak
- Aaron Voisine
- Sean Bowe
- Status: Draft
- Type: Standards Track
+ BIP: 39
+ Layer: Applications
+ Title: Mnemonic code for generating deterministic keys
+ Author: Marek Palatinus
+ Pavol Rusnak
+ Aaron Voisine
+ Sean Bowe
+ Comments-Summary: Unanimously Discourage for implementation
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0039
+ Status: Final
+ Type: Standards Track
Created: 2013-09-10
@@ -15,35 +18,35 @@
This BIP describes the implementation of a mnemonic code or mnemonic sentence --
a group of easy to remember words -- for the generation of deterministic wallets.
-It consists of two parts: generating the mnemonic, and converting it into a
+It consists of two parts: generating the mnemonic and converting it into a
binary seed. This seed can be later used to generate deterministic wallets using
BIP-0032 or similar methods.
==Motivation==
A mnemonic code or sentence is superior for human interaction compared to the
-handling of raw binary or hexidecimal representations of a wallet seed. The
+handling of raw binary or hexadecimal representations of a wallet seed. The
sentence could be written on paper or spoken over the telephone.
This guide is meant to be a way to transport computer-generated randomness with
-a human readable transcription. It's not a way to process user-created
+a human-readable transcription. It's not a way to process user-created
sentences (also known as brainwallets) into a wallet seed.
==Generating the mnemonic==
The mnemonic must encode entropy in a multiple of 32 bits. With more entropy
security is improved but the sentence length increases. We refer to the
-initial entropy length as ENT. The recommended size of ENT is 128-256 bits.
+initial entropy length as ENT. The allowed size of ENT is 128-256 bits.
First, an initial entropy of ENT bits is generated. A checksum is generated by
-taking the first
ENT / 32
bits of its SHA256 hash. This checksum is
+taking the first ENT / 32 bits of its SHA256 hash. This checksum is
appended to the end of the initial entropy. Next, these concatenated bits
are split into groups of 11 bits, each encoding a number from 0-2047, serving
as an index into a wordlist. Finally, we convert these numbers into words and
use the joined words as a mnemonic sentence.
The following table describes the relation between the initial entropy
-length (ENT), the checksum length (CS) and the length of the generated mnemonic
+length (ENT), the checksum length (CS), and the length of the generated mnemonic
sentence (MS) in words.
BIP: 42
+ Layer: Consensus (soft fork)
Title: A finite monetary supply for Bitcoin
Author: Pieter Wuille
- Status: Draft
+ Comments-Summary: Unanimously Recommended for implementation
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0042
+ Status: Final
Type: Standards Track
Created: 2014-04-01
+ License: PD
==Abstract==
Although it is widely believed that Satoshi was an inflation-hating goldbug he never said this, and in fact programmed Bitcoin's money supply to grow indefinitely, forever. He modeled the monetary supply as 4 gold mines being discovered per mibillenium (1024 years), with equal intervals between them, each one being depleted over the course of 140 years.
-This poses obvious problems, however. Prominent among them is the discussion on what to call 1 billion Bitcoin, which symbol color to use for it, and when wallet clients should switch to it by default.
+This poses obvious problems, however. Prominent among them is the discussion on what to call 1 billion bitcoin, which symbol color to use for it, and when wallet clients should switch to it by default.
To combat this, this document proposes a controversial change: making Bitcoin's monetary supply finite.
@@ -38,7 +42,7 @@ Note that several other programming languages do not exhibit this behaviour, mak
===Floating-point approximation===
-An obvious solution would be to reimplement the shape of the subsidy curve using floating-point approximations, such as simulated annealing or quantitative easing, which have already proven their worth in consensus systems. Unfortunately, since the financial crisis everyone considers numbers with decimal points in them fishy, and integers are not well supported by Javascript.
+An obvious solution would be to reimplement the shape of the subsidy curve using floating-point approximations, such as simulated annealing or quantitative easing, which have already proven their worth in consensus systems. Unfortunately, since the financial crisis everyone considers numbers with decimal points in them fishy, and integers are not well supported by Javascript.
===Truncation===
diff --git a/bip-0043.mediawiki b/bip-0043.mediawiki
index 8f20fc8c25..f07c94aa11 100644
--- a/bip-0043.mediawiki
+++ b/bip-0043.mediawiki
@@ -1,10 +1,13 @@
- BIP: BIP-0043
- Title: Purpose Field for Deterministic Wallets
- Authors: Marek Palatinus
- Pavol Rusnak
- Status: Draft
- Type: Standards Track
+ BIP: 43
+ Layer: Applications
+ Title: Purpose Field for Deterministic Wallets
+ Author: Marek Palatinus
+ Pavol Rusnak
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0043
+ Status: Final
+ Type: Standards Track
Created: 2014-04-24
@@ -39,6 +42,8 @@ We encourage different schemes to apply for assigning a separate BIP number
and use the same number for purpose field, so addresses won't be generated
from overlapping BIP32 spaces.
+Purpose codes from 10001 to 19999 are reserved for [[https://github.com/satoshilabs/slips|SLIPs]].
+
Example: Scheme described in BIP44 should use 44' (or 0x8000002C) as purpose.
Note that m / 0' / * is already taken by BIP32 (default account), which
diff --git a/bip-0044.mediawiki b/bip-0044.mediawiki
index 847eb9ebc0..5db540c70a 100644
--- a/bip-0044.mediawiki
+++ b/bip-0044.mediawiki
@@ -1,10 +1,13 @@
- BIP: BIP-0044
- Title: Multi-Account Hierarchy for Deterministic Wallets
- Authors: Marek Palatinus
- Pavol Rusnak
- Status: Draft
- Type: Standards Track
+ BIP: 44
+ Layer: Applications
+ Title: Multi-Account Hierarchy for Deterministic Wallets
+ Author: Marek Palatinus
+ Pavol Rusnak
+ Comments-Summary: Mixed review (one person)
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0044
+ Status: Final
+ Type: Standards Track
Created: 2014-04-24
@@ -149,10 +152,10 @@ All these constants are used as hardened derivation.
This BIP is not a central directory for the registered coin types, please
visit SatoshiLabs that maintains the full list:
-[[http://doc.satoshilabs.com/slips/slip-0044.html|SLIP-0044 : Registered coin types for BIP-0044]]
+[[https://github.com/satoshilabs/slips/blob/master/slip-0044.md|SLIP-0044 : Registered coin types for BIP-0044]]
To register a new coin type, an existing wallet that implements the standard
-is required. This can be done [[https://github.com/satoshilabs/docs/blob/master/slips/slip-0044.rst|here]].
+is required and a pull request to the above file should be created.
==Examples==
@@ -260,13 +263,6 @@ is required. This can be done [[https://github.com/satoshilabs/docs/blob/master/
|m / 44' / 1' / 1' / 1 / 1
|}
-==Compatible wallets==
-
-* [[https://mytrezor.com|myTREZOR web wallet]] ([[https://github.com/trezor/webwallet|source]])
-* [[https://play.google.com/store/apps/details?id=com.bonsai.wallet32|Wallet32 @ Android]] ([[https://github.com/ksedgwic/Wallet32|source]])
-* [[https://play.google.com/store/apps/details?id=com.mycelium.wallet|Mycelium Bitcoin Wallet (Android)]] ([[https://github.com/mycelium-com/wallet|source]])
-* [[https://maza.club/encompass|Encompass]] ([[https://github.com/mazaclub/encompass|source]])
-
==Reference==
* [[bip-0032.mediawiki|BIP32 - Hierarchical Deterministic Wallets]]
diff --git a/bip-0045.mediawiki b/bip-0045.mediawiki
index f93319d47f..d72158230b 100644
--- a/bip-0045.mediawiki
+++ b/bip-0045.mediawiki
@@ -1,11 +1,14 @@
- BIP: BIP-0045
- Title: Structure for Deterministic P2SH Multisignature Wallets
- Authors: Manuel Araoz
- Ryan X. Charles
- Matias Alejo Garcia
- Status: Draft
- Type: Standards Track
+ BIP: 45
+ Layer: Applications
+ Title: Structure for Deterministic P2SH Multisignature Wallets
+ Author: Manuel Araoz
+ Ryan X. Charles
+ Matias Alejo Garcia
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0045
+ Status: Proposed
+ Type: Standards Track
Created: 2014-04-25
@@ -13,7 +16,7 @@
This BIP defines a structure for hierarchical deterministic P2SH multi-party
multi-signature wallets (HDPM wallets from now on) based on the algorithm
-described in BIP-0032 (BIP32 from now on) and purpose scheme described in
+described in BIP-0032 (BIP32 from now on) and purpose scheme described in
BIP-0043 (BIP43 from now on).
This BIP is a particular application of BIP43.
@@ -59,8 +62,8 @@ Hardened derivation is used at this level.
The index of the party creating a P2SH multisig address. The indices can
be determined independently by lexicographically sorting the purpose public
-keys of each cosigner. Each cosigner creates addresses on it's own branch,
-even though they have independent extended master public key, as explained
+keys of each cosigner. Each cosigner creates addresses on its own branch,
+even though they have independent extended master public key, as explained
in the "Address generation" section.
Note that the master public key is not shared amongst the cosigners. Only the
@@ -76,12 +79,12 @@ purpose public keys:
03f76588e06c0d688617ef365d1e58a7f1aa84daa3801380b1e7f12acc9a69cd13
-it should use `m / 45 ' / 0 / *` for
-`039863fb5f07b667d9b1ca68773c6e6cdbcac0088ffba9af46f6f6acd153d44463`,
-`m / 45 ' / 1 / *` for
-`03a473275a750a20b7b71ebeadfec83130c014da4b53f1c4743fcf342af6589a38`,
-and `m / 45 ' / 2 / *` for
-`03f76588e06c0d688617ef365d1e58a7f1aa84daa3801380b1e7f12acc9a69cd13`,
+it should use m / 45 ' / 0 / * for
+039863fb5f07b667d9b1ca68773c6e6cdbcac0088ffba9af46f6f6acd153d44463,
+m / 45 ' / 1 / * for
+03a473275a750a20b7b71ebeadfec83130c014da4b53f1c4743fcf342af6589a38,
+and m / 45 ' / 2 / * for
+03f76588e06c0d688617ef365d1e58a7f1aa84daa3801380b1e7f12acc9a69cd13,
as dictated by their lexicographical order.
@@ -99,7 +102,7 @@ chain is used for addresses which are not meant to be visible outside of the
wallet and is used for return transaction change.
For example, if cosigner 2 wants to generate a change address, he would use
-`m / 45 ' / 2 / 1 / *`, and `m / 45 ' / 2 / 0 / *` for a receive
+m / 45 ' / 2 / 1 / *, and m / 45 ' / 2 / 0 / * for a receive
address.
Non-hardened derivation is used at this level.
@@ -115,7 +118,7 @@ Non-hardened derivation is used at this level.
Each party generates their own extended master keypair and shares the
extended purpose' public key with the others, which is stored encrypted.
Each party can generate any of the other's derived public keys, but only
-his own private keys.
+his own private keys.
===Address Generation Procedure===
When generating an address, each party can independently generate the N needed
@@ -134,18 +137,18 @@ others using the next index, and calculate the needed script for the address.
Example: Cosigner #2 wants to receive a payment to the shared wallet. His last
used index on his own branch is 4. Then, the path for the next receive
-address is `m/45'/2/0/5`. He uses this same path in all of the cosigners
+address is m/45'/2/0/5. He uses this same path in all of the cosigners
trees to generate a public key for each one, and from that he gets the new
p2sh address.
====Change address case====
Again, each cosigner generates addresses only on his own branch. One of the
n cosigners wants to create an outgoing payment, for which he'll need a change
address. He generates a new address using the same procedure as above, but
-using a separate index to track the used change addresses.
+using a separate index to track the used change addresses.
Example: Cosigner #5 wants to send a payment from the shared wallet, for which
he'll need a change address. His last used change index on his own branch is
-11. Then, the path for the next change address is `m/45'/5/1/12`. He uses
+11. Then, the path for the next change address is m/45'/5/1/12. He uses
this same path in all of the cosigners trees to generate a public key for each
one, and from that he gets the new p2sh address.
@@ -160,7 +163,7 @@ that specific address (using the same path that generated the public key in
that address, but deriving the private key instead), and sign it. Once the
proposal reaches m signatures, any cosigner can broadcast it to the network,
becoming final. The specifics of how this proposal is structured, and the
-protocol to accept or reject it, belong to another BIP, in my opinion.
+protocol to accept or reject it, belong to another BIP, in my opinion.
===Address discovery===
@@ -168,8 +171,8 @@ When the master seed is imported from an external source the software should
start to discover the addresses in the following manner:
# for each cosigner:
-# derive the cosigner's node (`m / 45' / cosigner_index`)
-# for both the external and internal chains on this node (`m / 45' / cosigner_index / 0` and `m / 45' / cosigner_index / 1`):
+# derive the cosigner's node (m / 45' / cosigner_index)
+# for both the external and internal chains on this node (m / 45' / cosigner_index / 0 and m / 45' / cosigner_index / 1):
# scan addresses of the chain; respect the gap limit described below
Please note that the algorithm uses the transaction history, not address
@@ -179,7 +182,7 @@ even if the earlier ones don't have transactions
===Address gap limit===
-Address gap limit is currently set to 20. If the software hits 20 unused
+Address gap limit is currently set to 20. If the software hits 20 unused
addresses (no transactions associated with that address) in a row, it expects
there are no used addresses beyond this point and stops searching the address chain.
@@ -189,13 +192,13 @@ an external chain by generating a new address.
===Rationale===
-This stucture provides a general way of doing HDPM wallets between m-of-n
+This structure provides a general way of doing HDPM wallets between m-of-n
parties. Here are some explanations about the design decisions made.
The reason for using separate branches for each cosigner is we don't want
two of them generating the same address and receiving simultaneous payments
to it. The ideal case is that each address receives at most one payment,
-requested by the corresponding cosigner.
+requested by the corresponding cosigner.
==Examples==
@@ -241,7 +244,7 @@ requested by the corresponding cosigner.
| m / 45' / 2 / 1 / 9
|}
-==Compatible walets==
+==Compatible wallets==
* [[https://copay.io|Copay wallet]] ([[https://github.com/bitpay/copay|source]])
diff --git a/bip-0046.mediawiki b/bip-0046.mediawiki
new file mode 100644
index 0000000000..2bc4039ef6
--- /dev/null
+++ b/bip-0046.mediawiki
@@ -0,0 +1,193 @@
+
+
+== Abstract ==
+
+This BIP defines the derivation scheme for HD wallets which create timelocked addresses used for creating fidelity bonds. It also gives advice to wallet developers on how to use fidelity bonds to sign over messages, such as certificates, which are needed when using fidelity bonds that are stored offline.
+
+== Copyright ==
+
+This document is licensed under the Creative Commons CC0 1.0 Universal license.
+
+== Motivation ==
+
+Fidelity bonds are used to resist sybil attacks in certain decentralized anonymous protocols. They are created by locking up bitcoins using the `OP_CHECKLOCKTIMEVERIFY` opcode.
+
+Having a common derivation scheme allows users of wallet software to have a backup of their fidelity bonds by storing only the HD seed and a reference to this BIP. Importantly the user does not need to backup any timelock values.
+
+We largely use the same approach used in BIPs 49, 84 and 86 for ease of implementation.
+
+This allows keeping the private keys of fidelity bonds in cold storage, which increases the sybil resistance of a system without hot wallet risk.
+
+== Backwards Compatibility ==
+
+This BIP is not backwards compatible by design as described in the Considerations section of [[bip-0049.mediawiki|BIP 49]]. An incompatible wallet will not discover fidelity bonds at all and the user will notice that something is wrong.
+
+== Background ==
+
+=== Fidelity bonds ===
+
+A fidelity bond is a mechanism where bitcoin value is deliberately sacrificed to make a cryptographic identity expensive to obtain. A way to create a fidelity bond is to lock up bitcoins by sending them to a timelocked address. The valuable thing being sacrificed is the time-value-of-money.
+
+The sacrifice must be done in a way that can be proven to a third party. This proof can be made by showing the UTXO outpoint, the address redeemscript and a signature which signs a message using the private key corresponding to the public key in the redeemscript.
+
+The sacrificed value is an objective measurement that can't be faked and which can be verified by anybody (just like, for example PoW mining). Sybil attacks can be made very expensive by forcing a hypothetical sybil attacker to lock up many bitcoins for a long time. JoinMarket implements fidelity bonds for protection from sybil attackers. At the time of writing over 600 BTC in total have been locked up with some for many years. Their UTXOs and signatures have been advertised to the world as proof. We can calculate that for a sybil attacker to succeed in unmixing all the CoinJoins, they would have to lock up over 100k BTC for several years.
+
+=== Fidelity bonds in cold storage ===
+
+To allow for holding fidelity bonds in cold storage, there is an intermediate keypair called the certificate.
+
+ UTXO key ---signs---> certificate ---signs---> endpoint
+
+Where the endpoint might be a IRC nickname or Tor onion hostname. The certificate keypair can be kept online and used to prove ownership of the fidelity bond. Even if the hot wallet private keys are stolen, the coins in the timelocked address will still be safe, although the thief will be able to impersonate the fidelity bond until the expiry.
+
+== Rationale ==
+
+It is useful for the user to avoid having to keep a record of the timelocks in the time-locked addresses. So only a limited small set of timelocks are defined by this BIP. This way the user must only store their seed phrase, and knowledge that they have coins stored using this BIP standard. The user doesn't need to remember or store any dates.
+
+This standard is already implemented and deployed in JoinMarket. As most changes would require a protocol change of a live system, there is limited scope for changing this standard in review. This BIP is more about documenting something which already exists, warts and all.
+
+== Specifications ==
+
+This BIP defines the two needed steps to derive multiple deterministic addresses based on a [[bip-0032.mediawiki|BIP 32]] master private key. It also defines the format of the certificate that can be signed by the deterministic address key.
+
+=== Public key derivation ===
+
+To derive a public key from the root account, this BIP uses a similar account-structure as defined in BIP [[bip-0084.mediawiki|44]] but with change set to 2.
+
+
+m / 84' / 0' / 0' / 2 / index
+
+
+A key derived with this derivation path pattern will be referred to as derived_key further
+in this document.
+
+For index, addresses are numbered from 0 in a sequentially increasing manner with a fixed upper bound: The index only goes up to 959 inclusive. Only 960 addresses can be derived for a given BIP32 master key. Furthermore there is no concept of a gap limit, instead wallets must always generate all 960 addresses and check for all of them if they have a balance and history.
+
+=== Timelock derivation ===
+
+The timelock used in the time-locked address is derived from the index. The timelock is a unix time. It is always at the start of the first second at the beginning of the month (see [[#Test vectors|Test vectors]]). The index counts upwards the months from January 2020, ending in December 2099. At 12 months per year for 80 years this totals 960 timelocks. Note that care must be taken with the year 2038 problem on 32-bit systems.
+
+
+year = 2020 + index // 12
+month = 1 + index % 12
+
+
+
+=== Address derivation ===
+
+To derive the address from the above calculated public key and timelock, we create a witness script which locks the funds until the timelock, and then checks the signature of the derived_key. The witness script is hashed with SHA256 to produce a 32-byte hash value that forms the witness program in the output script of the P2WSH address.
+
+ witnessScript: OP_CHECKLOCKTIMEVERIFY OP_DROP OP_CHECKSIG
+ witness:
+ scriptSig: (empty)
+ scriptPubKey: 0 <32-byte-hash>
+ (0x0020{32-byte-hash})
+
+=== Message signing ===
+
+In order to support signing of certificates, implementors should support signing ASCII messages.
+
+The certificate message is defined as `"fidelity-bond-cert" || "|" || cert_pubkey || "|" || cert_expiry`.
+
+The certificate expiry `cert_expiry` is the number of the 2016-block period after which the certificate is no longer valid. For example, if `cert_expiry` is 330 then the certificate will become invalid after block height 665280 (:=330x2016). The purpose of the expiry parameter is so that in case the certificate keypair is compromised, the attacker can only impersonate the fidelity bond for a limited amount of time.
+
+A certificate message can be created by another application external to this standard. It is then prepended with the string `0x18 || "Bitcoin Signed Message:\n"` and a byte denoting the length of the certificate message. The whole thing is then signed with the private key of the derived_key. This part is identical to the "Sign Message" function which many wallets already implement.
+
+Almost all wallets implementing this standard can use their already-existing "Sign Message" function to sign the certificate message. As the certificate message itself is always an ASCII string, the wallet may not need to specially implement this section at all but just rely on users copypasting their certificate message into the already-existing "Sign Message" user interface. This works as long as the wallet knows how to use the private key of the timelocked address for signing messages.
+
+It is most important for wallet implementations of this standard to support creating the certificate signature. Verifying the certificate signature is less important.
+
+
+== Test vectors ==
+
+
+mnemonic = abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about
+rootpriv = xprv9s21ZrQH143K3GJpoapnV8SFfukcVBSfeCficPSGfubmSFDxo1kuHnLisriDvSnRRuL2Qrg5ggqHKNVpxR86QEC8w35uxmGoggxtQTPvfUu
+rootpub = xpub661MyMwAqRbcFkPHucMnrGNzDwb6teAX1RbKQmqtEF8kK3Z7LZ59qafCjB9eCRLiTVG3uxBxgKvRgbubRhqSKXnGGb1aoaqLrpMBDrVxga8
+
+// First timelocked address = m/84'/0'/0'/2/0
+derived private_key = L2tQBEdhC48YLeEWNg3e4msk94iKfyVa9hdfzRwUERabZ53TfH3d
+derived public_key = 02a1b09f93073c63f205086440898141c0c3c6d24f69a18db608224bcf143fa011
+unix locktime = 1577836800
+string locktime = 2020-01-01 00:00:00
+redeemscript = 0400e10b5eb1752102a1b09f93073c63f205086440898141c0c3c6d24f69a18db608224bcf143fa011ac
+scriptPubKey = 0020bdee9515359fc9df912318523b4cd22f1c0b5410232dc943be73f9f4f07e39ad
+address = bc1qhhhf29f4nlyalyfrrpfrknxj9uwqk4qsyvkujsa7w0ulfur78xkspsqn84
+
+// Test certificate using the first timelocked address
+// Note that as signatures contains a random nonce, it might not be exactly the same when your code generates it
+// p2pkh address is the p2pkh address corresponding to the derived public key, it can be used to verify the message
+// signature in any wallet that supports Verify Message.
+// As mentioned before, it is more important for implementors of this standard to support signing such messages, not verifying them
+message = fidelity-bond-cert|020000000000000000000000000000000000000000000000000000000000000001|375
+address = bc1qhhhf29f4nlyalyfrrpfrknxj9uwqk4qsyvkujsa7w0ulfur78xkspsqn84
+p2pkh address = 16vmiGpY1rEaYnpGgtG7FZgr2uFCpeDgV6
+signature = H2b/90XcKnIU/D1nSCPhk8OcxrHebMCr4Ok2d2yDnbKDTSThNsNKA64CT4v2kt+xA1JmGRG/dMnUUH1kKqCVSHo=
+
+// 2nd timelocked address = m/84'/0'/0'/2/1
+derived private_key = KxctaFBzetyc9KXeUr6jxESCZiCEXRuwnQMw7h7hroP6MqnWN6Pf
+derived public_key = 02599f6db8b33265a44200fef0be79c927398ed0b46c6a82fa6ddaa5be2714002d
+unix locktime = 1580515200
+string locktime = 2020-02-01 00:00:00
+redeemscript = 0480bf345eb1752102599f6db8b33265a44200fef0be79c927398ed0b46c6a82fa6ddaa5be2714002dac
+scriptPubKey = 0020b8f898643991608524ed04e0c6779f632a57f1ffa3a3a306cd81432c5533e9ae
+address = bc1qhrufsepej9sg2f8dqnsvvaulvv490u0l5w36xpkds9pjc4fnaxhq7pcm4h
+
+// timelocked address after the year 2038 = m/84'/0'/0'/2/240
+derived private_key = L3SYqae23ZoDDcyEA8rRBK83h1MDqxaDG57imMc9FUx1J8o9anQe
+derived public_key = 03ec8067418537bbb52d5d3e64e2868e67635c33cfeadeb9a46199f89ebfaab226
+unix locktime = 2208988800
+string locktime = 2040-01-01 00:00:00
+redeemscript = 05807eaa8300b1752103ec8067418537bbb52d5d3e64e2868e67635c33cfeadeb9a46199f89ebfaab226ac
+scriptPubKey = 0020e7de0ad2720ae1d6cc9b6ad91af57eb74646762cf594c91c18f6d5e7a873635a
+address = bc1qul0q45njptsadnymdtv34at7karyva3v7k2vj8qc7m2702rnvddq0z20u5
+
+// last timelocked address = m/84'/0'/0'/2/959
+derived private_key = L5Z9DDMnj5RZMyyPiQLCvN48Xt7GGmev6cjvJXD8uz5EqiY8trNJ
+derived public_key = 0308c5751121b1ae5c973cdc7071312f6fc10ab864262f0cbd8134f056166e50f3
+unix locktime = 4099766400
+string locktime = 2099-12-01 00:00:00
+redeemscript = 0580785df400b175210308c5751121b1ae5c973cdc7071312f6fc10ab864262f0cbd8134f056166e50f3ac
+scriptPubKey = 0020803268e042008737cf439748cbb5a4449e311da9aa64ae3ac56d84d059654f85
+address = bc1qsqex3czzqzrn0n6rjayvhddygj0rz8df4fj2uwk9dkzdqkt9f7zs5c493u
+
+// Test certificate and endpoint signing using the first timelocked address = m/84'/0'/0'/2/0 (see above)
+bond private_key = L2tQBEdhC48YLeEWNg3e4msk94iKfyVa9hdfzRwUERabZ53TfH3d
+bond p2pkh address = 16vmiGpY1rEaYnpGgtG7FZgr2uFCpeDgV6
+
+certificate private_key = KyZpNDKnfs94vbrwhJneDi77V6jF64PWPF8x5cdJb8ifgg2DUc9d
+certificate public_key = 0330d54fd0dd420a6e5f8d3624f5f3482cae350f79d5f0753bf5beef9c2d91af3c
+certificate p2pkh address = 1JaUQDVNRdhfNsVncGkXedaPSM5Gc54Hso
+
+certificate message = fidelity-bond-cert|0330d54fd0dd420a6e5f8d3624f5f3482cae350f79d5f0753bf5beef9c2d91af3c|375
+certificate signature = INOP3cB9UW7F1e1Aglj8rI9QhnyxmgWDEPt+nOMvl7hJJne7rH/KCNDYvLiqNuB9qWaWUojutjRsgPJrvyDQ+0Y=
+
+// example endpoint signing two IRC nicknames (used in JoinMarket)
+endpoint message = J54LS6YyJPoseqFS|J55VZ6U6ZyFDNeuv
+endpoint signature = H18WE4MugDNoWZIf9jU0njhQptdUyBDUf7lToG9bpMKmeJK0lOoABaDs5bKnohSuZ0e9gnSco5OL9lXdKU7gP5E=
+
+
+Code generating these test vectors can be found here: https://github.com/chris-belcher/timelocked-addresses-fidelity-bond-bip-testvectors
+
+== Reference ==
+
+* [[https://gist.github.com/chris-belcher/18ea0e6acdb885a2bfbdee43dcd6b5af/|Design for improving JoinMarket's resistance to sybil attacks using fidelity bonds]]
+* [[https://github.com/JoinMarket-Org/joinmarket-clientserver/blob/master/docs/fidelity-bonds.md|JoinMarket fidelity bonds doc page]]
+* [[bip-0065.mediawiki|BIP65 - OP_CHECKLOCKTIMEVERIFY]]
+* [[bip-0032.mediawiki|BIP32 - Hierarchical Deterministic Wallets]]
+* [[bip-0044.mediawiki|BIP44 - Multi-Account Hierarchy for Deterministic Wallets]]
+* [[bip-0049.mediawiki|BIP49 - Derivation scheme for P2WPKH-nested-in-P2SH based accounts]]
+* [[bip-0084.mediawiki|BIP84 - Derivation scheme for P2WPKH based accounts]]
+* [[bip-0086.mediawiki|BIP86 - Key Derivation for Single Key P2TR Outputs]]
diff --git a/bip-0047.mediawiki b/bip-0047.mediawiki
index e460a12d81..c44bea9d3b 100644
--- a/bip-0047.mediawiki
+++ b/bip-0047.mediawiki
@@ -1,18 +1,26 @@
RECENT CHANGES:
-
-* (21 Sep 2015) Correct base58check version byte
-
-* (18 Sep 2015) Clarify decoding of notification transactions
+* (15 Feb 2021) Finalize specification
+* (28 Sep 2017) Adjust text to match test vectors
+* (19 Apr 2016) Define version 2 payment codes
+==Status==
+
+This BIP can be considered final in terms of enabling compatibility with wallets that implement version 1 and version 2 reusable payment codes, however future developments of the reusable payment codes specification will not be distributed via the BIP process.
+
+The Open Bitcoin Privacy Project RFC repo should be consulted for specifications related to version 3 or higher payment codes: https://github.com/OpenBitcoinPrivacyProject/rfc
+
==Abstract==
This BIP defines a technique for creating a payment code which can be publicly advertised and associated with a real-life identity without creating the loss of security or privacy inherent to P2PKH address reuse.
@@ -29,9 +37,29 @@ Payment codes add identity information to transactions which is useful in a merc
We define the following 3 levels in BIP32 path:
-
+
m / purpose' / coin_type' / identity'
-
+
+
+The child keys derived from an identity are used in different ways:
+
+
+m / purpose' / coin_type' / identity' / 0
+
+
+The 0th (non-hardened) child is the notification key.
+
+
+m / purpose' / coin_type' / identity' / 0 through 2147483647
+
+
+These (non-hardened) keypairs are used for ECDH to generate deposit addresses.
+
+
+m / purpose' / coin_type' / identity' / 0' through 2147483647'
+
+
+These (hardened) keypairs are ephemeral payment codes.
Apostrophe in the path indicates that BIP32 hardened derivation is used.
@@ -49,19 +77,51 @@ Hardened derivation is used at this level.
===Identity===
-Identity is a particular extended public/private key pair. The extended public key is a payment code.
+The identity derivation level produces an extended public key and its associated extended private key.
+
+When the extended public key at this level is combined with the metadata specified in the Representation section below, the resulting entity is called a "payment code."
-Identities SHOULD have 1:1 correspondence with a BIP44 account, as in each BIP44 account in an HD wallet should be assigned exactly one payment code which shares the same index value.
+This derivation level is equivalent to the Account level in BIP-44. Wallets SHOULD treat payment codes as intrinsically part of the BIP-44 account at the same index and create payment codes and accounts as pairs.
+
+For example, the payment code created represented by (m / 47' / 0' / 0') is part of the account represented by (m / 44' / 0' / 0').
+
+The second account in a wallet consists of the new account/payment code pair created by using an index of 1 in as the account/identity level of both paths.
+
+Incoming payments received via this specification are equivalent to payments received to BIP-44 addresses, and unspent outputs from both types of addresses can be used as inputs in the same outgoing transaction.
Hardened derivation is used at this level.
Except where noted, all keys derived from a payment code use the public derivation method.
+==Versions==
+
+Payment codes contain a version byte which identifies a specific set of behavior.
+
+Unless otherwise specified, payment codes of different versions are interoperable. If Alice uses a version x payment code, and Bob uses a version y payment code, they can still send and receive transactions between each other.
+
+Currently specified versions:
+
+* Version 1
+** Address type: P2PKH
+** Notification type: address
+* Version 2
+** Address type: P2PKH
+** Notification type: bloom-multisig
+
+===Recommended Versions===
+
+* Wallets which have bloom filtering capabilities SHOULD create version 2 payment codes instead of version 1 payment codes.
+* Version 1 payment codes are only recommended for wallets which lack access to bloom filtering capability.
+
+==Version 1==
+
+===Representation===
+
====Binary Serialization====
A payment code contains the following elements:
-* Byte 0: type. required value: 0x01
+* Byte 0: version. required value: 0x01
* Byte 1: features bit field. All bits must be zero except where specified elsewhere in this specification
** Bit 0: Bitmessage notification
** Bits 1-7: reserved
@@ -85,23 +145,28 @@ It is assumed that Alice can easily obtain Bob's payment code via a suitable met
====Definitions====
-* Payment code: an extended public key which is associated with a particular identity
+* Payment code: an extended public key and associated metadata which is associated with a particular identity/account
* Notification address: the P2PKH address associated with the 0th public key derived from a payment code
* Notification transaction: a transaction which sends an output to a notification address which includes an embedded payment code
+* Designated input: the first input in the notification transaction which exposes an secp256k1 pubkey in either its signature script, or in the redeem script or pubkey script of the output being spent
+* Designated pubkey: the first secp256k1 pubkey pushed to the stack during script execution for the designated input
+* Outpoint: the specific output of a previous transaction which is being spent. See the Reference section for the binary serialization
====Notification Transaction====
Prior to the first time Alice initiates a transaction to Bob, Alice MUST inform Bob of her payment code via the following procedure:
+Note: this procedure is used if Bob uses a version 1 payment code (regardless of the version of Alice's payment code). If Bob's payment code is not version 1, see the appropriate section in this specification.
+
# Alice constructs a transaction which sends a small quantity of bitcoins to Bob's notification address (notification transaction)
## The inputs selected for this transaction MUST NOT be easily associated with Alice's notification address
# Alice derives a unique shared secret using ECDH:
-## Alice selects the private key corresponding to the first exposed public key, of the first pubkey-exposing input, of the transaction:
a
+## Alice selects the private key corresponding to the designated pubkey:
a
## Alice selects the public key associated with Bob's notification address:
B, where B = bG
## Alice calculates a secret point:
S = aB
-## Alice calculates a 64 byte blinding factor:
s = HMAC-SHA512(x, o)
+## Alice calculates a 64 byte blinding factor:
s = HMAC-SHA512(o, x)
### "x" is the x value of the secret point
-### "o" is the outpoint being spent by the first pubkey-exposing input of the transaction.
+### "o" is the outpoint being spent by the designated input
# Alice serializes her payment code in binary form.
# Alice renders her payment code (P) unreadable to anyone except Bob:
## Replace the x value with x':
x' = x XOR (first 32 bytes of s)
@@ -112,12 +177,12 @@ Prior to the first time Alice initiates a transaction to Bob, Alice MUST inform
# Bob watches for any transactions which create an output at his notification address.
# When a transaction is received, the client examines it to determine if it contains a standard OP_RETURN output with an 80 byte payload (notification transactions).
# If the first byte of the payload in a notification transaction is 0x01:
-## Bob selects the first exposed public key, of the first pubkey-exposing input, of the transaction:
A, where A = aG
+## Bob selects the designated pubkey:
A, where A = aG
## Bob selects the private key associated with his notification address:
b
## Bob calculates a secret point:
S = bA
-## Bob calculates the binding factor:
s = HMAC-SHA512(x, o)
+## Bob calculates the blinding factor:
s = HMAC-SHA512(x, o)
### "x" is the x value of the secret point
-### "o" is the outpoint being spent by the first pubkey-exposing input of the transaction.
+### "o" is the outpoint being spent by the designated input.
## Bob interprets the 80 byte payload as a payment code, except:
### Replace the x value with x':
x' = x XOR (first 32 bytes of s)
### Replace the chain code with c':
c' = c XOR (last 32 bytes of s)
@@ -135,9 +200,31 @@ Bitcoins received via notification transactions require special handling in orde
# Outputs received to notification addresses MAY be passed through a mixing service before being added to the user's spendable balance.
# Outputs received to notification addresses MAY be donated to miners using dust-b-gone or an equivalent procedure.
+=====Standard Notification Transaction Scripts=====
+
+Alice SHOULD use an input script in one of the following standard forms to expose a public key, and compliant applications SHOULD recognize all of these forms.
+
+* P2PK (pay to pubkey)
+* P2PKH (pay to pubkey hash)
+* Multisig (bare multisig, without P2SH)
+* a script which spends any of the above script forms via P2SH (pay to script hash)
+
+Compatible wallets MAY provide a method for a user to manually specify the public key associated with a notification transaction in order to recover payment codes sent via non-standard notification transactions.
+
+=====Post-Notification Privacy Considerations=====
+
+Incautious handling of change outputs from notification transactions may cause unintended loss of privacy.
+
+The recipient of a transaction which spends a change output from a prior notification transaction will learn about the potential connection between the sender and the recipient of the notification transaction.
+
+The following actions are recommended to reduce this risk:
+
+* Wallets which support mixing SHOULD mix change outputs from notification transactions prior to spending them
+* Wallets which do not support mixing MAY simulate mixing by creating a transaction which spends the change output to the next external BIP44 address
+
====Sending====
-# Each time Alice wants to initiate a transaction to Bob, Alice derives a unique P2PKH address for the transaction using ECDH follows:
+# Each time Alice wants to initiate a transaction to Bob, Alice derives a unique P2PKH address for the transaction using ECDH as follows:
## Alice selects the 0th private key derived from her payment code:
a
## Alice selects the next unused public key derived from Bob's payment code, starting from zero:
B, where B = bG
### The "next unused" public key is based on an index specific to the Alice-Bob context, not global to either Alice or Bob
@@ -148,7 +235,7 @@ Bitcoins received via notification transactions require special handling in orde
# Bob is watching for incoming payments on B' ever since he received the notification transaction from Alice.
-## Bob calculates n shared secrets with Alice, using the 0th public key derived Alice's payment code, and private keys 0 - n derived from Bob's payment code, where n is his desired lookahead window.
+## Bob calculates n shared secrets with Alice, using the 0th public key derived from Alice's payment code, and private keys 0 - n derived from Bob's payment code, where n is his desired lookahead window.
## Bob calculates the ephemeral deposit addresses using the same procedure as Alice:
B' = B + sG
## Bob calculate the private key for each ephemeral address as:
b' = b + s
@@ -188,13 +275,15 @@ Normal operation of a payment code-enabled wallet can be performed by an SPV cli
Recovering a wallet from a seed, however, does require access to a fully-indexed blockchain.
-The required data may be obtained from copy of the blockchain under the control of the user, or via a publicly-queriable blockchain explorer.
+The required data may be obtained from copy of the blockchain under the control of the user, or via a publicly-queryable blockchain explorer.
When querying a public blockchain explorer, wallets SHOULD connect to the explorer through Tor (or equivalent) and SHOULD avoid grouping queries in a manner that associates ephemeral addresses with each other.
Previously-spendable funds will generally not be lost or become inaccessible after a recovery from a seed, but all information regarding previous outgoing payments will be lost.
-The metadata which a wallet must store regarding the state an identity consists of:
+In order to recover received funds from a seed, the wallet must obtain every notification it has ever received to its notification address, including all spent transactions. It then re-establishes its lookahead window for each subchain by scanning every derived address sequentially until it locates a contiguous block of unused addresses of a user-specified length.
+
+The metadata which a wallet must store to properly process outgoing transactions consists of:
# A list of every payment code to which the identity has sent a notification transaction.
## This list is lost if a wallet must be recovered from a seed.
@@ -229,11 +318,11 @@ A recipient specifies their preference for alternate notification by setting the
===Bitmessage Notification===
-A recipient prefers to receive notifications via Bitmessage indiates this preference by:
+A recipient which prefers to receive notifications via Bitmessage indicates this preference by:
* Setting bit 0 of the features byte to 1
* Setting byte 67 of the serialized payment code to the desired Bitmessage address version
-* Setting byte 67 of the serialized payment code to the desired Bitmessage stream number
+* Setting byte 68 of the serialized payment code to the desired Bitmessage stream number
The sender uses this information to construct a valid notification Bitmessage address:
@@ -247,12 +336,51 @@ The sender transmits their payment code in base58 form to the calculated Bitmess
In order to use Bitmessage notification, the recipient must have a Bitmessage client which listens at the address which the senders will derive and is capable of relaying received payment codes to the Bitcoin wallet.
+==Version 2==
+
+Version 2 payment codes behave identifically to version 1 payment codes, except as modified below.
+
+===Representation===
+
+====Binary Serialization====
+
+* Byte 0: version. required value: 0x02
+
+===Protocol===
+
+====Definitions====
+
+* Notification change output: the change output from a notification transaction which resides in the sender's wallet, but can be automatically located by the intended recipient
+* Payment code identifier: a 33 byte representation of a payment code constructed by prepending 0x02 to the SHA256 hash of the binary serialization of the payment code
+
+====Notification Transaction====
+
+Note: this procedure is used if Bob uses a version 2 payment code (regardless of the version of Alice's payment code). If Bob's payment code is not version 2, see the appropriate section in this specification.
+
+# Construct a notification transaction as per the version 1 instructions, except do not create the output to Bob's notification address
+# Create a notification change address as follows:
+## Obtain the pubkey corresponding to the next change address
+## Construct a multisig output in the form:
+
OP_1 OP_2 OP_CHECKMULTISIG
+
+The relative ordering of the payment code identifier and change address pubkey in the above script MAY be randomized
+
+Bob detects notification transactions by adding his payment code identifier to his bloom filter.
+
+# When the filter returns a notification transaction, the sender's payment code is unblinded using the same procedure as for version 1 notification transactions.
+
+Alice's wallet should spend the notification change output at the next appropriate opportunity.
+
+==Test Vectors==
+
+* [[https://gist.github.com/SamouraiDev/6aad669604c5930864bd|BIP47 Reusable Payment Codes Test Vectors]]
+
==Reference==
* [[bip-0032.mediawiki|BIP32 - Hierarchical Deterministic Wallets]]
* [[bip-0043.mediawiki|BIP43 - Purpose Field for Deterministic Wallets]]
* [[bip-0044.mediawiki|BIP44 - Multi-Account Hierarchy for Deterministic Wallets]]
-* [[https://bitcoin.org/en/glossary/outpoint|Outpoint]]
+* [[https://bitcoin.org/en/developer-reference#outpoint|Outpoint]]
* [[https://github.com/petertodd/dust-b-gone|dust-b-gone]]
* [[https://en.bitcoin.it/wiki/Base58Check_encoding|Base58Check encoding]]
* [[https://bitmessage.org/bitmessage.pdf|Bitmessage]]
diff --git a/bip-0048.mediawiki b/bip-0048.mediawiki
new file mode 100644
index 0000000000..dbfac3f247
--- /dev/null
+++ b/bip-0048.mediawiki
@@ -0,0 +1,251 @@
+
+
+==Abstract==
+
+This BIP defines a logical hierarchy for deterministic multi-sig wallets based on an algorithm
+described in BIP-0067 (BIP67 from now on), BIP-0032 (BIP32 from now on), purpose scheme described in
+BIP-0043 (BIP43 from now on), and multi-account hierarchy described in
+BIP-0044 (BIP44 from now on).
+
+This BIP is a particular application of BIP43.
+
+==Copyright==
+
+This BIP falls under the MIT License.
+
+==Motivation==
+
+The motivation of this BIP is to define the existing industry wide practice of utilizing m/48'
+derivation paths in hierarchical deterministic multi-sig wallets so that other developers may
+benefit from a standard. This BIP allows for future script types to easily be appended to the
+specification so that a new BIP is not required for every future script type.
+
+The hierarchy proposed in this paper is quite comprehensive. It allows the handling of
+multiple accounts, external and internal chains per account, multiple script types and
+millions of addresses per chain.
+
+This paper was inspired from BIP44.
+
+==Backwards compatibility==
+
+Currently a number of wallets utilize the m/48' derivation scheme for HD multi-sig accounts.
+This BIP is intended to maintain the *existing* real world use of the m/48' derivation.
+No breaking changes are made so as to avoid "loss of funds" to existing users.
+Wallets which currently support the m/48' derivation will not need to make any changes
+to comply with this BIP.
+
+==Specification==
+
+===Key sorting===
+
+Any wallet that supports BIP48 inherently supports deterministic key sorting as per BIP67 so that all possible
+multi-signature addresses/scripts are derived from deterministically sorted public keys.
+
+===Path levels===
+
+We define the following 6 levels in BIP32 path:
+
+
+
+h or ' in the path indicates that BIP32 hardened derivation is used.
+
+Each level has a special meaning, described in the chapters below.
+
+===Purpose===
+
+Purpose is a constant set to 48' following the BIP43 recommendation.
+It indicates that the subtree of this node is used according to this specification.
+
+Hardened derivation is used at this level.
+
+===Coin type===
+
+One master node (seed) can be used for multiple Bitcoin networks.
+Sharing the same space for various networks has some disadvantages.
+
+Avoiding reusing addresses across networks and improving privacy issues.
+
+Coin type 0 for mainnet and 1 for testnet.
+
+Hardened derivation is used at this level.
+
+===Account===
+
+This level splits the key space into independent user identities, following the BIP44 pattern,
+so the wallet never mixes the coins across different accounts.
+
+Users can use these accounts to organize the funds in the same
+fashion as bank accounts; for donation purposes (where all
+addresses are considered public), for saving purposes,
+for common expenses etc.
+
+Accounts are numbered from index 0 in sequentially increasing manner.
+This number is used as child index in BIP32 derivation.
+
+Hardened derivation is used at this level.
+
+===Script===
+
+This level splits the key space into two separate script_type(s). To provide
+forward compatibility for future script types this specification can be easily extended.
+
+Currently the only script types covered by this BIP are Native Segwit (p2wsh) and
+Nested Segwit (p2sh-p2wsh).
+
+The following path represents Nested Segwit (p2sh-p2wsh) mainnet, account 0:
+1': Nested Segwit (p2sh-p2wsh) m/48'/0'/0'/1'
+
+The following path represents Native Segwit (p2wsh) mainnet, account 0:
+2': Native Segwit (p2wsh) m/48'/0'/0'/2'
+
+The recommended default for wallets is pay to witness script hash m/48'/0'/0'/2'.
+
+To add new script types submit a PR to this specification and include it in the list above:
+X': Future script type m/48'/0'/0'/X'
+
+===Change===
+
+Constant 0 is used for external chain and constant 1 for internal chain (also
+known as change addresses). External chain is used for addresses that are meant
+to be visible outside of the wallet (e.g. for receiving payments). Internal
+chain is used for addresses which are not meant to be visible outside of the
+wallet and is used for return transaction change.
+
+Public derivation is used at this level.
+
+===Index===
+
+Addresses are numbered from index 0 in sequentially increasing manner.
+This number is used as child index in BIP32 derivation.
+
+Public derivation is used at this level.
+
+==Examples==
+
+{|
+|network
+|account
+|script
+|chain
+|address
+|path
+|-
+|mainnet
+|first
+|p2wsh
+|external
+|first
+|m / 48' / 0' / 0' / 2' / 0 / 0
+|-
+|mainnet
+|first
+|p2wsh
+|external
+|second
+|m / 48' / 0' / 0' / 2' / 0 / 1
+|-
+|mainnet
+|first
+|p2wsh
+|change
+|first
+|m / 48' / 0' / 0' / 2' / 1 / 0
+|-
+|mainnet
+|first
+|p2wsh
+|change
+|second
+|m / 48' / 0' / 0' / 2' / 1 / 1
+|-
+|mainnet
+|second
+|p2wsh
+|external
+|first
+|m / 48' / 0' / 1' / 2' / 0 / 0
+|-
+|mainnet
+|second
+|p2wsh
+|external
+|second
+|m / 48' / 0' / 1' / 2' / 0 / 1
+|-
+|testnet
+|first
+|p2sh-p2wsh
+|external
+|first
+|m / 48' / 1' / 0' / 1' / 0 / 0
+|-
+|testnet
+|first
+|p2wsh
+|external
+|second
+|m / 48' / 1' / 0' / 2' / 0 / 1
+|-
+|testnet
+|first
+|p2wsh
+|change
+|first
+|m / 48' / 1' / 0' / 2' / 1 / 0
+|-
+|testnet
+|first
+|p2wsh
+|change
+|second
+|m / 48' / 1' / 0' / 2' / 1 / 1
+|-
+|testnet
+|second
+|p2wsh
+|external
+|first
+|m / 48' / 1' / 1' / 2' / 0 / 0
+|-
+|testnet
+|second
+|p2wsh
+|external
+|second
+|m / 48' / 1' / 1' / 2' / 0 / 1
+|-
+|testnet
+|second
+|p2wsh
+|change
+|first
+|m / 48' / 1' / 1' / 2' / 1 / 0
+|-
+|testnet
+|second
+|p2wsh
+|change
+|second
+|m / 48' / 1' / 1' / 2' / 1 / 1
+|}
+
+
+==Reference==
+
+* [[bip-0067.mediawiki|BIP67 - Deterministic Pay-to-script-hash multi-signature addresses through public key sorting]]
+* [[bip-0032.mediawiki|BIP32 - Hierarchical Deterministic Wallets]]
+* [[bip-0043.mediawiki|BIP43 - Purpose Field for Deterministic Wallets]]
+* [[bip-0044.mediawiki|BIP44 - Multi-Account Hierarchy for Deterministic Wallets]]
diff --git a/bip-0049.mediawiki b/bip-0049.mediawiki
new file mode 100644
index 0000000000..3e37a0164b
--- /dev/null
+++ b/bip-0049.mediawiki
@@ -0,0 +1,117 @@
+
+ BIP: 49
+ Layer: Applications
+ Title: Derivation scheme for P2WPKH-nested-in-P2SH based accounts
+ Author: Daniel Weigl
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0049
+ Status: Final
+ Type: Standards Track
+ Created: 2016-05-19
+ License: PD
+
+
+==Abstract==
+
+This BIP defines the derivation scheme for HD wallets using the P2WPKH-nested-in-P2SH ([[bip-0141.mediawiki|BIP 141]]) serialization format for segregated witness transactions.
+
+==Motivation==
+
+With the usage of P2WPKH-nested-in-P2SH ([[bip-0141.mediawiki#p2wpkh-nested-in-bip16-p2sh|BIP 141]]) transactions it is necessary to have a common derivation scheme.
+It allows the user to use different HD wallets with the same masterseed and/or a single account seamlessly.
+
+Thus the user needs to create dedicated segregated witness accounts, which ensures that only wallets compatible with this BIP
+will detect the accounts and handle them appropriately.
+
+===Considerations===
+Two generally different approaches are possible for current BIP44 capable wallets:
+
+1) Allow the user to use the same account(s) that they already use, but add segregated witness encoded addresses to it.
+
+1.1) Use the same public keys as defined in BIP44, but in addition to the normal P2PKH address also derive the P2SH address from it.
+
+1.2) Use the same account root, but branch off and derive different external and internal chain roots to derive dedicated public keys for the segregated witness addresses.
+
+2) Create dedicated accounts used only for segregated witness addresses.
+
+The solutions from point 1 have a common disadvantage: if a user imports/recovers a BIP49-compatible wallet masterseed into/in a non-BIP49-compatible wallet, the account might show up but also it might miss some UTXOs.
+
+Therefore this BIP uses solution 2, which fails in a more visible way. Either the account shows up or not at all. The user does not have to check his balance after using the same seed in different wallets.
+
+
+==Specifications==
+
+This BIP defines the two needed steps to derive multiple deterministic addresses based on a [[bip-0032.mediawiki|BIP 32]] root account.
+
+===Public key derivation===
+
+To derive a public key from the root account, this BIP uses the same account-structure as defined in
+[[bip-0044.mediawiki|BIP 44]], but only uses a different purpose value to indicate the different transaction
+serialization method.
+
+
+
+For the `purpose`-path level it uses `49'`. The rest of the levels are used as defined in BIP44.
+
+
+===Address derivation===
+
+To derive the P2SH address from the above calculated public key, we use the encapsulation defined in [[bip-0141.mediawiki#p2wpkh-nested-in-bip16-p2sh|BIP 141]]:
+
+ witness:
+ scriptSig: <0 <20-byte-key-hash>>
+ (0x160014{20-byte-key-hash})
+ scriptPubKey: HASH160 <20-byte-script-hash> EQUAL
+ (0xA914{20-byte-script-hash}87)
+
+
+===Extended Key Version===
+
+When serializing extended keys, this scheme uses alternate version bytes. Extended public keys use 0x049d7cb2 to produce a "ypub" prefix, and private keys use 0x049d7878 to produce a "yprv" prefix. Testnet uses 0x044a5262 "upub" and 0x044a4e28 "uprv."
+
+Additional registered version bytes are listed in [[https://github.com/satoshilabs/slips/blob/master/slip-0132.md|SLIP-0132]].
+
+
+==Backwards Compatibility==
+
+This BIP is not backwards compatible by design as described under [[#considerations|considerations]]. An incompatible wallet will not discover accounts at all and the user will notice that something is wrong.
+
+
+==Test vectors==
+
+
+
+
+==Reference==
+
+* [[bip-0016.mediawiki|BIP16 - Pay to Script Hash]]
+* [[bip-0032.mediawiki|BIP32 - Hierarchical Deterministic Wallets]]
+* [[bip-0043.mediawiki|BIP43 - Purpose Field for Deterministic Wallets]]
+* [[bip-0044.mediawiki|BIP44 - Multi-Account Hierarchy for Deterministic Wallets]]
+* [[bip-0141.mediawiki|BIP141 - Segregated Witness (Consensus layer)]]
+
+== Copyright ==
+
+This document is placed in the public domain.
diff --git a/bip-0050.mediawiki b/bip-0050.mediawiki
index 9ff29d6f0f..0b41c8d220 100644
--- a/bip-0050.mediawiki
+++ b/bip-0050.mediawiki
@@ -2,33 +2,38 @@
BIP: 50
Title: March 2013 Chain Fork Post-Mortem
Author: Gavin Andresen
- Status: Draft
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0050
+ Status: Final
Type: Informational
Created: 2013-03-20
+ License: PD
==What went wrong==
-A block that had a larger number of total transaction inputs than previously seen was mined and broadcasted. Bitcoin 0.8 nodes were able to handle this, but some pre-0.8 Bitcoin nodes rejected it, causing an unexpected hard fork of the chain. The pre-0.8 incompatible chain at that point had around 60% of the hash power ensuring the split did not automatically resolve.
+A block that had a larger number of total transaction inputs than previously seen was mined and broadcasted. Bitcoin 0.8 nodes were able to handle this, but some pre-0.8 Bitcoin nodes rejected it, causing an unexpected fork of the blockchain. The pre-0.8-incompatible chain (from here on, the 0.8 chain) at that point had around 60% of the mining hash power ensuring the split did not automatically resolve (as would have occurred if the pre-0.8 chain outpaced the 0.8 chain in total work, forcing 0.8 nodes to reorganise to the pre-0.8 chain).
-In order to restore a canonical chain as soon as possible, BTCGuild and Slush downgraded their Bitcoin 0.8 nodes to 0.7 so their pools would also reject the larger block. This placed majority hashpower on the chain without the larger block.
+In order to restore a canonical chain as soon as possible, BTCGuild and Slush downgraded their Bitcoin 0.8 nodes to 0.7 so their pools would also reject the larger block. This placed majority hashpower on the chain without the larger block, thus eventually causing the 0.8 nodes to reorganise to the pre-0.8 chain.
During this time there was at least [https://bitcointalk.org/index.php?topic=152348.0 one large double spend]. However, it was done by someone experimenting to see if it was possible and was not intended to be malicious.
==What went right==
* The split was detected very quickly.
-* The right people were online and available in IRC or could be raised via Skype.
-* Marek Palatinus and Michael Marsee quickly downgraded their nodes to restore a pre-0.8 chain as canonical, despite the fact that this caused them to sacrifice significant amounts of money and they were the ones running the bug-free version.
+* The right people were online and available in IRC or could be contacted directly.
+* Marek Palatinus (Slush) and Michael Marsee (Eleuthria of BTCGuild) quickly downgraded their nodes to restore a pre-0.8 chain as canonical, despite the fact that this caused them to sacrifice significant amounts of money.
* Deposits to the major exchanges and payments via BitPay were also suspended (and then un-suspended) very quickly.
-* Fortunately, the only attack on a merchant was done by someone who was not intending to actually steal money
+* Fortunately, the only attack on a merchant was done by someone who was not intending to actually steal money.
==Root cause==
-Bitcoin versions prior to 0.8 configure an insufficient number of Berkeley DB locks to process large but technically valid blocks. Berkeley DB locks have to be manually configured by API users depending on anticipated load. The manual says this:
+Bitcoin versions prior to 0.8 configure an insufficient number of Berkeley DB locks to process large but otherwise valid blocks. Berkeley DB locks have to be manually configured by API users depending on anticipated load. The manual says this:
:The recommended algorithm for selecting the maximum number of locks, lockers, and lock objects is to run the application under stressful conditions and then review the lock system's statistics to determine the maximum number of locks, lockers, and lock objects that were used. Then, double these values for safety.
+With the insufficiently high BDB lock configuration, it implicitly had become a network consensus rule determining block validity (albeit an inconsistent and unsafe rule, since the lock usage could vary from node to node).
+
Because max-sized blocks had been successfully processed on the testnet, it did not occur to anyone that there could be blocks that were smaller but require more locks than were available. Prior to 0.7 unmodified mining nodes self-imposed a maximum block size of 500,000 bytes, which further prevented this case from being triggered. 0.7 made the target size configurable and miners had been encouraged to increase this target in the week prior to the incident.
-Bitcoin 0.8 does not use Berkeley DB. It uses LevelDB instead, which does not require this kind of pre-configuration. Therefore it was able to process the forking block successfully.
+Bitcoin 0.8 did not use Berkeley DB. It switched to LevelDB instead, which did not implement the same locking limits as BDB. Therefore it was able to process the forking block successfully.
Note that BDB locks are also required during processing of re-organizations. Versions prior to 0.8 may be unable to process some valid re-orgs.
@@ -39,10 +44,10 @@ This would be an issue even if the entire network was running version 0.7.2. It
===Immediately===
'''Done''': Release a version 0.8.1, forked directly from 0.8.0, that, for the next two months has the following new rules:
-# Reject blocks that could cause more than 10,000 locks to be taken.
+# Reject blocks that would probably cause more than 10,000 locks to be taken.
# Limit the maximum block-size created to 500,000 bytes
-# Release a patch for older versions that implements the same rules, but also increases the maximum number of locks to 120,000
-# Create a web page on bitcoin.org that will urge users to upgrade to 0.8.1, but will tell them how to set DB_CONFIG to 120,000 locks if they absolutely cannot.
+# Release a patch for older versions that implements the same rules, but also increases the maximum number of locks to 537,000
+# Create a web page on bitcoin.org that will urge users to upgrade to 0.8.1, but will tell them how to set DB_CONFIG to 537,000 locks if they absolutely cannot.
# Over the next 2 months, send a series of alerts to users of older versions, pointing to the web page.
===Alert system===
@@ -70,3 +75,7 @@ A double spend attack was successful, despite that both sides of the chain heard
===Resolution===
On 16 August, 2013 block 252,451 (0x0000000000000024b58eeb1134432f00497a6a860412996e7a260f47126eed07) was accepted by the main network, forking unpatched nodes off the network.
+
+==Copyright==
+
+This document is placed in the public domain.
diff --git a/bip-0052.mediawiki b/bip-0052.mediawiki
new file mode 100644
index 0000000000..aa42ab38f7
--- /dev/null
+++ b/bip-0052.mediawiki
@@ -0,0 +1,302 @@
+
+
+
+== Simple Summary ==
+
+Bitcoin's energy consumption is growing with its value (see Figure below).
+Although scaling PoW is necessary to maintain the security of the network,
+reliance on massive energy consumption has scaling drawbacks and leads to mining
+centralization. A major consequence of the central role of local electricity
+cost in mining is that today, most existing and potential participants in the
+Bitcoin network cannot profitably mine Bitcoin even if they have the capital to
+invest in mining hardware. From a practical perspective, Bitcoin adoption by
+companies like Tesla (which recently rescinded its acceptance of Bitcoin as
+payment) has been hampered by its massive energy consumption and perceived
+environmental impact.
+
+
+
+Figure. Bitcoin price and estimated Bitcoin energy consumption.
+Data sources: [https://cbeci.org Cambridge Bitcoin Electricity Consumption Index], [https://www.coindesk.com CoinDesk].
+
+We propose a novel proof-of-work paradigm for Bitcoin--Optical proof-of-work. It
+is designed to decouple Bitcoin mining from energy and make it feasible outside
+of regions with low electricity costs. ''Optical proof-of-work'' (oPoW) is a
+modification of Hashcash that is most efficiently computed using a new class of
+photonic processors. Without compromising the cryptographic or game-theoretical
+security of Hashcash, oPoW shifts the operating expenses of mining (OPEX), to
+capital expenses (CAPEX)--i.e. electricity to hardware. oPoW makes it possible
+for billions of new miners to enter the market simply by investing in a
+low-energy photonic miner. Shifting to a high-CAPEX PoW has the added benefit of
+making the hashrate resilient to Bitcoin's price fluctuations - once low-OPEX
+hardware is operating there is no reason to shut it down even if the value of
+mining rewards diminishes. oPoW is hardware-compatible with GPUs, FPGAs, and
+ASICs meaning that a transitional period of optical and traditional hardware
+mining in parallel on the network is feasible
+
+More information is available here: [https://www.powx.org/opow].
+
+== Abstract ==
+
+As Bitcoin gained utility and value over the preceding decade, the network incentivized the purchase of billions of dollars in mining equipment and electricity. With the growth of competition, home mining became unprofitable. Even the most sophisticated special-purpose hardware (ASIC miners) doesn’t cover its energy costs unless the miner also has direct access to very cheap electricity. This heavy reliance on energy makes it difficult for new miners to enter the market and leads to hashrate instability as miners shut off their machines when the price of Bitcoin falls. Additionally as the network stores ever more value, the percentage of world energy consumption that is associated with Bitcoin continues to grow, creating the potential for scaling failure and a general backlash. To ensure that Bitcoin can continue scaling and reach its full potential as a world currency and store of value, we propose a low-energy proof-of-work paradigm for Bitcoin. ''Optical proof of work (oPoW)'' is designed to decouple Bitcoin’s security from massive energy use and make bitcoin mining feasible outside of regions with low electricity costs. ''Optical proof-of-work'' is a modification of Hashcash that is most efficiently computed using a new class of photonic processors that has emerged as a leading solution for ultra-low energy computing over the last 5 years. oPoW shifts the operating expenses of mining (OPEX), to capital expenses (CAPEX)–i.e. electricity to hardware, without compromising the cryptographic or game-theoretical security of Hashcash. We provide an example implementation of oPoW, briefly discuss its cryptographic construction as well as the working principle of photonic processors. Additionally, we outline the potential benefits of oPoW to the bitcoin network, including geographic decentralization and democratization of mining as well as hashrate resilience to price fluctuations.
+
+== Copyright ==
+
+This BIP is dual-licensed under the Open Publication License and BSD 2-clause license.
+
+== Motivation ==
+
+As Bitcoin has grown over the past decade from a small network run by hobbyists to a global currency, the underlying Proof of Work protocol has not been updated. Initially pitched as a global decentralized network (“one CPU-one vote”), Bitcoin transactions today are secured by a small group of corporate entities. In practice, it is only feasible for [http://archive.is/YeDwh entities that can secure access to abundant, inexpensive energy]. The economics of mining limit profitability to places like Iceland, Texas, or Western China. Besides the negative environmental externalities, which may be significant, mining today is performed primarily with the consent (and in many cases, partnership) of large public utilities and the governments that control them. Although this may not be a problem in the short term, in the long term it stands to erode the censorship resistance and security of Bitcoin and other public blockchains through potential regulation or [https://arxiv.org/pdf/1605.07524.pdf partitioning attacks].
+
+Recent events, such as the [https://twitter.com/MustafaYilham/status/1384278267067203590 ~25% hashrate crash due to coal-powered grid failure in china] and Tesla’s rescinding of its acceptance of Bitcoin as a form of payment, show that there are practical real-world downsides to Proof of Works’s massive reliance on energy.
+
+
+
+Whether or not the Bitcoin community accepts this common criticism as entirely valid, it has real-world effects which will only get worse over time. Eliminating the exponentially growing energy use currently built into Bitcoin without eliminating the security of PoW would be ideal and should not be a partisan issue.
+
+New consensus mechanisms have been proposed as a means of securing cryptocurrencies whilst reducing energy cost, such as various forms of Proof of Stake and Proof of Space-Time. While many of these alternative mechanisms offer compelling guarantees, they generally require new security assumptions, which have not been stress-tested by live deployments at any adequate scale. Consequently, we still have relatively little empirical understanding of their safety. Completely changing the Bitcoin paradigm is likely to introduce new unforeseen problems. We believe that the major issues discussed above can be resolved by improving rather than eliminating Bitcoin’s fundamental security layer—Proof of Work. Instead of devising a new consensus architecture to fix these issues, it is sufficient to shift the economics of PoW. The financial cost imposed on miners need not be primarily composed of electricity. The situation can be significantly improved by reducing the operating expense (OPEX)—energy—as a major mining component. Then, by shifting the cost towards capital expense (CAPEX)—mining hardware—the dynamics of the mining ecosystem becomes much less dependent on electricity prices, and much less electricity is consumed as a whole.
+
+Moreover, a reduction in energy consumption automatically leads to
+geographically distributed mining, as mining becomes profitable even in regions
+with expensive electricity. Additionally, lower energy consumption will
+eliminate heating issues experienced by today’s mining operations, which will
+further decrease operating cost as well as noise associated with fans and
+cooling systems. All of this means that individuals and smaller entities would
+be able to enter the mining ecosystem simply for the cost of a miner, without
+first gaining access to cheap energy or a dedicated, temperature-controlled data
+center. To a degree, memory-hard PoW schemes like
+[https://github.com/tromp/cuckoo Cuckoo Cycle], which increase the use of SRAM
+in lieu of pure computation, push the CAPEX/OPEX ratio in the right direction by
+occupying ASIC chip area with memory. To maximize the CAPEX to OPEX ratio of the
+Optical Proof of Work algorithm, we developed
+[https://assets.pubpub.org/xi9h9rps/01581688887859.pdf ''HeavyHash''] [1].
+HeavyHash is a cryptographic construction that takes the place of SHA256 in
+Hashcash. Our algorithm is hardware-compatible with ultra-energy-efficient photonic co-processors that have been developed for machine learning hardware accelerators.
+
+HeavyHash uses a proven digital hash (SHA3) packaged with a large amount of MAC (Multiply-and-Accumulate) computation into a Proof of Work puzzle. Although HeavyHash can be computed on any standard digital hardware, it becomes hardware efficient only when a small digital core is combined with a low-power photonic co-processor for performing MAC operations. oPoW mining machines will have a small digital core flip-chipped onto a large, low-power photonic chip. This core will be bottlenecked by the throughput of the digital to analog and analog to digital converters. A prototype of such analogue optical matrix multiplier can be seen in the figure below.
+
+
+
+Figure. TOP: Photonic Circuit Diagram, A. Laser input (1550nm, common telecom wavelength) B. Metal pads for controlling modulators to transduce electrical data to optical C. Metal pads for tuning mesh of directional couplers D. Optical signal exits here containing the results of the computation and is output to fibers via a grating coupler the terminus of each waveguide. E. Alignment circuit for aligning fiber coupling stage. Bottom: a photograph of a bare oPoW miner prototype chip before wire and fiber bonding. On the right side of the die are test structures (F).
+
+The ''HeavyHash'' derives its name from the fact that it is bloated or weighted with additional computation. This means that a cost comparable oPoW miner will have a much lower nominal hashrate compared to a Bitcoin ASIC (HeavyHashes/second vs. SHA256 Hashes/second in equivalent ASIC). We provide the cryptographic security argument of the HeavyHash function in Section 3 in [https://assets.pubpub.org/xi9h9rps/01581688887859.pdf Towards Optical Proof of Work] [1]. In the article, we also provide a game-theoretic security argument for CAPEX-heavy PoW. For additional information, we recommend reading [https://uncommoncore.co/wp-content/uploads/2019/10/A-model-for-Bitcoins-security-and-the-declining-block-subsidy-v1.02.pdf this article].
+
+While traditional digital hardware relies on electrical currents, optical
+computing uses light as the basis for some of or all of its operations. Building
+on the development and commercialization of silicon photonic chips for telecom
+and datacom applications, modern photonic co-processors are silicon chips made
+using well-established and highly scalable silicon CMOS processes. However,
+unlike cutting edge electronics which require ever-smaller features (e.g. 5 nm),
+fabricated by exponentially more complex and expensive machinery, silicon
+photonics uses old fabrication nodes (90 nm). Due to the large de Broglie
+wavelength of photons, as compared to electrons, there is no benefit to using
+the small feature sizes. The result is that access to silicon photonic wafer
+fabrication is readily available, in contrast to the notoriously difficult
+process of accessing advanced nodes. Moreover, the overall cost of entry is
+lower as lithography masks for silicon photonics processes are an order of
+magnitude cheaper ($500k vs. $5M). Examples of companies developing optical
+processors for AI, which will be hardware-compatible with oPoW include [https://lightmatter.co/ Lightmatter], [https://www.lightelligence.ai/ Lightelligence], [https://luminous.co/ Luminous], [https://www.intel.com/content/www/us/en/architecture-and-technology/silicon-photonics/silicon-photonics-overview.html Intel], and other more recent entrants.
+
+== Specification ==
+
+=== HeavyHash ===
+
+The HeavyHash is performed in three stages:
+
+# Keccak hash
+# Matrix-vector multiplication
+# Keccak of the result xorred with the hashed input
+
+Note that the most efficient matrix-vector multiplication is performed on a
+photonic miner. However, this linear algebra operation can be performed on any
+conventional computing hardware (CPU, GPU, etc.), therefore making the HeavyHash
+hardware-compatible with any digital device.
+
+The algorithm’s pseudo-code:
+
+
// M is a Matrix 64 x 64 of Unsigned 4 values
+
+// 256-bitVector
+x1 <- keccak(input)
+
+// Reshape the obtained bitvector
+// into a 64-vector of unsigned 4-bit values
+x2 <- reshape(x1, 64)
+
+// Perform a matrix-vector multiplication.
+// The result is 64-vector of 14-bit unsigned.
+x3 <- vector_matrix_mult(x2, M)
+
+// Truncate all values to 4 most significant bits.
+// This is due to the specifics of analog
+// computing by the photonic accelerator.
+// Obtain a 64-vector of 4-bit unsigned.
+x4 <- truncate_to_msb(x3, 4)
+
+// Interpret as a 256-bitvector
+x5 <- flatten(x4)
+
+// 256-bitVector
+result <- keccak(xor(x5, x1))
+=== Random matrix generation ===
+
+The random matrix M (which is a HeavyHash parameter) is obtained in a deterministic way and is changed every block. Matrix M coefficients are generated using a pseudo-random number generation algorithm (xoshiro) from the previous block header. If the matrix is not full rank, it is repeatedly generated again.
+
+An example code to obtain the matrix M:
+
+
+
+== Discussion ==
+
+=== Geographic Distribution of Mining Relative to CAPEX-OPEX Ratio of Mining Costs ===
+
+Below is a simple model showing several scenarios for the geographic distribution of mining activity relative to the CAPEX/OPEX ratio of the cost of operating a single piece of mining hardware. As the ratio of energy consumption to hardware cost decreases, geographic variations in energy cost cease to be a determining factor in miner distribution.
+
+Underlying assumptions: 1. Electricity price y is fixed in time but varies geographically. 2. Every miner has access to the same hardware. 3. Each miner’s budget is limited by both the cost of mining equipment as well as the local cost of the electricity they consume
+
+budget = a(p+ey),
+
+where a is the number of mining machines, p is the machine price, e is the total energy consumption over machine lifetime, and y is electricity price.
+
+Note that in locations where mining is not profitable, hashrate is zero.
+
+
+
+
+
+
+
+An interactive version of this diagram can be found [https://www.powx.org/opow here].
+
+=== Why does CAPEX to OPEX shift lead to lower energy consumption? ===
+
+A common misconception about oPoW is that it makes mining “cheaper” by enabling energy-efficient hardware. There is no impact on the dollar cost of mining a block, rather the mix of energy vs. hardware investment changes from about 50/50 to 10/90 or better. We discuss this at length and rigorously in our paper[1].
+
+=== Working Principles of Photonic Processors ===
+
+Photonics accelerators are made by fabricating waveguides in silicon using standard lithography processes. Silicon is transparent to infrared light and can act as a tiny on-chip fiber optical cable. Silicon photonics found its first use during the 2000s in transceivers for sending and receiving optical signals via fiber and has advanced tremendously over the last decade.
+
+By encoding a vector into optical intensities passing through a series of parallel waveguides, interfering these signals in a mesh of tunable interferometers (acting as matrix coefficients), and then detecting the output using on-chip Germanium photodetectors, a matrix-vector multiplication is achieved. A generalized discussion of matrix multiplication setups using photonics/interference can be found in [https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.73.58 Reck et al.] and [https://arxiv.org/abs/1506.06220 Russell et al.] A detailed discussion of several integrated photonic architectures for matrix multiplication and corresponding tuning algorithms can be found in [https://arxiv.org/pdf/1909.06179.pdf Pai et al.]
+
+Below is a conceptual representation of a 3D-packaged oPoW mining chip. Note that the majority of the real estate and cost comes from the photonic die and the laser, with only a small digital SHA3 die needed (as opposed to a conventional miner of the same cost, which would have many copies of this die running in parallel).
+
+
+
+=== Block Reward Considerations ===
+
+Although it is out of the scope of this proposal, the authors strongly recommend the consideration of a change in the block reward schedule currently implemented in Bitcoin. There is no clear way to incentivize miners with transaction fees only, as has been successfully shown in [https://www.cs.princeton.edu/~smattw/CKWN-CCS16.pdf On the Instability of Bitcoin Without the Block Reward] and other publications, therefore looking a decade or two ahead it will be important to implement a fixed block reward or to slow the decay of the block reward to maintain the security of the network. Given that oPoW miners have low operating costs, once a large number of machines are running the reward level sufficient to keep them in operation and providing robust security can potentially be significantly smaller than in the case of the current SHA256 ASICs securing Bitcoin.
+
+=== Implementation on the Bitcoin Network ===
+
+A hard fork is not necessarily required for the Bitcoin network to test and eventually implement oPoW. It’s possible to add oPoW as a dual PoW to Bitcoin as a soft fork. Tuning the parameters to ensure that, for example, 99.9% of the security budget would be earned by miners via the SHA256 Hashcash PoW and 0.1% via oPoW would create sufficient incentive for oPoW to be stress-tested and to incentivize the manufacture of dedicated oPoW miners. If this test is successful, the parameters can be tuned continuously over time, e.g. oPoW share doubling at every halving, such that oPoW accounts for some target percentage (up to 100% in a complete SHA256 phase-out).
+
+
+==== Reverse compatibility ====
+
+Our understanding is that oPoW will not be reverse compatible.
+
+
+=== ASICBOOST ===
+
+Any new PoW algorithm carries the risk of hardware developers discovering and patenting an architecture with a significant speedup, as happened in the case of ASICBOOST for SHA256. HeavyHash is comprised of an SHA hash and 4-bit linear matrix-vector operations. The intent is for the matrix-vector multiplications to account for the majority of the work involved in computing a single HeavyHash operation. As we show in the Minimum Effective Hardness section of Towards Optical Proof of Work[1], there is no workaround to performing the matrix operations when computing HeavyHash, and since the SHA hashes are negligible, a true ASICBOOST-type speed up would require a speed up in linear matrix processing. Since matrix-vector multiplication is at the heart of neural networks and many other common computational workloads, it has been optimized very heavily and is generally very well understood. The acceleration of matrix-vector multiplication hardware (e.g. photonic coprocessors, memristors, etc.) is a very general problem and there are dozens of companies working on it, making it very unlikely for a single party to corner the market.
+
+== Endnotes ==
+
+With significant progress in optical and analog matrix-vector-multiplication chipsets over the last year, we hope to demonstrate commercial low-energy mining on our network in the next 6 months. The current generation of optical matrix processors under development is expected to have 10x better energy consumption per MAC operation than digital implementations, and we expect this to improve by another order of magnitude in future generations.
+
+PoWx will also be publishing the designs of the current optical miner prototypes in the near term under an open-source hardware license.
+
+== Acknowledgments ==
+
+We thank all the members of the Bitcoin community who have already given us feedback over the last several years as well as others in the optical computing community and beyond that have given their input.
+
+
+
+
+[1] M. Dubrovsky et al. Towards Optical Proof of Work, CES conference (2020) https://assets.pubpub.org/xi9h9rps/01581688887859.pdf
+
+[2] https://sciencex.com/news/2020-05-powering-bitcoin-silicon-photonics-power.html
+
+[3] KISS random number generator http://www.cse.yorku.ca/~oz/marsaglia-rng.html
+
diff --git a/bip-0052/btc_energy-small.png b/bip-0052/btc_energy-small.png
new file mode 100644
index 0000000000..32ffde301d
Binary files /dev/null and b/bip-0052/btc_energy-small.png differ
diff --git a/bip-0052/btc_energy.png b/bip-0052/btc_energy.png
new file mode 100644
index 0000000000..cc37d3ade5
Binary files /dev/null and b/bip-0052/btc_energy.png differ
diff --git a/bip-0052/emusk_tweet.png b/bip-0052/emusk_tweet.png
new file mode 100644
index 0000000000..6e7f0655b4
Binary files /dev/null and b/bip-0052/emusk_tweet.png differ
diff --git a/bip-0052/optical_chip.png b/bip-0052/optical_chip.png
new file mode 100644
index 0000000000..f3ec05c583
Binary files /dev/null and b/bip-0052/optical_chip.png differ
diff --git a/bip-0052/optminer.png b/bip-0052/optminer.png
new file mode 100644
index 0000000000..4fd639b89a
Binary files /dev/null and b/bip-0052/optminer.png differ
diff --git a/bip-0052/sim1.png b/bip-0052/sim1.png
new file mode 100644
index 0000000000..4b6b86324f
Binary files /dev/null and b/bip-0052/sim1.png differ
diff --git a/bip-0052/sim2.png b/bip-0052/sim2.png
new file mode 100644
index 0000000000..043cfc25e2
Binary files /dev/null and b/bip-0052/sim2.png differ
diff --git a/bip-0052/sim3.png b/bip-0052/sim3.png
new file mode 100644
index 0000000000..ee5f71ec55
Binary files /dev/null and b/bip-0052/sim3.png differ
diff --git a/bip-0060.mediawiki b/bip-0060.mediawiki
index ae9592ad1a..626a039725 100644
--- a/bip-0060.mediawiki
+++ b/bip-0060.mediawiki
@@ -1,10 +1,14 @@
==Abstract==
@@ -19,14 +23,14 @@ The implementation is problematic because the RelayTransactions flag is an optio
One property of Bitcoin messages is their fixed number of fields. This keeps the format simple and easily understood. Adding optional fields to messages will cause deserialisation issues when other fields come after the optional one.
-As an example, the length of version messages might be checked to ensure the byte stream is consistent. With optional fields, this checking is no longer possible. This is desirable to check for consistency inside internal deserialization code, and proper formatting of version messages originating from other nodes. In the future with diversification of the Bitcoin network, it will become desirable to enforce this kind of strict adherance to standard messages with field length compliance with every protocol version.
+As an example, the length of version messages might be checked to ensure the byte stream is consistent. With optional fields, this checking is no longer possible. This is desirable to check for consistency inside internal deserialization code, and proper formatting of version messages originating from other nodes. In the future with diversification of the Bitcoin network, it will become desirable to enforce this kind of strict adherence to standard messages with field length compliance with every protocol version.
Another property of fixed-length field messages is the ability to pass stream operators around for deserialization. This property is also lost, as now the deserialisation code must know the remaining length of bytes to parse. The parser now requires an additional piece of information (remaining size of the stream) for parsing instead of being a dumb reader.
==Specification==
=== version ===
-When a node creates an outgoing connection, it will immediately advertise its version. The remote node will respond with its version. No futher communication is possible until both peers have exchanged their version.
+When a node creates an outgoing connection, it will immediately advertise its version. The remote node will respond with its version. No further communication is possible until both peers have exchanged their version.
Payload:
diff --git a/bip-0061.mediawiki b/bip-0061.mediawiki
index aca329a729..384c0ff7ae 100644
--- a/bip-0061.mediawiki
+++ b/bip-0061.mediawiki
@@ -1,7 +1,10 @@
BIP: 61
+ Layer: Peer Services
Title: Reject P2P message
Author: Gavin Andresen
+ Comments-Summary: Controversial; some recommendation, and some discouragement
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0061
Status: Final
Type: Standards Track
Created: 2014-06-18
@@ -54,7 +57,7 @@ Every reject message begins with the following fields. Some messages append extr
|}
The human-readable string is intended only for debugging purposes; in particular, different implementations may
-use different strings. The string should not be shown to users or used for anthing besides diagnosing
+use different strings. The string should not be shown to users or used for anything besides diagnosing
interoperability problems.
The following reject code categories are used; in the descriptions below, "server" is the peer generating
@@ -80,7 +83,7 @@ the reject message, "client" is the peer that will receive the message.
==== reject version codes ====
-Codes generated during the intial connection process in response to a "version" message:
+Codes generated during the initial connection process in response to a "version" message:
{|
| Code || Description
diff --git a/bip-0062.mediawiki b/bip-0062.mediawiki
index 28b20dd822..7dd2b5b6db 100644
--- a/bip-0062.mediawiki
+++ b/bip-0062.mediawiki
@@ -2,17 +2,25 @@
==Abstract==
This document specifies proposed changes to the Bitcoin transaction validity rules in order to make malleability of transactions impossible (at least when the sender doesn't choose to avoid it).
+==Copyright==
+
+This BIP is licensed under the 2-clause BSD license.
+
==Motivation==
As of february 2014, Bitcoin transactions are malleable in multiple ways. This means a (valid) transaction can be modified in-flight, without invalidating it, but without access to the relevant private keys.
diff --git a/bip-0064.mediawiki b/bip-0064.mediawiki
index b03dcac140..02c4c2a8ea 100644
--- a/bip-0064.mediawiki
+++ b/bip-0064.mediawiki
@@ -1,8 +1,11 @@
@@ -83,7 +86,7 @@ If the requesting client is looking up outputs for a signed transaction that the
client can partly verify the returned output by running the input scripts with it. Currently this
verifies only that the script is correct. A future version of the Bitcoin protocol is likely to also
allow the value to be checked in this way. It does not show that the output is really unspent or was
-ever actually created in the block chain however. Additionally, the form of the provided scriptPubKey
+ever actually created in the block chain however. Additionally, the form of the provided scriptPubKey
should be checked before execution to ensure the remote peer doesn't just set the script to OP_TRUE.
If the requesting client has a mapping of chain heights to block hashes in the best chain e.g.
@@ -100,4 +103,4 @@ results.
==Implementation==
-https://github.com/bitcoin/bitcoin/pull/4351/files
\ No newline at end of file
+https://github.com/bitcoin/bitcoin/pull/4351/files
diff --git a/bip-0065.mediawiki b/bip-0065.mediawiki
index b48fa759aa..db10c0ca9f 100644
--- a/bip-0065.mediawiki
+++ b/bip-0065.mediawiki
@@ -1,10 +1,14 @@
==Abstract==
@@ -16,11 +20,17 @@ some point in the future.
==Summary==
-CHECKLOCKTIMEVERIFY redefines the existing NOP2 opcode. When executed it
-compares the top item on the stack to the nLockTime field of the transaction
-containing the scriptSig. If that top stack item is greater than the transaction's
-nLockTime field the script fails immediately, otherwise script evaluation continues
-as though a NOP was executed.
+CHECKLOCKTIMEVERIFY redefines the existing NOP2 opcode. When executed, if
+any of the following conditions are true, the script interpreter will terminate
+with an error:
+
+* the stack is empty; or
+* the top item on the stack is less than 0; or
+* the lock-time type (height vs. timestamp) of the top stack item and the nLockTime field are not the same; or
+* the top stack item is greater than the transaction's nLockTime field; or
+* the nSequence field of the txin is 0xffffffff;
+
+Otherwise, script execution will continue as if a NOP had been executed.
The nLockTime field in a transaction prevents the transaction from being mined
until either a certain block height, or block time, has been reached. By
@@ -84,7 +94,7 @@ There exist a number of protocols where a transaction output is created that
requires the co-operation of both parties to spend the output. To ensure the
failure of one party does not result in the funds becoming lost, refund
transactions are setup in advance using nLockTime. These refund transactions
-need to be created interactively, and additionaly, are currently vulnerable to
+need to be created interactively, and additionally, are currently vulnerable to
transaction malleability. CHECKLOCKTIMEVERIFY can be used in these protocols,
replacing the interactive setup with a non-interactive setup, and additionally,
making transaction malleability a non-issue.
@@ -92,7 +102,7 @@ making transaction malleability a non-issue.
====Two-factor wallets====
-Services like GreenAddress store Bitcoins with 2-of-2 multisig scriptPubKey's
+Services like GreenAddress store bitcoins with 2-of-2 multisig scriptPubKey's
such that one keypair is controlled by the user, and the other keypair is
controlled by the service. To spend funds the user uses locally installed
wallet software that generates one of the required signatures, and then uses a
@@ -126,7 +136,7 @@ transaction is created, tx3, to ensure that should the payee vanish the payor
can get their deposit back. The process by which the refund transaction is
created is currently vulnerable to transaction malleability attacks, and
additionally, requires the payor to store the refund. Using the same
-scriptPubKey from as in the Two-factor wallets example solves both these issues.
+scriptPubKey form as in the Two-factor wallets example solves both these issues.
===Trustless Payments for Publishing Data===
@@ -160,7 +170,7 @@ Proving the sacrifice of some limited resource is a common technique in a
variety of cryptographic protocols. Proving sacrifices of coins to mining fees
has been proposed as a ''universal public good'' to which the sacrifice could
be directed, rather than simply destroying the coins. However doing so is
-non-trivial, and even the best existing technqiue - announce-commit sacrifices
+non-trivial, and even the best existing technique - announce-commit sacrifices
- could encourage mining centralization. CHECKLOCKTIMEVERIFY can be used to
create outputs that are provably spendable by anyone (thus to mining fees
assuming miners behave optimally and rationally) but only at a time
@@ -195,18 +205,19 @@ transaction output ''can'' be spent.
Refer to the reference implementation, reproduced below, for the precise
semantics and detailed rationale for those semantics.
+
case OP_NOP2:
{
// CHECKLOCKTIMEVERIFY
//
// (nLockTime -- nLockTime )
-
+
if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY))
break; // not enabled; treat as a NOP
-
+
if (stack.size() < 1)
return false;
-
+
// Note that elsewhere numeric opcodes are limited to
// operands in the range -2**31+1 to 2**31-1, however it is
// legal for opcodes to produce results exceeding that
@@ -222,13 +233,13 @@ semantics and detailed rationale for those semantics.
// to 5-byte bignums, which are good until 2**32-1, the
// same limit as the nLockTime field itself.
const CScriptNum nLockTime(stacktop(-1), 5);
-
+
// In the rare event that the argument may be < 0 due to
// some arithmetic being done first, you can always use
// 0 MAX CHECKLOCKTIMEVERIFY.
if (nLockTime < 0)
return false;
-
+
// There are two types of nLockTime: lock-by-blockheight
// and lock-by-blocktime, distinguished by whether
// nLockTime < LOCKTIME_THRESHOLD.
@@ -241,12 +252,12 @@ semantics and detailed rationale for those semantics.
(txTo.nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
))
return false;
-
+
// Now that we know we're comparing apples-to-apples, the
// comparison is a simple numeric one.
if (nLockTime > (int64_t)txTo.nLockTime)
return false;
-
+
// Finally the nLockTime feature can be disabled and thus
// CHECKLOCKTIMEVERIFY bypassed if every txin has been
// finalized by setting nSequence to maxint. The
@@ -259,9 +270,9 @@ semantics and detailed rationale for those semantics.
// required to prove correct CHECKLOCKTIMEVERIFY execution.
if (txTo.vin[nIn].IsFinal())
return false;
-
+
break;
-
+
}
https://github.com/petertodd/bitcoin/commit/ab0f54f38e08ee1e50ff72f801680ee84d0f1bf4
@@ -270,7 +281,7 @@ https://github.com/petertodd/bitcoin/commit/ab0f54f38e08ee1e50ff72f801680ee84d0f
==Deployment==
We reuse the double-threshold IsSuperMajority() switchover mechanism used in
-BIP 66 with the same thresholds, but for nVersion = 4. The new rules are
+BIP66 with the same thresholds, but for nVersion = 4. The new rules are
in effect for every block (at height H) with nVersion = 4 and at least
750 out of 1000 blocks preceding it (with heights H-1000..H-1) also
have nVersion >= 4. Furthermore, when 950 out of the 1000 blocks
@@ -301,20 +312,24 @@ time.
==References==
-PayPub - https://github.com/unsystem/paypub
+PayPub
+
+* https://github.com/unsystem/paypub
+
+Jeremy Spilman Payment Channels
-Jeremy Spilman Payment Channels - https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2013-April/002433.html
+* https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2013-April/002433.html
==Implementations==
Python / python-bitcoinlib
-- https://github.com/petertodd/checklocktimeverify-demos
+* https://github.com/petertodd/checklocktimeverify-demos
JavaScript / Node.js / bitcore
-- https://github.com/mruddy/bip65-demos
+* https://github.com/mruddy/bip65-demos
==Copyright==
diff --git a/bip-0066.mediawiki b/bip-0066.mediawiki
index 1235afde90..53289f5521 100644
--- a/bip-0066.mediawiki
+++ b/bip-0066.mediawiki
@@ -1,16 +1,24 @@
==Abstract==
This document specifies proposed changes to the Bitcoin transaction validity rules to restrict signatures to strict DER encoding.
+==Copyright==
+
+This BIP is licensed under the 2-clause BSD license.
+
==Motivation==
Bitcoin's reference implementation currently relies on OpenSSL for signature validation, which means it is implicitly defining Bitcoin's block validity rules. Unfortunately, OpenSSL is not designed for consensus-critical behaviour (it does not guarantee bug-for-bug compatibility between versions), and thus changes to it can - and have - affected Bitcoin software.
@@ -29,7 +37,7 @@ These operators all perform ECDSA verifications on pubkey/signature pairs, itera
The following code specifies the behaviour of strict DER checking. Note that this function tests a signature byte vector which includes the 1-byte sighash flag that Bitcoin adds, even though that flag falls outside of the DER specification, and is unaffected by this proposal. The function is also not called for cases where the length of sig is 0, in order to provide a simple, short and efficiently-verifiable encoding for deliberately invalid signatures.
-DER is specified in http://www.itu.int/rec/T-REC-X.690-200811-I/en .
+DER is specified in https://www.itu.int/rec/T-REC-X.690/en .
bool static IsValidSignatureEncoding(const std::vector &sig) {
@@ -67,7 +75,7 @@ bool static IsValidSignatureEncoding(const std::vector &sig) {
// Verify that the length of the signature matches the sum of the length
// of the elements.
if ((size_t)(lenR + lenS + 7) != sig.size()) return false;
-
+
// Check whether the R element is an integer.
if (sig[2] != 0x02) return false;
@@ -132,5 +140,8 @@ An implementation for the reference client is available at https://github.com/bi
==Acknowledgements==
-This document is extracted from the previous BIP62 proposal, which had input from various people, in particular Greg Maxwell and Peter Todd, who gave feedback about this document as well.
+This document is extracted from the previous BIP62 proposal, which had input from various people, in particular Greg Maxwell and Peter Todd, who gave feedback about this document as well.
+
+==Disclosures==
+* Subsequent to the network-wide adoption and enforcement of this BIP, the author [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2015-July/009697.html disclosed] that strict DER signatures provided an indirect solution to a consensus bug he had previously discovered.
diff --git a/bip-0067.mediawiki b/bip-0067.mediawiki
index 8be5c9b265..94153d376a 100644
--- a/bip-0067.mediawiki
+++ b/bip-0067.mediawiki
@@ -1,11 +1,16 @@
-
BIP: 67
+ Layer: Applications
Title: Deterministic Pay-to-script-hash multi-signature addresses through public key sorting
- Author: Thomas Kerin, Jean-Pierre Rupp, Ruben de Vries
- Status: Draft
+ Author: Thomas Kerin
+ Jean-Pierre Rupp
+ Ruben de Vries
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0067
+ Status: Proposed
Type: Standards Track
Created: 2015-02-08
+ License: PD
==Abstract==
@@ -14,7 +19,7 @@ This BIP describes a method to deterministically generate multi-signature pay-to
==Motivation==
-Pay-to-script-hash (BIP-0011[https://github.com/bitcoin/bips/blob/master/bip-0011.mediawiki BIP-0011]) is a transaction type that allows funding of arbitrary scripts, where the recipient carries the cost of fee's associated with using longer, more complex scripts.
+Pay-to-script-hash (BIP-0011[https://github.com/bitcoin/bips/blob/master/bip-0011.mediawiki BIP-0011]) is a transaction type that allows funding of arbitrary scripts, where the recipient carries the cost of fee's associated with using longer, more complex scripts.
Multi-signature pay-to-script-hash transactions are defined in BIP-0016[https://github.com/bitcoin/bips/blob/master/bip-0016.mediawiki BIP-0016]. The redeem script does not require a particular ordering or encoding for public keys. This means that for a given set of keys and number of required signatures, there are as many as 2(n!) possible standard redeem scripts, each with its separate P2SH address. Adhering to an ordering and key encoding would ensure that a multi-signature “account” (set of public keys and required signature count) has a canonical P2SH address.
@@ -22,36 +27,36 @@ By adopting a sorting and encoding standard, compliant wallets will always produ
While most web wallets do not presently facilitate the setup of multisignature accounts with users of a different service, conventions which ensure cross-compatibility should make it easier to achieve this.
-Many wallet as a service providers use a 2of3 multi-signature schema where the user stores 1 of the keys (offline) as backup while using the other key for daily use and letting the service cosign his transactions.
+Many wallet as a service providers use a 2of3 multi-signature schema where the user stores 1 of the keys (offline) as backup while using the other key for daily use and letting the service cosign his transactions.
This standard will help in enabling a party other than the service provider to recover the wallet without any help from the service provider.
==Specification==
For a set of public keys, ensure that they have been received in compressed form:
-
+
022df8750480ad5b26950b25c7ba79d3e37d75f640f8e5d9bcd5b150a0f85014da
- 03e3818b65bcc73a7d64064106a859cc1a5a728c4345ff0b641209fba0d90de6e9
+ 03e3818b65bcc73a7d64064106a859cc1a5a728c4345ff0b641209fba0d90de6e9
021f2f6e1e50cb6a953935c3601284925decd3fd21bc445712576873fb8c6ebc18
-
-Sort them lexicographically according to their binary representation:
-
+
+Sort them lexicographically according to their binary representation:
+
021f2f6e1e50cb6a953935c3601284925decd3fd21bc445712576873fb8c6ebc18
022df8750480ad5b26950b25c7ba79d3e37d75f640f8e5d9bcd5b150a0f85014da
03e3818b65bcc73a7d64064106a859cc1a5a728c4345ff0b641209fba0d90de6e9
-..before using the resulting list of keys in a standard multisig redeem script:
-
- OP_2 021f2f6e1e50cb6a953935c3601284925decd3fd21bc445712576873fb8c6ebc18 022df8750480ad5b26950b25c7ba79d3e37d75f640f8e5d9bcd5b150a0f85014da 03e3818b65bcc73a7d64064106a859cc1a5a728c4345ff0b641209fba0d90de6e9 OP_3 OP_CHECKSIG
+..before using the resulting list of keys in a standard multisig redeem script:
+
+ OP_2 021f2f6e1e50cb6a953935c3601284925decd3fd21bc445712576873fb8c6ebc18 022df8750480ad5b26950b25c7ba79d3e37d75f640f8e5d9bcd5b150a0f85014da 03e3818b65bcc73a7d64064106a859cc1a5a728c4345ff0b641209fba0d90de6e9 OP_3 OP_CHECKMULTISIG
Hash the redeem script according to BIP-0016 to get the P2SH address.
-
+
3Q4sF6tv9wsdqu2NtARzNCpQgwifm2rAba
-
+
==Compatibility==
-* Uncompressed keys are incompatible with this specificiation. A compatible implementation should not automatically compress keys. Receiving an uncompressed key from a multisig participant should be interpreted as a sign that the user has an incompatible implementation.
-* P2SH addressses do not reveal information about the script that is receiving the funds. For this reason it is not technically possible to enforce this BIP as a rule on the network. Also, it would cause a hard fork.
+* Uncompressed keys are incompatible with this specification. A compatible implementation should not automatically compress keys. Receiving an uncompressed key from a multisig participant should be interpreted as a sign that the user has an incompatible implementation.
+* P2SH addresses do not reveal information about the script that is receiving the funds. For this reason it is not technically possible to enforce this BIP as a rule on the network. Also, it would cause a hard fork.
* Implementations that do not conform with this BIP will have compatibility issues with strictly-compliant wallets.
-* Implementations which do adopt this standard will be cross-compatible when choosing multisig addressses.
+* Implementations which do adopt this standard will be cross-compatible when choosing multisig addresses.
* If a group of users were not entirely compliant, there is the possibility that a participant will derive an address that the others will not recognize as part of the common multisig account.
==Test vectors==
@@ -70,11 +75,11 @@ Vector 1
** 39bgKC7RFbpoCRbtD5KEdkYKtNyhpsNa3Z
Vector 2 (Already sorted, no action required)
-* List:
+* List:
** 02632b12f4ac5b1d1b72b2a3b508c19172de44f6f46bcee50ba33f3f9291e47ed0
** 027735a29bae7780a9755fae7a1c4374c656ac6a69ea9f3697fda61bb99a4f3e77
** 02e2cc6bd5f45edd43bebe7cb9b675f0ce9ed3efe613b177588290ad188d11b404
-* Sorted:
+* Sorted:
** 02632b12f4ac5b1d1b72b2a3b508c19172de44f6f46bcee50ba33f3f9291e47ed0
** 027735a29bae7780a9755fae7a1c4374c656ac6a69ea9f3697fda61bb99a4f3e77
** 02e2cc6bd5f45edd43bebe7cb9b675f0ce9ed3efe613b177588290ad188d11b404
@@ -84,12 +89,12 @@ Vector 2 (Already sorted, no action required)
** 3CKHTjBKxCARLzwABMu9yD85kvtm7WnMfH
Vector 3:
-* List:
+* List:
** 030000000000000000000000000000000000004141414141414141414141414141
** 020000000000000000000000000000000000004141414141414141414141414141
** 020000000000000000000000000000000000004141414141414141414141414140
** 030000000000000000000000000000000000004141414141414141414141414140
-* Sorted:
+* Sorted:
** 020000000000000000000000000000000000004141414141414141414141414140
** 020000000000000000000000000000000000004141414141414141414141414141
** 030000000000000000000000000000000000004141414141414141414141414140
@@ -100,11 +105,11 @@ Vector 3:
** 32V85igBri9zcfBRVupVvwK18NFtS37FuD
Vector 4: (from bitcore)
-* List:
+* List:
** 022df8750480ad5b26950b25c7ba79d3e37d75f640f8e5d9bcd5b150a0f85014da
-** 03e3818b65bcc73a7d64064106a859cc1a5a728c4345ff0b641209fba0d90de6e9
+** 03e3818b65bcc73a7d64064106a859cc1a5a728c4345ff0b641209fba0d90de6e9
** 021f2f6e1e50cb6a953935c3601284925decd3fd21bc445712576873fb8c6ebc18
-* Sorted:
+* Sorted:
** 021f2f6e1e50cb6a953935c3601284925decd3fd21bc445712576873fb8c6ebc18
** 022df8750480ad5b26950b25c7ba79d3e37d75f640f8e5d9bcd5b150a0f85014da
** 03e3818b65bcc73a7d64064106a859cc1a5a728c4345ff0b641209fba0d90de6e9
@@ -114,14 +119,19 @@ Vector 4: (from bitcore)
** 3Q4sF6tv9wsdqu2NtARzNCpQgwifm2rAba
==Acknowledgements==
-The authors wish to thank BtcDrak and Luke-Jr for their involvement & contributions in the early discussions of this BIP.
+The authors wish to thank BtcDrak and Luke-Jr for their involvement & contributions in the early discussions of this BIP.
-==Usage & Implementations==
-* [[https://github.com/bitcoin/bips/blob/master/bip-0045.mediawiki#address-generation-procedure|BIP-0045]] - Structure for Deterministic P2SH Multisignature Wallets
-* [[https://github.com/bitpay/bitcore/blob/50a868cb8cdf2be04bb1c5bf4bcc064cc06f5888/lib/script/script.js#L541|Bitcore]]
-* [[https://github.com/haskoin/haskoin/blob/master/Network/Haskoin/Script/Parser.hs#L112-122|Haskoin]] Bitcoin implementation in haskell
-* [[https://github.com/etotheipi/BitcoinArmory/blob/268db0f3fa20c989057bd43343a43b2edbe89aeb/armoryengine/ArmoryUtils.py#L1441|Armory]]
+==Usage & Implementations==
+* [[https://github.com/bitcoin/bips/blob/master/bip-0045.mediawiki#address-generation-procedure|BIP-0045]] - Structure for Deterministic P2SH Multisignature Wallets
+* [[https://github.com/bitpay/bitcore/blob/50a868cb8cdf2be04bb1c5bf4bcc064cc06f5888/lib/script/script.js#L541|Bitcore]]
+* [[https://github.com/haskoin/haskoin-core/blob/b41b1deb0989334a7ead6fc993fb8b02f0c00810/haskoin-core/Network/Haskoin/Script/Parser.hs#L112-L122|Haskoin]] - Bitcoin implementation in Haskell
+* [[https://github.com/etotheipi/BitcoinArmory/blob/268db0f3fa20c989057bd43343a43b2edbe89aeb/armoryengine/ArmoryUtils.py#L1441|Armory]]
* [[https://github.com/bitcoinj/bitcoinj/blob/master/core/src/main/java/org/bitcoinj/script/ScriptBuilder.java#L331|BitcoinJ]]
== References ==
+
+
+== Copyright ==
+This document is placed in the public domain.
+
diff --git a/bip-0068.mediawiki b/bip-0068.mediawiki
index 02bc2a4e91..a84fce7cc4 100644
--- a/bip-0068.mediawiki
+++ b/bip-0068.mediawiki
@@ -1,11 +1,14 @@
BIP: 68
+ Layer: Consensus (soft fork)
Title: Relative lock-time using consensus-enforced sequence numbers
Author: Mark Friedenbach
BtcDrak
Nicolas Dorier
kinoshitajona
- Status: Draft
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0068
+ Status: Final
Type: Standards Track
Created: 2015-05-28
@@ -24,13 +27,15 @@ The transaction nLockTime is used to prevent the mining of a transaction until a
This specification defines the meaning of sequence numbers for transactions with an nVersion greater than or equal to 2 for which the rest of this specification relies on.
+All references to median-time-past (MTP) are as defined by BIP113.
+
If bit (1 << 31) of the sequence number is set, then no consensus meaning is applied to the sequence number and can be included in any block under all currently possible circumstances.
If bit (1 << 31) of the sequence number is not set, then the sequence number is interpreted as an encoded relative lock-time.
-The sequence number encoding is interpreted as follows:
+The sequence number encoding is interpreted as follows:
-Bit (1 << 22) determines if the relative lock-time is time-based or block based: If the bit is set, the relative lock-time specifies a timespan in units of 512 seconds granularity. The timespan starts from the median-time-past (MTP) of the output’s previous block, and ends either at the MTP of the previous block or at the nTime of the transaction’s block (depending on the enforcement status of BIP113). If the bit is not set, the relative lock-time specifies a number of blocks.
+Bit (1 << 22) determines if the relative lock-time is time-based or block based: If the bit is set, the relative lock-time specifies a timespan in units of 512 seconds granularity. The timespan starts from the median-time-past of the output’s previous block, and ends at the MTP of the previous block. If the bit is not set, the relative lock-time specifies a number of blocks.
The flag (1<<22) is the highest order bit in a 3-byte signed integer for use in bitcoin scripts as a 3-byte PUSHDATA with OP_CHECKSEQUENCEVERIFY (BIP 112).
@@ -41,145 +46,174 @@ This specification only interprets 16 bits of the sequence number as relative lo
For time based relative lock-time, 512 second granularity was chosen because bitcoin blocks are generated every 600 seconds. So when using block-based or time-based, the same amount of time can be encoded with the available number of bits. Converting from a sequence number to seconds is performed by multiplying by 512 = 2^9, or equivalently shifting up by 9 bits.
When the relative lock-time is time-based, it is interpreted as a minimum block-time constraint over the input's age. A relative time-based lock-time of zero indicates an input which can be included in any block. More generally, a relative time-based lock-time n can be included into any block produced 512 * n seconds after the mining date of the output it is spending, or any block thereafter.
-The mining date of the output is equals to the median-time-past of the previous block which mined it.
+The mining date of the output is equal to the median-time-past of the previous block which mined it.
-The block produced time is either equals to median time past of its parent or to its nTime field, depending on the state of BIP113 median-time-past.
+The block produced time is equal to the median-time-past of its previous block.
When the relative lock-time is block-based, it is interpreted as a minimum block-height constraint over the input's age. A relative block-based lock-time of zero indicates an input which can be included in any block. More generally, a relative block lock-time n can be included n blocks after the mining date of the output it is spending, or any block thereafter.
-This is proposed to be accomplished by replacing IsFinalTx() and CheckFinalTx(), existing consensus and non-consensus code functions that return true if a transaction's lock-time constraints are satisfied and false otherwise, with LockTime() and CheckLockTime(), new functions that return a non-zero value if a transaction's lock-time or sequence number constraints are not satisfied and zero otherwise:
-
-
- enum {
- /* Interpret sequence numbers as relative lock-time constraints. */
- LOCKTIME_VERIFY_SEQUENCE = (1 << 0),
- };
-
- /* Setting nSequence to this value for every input in a transaction
- * disables nLockTime. */
- static const uint32_t SEQUENCE_FINAL = 0xffffffff;
-
- /* If this flag set, CTxIn::nSequence is NOT interpreted as a
- * relative lock-time. Setting the most significant bit of a
- * sequence number disabled relative lock-time. */
- static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG = (1 << 31);
-
- /* If CTxIn::nSequence encodes a relative lock-time and this flag
- * is set, the relative lock-time has units of 512 seconds,
- * otherwise it specifies blocks with a granularity of 1. */
- static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG = (1 << 22);
-
- /* If CTxIn::nSequence encodes a relative lock-time, this mask is
- * applied to extract that lock-time from the sequence field. */
- static const uint32_t SEQUENCE_LOCKTIME_MASK = 0x0000ffff;
-
- /* In order to use the same number of bits to encode roughly the
- * same wall-clock duration, and because blocks are naturally
- * limited to occur every 600s on average, the minimum granularity
- * for time-based relative lock-time is fixed at 512 seconds.
- * Converting from CTxIn::nSequence to seconds is performed by
- * multiplying by 512 = 2^9, or equivalently shifting up by
- * 9 bits. */
- static const int SEQUENCE_LOCKTIME_GRANULARITY = 9;
-
- int64_t LockTime(const CTransaction &tx, int flags, const std::vector* prevHeights, const CBlockIndex& block)
- {
- assert(prevHeights == NULL || prevHeights->size() == tx.vin.size());
- int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
- ? block.GetAncestor(std::max(block.nHeight-1, 0))->GetMedianTimePast()
- : block.GetBlockTime();
-
- bool fEnforceBIP68 = static_cast(tx.nVersion) >= 2
- && flags & LOCKTIME_VERIFY_SEQUENCE;
-
- // Will be set to the equivalent height- and time-based nLockTime
- // values that would be necessary to satisfy all relative lock-
- // time constraints given our view of block chain history.
- int nMinHeight = 0;
- int64_t nMinTime = 0;
- // Will remain equal to true if all inputs are finalized
- // (CTxIn::SEQUENCE_FINAL).
- bool fFinalized = true;
- for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
- const CTxIn& txin = tx.vin[txinIndex];
- // Set a flag if we witness an input that isn't finalized.
- if (txin.nSequence == CTxIn::SEQUENCE_FINAL)
- continue;
- else
- fFinalized = false;
-
- // Do not enforce sequence numbers as a relative lock time
- // unless we have been instructed to, and a view has been
- // provided.
- if (!fEnforceBIP68)
- continue;
-
- // Sequence numbers with the most significant bit set are not
- // treated as relative lock-times, nor are they given any
- // consensus-enforced meaning at this point.
- if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
- continue;
-
- if (prevHeights == NULL)
- continue;
-
- int nCoinHeight = (*prevHeights)[txinIndex];
-
- if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) {
-
- int64_t nCoinTime = block.GetAncestor(std::max(nCoinHeight-1, 0))->GetMedianTimePast();
-
- // Time-based relative lock-times are measured from the
- // smallest allowed timestamp of the block containing the
- // txout being spent, which is the median time past of the
- // block prior.
- nMinTime = std::max(nMinTime, nCoinTime + (int64_t)((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) - 1);
- } else {
- // We subtract 1 from relative lock-times because a lock-
- // time of 0 has the semantics of "same block," so a lock-
- // time of 1 should mean "next block," but nLockTime has
- // the semantics of "last invalid block height."
- nMinHeight = std::max(nMinHeight, nCoinHeight + (int)(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1);
- }
- }
-
- // If all sequence numbers are CTxIn::SEQUENCE_FINAL, the
- // transaction is considered final and nLockTime constraints
- // are not enforced.
- if (fFinalized)
- return 0;
-
- if ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD)
- nMinHeight = std::max(nMinHeight, (int)tx.nLockTime);
- else
- nMinTime = std::max(nMinTime, (int64_t)tx.nLockTime);
-
- if (nMinHeight >= block.nHeight)
- return nMinHeight;
-
- if (nMinTime >= nBlockTime)
- return nMinTime;
-
- return 0;
- }
-
-Code conditional on the return value of IsFinalTx() / CheckLockTime() has to be updated as well, since the semantics of the return value has been inverted.
+The new rules are not applied to the nSequence field of the input of the coinbase transaction.
-==Example: Bidirectional payment channel==
-
-A bidirectional payment channel can be established by two parties funding a single output in the following way: Alice funds a 1 BTC output which is the 2-of-2 multisig of Alice AND Bob, or Alice's key only after a sufficiently long timeout, e.g. 30 days or 4320 blocks. The channel-generating transaction is signed by Alice and broadcast to the network.
-
-Alice desires to send Bob a payment of 0.1 BTC. She does so by constructing a transaction spending the 1 BTC output and sending 0.1 BTC to Bob and 0.9 BTC back to herself. She provides her signature for the 2-of-2 multisig constraint, and sets a relative lock-time using the sequence number field such that the transaction will become valid 24-hours or 144 blocks before the refund timeout. Two more times Alice sends Bob a payment of 0.1 BTC, each time generating and signing her half of a transaction spending the 1btc output and sending 0.2 BTC, then 0.3 BTC to Bob with a relative lock-time of 29 days from creation of the channel.
+==Implementation==
-Bob now desires to send Alice a refund of 0.25 BTC. He does so by constructing a transaction spending the 1btc output and sending 0.95 BTC (= 0.7 BTC + 0.25 BTC) to Alice and 0.05 BTC to himself. Since Bob will still have in his logs the transaction giving him 0.7 BTC 29 days after the creation of the channel, Alice demands that this new transaction have a relative lock-time of 28 days so she has a full day to broadcast it before the next transaction matures.
+A reference implementation is provided by the following pull request
-Alice and Bob continue to make payments to each other, decrementing the relative lock-time by one day each time the channel switches direction, until the present time is reached or either party desires to close out the channel. A close-out is performed by finalizing the input (nSequence = MAX_INT) and both parties signing.
+https://github.com/bitcoin/bitcoin/pull/7184
-==Implementation==
+
+enum {
+ /* Interpret sequence numbers as relative lock-time constraints. */
+ LOCKTIME_VERIFY_SEQUENCE = (1 << 0),
+};
+
+/* Setting nSequence to this value for every input in a transaction
+ * disables nLockTime. */
+static const uint32_t SEQUENCE_FINAL = 0xffffffff;
+
+/* Below flags apply in the context of BIP 68*/
+/* If this flag set, CTxIn::nSequence is NOT interpreted as a
+ * relative lock-time. */
+static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG = (1 << 31);
+
+/* If CTxIn::nSequence encodes a relative lock-time and this flag
+ * is set, the relative lock-time has units of 512 seconds,
+ * otherwise it specifies blocks with a granularity of 1. */
+static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG = (1 << 22);
+
+/* If CTxIn::nSequence encodes a relative lock-time, this mask is
+ * applied to extract that lock-time from the sequence field. */
+static const uint32_t SEQUENCE_LOCKTIME_MASK = 0x0000ffff;
+
+/* In order to use the same number of bits to encode roughly the
+ * same wall-clock duration, and because blocks are naturally
+ * limited to occur every 600s on average, the minimum granularity
+ * for time-based relative lock-time is fixed at 512 seconds.
+ * Converting from CTxIn::nSequence to seconds is performed by
+ * multiplying by 512 = 2^9, or equivalently shifting up by
+ * 9 bits. */
+static const int SEQUENCE_LOCKTIME_GRANULARITY = 9;
+
+/**
+ * Calculates the block height and previous block's median time past at
+ * which the transaction will be considered final in the context of BIP 68.
+ * Also removes from the vector of input heights any entries which did not
+ * correspond to sequence locked inputs as they do not affect the calculation.
+ */
+static std::pair CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector* prevHeights, const CBlockIndex& block)
+{
+ assert(prevHeights->size() == tx.vin.size());
+
+ // Will be set to the equivalent height- and time-based nLockTime
+ // values that would be necessary to satisfy all relative lock-
+ // time constraints given our view of block chain history.
+ // The semantics of nLockTime are the last invalid height/time, so
+ // use -1 to have the effect of any height or time being valid.
+ int nMinHeight = -1;
+ int64_t nMinTime = -1;
+
+ // tx.nVersion is signed integer so requires cast to unsigned otherwise
+ // we would be doing a signed comparison and half the range of nVersion
+ // wouldn't support BIP 68.
+ bool fEnforceBIP68 = static_cast(tx.nVersion) >= 2
+ && flags & LOCKTIME_VERIFY_SEQUENCE;
+
+ // Do not enforce sequence numbers as a relative lock time
+ // unless we have been instructed to
+ if (!fEnforceBIP68) {
+ return std::make_pair(nMinHeight, nMinTime);
+ }
+
+ for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
+ const CTxIn& txin = tx.vin[txinIndex];
+
+ // Sequence numbers with the most significant bit set are not
+ // treated as relative lock-times, nor are they given any
+ // consensus-enforced meaning at this point.
+ if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) {
+ // The height of this input is not relevant for sequence locks
+ (*prevHeights)[txinIndex] = 0;
+ continue;
+ }
-A reference implementation is provided by the following pull request
+ int nCoinHeight = (*prevHeights)[txinIndex];
+
+ if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) {
+ int64_t nCoinTime = block.GetAncestor(std::max(nCoinHeight-1, 0))->GetMedianTimePast();
+ // NOTE: Subtract 1 to maintain nLockTime semantics
+ // BIP 68 relative lock times have the semantics of calculating
+ // the first block or time at which the transaction would be
+ // valid. When calculating the effective block time or height
+ // for the entire transaction, we switch to using the
+ // semantics of nLockTime which is the last invalid block
+ // time or height. Thus we subtract 1 from the calculated
+ // time or height.
+
+ // Time-based relative lock-times are measured from the
+ // smallest allowed timestamp of the block containing the
+ // txout being spent, which is the median time past of the
+ // block prior.
+ nMinTime = std::max(nMinTime, nCoinTime + (int64_t)((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) - 1);
+ } else {
+ nMinHeight = std::max(nMinHeight, nCoinHeight + (int)(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1);
+ }
+ }
+
+ return std::make_pair(nMinHeight, nMinTime);
+}
+
+static bool EvaluateSequenceLocks(const CBlockIndex& block, std::pair lockPair)
+{
+ assert(block.pprev);
+ int64_t nBlockTime = block.pprev->GetMedianTimePast();
+ if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime)
+ return false;
+
+ return true;
+}
+
+bool SequenceLocks(const CTransaction &tx, int flags, std::vector* prevHeights, const CBlockIndex& block)
+{
+ return EvaluateSequenceLocks(block, CalculateSequenceLocks(tx, flags, prevHeights, block));
+}
+
+bool CheckSequenceLocks(const CTransaction &tx, int flags)
+{
+ AssertLockHeld(cs_main);
+ AssertLockHeld(mempool.cs);
+
+ CBlockIndex* tip = chainActive.Tip();
+ CBlockIndex index;
+ index.pprev = tip;
+ // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
+ // height based locks because when SequenceLocks() is called within
+ // ConnectBlock(), the height of the block *being*
+ // evaluated is what is used.
+ // Thus if we want to know if a transaction can be part of the
+ // *next* block, we need to use one more than chainActive.Height()
+ index.nHeight = tip->nHeight + 1;
+
+ // pcoinsTip contains the UTXO set for chainActive.Tip()
+ CCoinsViewMemPool viewMemPool(pcoinsTip, mempool);
+ std::vector prevheights;
+ prevheights.resize(tx.vin.size());
+ for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
+ const CTxIn& txin = tx.vin[txinIndex];
+ CCoins coins;
+ if (!viewMemPool.GetCoins(txin.prevout.hash, coins)) {
+ return error("%s: Missing input", __func__);
+ }
+ if (coins.nHeight == MEMPOOL_HEIGHT) {
+ // Assume all mempool transaction confirm in the next block
+ prevheights[txinIndex] = tip->nHeight + 1;
+ } else {
+ prevheights[txinIndex] = coins.nHeight;
+ }
+ }
-https://github.com/bitcoin/bitcoin/pull/6312
+ std::pair lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index);
+ return EvaluateSequenceLocks(index, lockPair);
+}
+
==Acknowledgments==
@@ -189,9 +223,13 @@ This BIP was edited by BtcDrak, Nicolas Dorier and kinoshitajona.
==Deployment==
-This BIP is to be deployed by either version-bits BIP9 or by isSuperMajority(). Exact details TDB.
+This BIP is to be deployed by "versionbits" BIP9 using bit 0.
+
+For Bitcoin '''mainnet''', the BIP9 '''starttime''' will be midnight 1st May 2016 UTC (Epoch timestamp 1462060800) and BIP9 '''timeout''' will be midnight 1st May 2017 UTC (Epoch timestamp 1493596800).
+
+For Bitcoin '''testnet''', the BIP9 '''starttime''' will be midnight 1st March 2016 UTC (Epoch timestamp 1456790400) and BIP9 '''timeout''' will be midnight 1st May 2017 UTC (Epoch timestamp 1493596800).
-It is recommended to deploy BIP112 and BIP113 at the same time as this BIP.
+This BIP must be deployed simultaneously with BIP112 and BIP113 using the same deployment mechanism.
==Compatibility==
@@ -207,7 +245,7 @@ The most efficient way to calculate sequence number from relative lock-time is w
// 0 <= nHeight < 65,535 blocks (1.25 years)
nSequence = nHeight;
nHeight = nSequence & 0x0000ffff;
-
+
// 0 <= nTime < 33,554,431 seconds (1.06 years)
nSequence = (1 << 22) | (nTime >> 9);
nTime = (nSequence & 0x0000ffff) << 9;
@@ -217,9 +255,11 @@ The most efficient way to calculate sequence number from relative lock-time is w
Bitcoin mailing list discussion: https://www.mail-archive.com/bitcoin-development@lists.sourceforge.net/msg07864.html
+BIP9: https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki
+
BIP112: https://github.com/bitcoin/bips/blob/master/bip-0112.mediawiki
BIP113: https://github.com/bitcoin/bips/blob/master/bip-0113.mediawiki
-Hashed Timelock Contrats (HTLCs): https://github.com/ElementsProject/lightning/raw/master/doc/deployable-lightning.pdf
+Hashed Timelock Contracts (HTLCs): https://github.com/ElementsProject/lightning/raw/master/doc/deployable-lightning.pdf
diff --git a/bip-0069.mediawiki b/bip-0069.mediawiki
index e23ff04205..7b5034eb7f 100644
--- a/bip-0069.mediawiki
+++ b/bip-0069.mediawiki
@@ -1,11 +1,15 @@
- BIP: BIP: 69
- Title: Lexicographical Indexing of Transaction Inputs and Outputs
- Authors: Kristov Atlas
- Editors: Daniel Cousens
- Status: Draft
- Type: Informational
+ BIP: 69
+ Layer: Applications
+ Title: Lexicographical Indexing of Transaction Inputs and Outputs
+ Author: Kristov Atlas
+ Editor: Daniel Cousens
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0069
+ Status: Proposed
+ Type: Informational
Created: 2015-06-12
+ License: PD
==Abstract==
@@ -21,11 +25,6 @@ This BIP is in the public domain.
==Motivation==
-Currently, there is no clear standard for how wallet clients ought to order transaction inputs and outputs.
-Since wallet clients are left to their own devices to determine this ordering, they often leak information about their users’ finances.
-For example, a wallet client might naively order inputs based on when addresses were added to a wallet by the user through importing or random generation.
-Many wallets will place spending outputs first and change outputs second, leaking information about both the sender and receiver’s finances to passive blockchain observers.
-Such information should remain private not only for the benefit of consumers, but in higher order financial systems must be kept secret to prevent fraud.
Currently, there is no clear standard for how wallet clients ought to order transaction inputs and outputs.
Since wallet clients are left to their own devices to determine this ordering, they often leak information about their users’ finances.
For example, a wallet client might naively order inputs based on when addresses were added to a wallet by the user through importing or random generation.
@@ -79,7 +78,7 @@ N.B. All comparisons do not need to operate in constant time since they are not
===Transaction Inputs===
-Transaction inputs are defined by the hash of a previous transaction, the output index of of a UTXO from that previous transaction, the size of an unlocking script, the unlocking script, and a sequence number. [3]
+Transaction inputs are defined by the hash of a previous transaction, the output index of a UTXO from that previous transaction, the size of an unlocking script, the unlocking script, and a sequence number. [3]
For sorting inputs, the hash of the previous transaction and the output index within that transaction are sufficient for sorting purposes; each transaction hash has an extremely high probability of being unique in the blockchain — this is enforced for coinbase transactions by BIP30 — and output indices within a transaction are unique.
For the sake of efficiency, transaction hashes should be compared first before output indices, since output indices from different transactions are often equivalent, while all bytes of the transaction hash are effectively random variables.
@@ -88,7 +87,7 @@ In the event of two matching transaction hashes, the respective previous output
If the previous output indices match, the inputs are considered equal.
Transaction malleability will not negatively impact the correctness of this process.
-Even if a wallet client follows this process using unconfirmed UTXOs as inputs and an attacker changes modifies the blockchain’s record of the hash of the previous transaction, the wallet client will include the invalidated previous transaction hash in its input data, and will still correctly sort with respect to that invalidated hash.
+Even if a wallet client follows this process using unconfirmed UTXOs as inputs and an attacker modifies the blockchain’s record of the hash of the previous transaction, the wallet client will include the invalidated previous transaction hash in its input data, and will still correctly sort with respect to that invalidated hash.
===Transaction Outputs===
@@ -148,7 +147,7 @@ Outputs:
==References==
* [[https://bitcoinmagazine.com/20273/bitstamp-exchange-activity-trackable-due-multisig-wallet-implementation/|1: Bitstamp Info Leak]]
-* [[https://github.com/OpenBitcoinPrivacyProject/wallet-ratings/blob/master/2015-1/criteria.md|2: OBPP Random Indexing as Countermeasure]]
+* [[https://github.com/OpenBitcoinPrivacyProject/wallet-ratings/blob/5a7e2e1555e91bb48edeca3aa710272777d98c2a/2015-1/criteria.md|2: OBPP Random Indexing as Countermeasure]]
* [[https://github.com/aantonop/bitcoinbook/blob/develop/ch05.asciidoc|3: Mastering Bitcoin]]
* [[https://en.bitcoin.it/wiki/Script|4: Bitcoin Wiki on Script]]
* [[http://www.cplusplus.com/reference/algorithm/lexicographical_compare|5: std::lexicographical_compare]]
@@ -162,6 +161,8 @@ Outputs:
* [[https://github.com/bitcoinjs/bip69/blob/master/index.js|BitcoinJS]]
* [[https://github.com/bitcoinjs/bip69/blob/master/test/fixtures.json|BitcoinJS Test Fixtures]]
* [[https://www.npmjs.com/package/bip69|NodeJS]]
+* [[https://github.com/blockchain/My-Wallet-V3/blob/v3.8.0/src/transaction.js#L120-L142|Blockchain.info public beta]]
+* [[https://github.com/btcsuite/btcutil/blob/master/txsort/txsort.go|Btcsuite]]
==Acknowledgements==
diff --git a/bip-0070.mediawiki b/bip-0070.mediawiki
index 3642784937..fce60234cb 100644
--- a/bip-0070.mediawiki
+++ b/bip-0070.mediawiki
@@ -1,7 +1,11 @@
BIP: 70
+ Layer: Applications
Title: Payment Protocol
- Authors: Gavin Andresen , Mike Hearn
+ Author: Gavin Andresen
+ Mike Hearn
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0070
Status: Final
Type: Standards Track
Created: 2013-07-29
@@ -310,7 +314,7 @@ http://datatracker.ietf.org/wg/jose/
Wikipedia's page on Invoices: http://en.wikipedia.org/wiki/Invoice
especially the list of Electronic Invoice standards
-sipa's payment protocol proposal: https://gist.github.com/1237788
+sipa's payment protocol proposal: https://gist.github.com/sipa/1237788
ThomasV's "Signed Aliases" proposal : http://ecdsa.org/bitcoin_URIs.html
diff --git a/bip-0071.mediawiki b/bip-0071.mediawiki
index 1fc8489243..b4e9def056 100644
--- a/bip-0071.mediawiki
+++ b/bip-0071.mediawiki
@@ -1,7 +1,10 @@
+
+==Abstract==
+
+This BIP alters the Payment Protocol to allow for zero value OP_RETURN outputs in serialized PaymentRequests.
+
+==Motivation==
+
+The Payment Protocol (defined in BIP70) gives merchants a way to build sophisticated transactions by serializing one or more outputs in the form of a PaymentRequest. The PaymentRequest is then served over http/https to a customer's wallet where the serialized transaction can be executed.
+
+While the Payment Protocol allows for any valid script in its outputs, it also ignores outputs with zero value. This means BIP70 implementations can encode an OP_RETURN script but must provide a greater than dust value for that output. The end result is a successful PaymentRequest transaction with an OP_RETURN but the value assigned to that output is lost forever.
+
+This BIP allows for zero value OP_RETURN outputs in serialized PaymentRequests. The change means that OP_RETURN scripts will work as they were originally intended from within PaymentRequests without permanently destroying Bitcoin value. Zero value non-OP_RETURN scripts should continue to be ignored.
+
+In addition to fixing the issue of destroyed value, this change opens up new use cases that were previously impossible.
+
+While storing data on the blockchain is controversial, when used responsibly OP_RETURN provides a powerful mechanism for attaching metadata to a transaction. This BIP effectively decouples the creation of transactions containing OP_RETURN data from the execution of those transactions. The result are positive benefits for both merchants and wallets/customers.
+
+By supporting this BIP, wallets can participate in current and future, unforeseen use cases that benefit from metadata stored in OP_RETURN. Until now OP_RETURN transactions have typically been created and submitted by custom software. If a wallet can process a PaymentRequest with OP_RETURN data as proposed by this BIP, it will support potentially sophisticated Bitcoin applications without the wallet developer having to have prior knowledge of that application.
+
+An example might be a merchant that adds the hash of a plain text invoice to the checkout transaction. The merchant could construct the PaymentRequest with the invoice hash in an OP_RETURN and pass it to the customer's wallet. The wallet could then submit the transaction, including the invoice hash from the PaymentRequest. The wallet will have encoded a proof of purchase to the blockchain without the wallet developer having to coordinate with the merchant software or add features beyond this BIP.
+
+Merchants and Bitcoin application developers benefit from this BIP because they can now construct transactions that include OP_RETURN data in a keyless environment. Again, prior to this BIP, transactions that used OP_RETURN (with zero value) needed to be constructed and executed in the same software. By separating the two concerns, this BIP allows merchant software to create transactions with OP_RETURN metadata on a server without storing public or private Bitcoin keys. This greatly enhances security where OP_RETURN applications currently need access to a private key to sign transactions.
+
+==Specification==
+
+The specification for this BIP is straightforward. BIP70 should be fully implemented with the following changes:
+
+* Outputs where the script is an OP_RETURN and the value is zero should be accepted by the wallet.
+
+BIP70 has special handling for the case with multiple zero value outputs:
+
+
+If the sum of outputs.amount is zero, the customer will be asked how much to pay, and the bitcoin client may choose any or all of the Outputs (if there are more than one) for payment. If the sum of outputs.amount is non-zero, then the customer will be asked to pay the sum, and the payment shall be split among the Outputs with non-zero amounts (if there are more than one; Outputs with zero amounts shall be ignored).
+
+
+This behavior should be retained with the exception of OP_RETURN handling. In the case of a multiple output transaction where the sum of the output values is zero, the user should be prompted for a value and that value should be distributed over any or all outputs ''except'' the OP_RETURN output. In the case where the sum of outputs.amount is non-zero then any OP_RETURN outputs should not be ignored but no value should be assigned to them.
+
+Payment requests also must contain at least one payable output (i.e. no payment requests with ''just'' an OP_RETURN).
+
+==Rationale==
+
+As with the discussion around vanilla OP_RETURN, the practice of storing data on the blockchain is controversial. While blockchain and network bloat is an undeniable issue, the benefits that come from attaching metadata to transactions has proven to be too powerful to dismiss entirely. In the absence of OP_RETURN support the Bitcoin ecosystem has seen alternative, less elegant and more wasteful methods employed for Blockchain data storage.
+
+As it exists today, BIP70 allows for OP_RETURN data storage at the expense of permanently destroyed Bitcoin. Even fully removing support for OP_RETURN values in the Payment Protocol would still leave the door open to suboptimal data encoding via burning a larger than dust value to an output with a false address designed to encode data.
+
+This BIP offers all of the same benefits that come from the OP_RETURN compromise. Mainly that OP_RETURN scripts are provably unspendable and thus can be pruned from the UTXO pool. Without supporting this BIP, wallets that support BIP70 will allow for wasteful data storage.
+
+==Compatibility==
+
+Since this BIP still supports OP_RETURN statements with a greater than zero value, it should be fully backwards compatible with any existing implementations.
+
+==Copyright==
+
+This document is placed in the public domain.
diff --git a/bip-0075.mediawiki b/bip-0075.mediawiki
new file mode 100644
index 0000000000..5057206466
--- /dev/null
+++ b/bip-0075.mediawiki
@@ -0,0 +1,428 @@
+
+ BIP: 75
+ Layer: Applications
+ Title: Out of Band Address Exchange using Payment Protocol Encryption
+ Author: Justin Newton
+ Matt David
+ Aaron Voisine
+ James MacWhyte
+ Comments-Summary: Recommended for implementation (one person)
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0075
+ Status: Final
+ Type: Standards Track
+ Created: 2015-11-20
+ License: CC-BY-4.0
+
+
+==Abstract==
+
+This BIP is an extension to BIP 70 that provides two enhancements to the existing Payment Protocol.
+
+# It allows the requester (Sender) of a PaymentRequest to voluntarily sign the original request and provide a certificate to allow the payee to know the identity of who they are transacting with.
+
+# It encrypts the PaymentRequest that is returned, before handing it off to the SSL/TLS layer to prevent man in the middle viewing of the Payment Request details.
+
+The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and
+"OPTIONAL" in this document are to be interpreted as described in RFC 2119.
+
+==Copyright==
+
+
+
+This work is licensed under a [[http://creativecommons.org/licenses/by/4.0/|Creative Commons Attribution 4.0 International License]].
+
+==Definitions==
+{| class="wikitable"
+| Sender || Entity wishing to transfer value that they control
+|-
+| Receiver || Entity receiving a value transfer
+|}
+
+==Motivation==
+
+The motivation for defining this extension to the [[bip-0070.mediawiki|BIP70]] Payment Protocol is to allow two parties to exchange payment information in a permissioned and encrypted way, such that wallet address communication can become a more automated process. This extension also expands the types of PKI (public-key infrastructure) data that is supported, and allows it to be shared by both parties (with [[bip-0070.mediawiki|BIP70]], only the receiver could provide PKI information). This allows for automated creation of off-blockchain transaction logs that are human readable, now including information about the sender and not just the recipient.
+
+The motivation for this extension to [[bip-0070.mediawiki|BIP70]] is threefold:
+
+# Ensure that the payment details can only be seen by the participants in the transaction, and not by any third party.
+
+# Enhance the Payment Protocol to allow for store and forward servers in order to allow, for example, mobile wallets to sign and serve Payment Requests.
+
+# Allow a sender of funds the option of sharing their identity with the receiver. This information could then be used to:
+
+#* Make Bitcoin logs (wallet transaction history) more human readable
+#* Give the user the ability to decide whether or not they share their Bitcoin address and other payment details when requested
+#* Allow for an open standards based way for businesses to keep verifiable records of their financial transactions, to better meet the needs of accounting practices or other reporting and statutory requirements
+#* Automate the active exchange of payment addresses, so static addresses and BIP32 X-Pubs can be avoided to maintain privacy and convenience
+
+In short we wanted to make Bitcoin more human, while at the same time improving transaction privacy.
+
+==Example Use Cases==
+
+1. Address Book
+
+A Bitcoin wallet developer would like to offer the ability to store an "address book" of payees, so users could send multiple payments to known entities without having to request an address every time. Static addresses compromise privacy, and address reuse is considered a security risk. BIP32 X-Pubs allow the generation of unique addresses, but watching an X-Pub chain for each person you wish to receive funds from is too resource-intensive for mobile applications, and there is always a risk of unknowingly sending funds to an X-Pub address after the owner has lost access to the corresponding private key.
+
+With this BIP, Bitcoin wallets could maintain an "address book" that only needs to store each payee's public key. Adding an entry to one's address book could be done by using a Wallet Name, scanning a QR code, sending a URI through a text message or e-mail, or searching a public repository. When the user wishes to make a payment, their wallet would do all the work in the background to communicate with the payee's wallet to receive a unique payment address. If the payee's wallet has been lost, replaced, or destroyed, no communication will be possible, and the sending of funds to a "dead" address is prevented.
+
+2. Individual Permissioned Address Release
+
+A Bitcoin wallet developer would like to allow users to view a potential sending party's identifying information before deciding whether or not to share payment information with them. Currently, [[bip-0070.mediawiki|BIP70]] shares the receiver’s payment address and identity information with anyone who requests it.
+
+With this BIP, Bitcoin wallets could use the sender’s identifying information to make a determination of whether or not to share their own information. This gives the receiving party more control over who receives their payment and identity information. Additionally, this could be used to automatically provide new payment addresses to whitelisted senders, or to protect users’ privacy from unsolicited payment requests.
+
+3. Using Store & Forward Servers
+
+A Bitcoin wallet developer would like to use a public Store & Forward service for an asynchronous address exchange. This is a common case for mobile and offline wallets.
+
+With this BIP, returned payment information is encrypted with an ECDH-computed shared key before sending to a Store & Forward service. In this case, a successful attack against a Store & Forward service would not be able to read or modify wallet address or payment information, only delete encrypted messages.
+
+==Modifying BIP70 pki_type==
+This BIP adds additional possible values for the pki_type variable in the PaymentRequest message. The complete list is now as follows:
+
+{| class="wikitable"
+! pki_type !! Description
+|-
+| x509+sha256 || A x.509 certificate, as described in BIP70
+|-
+| pgp+sha256 || An [[https://en.wikipedia.org/wiki/Pretty_Good_Privacy#OpenPGP|OpenPGP]] certificate
+|-
+| ecdsa+sha256 || A [[https://en.bitcoin.it/wiki/Secp256k1|secp256k1]] [[https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm|ECDSA]] public key
+|}
+
+'''NOTE''': Although SHA1 was supported in BIP70, it has been deprecated and BIP75 only supports SHA256. The hashing algorithm is still specified in the values listed above for forward and backwards compatibility.
+
+==New Messages==
+Updated [/bip-0075/paymentrequest.proto paymentrequest.proto] contains the existing PaymentRequest Protocol Buffer messages as well as the messages newly defined in this BIP.
+
+'''NOTE''': Public keys from both parties must be known to each other in order to facilitate encrypted communication. Although including both public keys in every message may get redundant, it provides the most flexibility as each message is completely self-contained.
+
+===InvoiceRequest===
+The '''InvoiceRequest''' message allows a Sender to send information to the Receiver such that the Receiver can create and return a PaymentRequest.
+
+
+
+{| class="wikitable"
+! Field Name !! Description
+|-
+| sender_public_key || Sender's SEC-encoded EC public key
+|-
+| amount || amount is integer-number-of-satoshis (default: 0)
+|-
+| pki_type || none / x509+sha256 / pgp+sha256 / ecdsa+sha256 (default: "none")
+|-
+| pki_data || Depends on pki_type
+|-
+| memo || Human-readable description of invoice request for the receiver
+|-
+| notification_url || Secure (usually TLS-protected HTTP) location where an [[#EncryptedProtocolMessage|EncryptedProtocolMessage]] SHOULD be sent when ready
+|-
+| signature || PKI-dependent signature
+|}
+
+===ProtocolMessageType Enum===
+This enum is used in the newly defined [[#ProtocolMessage|ProtocolMessage]] and [[#EncryptedProtocolMessage|EncryptedProtocolMessage]] messages to define the serialized message type. The '''ProtocolMessageType''' enum is defined in an extensible way to allow for new message type additions to the Payment Protocol.
+
+
+===ProtocolMessage===
+The '''ProtocolMessage''' message is an encapsulating wrapper for any Payment Protocol message. It allows two-way, non-encrypted communication of Payment Protocol messages. The message also includes a status code and a status message that is used for error communication such that the protocol does not rely on transport-layer error handling.
+
+
+{| class="wikitable"
+! Field Name !! Description
+|-
+|version || Protocol version number (Currently 1)
+|-
+|status_code || Payment Protocol Status Code
+|-
+|message_type || Message Type of serialized_message
+|-
+|serialized_message || Serialized Payment Protocol Message
+|-
+|status_message || Human-readable Payment Protocol status message
+|-
+|identifier || Unique key to identify this entire exchange on the server. Default value SHOULD be SHA256(Serialized Initial InvoiceRequest + Current Epoch Time in Seconds as a String)
+|}
+
+===Versioning===
+This BIP introduces version 1 of this protocol. All messages sent using these base requirements MUST use a value of 1 for the version number. Any future BIPs that modify this protocol (encryption schemes, etc) MUST each increment the version number by 1.
+
+When initiating communication, the version field of the first message SHOULD be set to the highest version number the sender understands. All clients MUST be able to understand all version numbers less than the highest number they support. If a client receives a message with a version number higher than they understand, they MUST send the message back to the sender with a status code of 101 ("version too high") and the version field set to the highest version number the recipient understands. The sender must then resend the original message using the same version number returned by the recipient or abort.
+
+===EncryptedProtocolMessage===
+The '''EncryptedProtocolMessage''' message is an encapsualting wrapper for any Payment Protocol message. It allows two-way, authenticated and encrypted communication of Payment Protocol messages in order to keep their contents secret. The message also includes a status code and status message that is used for error communication such that the protocol does not rely on transport-layer error handling.
+
+{| class="wikitable"
+! Field Name !! Description
+|-
+| version || Protocol version number
+|-
+| status_code || Payment Protocol Status Code
+|-
+| message_type || Message Type of Decrypted encrypted_message
+|-
+| encrypted_message || AES-256-GCM Encrypted (as defined in BIP75) Payment Protocol Message
+|-
+| receiver_public_key || Receiver's SEC-encoded EC Public Key
+|-
+| sender_public_key || Sender's SEC-encoded EC Public Key
+|-
+| nonce || Microseconds since epoch
+|-
+| identifier || Unique key to identify this entire exchange on the server. Default value SHOULD be SHA256(Serialized Initial InvoiceRequest + Current Epoch Time in Seconds as a String)
+|-
+| status_message || Human-readable Payment Protocol status message
+|-
+| signature || DER-encoded Signature over the full EncryptedProtocolMessage with EC Key Belonging to Sender / Receiver, respectively
+|}
+
+==Payment Protocol Process with InvoiceRequests==
+The full process overview for using '''InvoiceRequests''' in the Payment Protocol is defined below.
+
+All Payment Protocol messages MUST be encapsulated in either a [[#ProtocolMessage|ProtocolMessage]] or [[#EncryptedProtocolMessage|EncryptedProtocolMessage]]. Once the process begins using [[#EncryptedProtocolMessage|EncryptedProtocolMessage]] messages, all subsequent communications MUST use [[#EncryptedProtocolMessage|EncryptedProtocolMessages]].
+
+All Payment Protocol messages SHOULD be communicated using [[#EncryptedProtocolMessage|EncryptedProtocolMessage]] encapsulating messages with the exception that an [[#InvoiceRequest|InvoiceRequest]] MAY be communicated using the [[#ProtocolMessage|ProtocolMessage]] if the receiver's public key is unknown.
+
+
+The process of creating encrypted Payment Protocol messages is enumerated in [[#Sending_Encrypted_Payment_Protocol_Messages_using_EncryptedProtocolMessages|Sending Encrypted Payment Protocol Messages using EncryptedProtocolMessages]], and the process of decrypting encrypted messages can be found under [[#Validating_and_Decrypting_Payment_Protocol_Messages_using_EncryptedProtocolMessages|Validating and Decrypting Payment Protocol Messages using EncryptedProtocolMessages]].
+
+A standard exchange from start to finish would look like the following:
+
+# Sender creates InvoiceRequest
+# Sender encapsulates InvoiceRequest in (Encrypted)ProtocolMessage
+# Sender sends (Encrypted)ProtocolMessage to Receiver
+# Receiver retrieves InvoiceRequest in (Encrypted)ProtocolMessage from Sender
+# Receiver creates PaymentRequest
+# Receiver encapsulates PaymentRequest in EncryptedProtocolMessage
+# Receiver transmits EncryptedProtocolMessage to Sender
+# Sender validates PaymentRequest retrieved from the EncryptedProtocolMessage
+# The PaymentRequest is processed according to [[bip-0070.mediawiki|BIP70]], including optional Payment and PaymentACK messages encapsulated in EncryptedProtocolMessage messages.
+
+'''NOTE:''' See [[#Initial_Public_Key_Retrieval_for_InvoiceRequest_Encryption|Initial Public Key Retrieval for InvoiceRequest Encryption]] for possible options to retrieve Receiver's public key.
+
+
+
+==Message Interaction Details==
+
+===HTTP Content Types for New Message Types===
+When communicated via '''HTTP''', the listed messages MUST be transmitted via TLS-protected HTTP using the appropriate Content-Type header as defined here per message:
+
+{| class="wikitable"
+! Message Type !! Content Type
+|-
+| ProtocolMessage || application/bitcoin-paymentprotocol-message
+|-
+| EncryptedProtocolMessage || application/bitcoin-encrypted-paymentprotocol-message
+|}
+
+===Payment Protocol Status Communication===
+
+Every [[#ProtocolMessage|ProtocolMessage]] or [[#EncryptedProtocolMessage|EncryptedProtocolMessage]] MUST include a status code which conveys information about the last message received, if any (for the first message sent, use a status of 1 "OK" even though there was no previous message). In the case of an error that causes the Payment Protocol process to be stopped or requires that message be retried, a ProtocolMessage or EncryptedProtocolMessage SHOULD be returned by the party generating the error. The content of the message MUST contain the same '''serialized_message''' or '''encrypted_message''' and identifier (if present) and MUST have the status_code set appropriately.
+
+The status_message value SHOULD be set with a human readable explanation of the status code.
+
+====Payment Protocol Status Codes====
+{| class="wikitable"
+! Status Code !! Description
+|-
+| 1 || OK
+|-
+| 2 || Cancel
+|-
+| 100 || General / Unknown Error
+|-
+| 101 || Version Too High
+|-
+| 102 || Authentication Failed
+|-
+| 103 || Encrypted Message Required
+|-
+| 200 || Amount Too High
+|-
+| 201 || Amount Too Low
+|-
+| 202 || Amount Invalid
+|-
+| 203 || Payment Does Not Meet PaymentRequest Requirements
+|-
+| 300 || Certificate Required
+|-
+| 301 || Certificate Expired
+|-
+| 302 || Certificate Invalid for Transaction
+|-
+| 303 || Certificate Revoked
+|-
+| 304 || Certificate Not Well Rooted
+|-
+|}
+
++==Canceling A Message==+
+If a participant to a transaction would like to inform the other party that a previous message should be canceled, they can send the same message with a status code of 2 ("Cancel") and, where applicable, an updated nonce. How recipients make use of the "Cancel" message is up to developers. For example, wallet developers may want to offer users the ability to cancel payment requests they have sent to other users, and have that change reflected in the recipient's UI. Developers using the non-encrypted ProtocolMessage may want to ignore "Cancel" messages, as it may be difficult to authenticate that the message originated from the same user.
+
+===Transport Layer Communication Errors===
+Communication errors MUST be communicated to the party that initiated the communication via the communication layer's existing error messaging faciltiies. In the case of TLS-protected HTTP, this SHOULD be done through standard HTTP Status Code messaging ([https://tools.ietf.org/html/rfc7231 RFC 7231 Section 6]).
+
+==Extended Payment Protocol Process Details==
+This BIP extends the Payment Protocol as defined in [[bip-0070.mediawiki|BIP70]].
+
+For the following we assume the Sender already knows the Receiver's public key, and the exchange is being facilitated by a Store & Forward server which requires valid signatures for authentication.
+
+'''nonce''' MUST be set to a non-repeating number '''and''' MUST be chosen by the encryptor. The current epoch time in microseconds SHOULD be used, unless the creating device doesn't have access to a RTC (in the case of a smart card, for example). The service receiving the message containing the '''nonce''' MAY use whatever method to make sure that the '''nonce''' is never repeated.
+
+===InvoiceRequest Message Creation===
+* Create an [[#InvoiceRequest|InvoiceRequest]] message
+* '''sender_public_key''' MUST be set to the public key of an EC keypair
+* '''amount''' is optional. If the amount is not specified by the [[#InvoiceRequest|InvoiceRequest]], the Receiver MAY specify the amount in the returned PaymentRequest. If an amount is specified by the [[#InvoiceRequest|InvoiceRequest]] and a PaymentRequest cannot be generated for that amount, the [[#InvoiceRequest|InvoiceRequest]] SHOULD return the same [[#InvoiceRequest|InvoiceRequest]] in a [[#ProtocolMessage|ProtocolMessage]] or [[#EncryptedProtocolMessage|EncryptedProtocolMessage]] with the status_code and status_message fields set appropriately.
+* '''memo''' is optional. This MAY be set to a human readable description of the InvoiceRequest
+* Set '''notification_url''' to URL that the Receiver will submit completed PaymentRequest (encapsulated in an [[#EncryptedProtocolMessage|EncryptedProtocolMessage]]) to
+* If NOT including certificate, set '''pki_type''' to "none"
+* If including certificate:
+** Set '''pki_type''' to "x509+sha256"
+** Set '''pki_data''' as it would be set in BIP-0070 ([https://github.com/bitcoin/bips/blob/master/bip-0070.mediawiki#Certificates Certificates])
+** Sign [[#InvoiceRequest|InvoiceRequest]] with signature = "" using the X509 Certificate's private key
+** Set '''signature''' value to the computed signature
+
+===InvoiceRequest Validation===
+* Validate '''sender_public_key''' is a valid EC public key
+* Validate '''notification_url''', if set, contains characters deemed valid for a URL (avoiding XSS related characters, etc).
+* If '''pki_type''' is None, [[#InvoiceRequest|InvoiceRequest]] is VALID
+* If '''pki_type''' is x509+sha256 and '''signature''' is valid for the serialized [[#InvoiceRequest|InvoiceRequest]] where signature is set to "", [[#InvoiceRequest|InvoiceRequest]] is VALID
+
+===Sending Encrypted Payment Protocol Messages using EncryptedProtocolMessages===
+* Encrypt the serialized Payment Protocol message using AES-256-GCM setup as described in [[#ECDH_Point_Generation_and_AES256_GCM_Mode_Setup|ECDH Point Generation and AES-256 (GCM Mode) Setup]]
+* Create [[#EncryptedProtocolMessage|EncryptedProtocolMessage]] message
+* Set '''encrypted_message''' to be the encrypted value of the Payment Protocol message
+* '''version''' SHOULD be set to the highest version number the client understands (currently 1)
+* '''sender_public_key''' MUST be set to the public key of the Sender's EC keypair
+* '''receiver_public_key''' MUST be set to the public key of the Receiver's EC keypair
+* '''nonce''' MUST be set to the nonce used in the AES-256-GCM encryption operation
+* Set '''identifier''' to the identifier value received in the originating InvoiceRequest's ProtocolMessage or EncryptedProtocolMessage wrapper message
+* Set '''signature''' to ""
+* Sign the serialized [[#EncryptedProtocolMessage|EncryptedProtocolMessage]] message with the communicating party's EC public key
+* Set '''signature''' to the result of the signature operation above
+
+'''SIGNATURE NOTE:''' [[#EncryptedProtocolMessage|EncryptedProtocolMessage]] messages are signed with the public keys of the party transmitting the message. This allows a Store & Forward server or other transmission system to prevent spam or other abuses. For those who are privacy conscious and don't want the server to track the interactions between two public keys, the Sender can generate a new public key for each interaction to keep their identity anonymous.
+
+===Validating and Decrypting Payment Protocol Messages using EncryptedProtocolMessages===
+* The '''nonce''' MUST not be repeated. The service receiving the [[#EncryptedProtocolMessage|EncryptedProtocolMessage]] MAY use whatever method to make sure that the nonce is never repeated.
+* Decrypt the serialized Payment Protocol message using AES-256-GCM setup as described in [[#ECDH_Point_Generation_and_AES256_GCM_Mode_Setup|ECDH Point Generation and AES-256 (GCM Mode) Setup]]
+* Deserialize the serialized Payment Protocol message
+
+===ECDH Point Generation and AES-256 (GCM Mode) Setup===
+'''NOTE''': AES-256-GCM is used because it provides authenticated encryption facilities, thus negating the need for a separate message hash for authentication.
+
+* Generate the '''secret point''' using [https://en.wikipedia.org/wiki/Elliptic_curve_Diffie–Hellman ECDH] using the local entity's private key and the remote entity's public key as inputs
+* Initialize [http://csrc.nist.gov/publications/nistpubs/800-90A/SP800-90A.pdf HMAC_DRBG]
+** Use '''SHA512(secret point's X value in Big-Endian bytes)''' for Entropy
+** Use the given message's '''nonce''' field for Nonce, converted to byte string (Big Endian)
+
+* Initialize AES-256 in GCM Mode
+** Initialize HMAC_DRBG with Security Strength of 256 bits
+** Use HMAC_DRBG.GENERATE(32) as the Encryption Key (256 bits)
+** Use HMAC_DRBG.GENERATE(12) as the Initialization Vector (IV) (96 bits)
+
+====AES-256 GCM Authentication Tag Use====
+The 16 byte authentication tag resulting from the AES-GCM encrypt operation MUST be prefixed to the returned ciphertext. The decrypt operation will use the first 16 bytes of the ciphertext as the GCM authentication tag and the remainder of the ciphertext as the ciphertext in the decrypt operation.
+
+====AES-256 GCM Additional Authenticated Data====
+When either '''status_code''' OR '''status_message''' are present, the AES-256 GCM authenticated data used in both the encrypt and decrypt operations MUST be: STRING(status_code) || status_message. Otherwise, there is no additional authenticated data. This provides that, while not encrypted, the status_code and status_message are authenticated.
+
+===Initial Public Key Retrieval for InvoiceRequest Encryption===
+Initial public key retrieval for [[#InvoiceRequest|InvoiceRequest]] encryption via [[#EncryptedProtocolMessage|EncryptedProtocolMessage]] encapsulation can be done in a number of ways including, but not limited to, the following:
+# Wallet Name public key asset type resolution - DNSSEC-validated name resolution returns Base64 encoded DER-formatted EC public key via TXT Record [https://www.ietf.org/rfc/rfc5480.txt RFC 5480]
+# Key Server lookup - Key Server lookup (similar to PGP's pgp.mit.edu) based on key server identifier (i.e., e-mail address) returns Base64 encoded DER-formatted EC public key [https://www.ietf.org/rfc/rfc5480.txt RFC 5480]
+# QR Code - Use of QR-code to encode SEC-formatted EC public key [https://www.ietf.org/rfc/rfc5480.txt RFC 5480]
+# Address Service Public Key Exposure
+
+==Payment / PaymentACK Messages with a HTTP Store & Forward Server==
+If a Store & Forward server wishes to protect themselves from spam or abuse, they MAY enact whatever rules they deem fit, such as the following:
+
+* Once an InvoiceRequest or PaymentRequest is received, all subsequent messages using the same identifier must use the same Sender and Receiver public keys.
+* For each unique identifier, only one message each of type InvoiceRequest, PaymentRequest, and PaymentACK may be submitted. Payment messages may be submitted/overwritten multiple times. All messages submitted after a PaymentACK is received will be rejected.
+* Specific messages are only saved until they have been verifiably received by the intended recipient or a certain amount of time has passed, whichever comes first.
+
+
+Clients SHOULD keep in mind Receivers can broadcast a transaction without returning an ACK. If a Payment message needs to be updated, it SHOULD include at least one input referenced in the original transaction to prevent the Receiver from broadcasting both transactions and getting paid twice.
+
+==Public Key & Signature Encoding==
+* All x.509 certificates included in any message defined in this BIP MUST be DER [ITU.X690.1994] encoded.
+* All EC public keys ('''sender_public_key''', '''receiver_public_key''') in any message defined in this BIP MUST be [[SECP256k1|http://www.secg.org/sec2-v2.pdf]] ECDSA Public Key ECPoints encoded using [[SEC 2.3.3 Encoding|http://www.secg.org/sec1-v2.pdf]]. Encoding MAY be compressed.
+* All ECC signatures included in any message defined in this BIP MUST use the SHA-256 hashing algorithm and MUST be DER [ITU.X690.1994] encoded.
+* All OpenPGP certificates must follow [[https://tools.ietf.org/html/rfc4880|RFC4880]], sections 5.5 and 12.1.
+
+==Implementation==
+A reference implementation for a Store & Forward server supporting this proposal can be found here:
+
+[https://github.com/netkicorp/addressimo Addressimo]
+
+A reference client implementation can be found in the InvoiceRequest functional testing for Addressimo here:
+
+[https://github.com/netkicorp/addressimo/blob/master/functest/functest_bip75.py BIP75 Client Reference Implementation]
+
+==BIP70 Extension==
+The following flowchart is borrowed from [[bip-0070.mediawiki|BIP70]] and expanded upon in order to visually describe how this BIP is an extension to [[bip-0070.mediawiki|BIP70]].
+
+
+
+==Mobile to Mobile Examples==
+
+===Full Payment Protocol===
+The following diagram shows a sample flow in which one mobile client is sending value to a second mobile client with the use of an InvoiceRequest, a Store & Forward server, PaymentRequest, Payment and PaymentACK. In this case, the PaymentRequest, Payment and PaymentACK messages are encrypted using [[#EncryptedProtocolMessage|EncryptedProtocolMessage]] '''and''' the Receiver submits the transaction to the Bitcoin network.
+
+
+
+===Encrypting Initial InvoiceRequest via EncryptedProtocolMessage===
+The following diagram shows a sample flow in which one mobile client is sending value to a second mobile client using an [[#EncryptedProtocolMessage|EncryptedProtocolMessage]] to transmit the InvoiceRequest using encryption, Store & Forward server, and PaymentRequest. In this case, all Payment Protocol messages are encrypting using [[#EncryptedProtocolMessage|EncryptedProtocolMessage]] '''and''' the Sender submits the transaction to the Bitcoin network.
+
+
+
+==References==
+
+* [[bip-0070.mediawiki|BIP70 - Payment Protocol]]
+* [https://en.wikipedia.org/wiki/Elliptic_curve_Diffie–Hellman ECDH]
+* [http://csrc.nist.gov/publications/nistpubs/800-90A/SP800-90A.pdf HMAC_DRBG]
+* [http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf NIST Special Publication 800-38D - Recommendation for Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC]
+* [https://tools.ietf.org/html/rfc6979 RFC6979]
+* [https://en.bitcoin.it/wiki/Address_reuse Address Reuse]
+* [http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf FIPS 180-4 (Secure Hash Standard)]
diff --git a/bip-0075/bip70-extension.png b/bip-0075/bip70-extension.png
new file mode 100755
index 0000000000..e02db322d0
Binary files /dev/null and b/bip-0075/bip70-extension.png differ
diff --git a/bip-0075/encrypted-invoice-request-process.png b/bip-0075/encrypted-invoice-request-process.png
new file mode 100644
index 0000000000..918cf70888
Binary files /dev/null and b/bip-0075/encrypted-invoice-request-process.png differ
diff --git a/bip-0075/invoice-request-process.png b/bip-0075/invoice-request-process.png
new file mode 100644
index 0000000000..47a4fac558
Binary files /dev/null and b/bip-0075/invoice-request-process.png differ
diff --git a/bip-0075/mobile-sf-encrypted-ir-without-payment.png b/bip-0075/mobile-sf-encrypted-ir-without-payment.png
new file mode 100755
index 0000000000..fb0b5d1ff4
Binary files /dev/null and b/bip-0075/mobile-sf-encrypted-ir-without-payment.png differ
diff --git a/bip-0075/mobile-sf-ir-with-payment.png b/bip-0075/mobile-sf-ir-with-payment.png
new file mode 100755
index 0000000000..729fa79db1
Binary files /dev/null and b/bip-0075/mobile-sf-ir-with-payment.png differ
diff --git a/bip-0075/mobile-sf-ir-without-payment.png b/bip-0075/mobile-sf-ir-without-payment.png
new file mode 100755
index 0000000000..19cf842285
Binary files /dev/null and b/bip-0075/mobile-sf-ir-without-payment.png differ
diff --git a/bip-0075/paymentrequest.proto b/bip-0075/paymentrequest.proto
new file mode 100644
index 0000000000..5097abb7f2
--- /dev/null
+++ b/bip-0075/paymentrequest.proto
@@ -0,0 +1,87 @@
+//
+// Simple Bitcoin Payment Protocol messages
+//
+// Use fields 1000+ for extensions;
+// to avoid conflicts, register extensions via pull-req at
+// https://github.com/bitcoin/bips/bip-0070/extensions.mediawiki
+//
+
+package payments;
+option java_package = "org.bitcoin.protocols.payments";
+option java_outer_classname = "Protos";
+
+// Generalized form of "send payment to this/these bitcoin addresses"
+message Output {
+ optional uint64 amount = 1 [default = 0]; // amount is integer-number-of-satoshis
+ required bytes script = 2; // usually one of the standard Script forms
+}
+message PaymentDetails {
+ optional string network = 1 [default = "main"]; // "main" or "test"
+ repeated Output outputs = 2; // Where payment should be sent
+ required uint64 time = 3; // Timestamp; when payment request created
+ optional uint64 expires = 4; // Timestamp; when this request should be considered invalid
+ optional string memo = 5; // Human-readable description of request for the customer
+ optional string payment_url = 6; // URL to send Payment and get PaymentACK
+ optional bytes merchant_data = 7; // Arbitrary data to include in the Payment message
+}
+message PaymentRequest {
+ optional uint32 payment_details_version = 1 [default = 1];
+ optional string pki_type = 2 [default = "none"]; // none / x509+sha256 / x509+sha1
+ optional bytes pki_data = 3; // depends on pki_type
+ required bytes serialized_payment_details = 4; // PaymentDetails
+ optional bytes signature = 5; // pki-dependent signature
+}
+message X509Certificates {
+ repeated bytes certificate = 1; // DER-encoded X.509 certificate chain
+}
+message Payment {
+ optional bytes merchant_data = 1; // From PaymentDetails.merchant_data
+ repeated bytes transactions = 2; // Signed transactions that satisfy PaymentDetails.outputs
+ repeated Output refund_to = 3; // Where to send refunds, if a refund is necessary
+ optional string memo = 4; // Human-readable message for the merchant
+}
+message PaymentACK {
+ required Payment payment = 1; // Payment message that triggered this ACK
+ optional string memo = 2; // Human-readable message for customer
+}
+
+// BIP-IR Extensions
+message InvoiceRequest {
+ required bytes sender_public_key = 1; // Sender's DER-Encoded EC Public Key
+ optional uint64 amount = 2 [default = 0]; // amount is integer-number-of-satoshis
+ optional string pki_type = 3 [default = "none"]; // none / x509+sha256
+ optional bytes pki_data = 4; // Depends on pki_type
+ optional string memo = 5; // Human-readable description of invoice request for the receiver
+ optional string notification_url = 6; // URL to notify on EncryptedPaymentRequest ready
+ optional bytes signature = 7; // PKI-dependent signature
+}
+
+enum ProtocolMessageType {
+ UNKNOWN_MESSAGE_TYPE = 0;
+ INVOICE_REQUEST = 1;
+ PAYMENT_REQUEST = 2;
+ PAYMENT = 3;
+ PAYMENT_ACK = 4;
+}
+
+message ProtocolMessage {
+ required uint64 version = 1 [default = 1]; // Protocol version number
+ required uint64 status_code = 2 [default = 1]; // Payment Protocol Status Code (Default: 1 "OK")
+ required ProtocolMessageType message_type = 3; // Message Type of serialized_message
+ required bytes serialized_message = 4; // Serialized Payment Protocol Message
+ optional string status_message = 5; // Human-readable Payment Protocol status message
+ required bytes identifier = 6; // Unique key to identify this entire exchange on the server. Default value SHOULD be SHA256(Serialized Initial InvoiceRequest + Current Epoch Time in Seconds as a String)
+}
+
+message EncryptedProtocolMessage {
+ required uint64 version = 1 [default = 1]; // Protocol version number
+ required uint64 status_code = 2 [default = 1]; // Payment Protocol Status Code (Default: 1 "OK")
+ required ProtocolMessageType message_type = 3; // Message Type of Decrypted encrypted_message
+ required bytes encrypted_message = 4; // AES-256-GCM Encrypted (as defined in BIP75) Payment Protocol Message
+ required bytes receiver_public_key = 5; // Receiver's DER-encoded EC Public Key
+ required bytes sender_public_key = 6; // Sender's DER-encoded EC Public Key
+ required uint64 nonce = 7; // Microseconds since epoch
+ required bytes identifier = 8; // Unique key to identify this entire exchange on the server. Default value SHOULD be SHA256(Serialized Initial InvoiceRequest + Current Epoch Time in Seconds as a String)
+ optional string status_message = 9; // Human-readable Payment Protocol status message
+ optional bytes signature = 10; // Signature over the full EncryptedProtocolMessage with EC Key Belonging to Sender / Receiver, respectively
+}
\ No newline at end of file
diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki
new file mode 100644
index 0000000000..cc3ef5c307
--- /dev/null
+++ b/bip-0078.mediawiki
@@ -0,0 +1,684 @@
+
+
+==Introduction==
+
+===Abstract===
+
+This document proposes a protocol for two parties
+to negotiate a coinjoin transaction during a payment between them.
+
+===Copyright===
+
+This BIP is licensed under the 2-clause BSD license.
+
+===Motivation===
+
+When two parties (later referred to as sender and receiver) want to transact,
+most of the time, the sender creates a transaction spending their own Unspent Transaction Outputs (UTXOs), signs
+it and broadcasts it on the network.
+
+This simple model gave birth to several heuristics impacting the privacy of the parties and of the network as a whole.
+
+* Common input ownership heuristic: In most transactions, all the inputs belong to the same party.
+* Change identification from scriptPubKey type: If all inputs are spending UTXOs of a certain scriptPubKey type, then the change output is likely to have the same scriptPubKey type, too.
+* Change identification from round amount: If an output in the transaction has a round amount, it is likely an output belonging to the receiver.
+
+We will designate these three heuristics as common-input, change-scriptpubkey, change-round-amount.
+
+The problems we aim to solve are:
+* For the receiver, there is a missed opportunity to consolidate their own UTXOs or making payment in the sender's transaction.
+* For the sender, there are privacy leaks regarding their wallet that happen when someone applies the heuristics detailed above to their transaction.
+
+Our proposal gives an opportunity for the receiver to consolidate their UTXOs while also batching their own payments, without creating a new transaction. (Saving fees in the process)
+For the sender, it allows them to invalidate the three heuristics above. With the receiver's involvement, the heuristics can even be poisoned. (ie, using the heuristics to intentionally mislead blockchain analysis)
+
+Note that the existence of this proposal is also improving the privacy of parties who are not using it by making the three heuristics unreliable to the network as a whole.
+
+=== Relation to BIP79 (Bustapay) ===
+
+Another implementation proposal has been written: [[https://github.com/bitcoin/bips/blob/master/bip-0079.mediawiki|BIP79 Bustapay]].
+
+We decided to deviate from it for several reasons:
+* It was not using PSBT, so if the receiver wanted to bump the fee, they would need the full UTXO set.
+* Inability to change the payment output to match scriptPubKey type.
+* Lack of basic versioning negotiation if the protocol evolves.
+* No standardization of error condition for proper feedback to the sender.
+
+Other than that, our proposal is very similar.
+
+==Specification==
+
+===Protocol===
+
+In a payjoin payment, the following steps happen:
+
+* The receiver of the payment, presents a [[bip-0021.mediawiki|BIP 21 URI]] to the sender with a parameter pj= describing a payjoin endpoint.
+* The sender creates a signed, finalized PSBT with witness UTXO or previous transactions of the inputs. We call this PSBT the original.
+* The receiver replies back with a signed PSBT containing his own signed inputs/outputs and those of the sender. We call this PSBT Payjoin proposal.
+* The sender verifies the proposal, re-signs his inputs and broadcasts the transaction to the Bitcoin network. We call this transaction Payjoin transaction.
+
+The original PSBT is sent in the HTTP POST request body, base64 serialized, with text/plain in the Content-Type HTTP header and Content-Length set correctly.
+The payjoin proposal PSBT is sent in the HTTP response body, base64 serialized with HTTP code 200.
+
+To ensure compatibility with web-wallets and browser-based-tools, all responses (including errors) must contain the HTTP header Access-Control-Allow-Origin: *.
+
+The sender must ensure that the URL refers to a scheme or protocol using authenticated encryption, for example TLS with certificate validation, or a .onion link to a hidden service whose public key identifier has already been communicated via a TLS connection. Senders SHOULD NOT accept a URL representing an unencrypted or unauthenticated connection.
+
+The original PSBT MUST:
+* Have all the witnessUTXO or nonWitnessUTXO information filled in.
+* Be finalized.
+* Not include fields unneeded for the receiver such as global xpubs or keypath information.
+* Be broadcastable.
+
+The original PSBT MAY:
+* Have outputs unrelated to the payment for batching purpose.
+
+The payjoin proposal MUST:
+* Use all the inputs from the original PSBT.
+* Use all the outputs which do not belong to the receiver from the original PSBT.
+* Only finalize the inputs added by the receiver. (Referred later as additional inputs)
+* Only fill the witnessUTXO or nonWitnessUTXO for the additional inputs.
+
+The payjoin proposal MAY:
+* Add, remove or modify the outputs belonging to the receiver.
+
+The payjoin proposal MUST NOT:
+* Shuffle the order of inputs or outputs, the additional outputs or additional inputs must be inserted at a random index.
+* Decrease the absolute fee of the original transaction.
+
+===BIP21 payjoin parameters===
+
+This proposal is defining the following new [[bip-0021.mediawiki|BIP 21 URI]] parameters:
+* pj=: Represents an http(s) endpoint which the sender can POST the original PSBT.
+* pjos=0: Signal to the sender that they MUST disallow [[#output-substitution|payment output substitution]]. (See [[#unsecured-payjoin|Unsecured payjoin server]])
+
+===Optional parameters===
+
+When the payjoin sender posts the original PSBT to the receiver, he can optionally specify the following HTTP query string parameters:
+
+* v=, the version number of the payjoin protocol that the sender is using. The current version is 1.
+
+This can be used in the future so the receiver can reject a payjoin if the sender is using a version which is not supported via an error HTTP 400, version-unsupported.
+If not specified, the receiver will assume the sender is v=1.
+
+If the receiver does not support the version of the sender, they should send an error with the list of supported versions:
+
+{
+ "errorCode": "version-unsupported",
+ "supported" : [ 2, 3, 4 ],
+ "message": "The version is not supported anymore"
+}
+
+
+* additionalfeeoutputindex=, if the sender is willing to pay for increased fee, this indicate output can have its value subtracted to pay for it.
+
+If the additionalfeeoutputindex is out of bounds or pointing to the payment output meant for the receiver, the receiver should ignore the parameter. See [[#fee-output|fee output]] for more information.
+
+* maxadditionalfeecontribution=, if the sender is willing to pay for increased fee, an integer defining the maximum amount in satoshis that the sender is willing to contribute towards fees for the additional inputs. maxadditionalfeecontribution must be ignored if set to less than zero. See [[#fee-output|fee output]] for more information.
+
+Note that both maxadditionalfeecontribution= and additionalfeeoutputindex= must be specified and valid for the receiver to be allowed to decrease an output belonging to the sender.
+This fee contribution can't be used to pay for anything else than additional input's weight.
+
+* minfeerate=, a decimal in satoshi per vbyte that the sender can use to constraint the receiver to not drop the minimum fee rate too much.
+
+* disableoutputsubstitution=, a boolean indicating if the sender forbids the receiver to substitute the receiver's output, see [[#output-substitution|payment output substitution]]. (default to false)
+
+===Receiver's well known errors===
+
+If for some reason the receiver is unable to create a payjoin proposal, it will reply with a HTTP code different than 200.
+The receiver is not constrained to specific set of errors, some are specified in this proposal.
+
+The errors have the following format:
+
+{
+ "errorCode": "leaking-data",
+ "message": "Key path information or GlobalXPubs should not be included in the original PSBT."
+}
+
+
+The well-known error codes are:
+{| class="wikitable"
+!Error code
+!Meaning
+|-
+|unavailable
+|The payjoin endpoint is not available for now.
+|-
+|not-enough-money
+|The receiver added some inputs but could not bump the fee of the payjoin proposal.
+|-
+|version-unsupported
+|This version of payjoin is not supported.
+|-
+|original-psbt-rejected
+|The receiver rejected the original PSBT.
+|}
+
+The receiver is allowed to return implementation-specific errors which may assist the sender to diagnose any issue.
+
+However, it is important that error codes that are not well-known and that the message do not appear on the sender's software user interface.
+Such error codes or messages could be used maliciously to phish a non-technical user.
+Instead those errors or messages can only appear in debug logs.
+
+It is advised to hard code the description of the well known error codes into the sender's software.
+
+===Fee output===
+
+In some situation, the sender might want to pay some additional fee in the payjoin proposal.
+If such is the case, the sender must use both [[#optional-params|optional parameters]] additionalfeeoutputindex= and maxadditionalfeecontribution= to indicate which output and how much the receiver can subtract fee.
+
+There is several cases where a fee output is useful:
+
+* The sender's original transaction's fee rate is at the minimum accepted by the network, aka minimum relay transaction fee rate, which is typically 1 satoshi per vbyte.
+
+In such case, the receiver will need to increase the fee of the transaction after adding his own inputs to not drop below the minimum relay transaction fee rate.
+
+* The sender's wallet software is using round fee rate.
+
+If the sender's fee rate is always round, then a blockchain analyst can easily spot the transactions of the sender involving payjoin by checking if, when removing a single input to the suspected payjoin transaction, the resulting fee rate is round.
+To prevent this, the sender can agree to pay more fee so the receiver make sure that the payjoin transaction fee is also round.
+
+* The sender's transaction is time sensitive.
+
+When a sender picks a specific fee rate, the sender expects the transaction to be confirmed after a specific amount of time. But if the receiver adds an input without bumping the fee of the transaction, the payjoin transaction fee rate will be lower, and thus, longer to confirm.
+
+Our recommendation for maxadditionalfeecontribution= is originalPSBTFeeRate * vsize(sender_input_type).
+
+{| class="wikitable"
+!sender_input_type
+!vsize(sender_input_type)
+|-
+|P2WPKH
+|68
+|-
+|P2PKH
+|148
+|-
+|P2SH-P2WPKH
+|91
+|-
+|P2TR
+|58
+|}
+
+
+
+===Receiver's original PSBT checklist===
+
+The receiver needs to do some check on the original PSBT before proceeding:
+
+* Non-interactive receivers (like a payment processor) need to check that the original PSBT is broadcastable. *
+* If the sender included inputs in the original PSBT owned by the receiver, the receiver must either return error original-psbt-rejected or make sure they do not sign those inputs in the payjoin proposal.
+* If the sender's inputs are all from the same scriptPubKey type, the receiver must match the same type. If the receiver can't match the type, they must return error unavailable.
+* Make sure that the inputs included in the original transaction have never been seen before.
+** This prevents [[#probing-attack|probing attacks]].
+** This prevents reentrant payjoin, where a sender attempts to use payjoin transaction as a new original transaction for a new payjoin.
+
+*: Interactive receivers are not required to validate the original PSBT because they are not exposed to [[#probing-attack|probing attacks]].
+
+===Sender's payjoin proposal checklist===
+
+The sender should check the payjoin proposal before signing it to prevent a malicious receiver from stealing money.
+
+* Verify that the absolute fee of the payjoin proposal is equals or higher than the original PSBT.
+* If the receiver's BIP21 signalled pjos=0, disable payment output substitution.
+* Verify that the transaction version, and the nLockTime are unchanged.
+* Check that the sender's inputs' sequence numbers are unchanged.
+* For each input in the proposal:
+** Verify that no keypaths are in the PSBT input
+** Verify that no partial signature has been filled
+** If it is one of the sender's inputs:
+*** Verify that input's sequence is unchanged.
+*** Verify the PSBT input is not finalized
+*** Verify that non_witness_utxo and witness_utxo are not specified.
+** If it is one of the receiver's inputs:
+*** Verify the PSBT input is finalized
+*** Verify that non_witness_utxo or witness_utxo are filled in.
+** Verify that the payjoin proposal inputs all specify the same sequence value.
+** Verify that the payjoin proposal did not introduce mixed input's type.
+** Verify that all of sender's inputs from the original PSBT are in the proposal.
+* For each output in the proposal:
+** Verify that no keypaths are in the PSBT output
+** If the output is the [[#fee-output|fee output]]:
+*** The amount that was subtracted from the output's value is less than or equal to maxadditionalfeecontribution. Let's call this amount actual contribution.
+*** Make sure the actual contribution is only going towards fees: The actual contribution is less than or equals to the difference of absolute fee between the payjoin proposal and the original PSBT.
+*** Make sure the actual contribution is only paying for fees incurred by additional inputs: actual contribution is less than or equal to originalPSBTFeeRate * vsize(sender_input_type) * (count(payjoin_proposal_inputs) - count(original_psbt_inputs)). (see [[#fee-output|Fee output]] section)
+** If the output is the payment output and payment output substitution is allowed,
+*** Do not make any check
+** Else
+*** Make sure the output's value did not decrease.
+** Verify that all sender's outputs (ie, all outputs except the output actually paid to the receiver) from the original PSBT are in the proposal.
+* Once the proposal is signed, if minfeerate was specified, check that the fee rate of the payjoin transaction is not less than this value.
+
+The sender must be careful to only sign the inputs that were present in the original PSBT and nothing else.
+
+Note:
+* The sender must allow the receiver to add/remove or modify the receiver's own outputs. (if payment output substitution is disabled, the receiver's outputs must not be removed or decreased in value)
+* The sender should allow the receiver to not add any inputs. This is useful for the receiver to change the payment output scriptPubKey type.
+* If the receiver added no inputs, the sender's wallet implementation should accept the payjoin proposal, but not mark the transaction as an actual payjoin in the user interface.
+
+Our method of checking the fee allows the receiver and the sender to batch payments in the payjoin transaction.
+It also allows the receiver to pay the fee for batching adding his own outputs.
+
+==Rationale==
+
+There is several consequences of our proposal:
+
+* The receiver can bump the fee of the original transaction.
+* The receiver can modify the outputs of the original PSBT.
+* The sender must provide the UTXO information (Witness or previous transaction) in the PSBT.
+
+===Respecting the minimum relay fee policy===
+
+To be properly relayed, a Bitcoin transaction needs to pay at least 1 satoshi per virtual byte.
+When blocks are not full, the original transaction might already at the minimum relay fee rate (currently 1 satoshi per virtual byte), so if the receiver adds their own input, they need to make sure the fee is increased such that the rate does not drop below the minimum relay fee rate.
+In such case, the sender must set both maxadditionalfeecontribution= and additionalfeeoutputindex=.
+
+See the [[#fee-output|Fee output]] section for more information.
+
+We also recommend the sender to set minfeerate=, as the sender's node policy might be different from the receiver's policy.
+
+===Defeating heuristics based on the fee calculation===
+
+Most wallets are creating a round fee rate (like 2 sat/b).
+If the payjoin transaction's fee was not increased by the added size, then those payjoin transactions could easily be identifiable on the blockchain.
+
+Not only would those transactions stand out by not having a round fee (like 1.87 sat/b), but any suspicion of payjoin could be confirmed by checking if removing one input would create a round fee rate.
+In such case, the sender must set both maxadditionalfeecontribution= and additionalfeeoutputindex=.
+
+The recommended value maxadditionalfeecontribution= is explained in the [[#fee-output|Fee output]] section.
+We also recommend the sender to set minfeerate=, as the sender's node policy might be different from the receiver's policy.
+
+===Receiver does not need to be a full node===
+
+Because the receiver needs to bump the fee to keep the same fee rate as the original PSBT, it needs the input's UTXO information to know what is the original fee rate. Without PSBT, light wallets like Wasabi Wallet would not be able to receive a payjoin transaction.
+
+The validation (policy and consensus) of the original transaction is optional: a receiver without a full node can decide to create the payjoin transaction and automatically broadcast the original transaction after a timeout of 1 minute, and only verify that it has been propagated in the network.
+
+However, non-interactive receivers (like a payment processor) need to verify the transaction to prevent UTXO probing attacks.
+
+This is not a concern for interactive receivers like Wasabi Wallet, because those receivers can just limit the number of original PSBT proposals of a specific address to one. With such wallets, the attacker has no way to generate new deposit addresses to probe the UTXOs.
+
+===Spare change donation===
+
+Small change inside wallets are detrimental to privacy. Mixers like Wasabi wallet, because of its protocol, eventually generate such [[https://docs.wasabiwallet.io/using-wasabi/ChangeCoins.html#first-round-coinjoin-change|small change]].
+
+A common way to protect your privacy is to donate those spare changes, to deposit them in an exchange or on your favorite merchant's store account. Those kind of transactions can easily be spotted on the blockchain: There is only one output.
+
+However, if you donate via payjoin, it will look like a normal transaction.
+
+On top of this the receiver can poison analysis by randomly faking a round amount of satoshi for the additional output.
+
+===Payment output substitution===
+
+Unless disallowed by the sender explicitly via disableoutputsubstitution=true or by the BIP21 URL via the query parameter pjos=0, the receiver is free to decrease the amount, remove, or change the scriptPubKey output paying to himself.
+Note that if payment output substitution is disallowed, the reveiver can still increase the amount of the output. (See [[#reference-impl|the reference implementation]])
+
+For example, if the sender's scriptPubKey type is P2WPKH while the receiver's payment output in the original PSBT is P2SH, then the receiver can substitute the payment output to be P2WPKH to match the sender's scriptPubKey type.
+
+===Unsecured payjoin server===
+
+A receiver might run the payment server (generating the BIP21 invoice) on a different server than the payjoin server, which could be less trusted than the payment server.
+
+In such case, the payment server can signal to the sender, via the BIP21 parameter pjos=0, that they MUST disallow [[#output-substitution|payment output substitution]].
+A compromised payjoin server could steal the hot wallet outputs of the receiver, but would not be able to re-route payment to himself.
+
+===Impacted heuristics===
+
+Our proposal of payjoin breaks the following blockchain heuristics:
+
+* Common inputs heuristics.
+
+Because payjoin is mixing the inputs of the sender and receiver, this heuristic becomes unreliable.
+
+* Change identification from scriptPubKey type heuristics
+
+When Alice pays Bob, if Alice is using P2SH but Bob's deposit address is P2WPKH, the heuristic would assume that the P2SH output is the change address of Alice.
+This is now however a broken assumption, as the payjoin receiver has the freedom to mislead analytics by purposefully changing the invoice's address in the payjoin transaction.
+
+See [[#output-substitution|payment output substitution]].
+
+* Change identification from round change amount
+
+If Alice pays Bob, she might be tempted to pay him a round amount, like 1.23000000 BTC. When this happens, blockchain analysis often identifies the output without the round amount as the change of the transaction.
+
+For this reason, during a [[#spare-change|spare change]] case, the receiver may add an output with a rounded amount randomly.
+
+==Attack vectors==
+
+===On the receiver side: UTXO probing attack===
+
+When the receiver creates a payjoin proposal, they expose one or more inputs belonging to them.
+
+An attacker could create multiple original transactions in order to learn the UTXOs of the receiver, while not broadcasting the payjoin proposal.
+
+While we cannot prevent this type of attack entirely, we implemented the following mitigations:
+
+* When the receiver detects an original transaction being broadcast, or if the receiver detects that the original transaction has been double spent, then they will reuse the UTXO that was exposed for the next payjoin.
+* While the exposed UTXO will be reused in priority to not leak other UTXOs, there is no strong guarantee about it. This prevents the attacker from detecting with certainty the next payjoin of the merchant to another peer.
+
+Note that probing attacks are only a problem for automated payment systems such as BTCPay Server. End-user wallets with payjoin capabilities are not affected, as the attacker can't create multiple invoices to force the receiver to expose their UTXOs.
+
+===On the sender side: Double payment risk for hardware wallets===
+
+For a successful payjoin to happen, the sender needs to sign two transactions double spending each other: The original transaction and the payjoin proposal.
+
+The sender's software wallet can verify that the payjoin proposal is legitimate by the sender's checklist.
+
+However, a hardware wallet can't verify that this is indeed the case. This means that the security guarantee of the hardware wallet is decreased. If the sender's software is compromised, the hardware wallet would sign two valid transactions, thus sending two payments.
+
+Without payjoin, the maximum amount of money that could be lost by a compromised software is equal to one payment (via [[#output-substitution|payment output substitution]]).
+Note that the sender can disallow [[#output-substitution|payment output substitution]] by using the optional parameter disableoutputsubstitution=true.
+
+With payjoin, the maximum amount of money that can be lost is equal to two payments.
+
+==Reference sender's implementation==
+
+Here is pseudo code of a sender implementation.
+RequestPayjoin takes the BIP21 URI of the payment, the wallet and the signedPSBT.
+
+The signedPSBT represents a PSBT which has been fully signed, but not yet finalized.
+We then prepare originalPSBT from the signedPSBT via the CreateOriginalPSBT function and get back the proposal.
+
+While we verify the proposal, we also import into it information about our own inputs and outputs from the signedPSBT.
+At the end of this RequestPayjoin, the proposal is verified and ready to be signed.
+
+We logged the different PSBT involved, and show the result in our [[#test-vectors|test vectors]].
+
+public async Task RequestPayjoin(
+ BIP21Uri bip21,
+ Wallet wallet,
+ PSBT signedPSBT,
+ PayjoinClientParameters optionalParameters)
+{
+ Log("Unfinalized signed PSBT" + signedPSBT);
+ // Extracting the pj link.
+ var endpoint = bip21.ExtractPayjointEndpoint();
+ if (signedPSBT.IsAllFinalized())
+ throw new InvalidOperationException("The original PSBT should not be finalized.");
+ ScriptPubKeyType inputScriptType = wallet.ScriptPubKeyType();
+ PSBTOutput feePSBTOutput = null;
+
+ bool allowOutputSubstitution = !optionalParameters.DisableOutputSubstitution;
+ if (bip21.Parameters.Contains("pjos") && bip21.Parameters["pjos"] == "0")
+ allowOutputSubstitution = false;
+
+ if (optionalParameters.AdditionalFeeOutputIndex != null && optionalParameters.MaxAdditionalFeeContribution != null)
+ feePSBTOutput = signedPSBT.Outputs[optionalParameters.AdditionalFeeOutputIndex];
+ Script paymentScriptPubKey = bip21.Address == null ? null : bip21.Address.ScriptPubKey;
+ decimal originalFee = signedPSBT.GetFee();
+ PSBT originalPSBT = CreateOriginalPSBT(signedPSBT);
+ Transaction originalGlobalTx = signedPSBT.GetGlobalTransaction();
+ TxOut feeOutput = feePSBTOutput == null ? null : originalGlobalTx.Outputs[feePSBTOutput.Index];
+ var originalInputs = new Queue<(TxIn OriginalTxIn, PSBTInput SignedPSBTInput)>();
+ for (int i = 0; i < originalGlobalTx.Inputs.Count; i++)
+ {
+ originalInputs.Enqueue((originalGlobalTx.Inputs[i], signedPSBT.Inputs[i]));
+ }
+ var originalOutputs = new Queue<(TxOut OriginalTxOut, PSBTOutput SignedPSBTOutput)>();
+ for (int i = 0; i < originalGlobalTx.Outputs.Count; i++)
+ {
+ originalOutputs.Enqueue((originalGlobalTx.Outputs[i], signedPSBT.Outputs[i]));
+ }
+ // Add the client side query string parameters
+ endpoint = ApplyOptionalParameters(endpoint, optionalParameters);
+ Log("original PSBT" + originalPSBT);
+ PSBT proposal = await SendOriginalTransaction(endpoint, originalPSBT, cancellationToken);
+ Log("payjoin proposal" + proposal);
+ // Checking that the PSBT of the receiver is clean
+ if (proposal.GlobalXPubs.Any())
+ {
+ throw new PayjoinSenderException("GlobalXPubs should not be included in the receiver's PSBT");
+ }
+ ////////////
+
+ if (proposal.CheckSanity() is List errors && errors.Count > 0)
+ throw new PayjoinSenderException($"The proposal PSBT is not sane ({errors[0]})");
+
+ var proposalGlobalTx = proposal.GetGlobalTransaction();
+ // Verify that the transaction version, and nLockTime are unchanged.
+ if (proposalGlobalTx.Version != originalGlobalTx.Version)
+ throw new PayjoinSenderException($"The proposal PSBT changed the transaction version");
+ if (proposalGlobalTx.LockTime != originalGlobalTx.LockTime)
+ throw new PayjoinSenderException($"The proposal PSBT changed the nLocktime");
+
+ HashSet sequences = new HashSet();
+ // For each inputs in the proposal:
+ foreach (PSBTInput proposedPSBTInput in proposal.Inputs)
+ {
+ if (proposedPSBTInput.HDKeyPaths.Count != 0)
+ throw new PayjoinSenderException("The receiver added keypaths to an input");
+ if (proposedPSBTInput.PartialSigs.Count != 0)
+ throw new PayjoinSenderException("The receiver added partial signatures to an input");
+ PSBTInput proposedTxIn = proposalGlobalTx.Inputs.FindIndexedInput(proposedPSBTInput.PrevOut).TxIn;
+ bool isOurInput = originalInputs.Count > 0 && originalInputs.Peek().OriginalTxIn.PrevOut == proposedPSBTInput.PrevOut;
+ // If it is one of our input
+ if (isOurInput)
+ {
+ OutPoint inputPrevout = ourPrevouts.Dequeue();
+ TxIn originalTxin = originalGlobalTx.Inputs.FromOutpoint(inputPrevout);
+ PSBTInput originalPSBTInput = originalPSBT.Inputs.FromOutpoint(inputPrevout);
+ // Verify that sequence is unchanged.
+ if (input.OriginalTxIn.Sequence != proposedTxIn.Sequence)
+ throw new PayjoinSenderException("The proposedTxIn modified the sequence of one of our inputs")
+ // Verify the PSBT input is not finalized
+ if (proposedPSBTInput.IsFinalized())
+ throw new PayjoinSenderException("The receiver finalized one of our inputs");
+ // Verify that non_witness_utxo and witness_utxo are not specified.
+ if (proposedPSBTInput.NonWitnessUtxo != null || proposedPSBTInput.WitnessUtxo != null)
+ throw new PayjoinSenderException("The receiver added non_witness_utxo or witness_utxo to one of our inputs");
+ sequences.Add(proposedTxIn.Sequence);
+
+ // Fill up the info from the original PSBT input so we can sign and get fees.
+ proposedPSBTInput.NonWitnessUtxo = input.SignedPSBTInput.NonWitnessUtxo;
+ proposedPSBTInput.WitnessUtxo = input.SignedPSBTInput.WitnessUtxo;
+ // We fill up information we had on the signed PSBT, so we can sign it.
+ foreach (var hdKey in input.SignedPSBTInput.HDKeyPaths)
+ proposedPSBTInput.HDKeyPaths.Add(hdKey.Key, hdKey.Value);
+ proposedPSBTInput.RedeemScript = signedPSBTInput.RedeemScript;
+ proposedPSBTInput.RedeemScript = input.SignedPSBTInput.RedeemScript;
+ }
+ else
+ {
+ // Verify the PSBT input is finalized
+ if (!proposedPSBTInput.IsFinalized())
+ throw new PayjoinSenderException("The receiver did not finalized one of their input");
+ // Verify that non_witness_utxo or witness_utxo are filled in.
+ if (proposedPSBTInput.NonWitnessUtxo == null && proposedPSBTInput.WitnessUtxo == null)
+ throw new PayjoinSenderException("The receiver did not specify non_witness_utxo or witness_utxo for one of their inputs");
+ sequences.Add(proposedTxIn.Sequence);
+ // Verify that the payjoin proposal did not introduced mixed inputs' type.
+ if (inputScriptType != proposedPSBTInput.GetInputScriptPubKeyType())
+ throw new PayjoinSenderException("Mixed input type detected in the proposal");
+ }
+ }
+
+ // Verify that all of sender's inputs from the original PSBT are in the proposal.
+ if (originalInputs.Count != 0)
+ throw new PayjoinSenderException("Some of our inputs are not included in the proposal");
+
+ // Verify that the payjoin proposal did not introduced mixed inputs' sequence.
+ if (sequences.Count != 1)
+ throw new PayjoinSenderException("Mixed sequence detected in the proposal");
+
+ decimal newFee = proposal.GetFee();
+ decimal additionalFee = newFee - originalFee;
+ if (additionalFee < 0)
+ throw new PayjoinSenderException("The receiver decreased absolute fee");
+ // For each outputs in the proposal:
+ foreach (PSBTOutput proposedPSBTOutput in proposal.Outputs)
+ {
+ // Verify that no keypaths is in the PSBT output
+ if (proposedPSBTOutput.HDKeyPaths.Count != 0)
+ throw new PayjoinSenderException("The receiver added keypaths to an output");
+ if (originalOutputs.Count == 0)
+ continue;
+ var originalOutput = originalOutputs.Peek();
+ bool isOriginalOutput = originalOutput.OriginalTxOut.ScriptPubKey == proposedPSBTOutput.ScriptPubKey;
+ bool substitutedOutput = !isOriginalOutput &&
+ allowOutputSubstitution &&
+ originalOutput.OriginalTxOut.ScriptPubKey == paymentScriptPubKey;
+ if (isOriginalOutput || substitutedOutput)
+ {
+ originalOutputs.Dequeue();
+ if (output.OriginalTxOut == feeOutput)
+ {
+ var actualContribution = feeOutput.Value - proposedPSBTOutput.Value;
+ // The amount that was subtracted from the output's value is less than or equal to maxadditionalfeecontribution
+ if (actualContribution > optionalParameters.MaxAdditionalFeeContribution)
+ throw new PayjoinSenderException("The actual contribution is more than maxadditionalfeecontribution");
+ // Make sure the actual contribution is only paying fee
+ if (actualContribution > additionalFee)
+ throw new PayjoinSenderException("The actual contribution is not only paying fee");
+ // Make sure the actual contribution is only paying for fee incurred by additional inputs
+ int additionalInputsCount = proposalGlobalTx.Inputs.Count - originalGlobalTx.Inputs.Count;
+ if (actualContribution > originalFeeRate * GetVirtualSize(inputScriptType) * additionalInputsCount)
+ throw new PayjoinSenderException("The actual contribution is not only paying for additional inputs");
+ }
+ else if (allowOutputSubstitution && output.OriginalTxOut.ScriptPubKey == paymentScriptPubKey)
+ {
+ // That's the payment output, the receiver may have changed it.
+ }
+ else
+ {
+ if (originalOutput.OriginalTxOut.Value > proposedPSBTOutput.Value)
+ throw new PayjoinSenderException("The receiver decreased the value of one of the outputs");
+ }
+ // We fill up information we had on the signed PSBT, so we can sign it.
+ foreach (var hdKey in output.SignedPSBTOutput.HDKeyPaths)
+ proposedPSBTOutput.HDKeyPaths.Add(hdKey.Key, hdKey.Value);
+ proposedPSBTOutput.RedeemScript = output.SignedPSBTOutput.RedeemScript;
+ }
+ }
+ // Verify that all of sender's outputs from the original PSBT are in the proposal.
+ if (originalOutputs.Count != 0)
+ {
+ // The payment output may have been substituted
+ if (!allowOutputSubstitution ||
+ originalOutputs.Count != 1 ||
+ originalOutputs.Dequeue().OriginalTxOut.ScriptPubKey != paymentScriptPubKey)
+ {
+ throw new PayjoinSenderException("Some of our outputs are not included in the proposal");
+ }
+ }
+
+ // After signing this proposal, we should check if minfeerate is respected.
+ Log("payjoin proposal filled with sender's information" + proposal);
+ return proposal;
+}
+
+int GetVirtualSize(ScriptPubKeyType? scriptPubKeyType)
+{
+ switch (scriptPubKeyType)
+ {
+ case ScriptPubKeyType.Legacy:
+ return 148;
+ case ScriptPubKeyType.Segwit:
+ return 68;
+ case ScriptPubKeyType.SegwitP2SH:
+ return 91;
+ default:
+ return 110;
+ }
+}
+
+// Finalize the signedPSBT and remove confidential information
+PSBT CreateOriginalPSBT(PSBT signedPSBT)
+{
+ var original = signedPSBT.Clone();
+ original = original.Finalize();
+ foreach (var input in original.Inputs)
+ {
+ input.HDKeyPaths.Clear();
+ input.PartialSigs.Clear();
+ input.Unknown.Clear();
+ }
+ foreach (var output in original.Outputs)
+ {
+ output.Unknown.Clear();
+ output.HDKeyPaths.Clear();
+ }
+ original.GlobalXPubs.Clear();
+ return original;
+}
+
+
+==Implementations==
+
+* [[https://github.com/BlueWallet/BlueWallet|BlueWallet]] is in the process of implementing the protocol.
+* [[https://github.com/btcpayserver/btcpayserver|BTCPay Server]] has implemented sender and receiver side of this protocol.
+* [[https://github.com/zkSNACKs/WalletWasabi/|Wasabi Wallet]] has merged sender's support.
+* [[https://github.com/JoinMarket-Org/joinmarket-clientserver|Join Market]] has implemented sender and receiver side of this protocol.
+* [[https://github.com/bitcoinjs/payjoin-client|JavaScript sender implementation]].
+
+==Backward compatibility==
+
+The receivers advertise payjoin capabilities through [[bip-0021.mediawiki|BIP21's URI Scheme]].
+
+Senders not supporting payjoin will just ignore the pj variable and thus, will proceed to normal payment.
+
+==Special thanks==
+
+Special thanks to Kukks for developing the initial support to BTCPay Server, to junderw, AdamISZ, lukechilds, ncoelho, nopara73, lontivero, yahiheb, SomberNight, andrewkozlik, instagibbs, RHavar for all the feedback we received since our first implementation.
+Thanks again to RHavar who wrote the [[bip-0079.mediawiki|BIP79 Bustapay]] proposal, this gave a good starting point for our proposal.
diff --git a/bip-0079.mediawiki b/bip-0079.mediawiki
new file mode 100644
index 0000000000..0c31c1c82a
--- /dev/null
+++ b/bip-0079.mediawiki
@@ -0,0 +1,125 @@
+
+
+
+==Abstract==
+
+The way bitcoin transactions are normally created leaks more information than desirable, and as a result has been exploited by unreasonably effective blockchain analysis techniques to jeopardize important properties that are expected of a useful currency.
+
+Bustapay is a simple and practical protocol for the sender and receiver of a payment to collaboratively sign a bitcoin transaction in such a way that busts some analysis assumptions to the immediate benefit of the sender and receiver. Furthermore it does so in such a way that gives a significant amount of control to the receiver to help manage their utxo set size, a constant problem for bitcoin merchants.
+
+==Copyright==
+
+This document is licensed under the Creative Commons CC0 1.0 Universal license.
+
+==Motivation==
+
+One of the most powerful blockchain analysis heuristics has been to assume all inputs of a transaction are controlled by a single party unless otherwise known (such as by the distinctive structure of a traditional coinjoin, or multisig spends that are validated onchain). Combined with other techniques (notably change-output guessing) this has lead to unexpectedly accurate tracking that has exposed bitcoin participants to unacceptable personal, business and financial risks -- undermining bitcoin's utility and fungibility -- and ultimately jeopardizing its ability to function as useful money.
+
+We however can bust these assumptions with a sender-receiver coinjoin. To prevent costless spy/DoS attacks, we require the sending party to provide a fully-valid ready-to-propagate transaction to initiate the process, that the receiver can broadcast if the sender never completes the coinjoin thus tying the cost to that of spending a utxo. Most promisingly, bustapay transactions do not have an identifiable structure so any network analysis will be not able to tell if a given transaction is a bustapay transaction or not which erodes the confidence of their entire models, providing positive externalities for the entire bitcoin ecosystem.
+
+Bustapay transactions also do not grow the receiver's count of unspent transaction outputs, and in fact gives the receiver an opportunity to better manage their utxo set, something normally only done when sending payments. Large utxo sets are often problematic and expensive, and frequently requiring privacy-destroying consolidation. Besides busting clustering assumptions, bustapay also provides a layer of obfuscation of send amounts.
+
+It is worth noting that this specification has eschewed complexity and potentially useful extensions on the assumption that simplicity is of the most important to encourage adoption.
+
+
+==Overview==
+
+A bustapay payment is made from a sender to a receiver.
+
+====Step 1. Sender creates a bitcoin transaction paying the receiver====
+
+This transaction must use segwit for all inputs, and be fully valid and signed. The transaction must be eligible for propagation on the network (but not done so at this stage)
+
+====Step 2. Sender gives the "template transaction" to the receiver====
+
+This is done via an HTTP POST request, sent to a "bustapay url"
+
+====Step 3. Receiver processes the transaction and returns a partially signed coinjoin====
+
+The receiver validates the transaction, and pays himself. The receiver then adds one or more of his own inputs (known as the ''contributed inputs'') and (optionally) increases the output that pays himself (generally by the sum of the ''contributed inputs''). Doing so creates a ''partial transaction'', which the receiver returns to the sender. It is called such as it requires the sender to re-sign his own inputs.
+
+====Step 4. Sender validates, re-signs, and propagates on the bitcoin network====
+
+The sender MUST validate the ''partial transaction'' was changed correctly and non-maliciously (to allow using potentially untrusted communication channels), re-sign its original inputs and propagate the final transaction over the bitcoin network.
+
+====Step 5. Receiver observes the finalized transaction on the bitcoin network====
+
+Once the receiver has seen the finalized transactions on the network (and has enough confirmations) it can process it like a normal payment for the sent amount (as opposed to the amount that it looks like on the network). If the receiver does not see the finalized transaction after a timeout, they will propagate the original "template transaction", which ensures the payment happens and functions a strong anti-DoS mechanism.
+
+== Specification ==
+
+The standard way of letting a sender know where to send a bustapay transaction is done via a bip21 encoded address. The key value "bpu" (short for "BustaPayUrl") should be used. An example of such address would be bitcoin:2NABbUr9yeRCp1oUCtVmgJF8HGRCo3ifpTT?bpu=https://bp.bustabit.com/submit It is highly encouraged that urls are kept short.
+
+When the sender is creating a "template transaction" it is done almost identically to creating a normal send, with the exception that *only* segwit inputs may be used. The sender is also encouraged to use a slightly more aggressive feerate than usual as well as BIP125 (Opt-in Full Replace-by-Fee Signaling), but neither is strictly required.
+
+The template transaction should be sent to the receiver via an HTTP POST to the bustapay url, with a binary encoded body.
+
+The receiver is then responsible for validating the template transaction. If there is a problem with the transaction, or the receiver is generally unhappy with the transaction (e.g. fees are too small) the HTTP response code of 422 should be used and a human-readable string containing information on why which can be directly given to the user.
+
+Should the receiver reject a transaction, it should not attempt to propagate it on the network. However it is important for the sender to be aware that the receiver *could* at any time (regardless of which error was given) send this transaction. The client should therefore assume the receiver will, and act accordingly (either retry with adjustments or just propagate the transaction). It is imperative that the sender never finds themselves in a situation where two payments to the sender could be valid.
+
+=== Contributed Input Choice ===
+
+The receiver must add at least one input to the transaction (the "contributed inputs"). If the receiver has no inputs, it should use a 500 internal server error, so the client can send the transaction as per normal (or try again later). Its generally advised to only add a single contributed input, however they are circumstances where adding more than a single input can be useful.
+
+To prevent an attack where a receiver is continually sent variations of the same transaction to enumerate the receivers utxo set, it is essential that the receiver always returns the same contributed inputs when it's seen the same inputs.
+
+It is strongly preferable that the receiver makes an effort to pick a contributed input of the same type as the other transaction inputs if possible.
+
+=== Output Adjustment ===
+
+After adding inputs to the transaction, the receiver generally will want to adjust the output that pays himself by increasing it by the sum of the contributed input amounts (minus any fees he wants to contribute). However the only strict requirement is that the receiver *must never* remove inputs, and *must not* ever decrease any output amount.
+
+=== Returning the partial transaction ===
+
+The receiver must sign all contributed inputs in the partial transaction. The partial transaction should also remove all witnesses from the original template transaction as they are no longer valid, and need to be recalculated by the sender. The receiver returns the partial transaction as a binary-encoded HTTP response with a status code of 200. To ensure compatibility with web-wallets and browser-based-tools, all responses (including errors) must contain the HTTP header "Access-Control-Allow-Origin: *"
+
+
+=== Sender Validation ===
+
+The sender *must* do important validation on the partial transaction. They *must* verify:
+
+* All template transaction inputs are in the partial transaction (but perhaps different order) and have the same sequence numbers.
+* The partial transaction contains at least one new (and signed) segwit input (owned by the receiver)
+* All outputs from the template transaction exist in the partial transaction, except they are allowed to be reordered and have their amounts increased (but *never* decreased)
+
+=== Creating Final Transaction ===
+
+After validating the partial transaction, the sender signs all its inputs to create what is now the final transaction. It is important that the sender is careful to not be tricked by the receiver into signing other inputs it owns. The sender must only sign inputs that existed in the template transaction. If the sender is not careful the receiver may "contribute" inputs that are actually owned with by the sender, with the hope the sender blindly signs everything.
+
+
+=== Transaction Publishing ===
+
+Once the final transaction is created, the sender should publish it directly onto the bitcoin network. If the sender does not do this after a reasonable time (e.g. 1 minute), the receiver should publish the template transaction as an important anti-spy/anti-DoS tactic . The sender may also choose to publish the template transaction instead of the final transaction if they believe the receiver to have unreasonably lowered the feerate of the transaction (i.e. increased the size of the transaction, but not the feerate enough). And both parties can consider publishing the template transaction even after the finalized transaction is on the network (taking advantage of replace-by-fee) if the final transaction is not confirming and the template transaction has more fees.
+
+
+=== Implementation Notes ===
+For anyone wanting to implement bustapay payments, here are some notes for receivers:
+
+* A transaction can easily be checked if it's suitable for the mempool with testmempoolaccept in bitcoin core 0.17+
+* Tracking transactions by txid is precarious. To keep your sanity make sure all inputs are segwit. But remember segwit does not prevent txid malleability unless you validate the transaction. So really make sure you're using testmempoolaccept at the very least
+* Bustapay could be abused by a malicious party to query if you own a deposit address or not. So never accept a bustapay transaction that pays an already used deposit address
+* You will need to keep a mapping of which utxos people have showed you and which you revealed. So if you see them again, you can reveal the same one of your own
+* Check if the transaction was already sorted according to BIP69, if so ensure the result stays that way. Otherwise probably just shuffle the inputs/outputs
+* A reference implementation is maintained at https://github.com/rhavar/bustapay which functions as a wrapper around some RPC calls to bitcoin core's wallet.
+* The sender must be careful of an attack where the receiver tries to add additional inputs that are controlled by the sender, with the hope that the sender blindly signs it.
+
+== Backwards Compatibility ==
+
+Bustapay is an optional payment protocol and therefore has no backwards compatibility concerns. It in fact can only be supported in addition to normal transaction processing, as falling back to a normal bitcoin transaction is a required behavior.
+
+
+== Credits ==
+The idea is obviously based upon Dr. Maxwell's seminal CoinJoin proposal, and reduced scope inspired by a simplification of the "pay 2 endpoint" blog post by blockstream.
diff --git a/bip-0080.mediawiki b/bip-0080.mediawiki
new file mode 100644
index 0000000000..f367c71a70
--- /dev/null
+++ b/bip-0080.mediawiki
@@ -0,0 +1,78 @@
+
+ BIP: 80
+ Title: Hierarchy for Non-Colored Voting Pool Deterministic Multisig Wallets
+ Author: Justus Ranvier
+ Jimmy Song
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0080
+ Status: Deferred
+ Type: Informational
+ Created: 2014-08-11
+ License: PD
+
+
+==Abstract==
+
+This BIP defines a logical hierarchy for non-colored voting pool deterministic multisig wallets based on an algorithm described in BIP-0032 (BIP32 from now on) and purpose scheme described in BIP-0043 (BIP43 from now on).
+
+This BIP is a particular application of BIP43 and is based on BIP44.
+
+==Motivation==
+
+The hierarchy proposed in this paper allows the handling of multiple coins and multiple series from a single seed.
+
+==Path levels==
+
+We define the following 4 levels in BIP32 path:
+
+
+
+Apostrophe in the path indicates that BIP32 hardened derivation is used.
+
+Each level has a special meaning, described in the chapters below.
+
+===Purpose===
+
+Purpose is a constant set following the BIP43 recommendation to: the ASCII value of "80" with the most significant bit set to indicate hardened derivation (0x80000050). It indicates that the subtree of this node is used according to this specification.
+
+Hardened derivation is used at this level.
+
+===Coin type===
+
+One master node (seed) can be used for unlimited number of independent cryptocoins such as Bitcoin, Litecoin or Namecoin. However, sharing the same space for various cryptocoins has some disadvantages.
+
+This level creates a separate subtree for every cryptocoin, avoiding reusing addresses across cryptocoins and improving privacy issues.
+
+Coin type is a constant, set for each cryptocoin. The list of registered coin type constants should be obtained from BIP44.
+
+Hardened derivation is used at this level.
+
+===Series===
+
+Series are used by voting pools in order to implement FIFO cold storage. By directing deposits into multiple series, the private keys for most of the deposits can be kept offline, and a limited portion can be brought online to process withdrawals.
+
+Hardened derivation is used at this level.
+
+===Index===
+
+Public/private keypairs are numbered from index 0 in sequentially increasing manner. This number is used as child index in BIP32 derivation.
+
+Public keys obtained at this level of the hierarchy are used to construct multisig deposit scripts, using a schema that is shared between the members as an out-of-band contract.
+
+Public derivation is used at this level.
+
+==Compatible wallets==
+
+* [[https://github.com/btcsuite/btcwallet|btcwallet]] is the reference Bitcoin wallet for voting pools.
+
+==Copyright==
+
+This document is placed in the public domain.
+
+==Reference==
+
+* [[bip-0032.mediawiki|BIP32 - Hierarchical Deterministic Wallets]]
+* [[bip-0043.mediawiki|BIP43 - Purpose Field for Deterministic Wallets]]
+* [[bip-0044.mediawiki|BIP44 - Multi-Account Hierarchy for Deterministic Wallets]]
diff --git a/bip-0081.mediawiki b/bip-0081.mediawiki
new file mode 100644
index 0000000000..923917c550
--- /dev/null
+++ b/bip-0081.mediawiki
@@ -0,0 +1,75 @@
+
+ BIP: 81
+ Title: Hierarchy for Colored Voting Pool Deterministic Multisig Wallets
+ Author: Justus Ranvier
+ Jimmy Song
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0081
+ Status: Deferred
+ Type: Informational
+ Created: 2014-08-11
+ License: PD
+
+
+==Abstract==
+
+This BIP defines a logical hierarchy for colored coin voting pool deterministic multisig wallets based on an algorithm described in BIP-0032 (BIP32 from now on) and purpose scheme described in BIP-0043 (BIP43 from now on).
+
+This BIP is a particular application of BIP43 and is based on BIP44.
+
+==Motivation==
+
+The hierarchy proposed in this paper allows the handling of multiple color definitions from a single seed.
+
+==Path levels==
+
+We define the following 8 levels in BIP32 path:
+
+
+
+Apostrophe in the path indicates that BIP32 hardened derivation is used.
+
+Each level has a special meaning, described in the chapters below.
+
+===Purpose===
+
+Purpose is a constant set following the BIP43 recommendation to: the ASCII value of "81" with the most significant bit set to indicate hardened derivation (0x80000051). It indicates that the subtree of this node is used according to this specification.
+
+Hardened derivation is used at this level.
+
+===Color Definition===
+
+Index values which can be applied to a BIP32 node are limited to 4 bytes (32 bits).
+
+Since this is not sufficient to identify color definitions without a risk of collision, multiple levels are used.
+
+Color definitions are first shortened to 20 bytes using the Bitcoin hash160 function.
+
+The resulting 20 bytes are split into five groups in little endian format, and where each group is used as the seed for the five levels of color definition levels
+
+Public derivation is used at these levels, even when the index exceeds 2^31.
+
+===Index===
+
+Public/private keypairs are numbered from index 0 in sequentially increasing manner. This number is used as child index in BIP32 derivation.
+
+Public keys obtained at this level of the hierarchy are used to construct multisig deposit scripts, using a schema that is shared between the members as an out-of-band contract.
+
+Public derivation is used at this level.
+
+==Compatible wallets==
+
+* [[https://github.com/btcsuite/btcwallet|btcwallet]] is the reference Bitcoin wallet for voting pools.
+
+==Copyright==
+
+This document is placed in the public domain.
+
+==Reference==
+
+* [[bip-0032.mediawiki|BIP32 - Hierarchical Deterministic Wallets]]
+* [[bip-0043.mediawiki|BIP43 - Purpose Field for Deterministic Wallets]]
+* [[bip-0044.mediawiki|BIP44 - Multi-Account Hierarchy for Deterministic Wallets]]
+* [[bip-0080.mediawiki|BIP80 - Hierarchy for Non-Colored Voting Pool Deterministic Multisig Wallets]]
diff --git a/bip-0083.mediawiki b/bip-0083.mediawiki
new file mode 100644
index 0000000000..8c6f4443f7
--- /dev/null
+++ b/bip-0083.mediawiki
@@ -0,0 +1,96 @@
+
+
+==Abstract==
+
+This BIP defines a scheme for key derivation that allows for dynamic creation of key hierarchies based on the algorithm described in BIP32.
+
+==Motivation==
+
+Several proposals have been made to try to standardize a structure for hierarchical deterministic wallets for the sake of interoperability (reference BIP32, BIP44, BIP45). However, all proposals to date have tried to impose a specific structure upfront without providing any flexibility for dynamic creation of new hierarchical levels with different semantics or mapping between different applications that use distinct structures.
+
+Instead of attempting to impose a specific structure upfront, this BIP proposes that we design the derivation in such a way that we can continue extending hierarchies arbitrarily and indefinitely.
+
+==Specification==
+
+BIP32 provides a hierarchical derivation scheme where every node in the tree can be either used to derive child nodes or used as a signing key for ECDSA. This means that as soon as we choose to use a node as a signing key, we can no longer derive children from that node. To draw an analogy to file systems, each node is either a file or a directory but never both. However, given the need to predictably know the location of new children, it is generally not a good idea to mix both signing keys and parent nodes at the same level in the hierarchy. This means that as soon as we've decided that a particular level in the hierarchy is to be used for signing keys, we've lost the ability to nest deeper levels into the tree.
+
+At every level of the hierarchy, we reserve the child with index 0 to allow further nesting, and for signing key parent nodes use child indices 1 to MAX_INDEX (231 - 1) for signing keys. We can use either hardened or nonhardened derivation.
+
+Let p denote a specific signing key parent node and k be an index greater than 0. The children signing keys are then:
+
+p / k
+
+with k > 0.
+
+To create sublevels, we derive the nested nodes:
+
+p / 0 / n
+
+with n ≥ 0.
+
+Each of these nodes can now contain signing key children of their own, and again we reserve index 0 to allow deeper nesting.
+
+==Notation==
+
+We propose the following shorthand for writing nested node derivations:
+
+p // n instead of p / 0 / n
+
+p //' n instead of p / 0' / n
+
+==Mappings==
+
+Rather than specifying upfront which path is to be used for a specific purpose (i.e. external invoicing vs. internal change), different applications can specify arbitrary parent nodes and derivation paths. This allows for nesting of sublevels to arbitrary depth with application-specified semantics. Rather than trying to specify use cases upfront, we leave the design completely open-ended. Different applications can exchange these mappings for interoperability. Eventually, if certain mappings become popular, application user interfaces can provide convenient shortcuts or use them as defaults.
+
+Note that BIP32 suggests reserving child 0 for the derivation of signing keys rather than sublevels. It is not really necessary to reserve signing key parents, however, as each key's parent's path can be explicitly stated. But unless we reserve a child for sublevel derivation, we lose the ability to nest deeper levels into the hierarchy. While we could reserve any arbitrary index for nesting sublevels, reserving child 0 seems simplest to implement, leaving all indices > 0 for contiguously indexed signing keys. We could also use MAX_INDEX (231 - 1) for this purpose. However, we believe doing so introduces more idiosyncrasies into the semantics and will present a problem if we ever decide to extend the scheme to use indices larger than 31 bits.
+
+==Use Cases==
+
+===Account Hierarchies===
+
+For all that follows, we assume that key indices k > 0 and parent node indices n ≥ 0.
+
+From a master seed m, we can construct a default account using the following derivations for nonhardened signing keys:
+
+m / 1 / k (for change/internal outputs)
+
+m / 2 / k (for invoice/external outputs)
+
+To create subaccount an, we use:
+
+an = m // n
+
+To generate keys for subaccount an, we use:
+
+an / 1 / k (for change/internal outputs)
+
+an / 2 / k (for invoice/external outputs)
+
+We can continue creating subaccounts indefinitely using this scheme.
+
+===Bidirectional Payment Channels===
+
+In order to create a bidirectional payment channel, it is necessary that previous commitments be revokable. In order to revoke previous commitments, each party reveals a secret to the other that would allow them to steal the funds in the channel if a transaction for a previous commitment is inserted into the blockchain.
+
+By allowing for arbitrary nesting of sublevels, we can construct decision trees of arbitrary depth and revoke an entire branch by revealing a parent node used to derive all the children.
+
+==References==
+
+* [[bip-0032.mediawiki|BIP32 - Hierarchical Deterministic Wallets]]
+* [[https://lightning.network/lightning-network-paper.pdf|Lightning Network Whitepaper]]
+
+==Copyright==
+
+This document is placed in the public domain.
+
diff --git a/bip-0084.mediawiki b/bip-0084.mediawiki
new file mode 100644
index 0000000000..93fe64bb82
--- /dev/null
+++ b/bip-0084.mediawiki
@@ -0,0 +1,100 @@
+
+ BIP: 84
+ Layer: Applications
+ Title: Derivation scheme for P2WPKH based accounts
+ Author: Pavol Rusnak
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0084
+ Status: Final
+ Type: Standards Track
+ Created: 2017-12-28
+ License: CC0-1.0
+
+
+==Abstract==
+
+This BIP defines the derivation scheme for HD wallets using the P2WPKH ([[bip-0173.mediawiki|BIP 173]]) serialization format for segregated witness transactions.
+
+==Motivation==
+
+With the usage of P2WPKH transactions it is necessary to have a common derivation scheme.
+It allows the user to use different HD wallets with the same masterseed and/or a single account seamlessly.
+
+Thus the user needs to create dedicated segregated witness accounts, which ensures that only wallets compatible with this BIP will detect the accounts and handle them appropriately.
+
+===Considerations===
+
+We use the same rationale as described in Considerations section of [[bip-0049.mediawiki|BIP 49]].
+
+==Specifications==
+
+This BIP defines the two needed steps to derive multiple deterministic addresses based on a [[bip-0032.mediawiki|BIP 32]] root account.
+
+===Public key derivation===
+
+To derive a public key from the root account, this BIP uses the same account-structure as defined in [[bip-0044.mediawiki|BIP 44]] and [[bip-0049.mediawiki|BIP 49]], but only uses a different purpose value to indicate the different transaction serialization method.
+
+
+
+For the purpose-path level it uses 84'. The rest of the levels are used as defined in BIP44 or BIP49.
+
+
+===Address derivation===
+
+To derive the P2WPKH address from the above calculated public key, we use the encapsulation defined in [[bip-0141.mediawiki#p2wpkh|BIP 141]]:
+
+
+ witness:
+ scriptSig: (empty)
+ scriptPubKey: 0 <20-byte-key-hash>
+ (0x0014{20-byte-key-hash})
+
+
+===Extended Key Version===
+
+When serializing extended keys, this scheme uses alternate version bytes. Extended public keys use 0x04b24746 to produce a "zpub" prefix, and private keys use 0x04b2430c to produce a "zprv" prefix. Testnet uses 0x045f1cf6 "vpub" and 0x045f18bc "vprv."
+
+Additional registered version bytes are listed in [[https://github.com/satoshilabs/slips/blob/master/slip-0132.md|SLIP-0132]].
+
+
+==Backwards Compatibility==
+
+This BIP is not backwards compatible by design as described under [[#considerations|considerations]]. An incompatible wallet will not discover accounts at all and the user will notice that something is wrong.
+
+==Test vectors==
+
+
+
+==Abstract==
+
+''"One Seed to rule them all,''
+''One Key to find them,''
+''One Path to bring them all,''
+''And in cryptography bind them."''
+
+It is not possible to maintain one single (mnemonic) seed backup for all keychains used across various wallets because there are a variety of incompatible standards. Sharing of seeds across multiple wallets is not desirable for security reasons. Physical storage of multiple seeds is difficult depending on the security and redundancy required.
+
+As HD keychains are essentially derived from initial entropy, this proposal provides a way to derive entropy from the keychain which can be fed into whatever method a wallet uses to derive the initial mnemonic seed or root key.
+
+==Copyright==
+
+This BIP is dual-licensed under the Open Publication License and BSD 2-clause license.
+
+==Definitions==
+
+The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.
+
+The terminology related to keychains used in the wild varies widely, for example `seed` has various different meanings. In this document we define the terms
+
+# '''BIP32 root key''' is the root extended private key that is represented as the top root of the keychain in BIP32.
+# '''BIP39 mnemonic''' is the mnemonic phrase that is calculated from the entropy used before hashing of the mnemonic in BIP39.
+# '''BIP39 seed''' is the result of hashing the BIP39 mnemonic seed.
+
+When in doubt, assume big endian byte serialization, such that the leftmost
+byte is the most significant.
+
+==Motivation==
+
+Most wallets implement BIP32 which defines how a BIP32 root key can be used to derive keychains. As a consequence, a backup of just the BIP32 root key is sufficient to include all keys derived from it. BIP32 does not have a human-friendly serialization of the BIP32 root key (or BIP32 extended keys in general), which makes paper backups or manually restoring the key more error-prone. BIP39 was designed to solve this problem, but rather than serialize the BIP32 root key, it takes some entropy, encoded to a "seed mnemonic", which is then hashed to derive the BIP39 seed, which can be turned into the BIP32 root key. Saving the BIP39 mnemonic is enough to reconstruct the entire BIP32 keychain, but a BIP32 root key cannot be reversed back to the BIP39 mnemonic.
+
+Most wallets implement BIP39, so on initialization or restoration, the user must interact with a BIP39 mnemonic. Most wallets do not support BIP32 extended private keys, so each wallet must either share the same BIP39 mnemonic, or have a separate BIP39 mnemonic entirely. Neither scenario is particularly satisfactory for security reasons. For example, some wallets may be inherently less secure, like hot wallets on smartphones, JoinMarket servers, or Lightning Network nodes. Having multiple seeds is far from desirable, especially for those who rely on split key or redundancy backups in different geological locations. Adding keys is necessarily difficult and may result in users being more lazy with subsequent keys, resulting in compromised security or loss of keys.
+
+There is an added complication with wallets that implement other standards, or no standards at all. The Bitcoin Core wallet uses a WIF as the ''hdseed'', and yet other wallets, like Electrum, use different mnemonic schemes to derive the BIP32 root key. Other cryptocurrencies, like Monero, use an entirely different mnemonic scheme.
+
+Ultimately, all of the mnemonic/seed schemes start with some "initial entropy" to derive a mnemonic/seed, and then process the mnemonic into a BIP32 key, or private key. We can use BIP32 itself to derive the "initial entropy" to then recreate the same mnemonic or seed according to the specific application standard of the target wallet. We can use a BIP44-like categorization to ensure uniform derivation according to the target application type.
+
+==Specification==
+
+We assume a single BIP32 master root key. This specification is not concerned with how this was derived (e.g. directly or via a mnemonic scheme such as BIP39).
+
+For each application that requires its own wallet, a unique private key is derived from the BIP32 master root key using a fully hardened derivation path. The resulting private key (k) is then processed with HMAC-SHA512, where the key is "bip-entropy-from-k", and the message payload is the private key k: HMAC-SHA512(key="bip-entropy-from-k", msg=k)
+
+The reason for running the derived key through HMAC-SHA512 and truncating the result as necessary is to prevent leakage of the parent tree should the derived key (''k'') be compromised. While the specification requires the use of hardended key derivation which would prevent this, we cannot enforce hardened derivation, so this method ensures the derived entropy is hardened. Also, from a semantic point of view, since the purpose is to derive entropy and not a private key, we are required to transform the child key. This is done out of an abundance of caution, in order to ward off unwanted side effects should ''k'' be used for a dual purpose, including as a nonce ''hash(k)'', where undesirable and unforeseen interactions could occur.
+.
+The result produces 512 bits of entropy. Each application SHOULD use up to the required number of bits necessary for their operation, and truncate the rest.
+
+The HMAC-SHA512 function is specified in [https://tools.ietf.org/html/rfc4231 RFC 4231].
+
+===Test vectors===
+
+====Test case 1====
+INPUT:
+* MASTER BIP32 ROOT KEY: xprv9s21ZrQH143K2LBWUUQRFXhucrQqBpKdRRxNVq2zBqsx8HVqFk2uYo8kmbaLLHRdqtQpUm98uKfu3vca1LqdGhUtyoFnCNkfmXRyPXLjbKb
+* PATH: m/83696968'/0'/0'
+
+OUTPUT:
+* DERIVED KEY=cca20ccb0e9a90feb0912870c3323b24874b0ca3d8018c4b96d0b97c0e82ded0
+* DERIVED ENTROPY=efecfbccffea313214232d29e71563d941229afb4338c21f9517c41aaa0d16f00b83d2a09ef747e7a64e8e2bd5a14869e693da66ce94ac2da570ab7ee48618f7
+
+====Test case 2====
+INPUT:
+* MASTER BIP32 ROOT KEY: xprv9s21ZrQH143K2LBWUUQRFXhucrQqBpKdRRxNVq2zBqsx8HVqFk2uYo8kmbaLLHRdqtQpUm98uKfu3vca1LqdGhUtyoFnCNkfmXRyPXLjbKb
+*PATH: m/83696968'/0'/1'
+
+OUTPUT
+* DERIVED KEY=503776919131758bb7de7beb6c0ae24894f4ec042c26032890c29359216e21ba
+* DERIVED ENTROPY=70c6e3e8ebee8dc4c0dbba66076819bb8c09672527c4277ca8729532ad711872218f826919f6b67218adde99018a6df9095ab2b58d803b5b93ec9802085a690e
+
+==BIP85-DRNG==
+
+BIP85-DRNG-SHAKE256 is a deterministic random number generator for cryptographic functions that require deterministic outputs, but where the input to that function requires more than the 64 bytes provided by BIP85's HMAC output. BIP85-DRNG-SHAKE256 uses BIP85 to seed a SHAKE256 stream (from the SHA-3 standard). The input must be exactly 64 bytes long (from the BIP85 HMAC output).
+
+RSA key generation is an example of a function that requires orders of magnitude more than 64 bytes of random input. Further, it is not possible to precalculate the amount of random input required until the function has completed.
+
+ drng_reader = BIP85DRNG.new(bip85_entropy)
+ rsa_key = RSA.generate_key(4096, drng_reader.read)
+
+===Test Vectors===
+INPUT:
+xprv9s21ZrQH143K2LBWUUQRFXhucrQqBpKdRRxNVq2zBqsx8HVqFk2uYo8kmbaLLHRdqtQpUm98uKfu3vca1LqdGhUtyoFnCNkfmXRyPXLjbKb
+* MASTER BIP32 ROOT KEY: m/83696968'/0'/0'
+
+OUTPUT
+* DERIVED KEY=cca20ccb0e9a90feb0912870c3323b24874b0ca3d8018c4b96d0b97c0e82ded0
+* DERIVED ENTROPY=efecfbccffea313214232d29e71563d941229afb4338c21f9517c41aaa0d16f00b83d2a09ef747e7a64e8e2bd5a14869e693da66ce94ac2da570ab7ee48618f7
+
+* DRNG(80 bytes)=b78b1ee6b345eae6836c2d53d33c64cdaf9a696487be81b03e822dc84b3f1cd883d7559e53d175f243e4c349e822a957bbff9224bc5dde9492ef54e8a439f6bc8c7355b87a925a37ee405a7502991111
+
+==Applications==
+
+The Application number defines how entropy will be used post processing. Some basic examples follow:
+
+Derivation paths follow the format m/83696968'/{app_no}'/{index}', where ''{app_no}'' is the path for the application, and ''{index}'' is the index.
+
+Application numbers should be semantic in some way, such as a BIP number or ASCII character code sequence.
+
+===BIP39===
+Application number: 39'
+
+Truncate trailing (least significant) bytes of the entropy to the number of bits required to map to the relevant word length: 128 bits for 12 words, 256 bits for 24 words.
+
+The derivation path format is: m/83696968'/39'/{language}'/{words}'/{index}'
+
+Example: a BIP39 mnemonic with 12 English words (first index) would have the path m/83696968'/39'/0'/12'/0', the next key would be m/83696968'/39'/0'/12'/1' etc.
+
+Language Table
+
+{|
+!Wordlist
+!Code
+|-
+| English
+| 0'
+|-
+| Japanese
+| 1'
+|-
+| Korean
+| 2'
+|-
+| Spanish
+| 3'
+|-
+| Chinese (Simplified)
+| 4'
+|-
+| Chinese (Traditional)
+| 5'
+|-
+| French
+| 6'
+|-
+| Italian
+| 7'
+|-
+| Czech
+| 8'
+|-
+| Portuguese
+| 9'
+|-
+|}
+
+Words Table
+
+{|
+!Words
+!Entropy
+!Code
+|-
+| 12 words
+| 128 bits
+| 12'
+|-
+| 15 words
+| 160 bits
+| 15'
+|-
+| 18 words
+| 192 bits
+| 18'
+|-
+| 21 words
+| 224 bits
+| 21'
+|-
+| 24 words
+| 256 bits
+| 24'
+|}
+
+====12 English words====
+BIP39 English 12 word mnemonic seed
+
+128 bits of entropy as input to BIP39 to derive 12 word mnemonic
+
+INPUT:
+* MASTER BIP32 ROOT KEY: xprv9s21ZrQH143K2LBWUUQRFXhucrQqBpKdRRxNVq2zBqsx8HVqFk2uYo8kmbaLLHRdqtQpUm98uKfu3vca1LqdGhUtyoFnCNkfmXRyPXLjbKb
+* PATH: m/83696968'/39'/0'/12'/0'
+
+OUTPUT:
+* DERIVED ENTROPY=6250b68daf746d12a24d58b4787a714b
+* DERIVED BIP39 MNEMONIC=girl mad pet galaxy egg matter matrix prison refuse sense ordinary nose
+
+====18 English words====
+BIP39 English 18 word mnemonic seed
+
+196 bits of entropy as input to BIP39 to derive 18 word mnemonic
+
+INPUT:
+* MASTER BIP32 ROOT KEY: xprv9s21ZrQH143K2LBWUUQRFXhucrQqBpKdRRxNVq2zBqsx8HVqFk2uYo8kmbaLLHRdqtQpUm98uKfu3vca1LqdGhUtyoFnCNkfmXRyPXLjbKb
+* PATH: m/83696968'/39'/0'/18'/0'
+
+OUTPUT:
+* DERIVED ENTROPY=938033ed8b12698449d4bbca3c853c66b293ea1b1ce9d9dc
+* DERIVED BIP39 MNEMONIC=near account window bike charge season chef number sketch tomorrow excuse sniff circle vital hockey outdoor supply token
+
+====24 English words====
+Derives 24 word BIP39 mnemonic seed
+
+256 bits of entropy as input to BIP39 to derive 24 word mnemonic
+
+INPUT:
+* MASTER BIP32 ROOT KEY: xprv9s21ZrQH143K2LBWUUQRFXhucrQqBpKdRRxNVq2zBqsx8HVqFk2uYo8kmbaLLHRdqtQpUm98uKfu3vca1LqdGhUtyoFnCNkfmXRyPXLjbKb
+* PATH: m/83696968'/39'/0'/24'/0'
+
+OUTPUT:
+* DERIVED ENTROPY=ae131e2312cdc61331542efe0d1077bac5ea803adf24b313a4f0e48e9c51f37f
+* DERIVED BIP39 MNEMONIC=puppy ocean match cereal symbol another shed magic wrap hammer bulb intact gadget divorce twin tonight reason outdoor destroy simple truth cigar social volcano
+
+===HD-Seed WIF===
+Application number: 2'
+
+Uses the most significant 256 bits
+There is a very small chance that you'll make an invalid
+key that is zero or larger than the order of the curve. If this occurs, software
+should hard fail (forcing users to iterate to the next index). From BIP32:
+
+In case parse256(IL) ≥ n or ki = 0, the resulting key is invalid, and one should proceed with the next value for i. (Note: this has probability lower than 1 in 2127.)
+
+
+of entropy as the secret exponent to derive a private key and encode as a compressed
+WIF that will be used as the hdseed for Bitcoin Core wallets.
+
+Path format is m/83696968'/2'/{index}'
+
+INPUT:
+* MASTER BIP32 ROOT KEY: xprv9s21ZrQH143K2LBWUUQRFXhucrQqBpKdRRxNVq2zBqsx8HVqFk2uYo8kmbaLLHRdqtQpUm98uKfu3vca1LqdGhUtyoFnCNkfmXRyPXLjbKb
+* PATH: m/83696968'/2'/0'
+
+OUTPUT
+* DERIVED ENTROPY=7040bb53104f27367f317558e78a994ada7296c6fde36a364e5baf206e502bb1
+* DERIVED WIF=Kzyv4uF39d4Jrw2W7UryTHwZr1zQVNk4dAFyqE6BuMrMh1Za7uhp
+
+===XPRV===
+Application number: 32'
+
+Taking 64 bytes of the HMAC digest, the first 32 bytes are the chain code, and the second 32 bytes are the private key for the BIP32 XPRV value. Child number, depth, and parent fingerprint are forced to zero.
+
+''Warning'': The above order reverses the order of BIP32, which takes the first 32 bytes as the private key, and the second 32 bytes as the chain code.
+
+Applications may support Testnet by emitting TPRV keys if and only if the input root key is a Testnet key.
+
+Path format is m/83696968'/32'/{index}'
+
+INPUT:
+* MASTER BIP32 ROOT KEY: xprv9s21ZrQH143K2LBWUUQRFXhucrQqBpKdRRxNVq2zBqsx8HVqFk2uYo8kmbaLLHRdqtQpUm98uKfu3vca1LqdGhUtyoFnCNkfmXRyPXLjbKb
+* PATH: m/83696968'/32'/0'
+
+OUTPUT
+* DERIVED ENTROPY=ead0b33988a616cf6a497f1c169d9e92562604e38305ccd3fc96f2252c177682
+* DERIVED XPRV=xprv9s21ZrQH143K2srSbCSg4m4kLvPMzcWydgmKEnMmoZUurYuBuYG46c6P71UGXMzmriLzCCBvKQWBUv3vPB3m1SATMhp3uEjXHJ42jFg7myX
+
+===HEX===
+Application number: 128169'
+
+The derivation path format is: m/83696968'/128169'/{num_bytes}'/{index}'
+
+`16 <= num_bytes <= 64`
+
+Truncate trailing (least significant) bytes of the entropy after `num_bytes`.
+
+INPUT:
+* MASTER BIP32 ROOT KEY: xprv9s21ZrQH143K2LBWUUQRFXhucrQqBpKdRRxNVq2zBqsx8HVqFk2uYo8kmbaLLHRdqtQpUm98uKfu3vca1LqdGhUtyoFnCNkfmXRyPXLjbKb
+* PATH: m/83696968'/128169'/64'/0'
+
+OUTPUT
+* DERIVED ENTROPY=492db4698cf3b73a5a24998aa3e9d7fa96275d85724a91e71aa2d645442f878555d078fd1f1f67e368976f04137b1f7a0d19232136ca50c44614af72b5582a5c
+
+===PWD BASE64===
+Application number: 707764'
+
+The derivation path format is: m/83696968'/707764'/{pwd_len}'/{index}'
+
+`20 <= pwd_len <= 86`
+
+[https://datatracker.ietf.org/doc/html/rfc4648 Base64] encode all 64 bytes of entropy.
+Remove any spaces or new lines inserted by Base64 encoding process. Slice base64 result string
+on index 0 to `pwd_len`. This slice is the password. As `pwd_len` is limited to 86, passwords will not contain padding.
+
+Entropy calculation:
+R = 64 (base64 - do not count padding)
+L = pwd_len
+Entropy = log2(R ** L)
+
+{| class="wikitable" style="margin:auto"
+! pwd_length !! (cca) entropy
+|-
+| 20 || 120.0
+|-
+| 24 || 144.0
+|-
+| 32 || 192.0
+|-
+| 64 || 384.0
+|-
+| 86 || 516.0
+|}
+
+INPUT:
+* MASTER BIP32 ROOT KEY: xprv9s21ZrQH143K2LBWUUQRFXhucrQqBpKdRRxNVq2zBqsx8HVqFk2uYo8kmbaLLHRdqtQpUm98uKfu3vca1LqdGhUtyoFnCNkfmXRyPXLjbKb
+* PATH: m/83696968'/707764'/21'/0'
+
+OUTPUT
+* DERIVED ENTROPY=74a2e87a9ba0cdd549bdd2f9ea880d554c6c355b08ed25088cfa88f3f1c4f74632b652fd4a8f5fda43074c6f6964a3753b08bb5210c8f5e75c07a4c2a20bf6e9
+* DERIVED PWD=dKLoepugzdVJvdL56ogNV
+
+===PWD BASE85===
+Application number: 707785'
+
+The derivation path format is: m/83696968'/707785'/{pwd_len}'/{index}'
+
+`10 <= pwd_len <= 80`
+
+Base85 encode all 64 bytes of entropy.
+Remove any spaces or new lines inserted by Base64 encoding process. Slice base85 result string
+on index 0 to `pwd_len`. This slice is the password. `pwd_len` is limited to 80 characters.
+
+Entropy calculation:
+R = 85
+L = pwd_len
+Entropy = log2(R ** L)
+
+{| class="wikitable" style="margin:auto"
+! pwd_length !! (cca) entropy
+|-
+| 10 || 64.0
+|-
+| 15 || 96.0
+|-
+| 20 || 128.0
+|-
+| 30 || 192.0
+|-
+| 80 || 512.0
+|}
+
+INPUT:
+* MASTER BIP32 ROOT KEY: xprv9s21ZrQH143K2LBWUUQRFXhucrQqBpKdRRxNVq2zBqsx8HVqFk2uYo8kmbaLLHRdqtQpUm98uKfu3vca1LqdGhUtyoFnCNkfmXRyPXLjbKb
+* PATH: m/83696968'/707785'/12'/0'
+
+OUTPUT
+* DERIVED ENTROPY=f7cfe56f63dca2490f65fcbf9ee63dcd85d18f751b6b5e1c1b8733af6459c904a75e82b4a22efff9b9e69de2144b293aa8714319a054b6cb55826a8e51425209
+* DERIVED PWD=_s`{TW89)i4`
+
+===RSA===
+
+Application number: 828365'
+
+The derivation path format is: m/83696968'/828365'/{key_bits}'/{key_index}'
+
+The RSA key generator should use BIP85-DRNG as the input RNG function.
+
+===RSA GPG===
+
+Keys allocated for RSA-GPG purposes use the following scheme:
+
+ - Main key m/83696968'/828365'/{key_bits}'/{key_index}'
+ - Sub keys: m/83696968'/828365'/{key_bits}'/{key_index}'/{sub_key}'
+
+ - key_index is the parent key for CERTIFY capability
+ - sub_key 0' is used as the ENCRYPTION key
+ - sub_key 1' is used as the AUTHENTICATION key
+ - sub_key 2' is usually used as SIGNATURE key
+
+Note on timestamps:
+
+The resulting RSA key can be used to create a GPG key where the creation date MUST be fixed to unix Epoch timestamp 1231006505 (the Bitcoin genesis block time '2009-01-03 18:05:05' UTC) because the key fingerprint is affected by the creation date (Epoch timestamp 0 was not chosen because of legacy behavior in GNUPG implementations for older keys). Additionally, when importing sub-keys under a key in GNUPG, the system time must be frozen to the same timestamp before importing (e.g. by use of faketime).
+
+Note on GPG key capabilities on smartcard/hardware devices:
+
+GPG capable smart-cards SHOULD be loaded as follows: The encryption slot SHOULD be loaded with the ENCRYPTION capable key; the authentication slot SHOULD be loaded with the AUTHENTICATION capable key. The signature capable slot SHOULD be loaded with the SIGNATURE capable key.
+
+However, depending on available slots on the smart-card, and preferred policy, the CERTIFY capable key MAY be flagged with CERTIFY and SIGNATURE capabilities and loaded into the SIGNATURE capable slot (for example where the smart-card has only three slots and the CERTIFY capability is required on the same card). In this case, the SIGNATURE capable sub-key would be disregarded because the CERTIFY capable key serves a dual purpose.
+
+===DICE===
+
+Application number: 89101'
+
+The derivation path format is: m/83696968'/89101'/{sides}'/{rolls}'/{index}'
+
+ 2 <= sides <= 2^32 - 1
+ 1 <= rolls <= 2^32 - 1
+
+Use this application to generate PIN numbers, numeric secrets, and secrets over custom alphabets.
+For example, applications could generate alphanumeric passwords from a 62-sided die (26 + 26 + 10).
+
+Roll values are zero-indexed, such that an N-sided die produces values in the range
+[0, N-1], inclusive. Applications should separate printed rolls by a comma or similar.
+
+Create a BIP85 DRNG whose seed is the derived entropy.
+
+Calculate the following integers:
+
+ bits_per_roll = ceil(log_2(sides))
+ bytes_per_roll = ceil(bits_per_roll / 8)
+
+Read bytes_per_roll bytes from the DRNG.
+Trim any bits in excess of bits_per_roll (retain the most
+significant bits). The resulting integer represents a single roll or trial.
+If the trial is greater than or equal to the number of sides, skip it and
+move on to the next one. Repeat as needed until all rolls are complete.
+
+INPUT:
+* MASTER BIP32 ROOT KEY: xprv9s21ZrQH143K2LBWUUQRFXhucrQqBpKdRRxNVq2zBqsx8HVqFk2uYo8kmbaLLHRdqtQpUm98uKfu3vca1LqdGhUtyoFnCNkfmXRyPXLjbKb
+* PATH: m/83696968'/89101'/6'/10'/0'
+OUTPUT
+* DERIVED ENTROPY=5e41f8f5d5d9ac09a20b8a5797a3172b28c806aead00d27e36609e2dd116a59176a738804236586f668da8a51b90c708a4226d7f92259c69f64c51124b6f6cd2
+* DERIVED ROLLS=1,0,0,2,0,1,5,5,2,4
+
+==Backwards Compatibility==
+
+This specification is not backwards compatible with any other existing specification.
+
+This specification relies on BIP32 but is agnostic to how the BIP32 root key is derived. As such, this standard is able to derive wallets with initialization schemes like BIP39 or Electrum wallet style mnemonics.
+
+==References==
+
+BIP32, BIP39
+
+==Reference Implementations==
+
+* 1.3.0 Python 3.x library implementation: [https://github.com/akarve/bipsea]
+* 1.1.0 Python 2.x library implementation: [https://github.com/ethankosakovsky/bip85]
+* 1.0.0 JavaScript library implementation: [https://github.com/hoganri/bip85-js]
+
+==Changelog==
+
+===1.3.0 (2024-10-22)===
+
+====Added====
+
+* Dice application 89101'
+* Czech language code to application 39'
+* TPRV guidance for application 32'
+* Warning on application 32' key and chain code ordering
+
+===1.2.0 (2022-12-04)===
+
+====Added====
+
+* Base64 application 707764'
+* Base85 application 707785'
+
+===1.1.0 (2020-11-19)===
+
+====Added====
+
+* BIP85-DRNG-SHAKE256
+* RSA application 828365'
+
+===1.0.0 (2020-06-11)===
+
+* Initial version
+
+==Footnotes==
+
+
+
+==Acknowledgements==
+
+Many thanks to Peter Gray and Christopher Allen for their input, and to Peter for suggesting extra application use cases.
diff --git a/bip-0086.mediawiki b/bip-0086.mediawiki
new file mode 100644
index 0000000000..7bcaf14666
--- /dev/null
+++ b/bip-0086.mediawiki
@@ -0,0 +1,128 @@
+
+ BIP: 86
+ Layer: Applications
+ Title: Key Derivation for Single Key P2TR Outputs
+ Author: Ava Chow
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0086
+ Status: Final
+ Type: Standards Track
+ Created: 2021-06-22
+ License: BSD-2-Clause
+
+
+==Abstract==
+
+This document suggests a derivation scheme for HD wallets whose keys are involved in single key
+P2TR ([[bip-0341.mediawiki|BIP 341]]) outputs as the Taproot internal key.
+
+===Copyright===
+
+This BIP is licensed under the 2-clause BSD license.
+
+==Motivation==
+
+With the usage of single key P2TR transactions, it is useful to have a common derivation scheme so
+that HD wallets that only have a backup of the HD seed can be likely to recover single key Taproot
+outputs. Although there are now solutions which obviate the need for fixed derivation paths for
+specific script types, many software wallets and hardware signers still use seed backups which
+lack derivation path and script information. Thus we largely use the same approach used in BIPs
+[[bip-0049.mediawiki|49]] and [[bip-0084.mediawiki|84]] for ease of implementation.
+
+==Specifications==
+
+This BIP defines the two needed steps to derive multiple deterministic addresses based on a
+[[bip-0032.mediawiki|BIP 32]] master private key.
+
+===Public key derivation===
+
+To derive a public key from the root account, this BIP uses the same account-structure as
+defined in BIPs [[bip-0044.mediawiki|44]], [[bip-0049.mediawiki|49]], and [[bip-0084.mediawiki|84]],
+but with a different purpose value for the script type.
+
+
+
+For the purpose-path level it uses 86'.
+The rest of the levels are used as defined in BIPs 44, 49, and 84.
+
+A key derived with this derivation path pattern will be referred to as derived_key further
+in this document.
+
+===Address derivation===
+
+
+[[bip-0341.mediawiki#cite_ref-22-0|BIP 341]] states: "If the spending conditions do not require a
+script path, the output key should commit to an unspendable script path instead of having no
+script path. This can be achieved by computing the output key point as
+''Q = P + int(hashTapTweak(bytes(P)))G''." Thus:
+
+
+
+==Backwards Compatibility==
+
+This BIP is not backwards compatible by design.
+An incompatible wallet will not discover these accounts at all and the user will notice that
+something is wrong.
+
+However this BIP uses the same method used in BIPs 44, 49, and 84, so it should not be difficult
+to implement.
+
+==Test vectors==
+
+
+
+==Abstract==
+
+This BIP defines a sane hierarchy for deterministic multisig wallets based on an algorithm described in BIP-0032 (BIP32 from now on), purpose scheme described in BIP-0043 (BIP43 from now on), and multi-account hierarchy described in BIP-0044 (BIP44 from now on).
+
+This BIP is a particular application of BIP43.
+
+==Copyright==
+
+This BIP is licensed under the 2-clause BSD license.
+
+==Motivation==
+
+With the increase of more user friendly (offline) multisignature wallets, and adoption of new technologies such as [https://github.com/bitcoin/bitcoin/blob/master/doc/descriptors.md the descriptor language] and [https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki BIP-0174 (Partially Signed Bitcoin Transactions)], it is necessary to create a common derivation scheme that makes use of all new technologies.
+
+As background, BIP 44/49/84 specifies:
+
+
+
+where the BIP43 purpose' path is separate for each script (P2PKH, P2WPKH-in-P2SH, and P2WPKH respectively). Having a script-per-derivation for single sig wallets allows for easy backup and restore, with just the private key information.
+
+Multisignature wallets need more information to backup and restore (such as all cosigner public keys), and these per-script derivations are made redundant with descriptors, which provide that information (while also specifying a collection of output scripts).
+A modern standardization is needed for multisig derivation paths. There are some in existence, but all have issues. For example, BIP45 specifies:
+
+
+
+BIP45 unnecessarily demands a single script type (here, P2SH). In addition, BIP45 sets cosigner_index in order to sort the purpose' public keys of each cosigner. This too is redundant, as descriptors can set the order of the public keys with multi or have them sorted lexicographically (as described in [https://github.com/bitcoin/bips/blob/master/bip-0067.mediawiki BIP67]) with sortedmulti. Sorting public keys between cosigners in order to create the full derivation path, prior to sending the key record to the coordinator to create the descriptor, merely adds additional unnecessary communication rounds.
+
+The second multisignature "standard" in use is m/48', which specifies:
+
+
+
+Rather than following in BIP 44/49/84's path and having a separate BIP per script after P2SH (BIP45), vendors decided to insert script_type' into the derivation path (where P2SH-P2WSH=1, P2WSH=2, Future_Script=3, etc). As described previously, this is unnecessary, as the descriptor sets the script. While it attempts to reduce maintenance work by getting rid of new BIPs-per-script, it still requires maintaining an updated, redundant, script_type list.
+
+The structure proposed later in this paper solves these issues and is quite comprehensive. It allows for the handling of multiple accounts, external and internal chains per account, and millions of addresses per chain, in a multi-party, multisignature, hierarchical deterministic wallet regardless of the script type '''Why propose this structure only for multisignature wallets?''' Currently, single-sig wallets are able to restore funds using just the master private key data (in the format of BIP39 usually). Even if the user doesn't recall the derivation used, the wallet implementation can iterate through common schemes (BIP44/49/84). With this proposed hierarchy, the user would either have to now backup additional data (the descriptor), or the wallet would have to attempt all script types for every account level when restoring. Because of this, even though the descriptor language handles the signature type just like it does the script type, it is best to restrict this script-agnostic hierarchy to multisignature wallets only..
+
+This paper was inspired from BIP44.
+
+==Specification==
+
+===Key sorting===
+
+Any wallet that supports descriptors inherently supports deterministic key sorting as per BIP67 (through the sortedmulti function) so that all possible multisignature addresses/scripts are derived from deterministically sorted public keys.
+
+===Path levels===
+
+We should not be mixing keys and scripts in the same layer. The wallet should create extended private/public keys independent of the script type, whereas the descriptor language tells wallets to watch the multisig outputs with the specified public keys.
+
+We define the following 5 levels in the BIP32 path:
+
+
+
+h or ' in the path indicates that BIP32 hardened derivation is used.
+
+Each level has a special meaning, described in the chapters below.
+
+===Purpose===
+
+Purpose is a constant set to 87' following the BIP43 recommendation.
+It indicates that the subtree of this node is used according to this specification.
+
+Hardened derivation is used at this level.
+
+===Coin type===
+
+One master node (seed) can be used for multiple Bitcoin networks.
+Sharing the same space for various networks has some disadvantages.
+
+This level creates a separate subtree for every network, avoiding reusing addresses across networks and improving privacy issues.
+
+Coin type 0 for mainnet and 1 for testnets (testnet, regtest, and signet).
+
+Hardened derivation is used at this level.
+
+===Account===
+
+This level splits the key space into independent user identities, following the BIP44 pattern, so the wallet never mixes the coins across different accounts.
+
+Users can use these accounts to organize the funds in the same fashion as bank accounts; for donation purposes (where all addresses are considered public), for saving purposes, for common expenses, etc.
+
+Accounts are numbered from index 0 in sequentially increasing manner.
+This number is used as child index in BIP32 derivation.
+
+Hardened derivation is used at this level.
+
+It is crucial that this level is increased for each new wallet joined or private/public keys created; for both privacy and cryptographic purposes.
+For example, before sending a new key record to a coordinator, the wallet must increment the account' level.
+This prevents key reuse - across ECDSA and Schnorr signatures, across different script types, and in between the same wallet types.
+
+===Change===
+
+Constant 0 is used for external chain and constant 1 for internal chain (also known as change addresses). External chain is used for addresses that are meant to be visible outside of the wallet (e.g. for receiving payments). Internal chain is used for addresses which are not meant to be visible outside of the wallet and is used for return transaction change.
+
+Public derivation is used at this level.
+
+===Index===
+
+Addresses are numbered from index 0 in sequentially increasing manner.
+This number is used as child index in BIP32 derivation.
+
+Public derivation is used at this level.
+
+==Address Discovery==
+
+The multisig descriptors or descriptor template that is generated from the cosigners' combined key records should be used to generate and discover addresses.
+
+Please see [https://github.com/bitcoin/bips/blob/master/bip-0129.mediawiki BIP-0129 (Bitcoin Secure Multisig Setup)] for an introduction on descriptor templates.
+The descriptor or descriptor template should contain the key origin information for maximum compatibility with BIP-0174.
+
+For example:
+
+The following descriptor template and derivation path restrictions:
+
+wsh(sortedmulti(2,[xfpForA/87'/0'/0']XpubA/**,[xfpForB/87'/0'/0']XpubB/**))
+
+/0/*,/1/*
+
+Expands to the two concrete descriptors:
+
+wsh(sortedmulti(2,[xfpForA/87'/0'/0']XpubA/0/*,[xfpForB/87'/0'/0']XpubB/0/*))
+
+wsh(sortedmulti(2,[xfpForA/87'/0'/0']XpubA/1/*,[xfpForB/87'/0'/0']XpubB/1/*))
+
+To discover addresses, import both the receiving and change descriptors; respect the gap limit described below.
+
+===Address Gap Limit===
+
+Address gap limit is currently set to 20. If the software hits 20 unused addresses in a row, it expects there are no used addresses beyond this point and stops searching the address chain.
+
+Wallet software should warn when the user is trying to exceed the gap limit on an external descriptor by generating multiple unused addresses.
+
+==Backwards Compatibility==
+
+Any script that is supported by descriptors (and the specific wallet implementation) is compatible with this BIP.
+
+As wallets complying with this BIP are descriptor wallets, this therefore necessitates that the cosigners backup their private key information and the descriptor, in order to properly restore at a later time. This shouldn't be a user burden, since (to much user surprise), all cosigner public keys need to be supplied in addition to M seeds in any M of N multisig restore operation. The descriptor provides this information in a standardized format, with key origin information and error detection.
+
+==Rationale==
+
+
+
+==Examples==
+
+{|
+|network
+|account
+|chain
+|address
+|path
+|-
+|mainnet
+|first
+|external
+|first
+|m / 87' / 0' / 0' / 0 / 0
+|-
+|mainnet
+|first
+|external
+|second
+|m / 87' / 0' / 0' / 0 / 1
+|-
+|mainnet
+|first
+|change
+|first
+|m / 87' / 0' / 0' / 1 / 0
+|-
+|mainnet
+|first
+|change
+|second
+|m / 87' / 0' / 0' / 1 / 1
+|-
+|mainnet
+|second
+|external
+|first
+|m / 87' / 0' / 1' / 0 / 0
+|-
+|mainnet
+|second
+|external
+|second
+|m / 87' / 0' / 1' / 0 / 1
+|-
+|testnet
+|first
+|external
+|first
+|m / 87' / 1' / 0' / 0 / 0
+|-
+|testnet
+|first
+|external
+|second
+|m / 87' / 1' / 0' / 0 / 1
+|-
+|testnet
+|first
+|change
+|first
+|m / 87' / 1' / 0' / 1 / 0
+|-
+|testnet
+|first
+|change
+|second
+|m / 87' / 1' / 0' / 1 / 1
+|-
+|testnet
+|second
+|external
+|first
+|m / 87' / 1' / 1' / 0 / 0
+|-
+|testnet
+|second
+|external
+|second
+|m / 87' / 1' / 1' / 0 / 1
+|-
+|testnet
+|second
+|change
+|first
+|m / 87' / 1' / 1' / 1 / 0
+|-
+|testnet
+|second
+|change
+|second
+|m / 87' / 1' / 1' / 1 / 1
+|}
+
+==Reference Implementation==
+
+None at the moment.
+
+==Acknowledgement==
+
+Special thanks to SomberNight, Craig Raw, David Harding, Jochen Hoenicke, Sjors Provoost, and others for their feedback on the specification.
+
+==References==
+
+Original mailing list thread: https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2021-March/018630.html
+
+* [https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki BIP-0032 (Hierarchical Deterministic Wallets)]
+* [https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki BIP-0043 (Purpose Field for Deterministic Wallets)]
+* [https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki BIP-0044 (Multi-Account Hierarchy for Deterministic Wallets)]
+* [https://github.com/bitcoin/bitcoin/blob/master/doc/descriptors.md Output Descriptors]
+* [https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki BIP-0174 (Partially Signed Bitcoin Transaction Format)]
+* [https://github.com/bitcoin/bips/blob/master/bip-0067.mediawiki BIP-0067 (Deterministic Pay-to-script-hash multi-signature addresses through public key sorting)]
+* [https://github.com/bitcoin/bips/blob/master/bip-0129.mediawiki BIP-0129 (Bitcoin Secure Multisig Setup)]
diff --git a/bip-0088.mediawiki b/bip-0088.mediawiki
new file mode 100644
index 0000000000..342357945c
--- /dev/null
+++ b/bip-0088.mediawiki
@@ -0,0 +1,233 @@
+
+
+==Abstract==
+
+This document describes a format for the representation of the templates that specify
+the constraints that can be imposed on BIP32 derivation paths.
+
+The constraints specified by the templates allow to easily discern 'valid' paths,
+that match the constraints, and 'invalid' paths, that exceed the constraints.
+
+==Copyright==
+
+This BIP is licensed under the 2-clause BSD license.
+
+==Motivation==
+
+BIP32 derivation path format is universal, and a number of schemes for derivation were proposed
+in BIP43 and other documents, such as BIPs 44,45,49,84. The flexibility of the format also allowed
+industry participants to implement custom derivation schemes that fit particular purposes,
+but not necessarily useful in general.
+
+Even when existing BIPs for derivation schemes are used, their usage is not uniform across
+the different wallets, in part because software vendors might have different considerations
+and priorities when making decisions about derivation paths. This creates friction for users,
+which might face problems when they try to access their coins using the wallet that derives
+addresses differently than the one they used before.
+
+===Known solutions===
+
+The problem is common enough to warrant the creation of a dedicated website
+([https://walletsrecovery.org/ walletsrecovery.org]) that tracks paths used by different wallets.
+
+At the time of writing, this website has used their own format to succinctly describe multiple
+derivation paths. As far as author knows, it was the only publicly used format to describe
+path templates before introduction of this BIP. The format was not specified anywhere beside
+the main page of the website. It used | to denote alternative derivation indexes
+(example: m/|44'|49'|84'/0'/0') or whole alternative paths (m/44'/0'/0'|m/44'/1'/0').
+
+It was not declared as a template format to use for processing by software, and seems to be
+an ad-hoc format only intended for illustration. In contrast to this ad-hoc format, the format
+described in this BIP is intended for unambiguous parsing by software, and to be easily read by humans
+at the same time. Humans can visually detect the 'templated' parts of the path more easily than the use
+of | in the template could allow. Wider range of paths can be defined in a single template more
+succinctly and unambiguously.
+
+===Intended use and advantages===
+
+Wallet software authors can use the proposed format to describe the derivation paths that
+their software uses. This can improve user experience when switching to different wallet
+software, restoring access to old wallets, etc.
+
+Unrestricted derivation path usage might be unsafe in certain contexts. In particular, when "change"
+outputs of a transaction are sent to the addresses derived via paths unknown to the sender, the sender
+might lose access to the whole change amount.
+
+A simplistic approach of hard-coding the checks for well-known paths into software and firmware leads
+to reduced interoperability. Vendors cannot choose custom paths that are appropriate for
+their particular, non-general-purpose applications, and are forced to shoehorn their solutions
+into using well-known paths, or convince other vendors to support their custom paths. This approach
+scales poorly.
+
+A flexible approach proposed in this document is to define a standard notation for "BIP32 path templates"
+that succinctly describes the constraints to impose on the derivation path.
+
+Wide support for these path templates will increase interoperability and flexibility of solutions,
+and will allow vendors and individual developers to easily define their own custom restrictions.
+This way, they will be able to deal with the risks of accidental or malicious use of unrestricted
+derivation paths in a more flexible and precise manner.
+
+Well-known path templates can be pre-configured by default on devices and applications,
+but users can have an option to turn off the templates that are not relevant to their uses.
+
+Having a standardized format for custom path templates will enable a common approach to be developed
+in the enforcement of application-specific path restrictions in devices and applications.
+One example of such an approach might be for devices to allow application-specific profiles
+with path templates and possibly other custom parameters. Care must be taken to prevent the accidental
+installation of malicious or incorrect profiles, though.
+
+==Specification==
+
+The format for the template was chosen to make it easy to read, convenient and visually unambiguous.
+
+Template starts with optional prefix m/, and then one or more sections delimited by the slash character (/).
+
+Implementations MAY limit the maximum number of sections.
+
+Each section consists of ''index template'', optionally followed by the hardened marker: either an apostrophe (') or letter h.
+
+Index template can be:
+
+* An integer value from 0 to 2147483647 ("Unit index template")
+* A single * character, which denotes any value from 0 to 2147483647 ("Wildcard index template")
+* The { character, followed by a number of ''index ranges'' delimited by commas (,), followed by } character ("Ranged index template")
+
+Implementations MAY limit the maximum number of index ranges within the Ranged index template.
+
+If an index template is immediately followed by hardened marker, this means that all values specified in this index template is to be increased by 2147483648 for the purposes of matching.
+
+Index range can be:
+
+* An integer value from 0 to 2147483647 ("Unit range")
+* An integer value from 0 to 2147483647, followed by the - character, followed by another integer value from 0 to 2147483647 ("Non-unit range")
+
+For Non-unit range, value on the left side of the - character is the range_start, and the value on the right side of the - character is the range_end.
+
+For Unit range, we say that range_start is equal to range_end, even though there is no start/end in the Unit range.
+
+Unit index template contains a single index range, which is the Unit range
+
+Wildcard index template contains a single index range, and we say that its range_start is set to 0 and its range_end is set to 2147483647
+
+Constraints:
+
+# To avoid ambiguity, whitespace MUST NOT appear within the path template.
+# Commas within the Ranged index template MUST only appear in between index ranges.
+# To avoid ambiguity, an index range that matches a single value MUST be specified as Unit range.
+# To avoid ambiguity, an index range 0-2147483647 is not allowed, and MUST be specified as Wildcard index template instead
+# For Non-unit range, range_end MUST be larger than range_start.
+# If there is more than one index range within the Ranged index template, range_start of the second and any subsequent range MUST be larger than the range_end of the preceding range.
+# To avoid ambiguity, all representations of integer values larger than 0 MUST NOT start with character 0 (no leading zeroes allowed).
+# If hardened marker appears within any section in the path template, all preceding sections MUST also specify hardened matching.
+# To avoid ambiguity, if a hardened marker appears within any section in the path template, all preceding sections MUST also use the same hardened marker (either h or ').
+# To avoid ambiguity, trailing slashes (for example, 1/2/) and duplicate slashes (for example, 0//1) MUST NOT appear in the template.
+
+It may be desirable to have fully unambiguous encoding, where for each valid path template string, there is no other valid template string that matches the exact same set of paths. This would enable someone to compare templates for equality through a simple string equality check, without any parsing.
+
+To achieve this, two extra rules are needed:
+
+* Within Ranged index template, subsequent range MUST NOT start with the value that is equal to the end of the previous range plus one. Thus, {1,2,3-5} is not allowed, and should be specified as {1-5} instead. This rule might make templates less convenient for frequent edits, though.
+
+* Only one type of hardened marker should be allowed (either h or ').
+
+Instead of requiring the second extra rule, implementations can simply replace one type of marker with another in the template strings before comparing them.
+
+==Full and partial templates==
+
+If the template starts with m/, that means that this is the "full" template, that matches the whole path.
+
+If the template does not start with m/, that means that this is a "partial" template, and it can be used to match a part of the path, in the contexts where this might be appropriate (for example, when constraints for the suffix of the path might be dynamic, while constraints for the prefix of the path are fixed).
+
+Full template can be combined with partial template, where partial template extends full template,
+resulting in new, longer full template.
+
+Partial template can be combined with another partial template, resulting in new, longer partial template.
+
+Full template can not be combined with another full template.
+
+Implementations MUST support parsing full templates and matching paths against full templates.
+
+Implementations MAY support parsing partial templates and matching portions of the paths against partial templates, as well as combining the templates.
+
+==Parsing result==
+
+The result of successful parsing of a valid path template can be represented by a list of sections, where each section is a list of index ranges, where index range is a tuple of (range_start, range_end). The length of the list of sections is also referred to as the "length of the template".
+
+==Matching==
+
+The matching is to be performed against a list of integer values that represent a BIP32 path (or a portion of BIP32 path, for partial templates). The length of this list is referred to as the "length of the path".
+
+Non-hardened indexes in this list should be represented by values from 0 to 2147483647.
+
+Hardened indexes in this list should be represented by values from 2147483648 to 4294967295.
+
+The matching algorithm:
+
+ 1. If the length of the path differs from the length of the template, fail
+ 2. For each value V at position N in the path:
+ If for all index ranges within the section at position N in the template,
+ value V is either less than range_start, or greater than range_end, fail
+ 3. Otherwise, succeed
+
+==Formal specification==
+
+The finite state machine (FSM) for the parser of the described template format,
+and the matching formula are specified in TLA+ specification language at https://github.com/dgpv/bip32_template_parse_tplaplus_spec
+
+The specification can be used with TLC checker and accompanying script to generate test data for the implementations.
+
+==Implementations==
+
+While the formal specification specifies an FSM, which would be convenient for implementation without access to rich string handling facilities, when such facilities are available, the implementation might use the whole-string deconstruction approach where the templates are first split into sections, then sections are split into index templates, and then each index template are parsed individually.
+
+A FSM-based approach can be made close to the formal specification, though, and the test data generated with TLC checker would give much better coverage for a FSM based implementation. If the template string contains several errors, an implementation that uses deconstruction approach might detect some of these errors earlier than FSM-based implementation, and vise versa.
+
+At the moment, three implementations exist:
+
+* FSM implementation in C: https://github.com/dgpv/bip32_template_c_implementation
+* FSM implementation in Python (micropython compatible): https://github.com/dgpv/bip32_template_python_implementation
+* non-FSM implementation in python: BIP32PathTemplate class in bitcointx.core.key module of python-bitcointx library (https://github.com/Simplexum/python-bitcointx)
+
+==Compatibility==
+
+The full path template that only contains Unit index templates represents a fully valid BIP32 path.
+
+There's no other path template standards that is known to the author currently.
+
+There is a discussion on path templating for bitcoin script descriptors at https://github.com/bitcoin/bitcoin/issues/17190, which proposes the format xpub...{0,1}/*, of which the {0,1}/* part would correspond to the partial path template in the format of this BIP.
+
+==Examples==
+
+m/{44,49,84}'/0'/0'/{0-1}/{0-50000} specifies a full template that matches both external and internal chains of BIP44, BIP49 and BIP84 paths, with a constraint that the address index cannot be larger than 50000
+
+Its representation after parsing can be (using Python syntax, ignoring full/partial distinction):
+ [[(2147483692, 2147483692), (2147483697, 2147483697), (2147483732, 2147483732)),
+ [(2147483648, 2147483648)],
+ [(2147483648, 2147483648)],
+ [(0, 1)],
+ [(0, 50000)]]
+
+{0-2,33,123}/* specifies a partial template that matches non-hardened values 0, 1, 2, 33, 123 as first index, and any non-hardened value at second index
+
+Its representation after parsing can be:
+ [[(0, 2), (33, 33), (123, 123)], [(0, 2147483647)]]
+
+*h/0 specifies a partial template that matches any hardened index followed by non-hardened index 0
+
+Its representation after parsing can be:
+ [[(2147483648, 4294967295)], [(0, 0)]]
+
+==Acknowledgements==
+
+Special thanks to Peter D. Gray, Dr. Maxim Orlovsky, Robert Spigler and others for their feedback on the specification, and to Janine (github:@Enegnei) for the help in preparing the draft.
diff --git a/bip-0090.mediawiki b/bip-0090.mediawiki
new file mode 100644
index 0000000000..48d415194b
--- /dev/null
+++ b/bip-0090.mediawiki
@@ -0,0 +1,99 @@
+
+ BIP: 90
+ Title: Buried Deployments
+ Author: Suhas Daftuar
+ Comments-Summary: Mostly Recommended for implementation, with some Discouragement
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0090
+ Status: Final
+ Type: Informational
+ Created: 2016-11-08
+ License: PD
+
+
+
+==Abstract==
+
+Prior soft forks (BIP 34, BIP 65, and BIP 66) were activated via miner signaling in block version numbers. Now that the chain has long since passed the blocks at which those consensus rules have triggered, we can (as a simplification) replace the trigger mechanism by caching the block heights at which those consensus rules became enforced.
+
+==Motivation==
+
+BIPs 34, 65 and 66 were deployed on mainnet using miner signaling using block version numbers. In short, new consensus rules were proposed for use in blocks with a higher version number (N+1) than the prevailing block version (N) in use on the network, and those rules became enforced under the following conditions:
+# 75% rule: If 750 of the prior 1000 blocks are version N+1 or higher, then blocks with version N+1 or higher must correctly enforce the new consensus rule.
+# 95% rule: If 950 of the prior 1000 blocks are version N+1 or higher, then blocks with version less than N+1 are invalid.
+
+Please see those [[#References|BIPs]] for more details.
+
+Note that this trigger mechanism is dependent on the chain history. To validate a block, we must test whether the trigger was met by looking at the previous 1000 blocks in the chain before it, which can be inefficient.
+
+In addition, this mechanism for code deployments have been deprecated in favor of BIP 9 deployments, which offer several advantages (please see [https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki BIP 9]).
+
+Thus we propose elimination of the logic implementing these kinds of deployments, by replacing the test which governs enforcement of BIP 34, BIP 65, and BIP 66 with simple height checks, which we choose to be the block height triggering the 95% activation rule on mainnet for each of those deployments. This simplification of the consensus rules would reduce the technical debt associated with deployment of those consensus changes.
+
+==Considerations==
+
+It is technically possible for this to be a non-backwards compatible change. For example, if an alternate chain were created in which BIP 34's 95% activation triggered at a lower height (H') than it did on the current mainnet chain (H), then older software would enforce that version 1 blocks were invalid at heights between H' and H, while newer software implementing this change would not. Similarly, this BIP proposes doing away with the 75% threshold check altogether, which means, for example, that a version 2 block forking off of mainnet at height H-1 which omitted the height in coinbase would be invalid to older software, while accepted by newer software.
+
+However, while newer software and older software might validate old blocks differently, that could only cause a consensus split if there were an extremely large blockchain reorganization onto a chain built off such a block. As of November 2016, the most recent of these changes (BIP 65, enforced since December 2015) has nearly 50,000 blocks built on top of it. The occurrence of such a reorg that would cause the activating block to be disconnected would raise fundamental concerns about the security assumptions of Bitcoin, a far bigger issue than any non-backwards compatible change.
+
+So while this proposal could theoretically result in a consensus split, it is extremely unlikely, and in particular any such circumstances would be sufficiently damaging to the Bitcoin network to dwarf any concerns about the effects of this proposed change.
+
+==Specification==
+
+The BIP 34, 66, and 65 activation heights are set to 227931, 363725, and 388381, respectively.
+
+The 1000-block lookback test, first described in BIP 34, is no longer performed during validation of any blocks. Instead, a new check is added:
+
+ if((block.nVersion < 2 && nHeight >= consensusParams.BIP34Height) ||
+ (block.nVersion < 3 && nHeight >= consensusParams.BIP66Height) ||
+ (block.nVersion < 4 && nHeight >= consensusParams.BIP65Height))
+ return state.Invalid(false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", block.nVersion),
+ strprintf("rejected nVersion=0x%08x block", block.nVersion));
+
+Furthermore, rather than consider the block versions of the prior 1000 blocks to determine whether to enforce BIP 34, BIP 65, or BIP 66 on a given block, we instead just compare the height of the block being validated with the stored activation heights:
+
+ // Enforce rule that the coinbase starts with serialized block height
+ if (nHeight >= consensusParams.BIP34Height)
+ {
+ CScript expect = CScript() << nHeight;
+ if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
+ !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
+ return state.DoS(100, false, REJECT_INVALID, "bad-cb-height", false, "block height mismatch in coinbase");
+ }
+ }
+
+and
+
+ // Start enforcing the DERSIG (BIP66) rule
+ if (pindex->nHeight >= chainparams.GetConsensus().BIP66Height) {
+ flags |= SCRIPT_VERIFY_DERSIG;
+ }
+
+ // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
+ if (pindex->nHeight >= chainparams.GetConsensus().BIP65Height) {
+ flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
+ }
+
+Please see the implementation for additional details.
+
+==Implementation==
+
+https://github.com/bitcoin/bitcoin/pull/8391.
+
+
+==References==
+
+[https://github.com/bitcoin/bips/blob/master/bip-0034.mediawiki BIP34 Block v2, Height in Coinbase]
+
+[https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki BIP66 Strict DER signatures]
+
+[https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki BIP65 OP_CHECKLOCKTIMEVERIFY]
+
+[https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki BIP9 Version bits with timeout and delay]
+
+==Acknowledgements==
+
+Thanks to Nicolas Dorier for drafting an initial version of this BIP, and to Alex Morcos, Matt Corallo, and Greg Maxwell for suggestions and feedback.
+
+==Copyright==
+
+This document is placed in the public domain.
diff --git a/bip-0091.mediawiki b/bip-0091.mediawiki
new file mode 100644
index 0000000000..fa3d199538
--- /dev/null
+++ b/bip-0091.mediawiki
@@ -0,0 +1,117 @@
+
+
+==Abstract==
+
+This document specifies a method to activate the existing BIP9 segwit deployment with a majority hashpower less than 95%.
+
+==Definitions==
+
+"existing segwit deployment" refer to the BIP9 "segwit" deployment using bit 1, between November 15th 2016 and November 15th 2017 to activate BIP141, BIP143 and BIP147.
+
+==Motivation==
+
+Segwit increases the blocksize, fixes transaction malleability, and makes scripting easier to upgrade as well as bringing many other [https://bitcoincore.org/en/2016/01/26/segwit-benefits/ benefits].
+
+This BIP provides a way for a simple majority of miners to coordinate activation of the existing segwit deployment with less than 95% hashpower. For a number of reasons a complete redeployment of segwit is difficult to do until the existing deployment expires. This is due to 0.13.1+ having many segwit related features active already, including all the P2P components, the new network service flag, the witness-tx and block messages, compact blocks v2 and preferential peering. A redeployment of segwit will need to redefine all these things and doing so before expiry would greatly complicate testing.
+
+==Specification==
+
+While this BIP is active, all blocks must set the nVersion header top 3 bits to 001 together with bit field (1<<1) (according to the existing segwit deployment). Blocks that do not signal as required will be rejected.
+
+==Deployment==
+
+This BIP will be deployed by a "version bits" with an 80%(this can be adjusted if desired) 269 block activation threshold and 336 block confirmation window BIP9 with the name "segsignal" and using bit 4.
+
+This BIP will have a start time of midnight June 1st, 2017 (epoch time 1496275200) and timeout on midnight November 15th 2017 (epoch time 1510704000). This BIP will cease to be active when segwit (BIP141) is locked-in, active, or failed
+
+=== Reference implementation ===
+
+
+
+https://github.com/segsignal/bitcoin
+
+==Backwards Compatibility==
+
+This deployment is compatible with the existing "segwit" bit 1 deployment scheduled between midnight November 15th, 2016 and midnight November 15th, 2017. Miners will need to upgrade their nodes to support segsignal otherwise they may build on top of an invalid block. While this bip is active users should either upgrade to segsignal or wait for additional confirmations when accepting payments.
+
+==Rationale==
+
+Historically we have used IsSuperMajority() to activate soft forks such as BIP66 which has a mandatory signalling requirement for miners once activated, this ensures that miners are aware of new rules being enforced. This technique can be leveraged to lower the signalling threshold of a soft fork while it is in the process of being deployed in a backwards compatible way.
+
+By orphaning non-signalling blocks during the BIP9 bit 1 "segwit" deployment, this BIP can cause the existing "segwit" deployment to activate without needing to release a new deployment.
+
+==References==
+
+*[https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2017-March/013714.html Mailing list discussion]
+*[https://github.com/bitcoin/bitcoin/blob/v0.6.0/src/main.cpp#L1281-L1283 P2SH flag day activation]
+*[[bip-0009.mediawiki|BIP9 Version bits with timeout and delay]]
+*[[bip-0016.mediawiki|BIP16 Pay to Script Hash]]
+*[[bip-0141.mediawiki|BIP141 Segregated Witness (Consensus layer)]]
+*[[bip-0143.mediawiki|BIP143 Transaction Signature Verification for Version 0 Witness Program]]
+*[[bip-0147.mediawiki|BIP147 Dealing with dummy stack element malleability]]
+*[[bip-0148.mediawiki|BIP148 Mandatory activation of segwit deployment]]
+*[[bip-0149.mediawiki|BIP149 Segregated Witness (second deployment)]]
+*[https://bitcoincore.org/en/2016/01/26/segwit-benefits/ Segwit benefits]
+
+==Copyright==
+
+This document is dual licensed as BSD 3-clause, and Creative Commons CC0 1.0 Universal.
+
diff --git a/bip-0093.mediawiki b/bip-0093.mediawiki
new file mode 100644
index 0000000000..22a7ba32e9
--- /dev/null
+++ b/bip-0093.mediawiki
@@ -0,0 +1,599 @@
+
+
+==Introduction==
+
+===Abstract===
+
+This document describes a standard for backing up and restoring the master seed of a
+[https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki BIP-0032] hierarchical deterministic wallet, using Shamir's secret sharing.
+It includes an encoding format, a BCH error-correcting checksum, and algorithms for share generation and secret recovery.
+Secret data can be split into up to 31 shares.
+A minimum threshold of shares, which can be between 1 and 9, is needed to recover the secret, whereas without sufficient shares, no information about the secret is recoverable.
+
+===Copyright===
+
+This document is licensed under the 3-clause BSD license.
+
+===Motivation===
+
+BIP-0032 master seed data is the source entropy used to derive all private keys in an HD wallet.
+Safely storing this secret data is the hardest and most important part of self-custody.
+However, there is a tension between security, which demands limiting the number of backups, and resilience, which demands widely replicated backups.
+Encrypting the seed does not change this fundamental tradeoff, since it leaves essentially the same problem of how to back up the encryption key(s).
+
+To allow users freedom to make this tradeoff, we use Shamir's secret sharing, which guarantees that any number of shares less than the threshold leaks no information about the secret.
+This approach allows increasing safety by widely distributing the generated shares, while also providing security against the compromise of one or more shares (as long as fewer than the threshold have been compromised).
+
+[https://github.com/satoshilabs/slips/blob/master/slip-0039.md SLIP-0039] has essentially the same motivations as this standard.
+However, unlike SLIP-0039,
+
+* this standard aims to be simple enough for hand computation
+* we use the bech32 alphabet rather than a word list, resulting in fixed-length compact encodings
+* we do not support multi-level secret sharing (splitting of shares), although it is technically possible and may be added in a future BIP
+* because of the need to support hand computation, we '''do not''' support passphrases or key hardening
+
+Users who demand a higher level of security for particular secrets, or have a general distrust in digital electronic devices, have the option of using hand computation to backup and restore secret data in an interoperable manner.
+In particular, all computations can be done with simple lookup tables.
+'''It is therefore possible to compute and verify checksums, and to split and recover seeds, entirely using pen and paper.'''
+For long-lived rarely-used seeds, the ability to hand-verify checksums has a significant benefit even for users who do not care to do any other part of this process by hand.
+It means that they can verify the integrity (against non-malicious tampering) of their shares regularly, say, on an annual basis, without needing to continually expose secret data to new hardware.
+
+The ability to compute properties by hand comes from our choice of a small field and our use of linear error correcting codes.
+It does not come with any reduction in security, as long as users use high-quality randomness.
+Note that hand computation is optional, the particular details of hand computation are outside the scope of this standard, and implementers do not need to be concerned with this possibility.
+
+[https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki BIP-0039] serves the same purpose as this standard: encoding master seeds for storage by users.
+However, BIP-0039 has no error-correcting ability, cannot sensibly be extended to support secret sharing, has no support for versioning or other metadata, and has many technical design decisions that make implementation and interoperability difficult (for example, the use of SHA-512 to derive seeds, or the use of 11-bit words).
+
+==Specification==
+
+===codex32===
+
+A codex32 string is similar to a bech32 string defined in [https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki BIP-0173].
+It reuses the base-32 character set from BIP-0173, and consists of:
+
+* A human-readable part, which is the string "ms" (or "MS").
+* A separator, which is always "1".
+* A data part which is in turn subdivided into:
+** A threshold parameter, which MUST be a single digit between "2" and "9", or the digit "0".
+*** If the threshold parameter is "0" then the share index, defined below, MUST have a value of "s" (or "S").
+** An identifier consisting of 4 bech32 characters.
+** A share index, which is any bech32 character. Note that a share index value of "s" (or "S") is special and denotes the unshared secret (see section "Unshared Secret").
+** A payload which is a sequence of up to 74 bech32 characters. (However, see '''Long codex32 Strings''' below for an exception to this limit.)
+** A checksum which consists of 13 bech32 characters as described below.
+
+As with bech32 strings, a codex32 string MUST be entirely uppercase or entirely lowercase.
+For presentation, lowercase is usually preferable, but uppercase SHOULD be used for handwritten codex32 strings.
+If a codex32 string is encoded in a QR code, it SHOULD use the uppercase form, as this is encoded more compactly.
+
+===Checksum===
+
+The last thirteen characters of the data part form a checksum and contain no information.
+Valid strings MUST pass the criteria for validity specified by the Python 3 code snippet below.
+The function ms32_verify_checksum must return true when its argument is the data part as a list of integers representing the characters converted using the bech32 character table from BIP-0173.
+
+To construct a valid checksum given the data-part characters (excluding the checksum), the ms32_create_checksum function can be used.
+
+
+
+===Error Correction===
+
+A codex32 string without a valid checksum MUST NOT be used.
+The checksum is designed to be an error correcting code that can correct up to 4 character substitutions, up to 8 unreadable characters (called erasures), or up to 13 consecutive erasures.
+Implementations SHOULD provide the user with a corrected valid codex32 string if possible.
+However, implementations SHOULD NOT automatically proceed with a corrected codex32 string without user confirmation of the corrected string, either by prompting the user, or returning a corrected string in an error message and allowing the user to repeat their action.
+We do not specify how an implementation should implement error correction. However, we recommend that:
+
+* Implementations make suggestions to substitute non-bech32 characters with bech32 characters in some situations, such as replacing "B" with "8", "O" with "0", "I" with "l", etc.
+* Implementations interpret "?" as an erasure.
+* Implementations optionally interpret other non-bech32 characters, or characters with incorrect case, as erasures.
+* If a string with 8 or fewer erasures can have those erasures filled in to make a valid codex32 string, then the implementation suggests such a string as a correction.
+* If a string consisting of valid bech32 characters in the proper case can be made valid by substituting 4 or fewer characters, then the implementation suggests such a string as a correction.
+
+===Unshared Secret===
+
+When the share index of a valid codex32 string (converted to lowercase) is the letter "s", we call the string a codex32 secret.
+The payload in a codex32 secret is a direct encoding of a BIP-0032 HD master seed.
+
+The master seed is decoded by converting the payload to bytes:
+
+* Translate the characters to 5 bits values using the bech32 character table from BIP-0173, most significant bit first.
+* Re-arrange those bits into groups of 8 bits. Any incomplete group at the end MUST be 4 bits or less, and is discarded.
+
+Note that unlike the decoding process in BIP-0173, we do NOT require that the incomplete group be all zeros.
+
+For an unshared secret, the threshold parameter (the first character of the data part) is ignored (beyond the fact it must be a digit for the codex32 string to be valid).
+We recommend using the digit "0" for the threshold parameter in this case.
+The 4 character identifier also has no effect beyond aiding users in distinguishing between multiple different master seeds in cases where they have more than one.
+
+===Recovering Master Seed===
+
+When the share index of a valid codex32 string (converted to lowercase) is not the letter "s", we call the string an codex32 share.
+The first character of the data part indicates the threshold of the share, and it is required to be a non-"0" digit.
+
+In order to recover a master seed, one needs a set of valid codex32 shares such that:
+
+* All shares have the same threshold value, the same identifier, and the same length.
+* All of the share index values are distinct.
+* The number of codex32 shares is exactly equal to the (common) threshold value.
+
+If all the above conditions are satisfied, the ms32_recover function will return a codex32 secret when its argument is the list of codex32 shares with each share represented as a list of integers representing the characters converted using the bech32 character table from BIP-0173.
+
+
+
+===Generating Shares===
+
+If we already have ''t'' valid codex32 strings such that:
+
+* All strings have the same threshold value ''t'', the same identifier, and the same length
+* All of the share index values are distinct
+
+Then we can derive additional shares with the ms32_interpolate function by passing it a list of exactly ''t'' of these codex32 strings, together with a fresh share index distinct from all of the existing share indexes.
+The newly derived share will have the provided share index.
+
+Once a user has generated ''n'' codex32 shares, they may discard the codex32 secret (if it exists).
+The ''n'' shares form a ''t'' of ''n'' Shamir's secret sharing scheme of a codex32 secret.
+
+There are two ways to create an initial set of ''t'' valid codex32 strings, depending on whether the user already has an existing master seed to split.
+
+====For a fresh master seed====
+
+In the case that the user wishes to generate a fresh master seed, the user generates random initial shares, as follows:
+
+# Choose a bitsize, between 128 and 512, which must be a multiple of 8.
+# Choose a threshold value ''t'' between 2 and 9, inclusive
+# Choose a 4 bech32 character identifier
+#* We do not define how to choose the identifier, beyond noting that it SHOULD be distinct for every master seed the user may need to disambiguate.
+# ''t'' many times, generate a random share by:
+## Take the next available letter from the bech32 alphabet, in alphabetical order, as a, c, d, ..., to be the share index
+## Set the first nine characters to be the prefix ms1, the threshold value ''t'', the 4-character identifier, and then the share index
+## Choose the next ceil(''bitlength / 5'') characters uniformly at random
+## Generate a valid checksum in accordance with the Checksum section, and append this to the resulting shares
+
+The result will be ''t'' distinct shares, all with the same initial 8 characters, and a distinct share index as the 9th character.
+
+With this set of ''t'' codex32 shares, new shares can be derived as discussed above. This process generates a fresh master seed, whose value can be retrieved by running the recovery process on any ''t'' of these shares.
+
+====For an existing master seed====
+
+Before generating shares for an existing master seed, it first must be converted into a codex32 secret, as described above.
+The conversion process consists of:
+
+# Choose a threshold value ''t'' between 2 and 9, inclusive
+# Choose a 4 bech32 character identifier
+#* We do not define how to choose the identifier, beyond noting that it SHOULD be distinct for every master seed the user may need to disambiguate.
+# Set the share index to s
+# Set the payload to a bech32 encoding of the master seed, padded with arbitrary bits
+# Generating a valid checksum in accordance with the Checksum section
+
+Along with the codex32 secret, the user must generate ''t''-1 other codex32 shares, each with the same threshold value, the same identifier, and a distinct share index.
+These shares should be generated as described in the "fresh master seed" section.
+
+The codex32 secret and the ''t''-1 codex32 shares form a set of ''t'' valid codex32 strings from which additional shares can be derived as described above.
+
+===Long codex32 Strings===
+
+The 13 character checksum design only supports up to 80 data characters.
+Excluding the threshold, identifier and index characters, this limits the payload to 74 characters or 46 bytes.
+While this is enough to support the 32-byte advised size of BIP-0032 master seeds, BIP-0032 allows seeds to be up to 64 bytes in size.
+We define a long codex32 string format to support these longer seeds by defining an alternative checksum.
+
+
+
+A long codex32 string follows the same specification as a regular codex32 string with the following changes.
+
+* The payload is a sequence of between 75 and 103 bech32 characters.
+* The checksum consists of 15 bech32 characters as defined above.
+
+A codex32 string with a data part of 94 or 95 characters is never legal as a regular codex32 string is limited to 93 data characters and a long codex32 string is at least 96 characters.
+
+Generation of long shares and recovery of the master seed from long shares proceeds in exactly the same way as for regular shares with the ms32_interpolate function.
+
+The long checksum is designed to be an error correcting code that can correct up to 4 character substitutions, up to 8 unreadable characters (called erasures), or up to 15 consecutive erasures.
+As with regular checksums we do not specify how an implementation should implement error correction, and all our recommendations for error correction of regular codex32 strings also apply to long codex32 strings.
+
+==Rationale==
+
+This scheme is based on the observation that the Lagrange interpolation of valid codewords in a BCH code will always be a valid codeword.
+This means that derived shares will always have valid checksum, and a sufficient threshold of shares with valid checksums will derive a secret with a valid checksum.
+
+The header system is also compatible with Lagrange interpolation, meaning all derived shares will have the same identifier and will have the appropriate share index.
+This fact allows the header data to be covered by the checksum.
+
+The checksum size and identifier size have been chosen so that the encoding of 128-bit seeds and shares fit within 48 characters.
+This is a standard size for many common seed storage formats, which has been popularized by the 12 four-letter word format of the BIP-0039 mnemonic.
+
+The 13 character checksum is adequate to correct 4 errors in up to 93 characters (80 characters of data and 13 characters of the checksum).
+We can correct up to 8 erasures (errors with known locations), and up to 13 consecutive errors (burst errors).
+Beyond that, our code is guaranteed to detect up to 8 errors.
+More generally, any number of random errors will be detected with overwhelming (1 - 2^65) probability. However, the checksum does not protect against maliciously constructed errors.
+These parameters are slightly better than those of the checksum used in SLIP-0039.
+
+For 256-bit seeds and shares our strings are 74 characters, which fits into the 96 character format of the 24 four-letter word format of the BIP-0039 mnemonic, with plenty of room to spare.
+
+A longer checksum is needed to support up to 512-bit seeds, the longest seed length specified in BIP-0032, as the 13 character checksum isn't adequate for more than 80 data characters.
+While we could use the 15 character checksum for both cases, we prefer to keep the strings as short as possible for the more common cases of 128-bit and 256-bit master seeds.
+We only guarantee to correct 4 characters no matter how long the string is.
+Longer strings mean more chances for transcription errors, so shorter strings are better.
+
+The longest data part using the regular 13 character checksum is 93 characters and corresponds to a 400-bit secret.
+At this length, the prefix MS1 is not covered by the checksum.
+This is acceptable because the checksum scheme itself requires you to know that the MS1 prefix is being used in the first place.
+If the prefix is damaged and a user is guessing that the data might be using this scheme, then the user can enter the available data explicitly using the suspected MS1 prefix.
+
+===Not BIP-0039 Entropy===
+
+Instead of encoding a BIP-0032 master seed, an alternative would be to encode BIP-0039 entropy.
+However this alternative approach is fraught with difficulties.
+
+On approach would be to encode the BIP-0039 entropy along with the BIP-0039 checksum data.
+This data can directly be recovered from the BIP-0039 mnemonic, and the process can be reversed if one knows the target language.
+However, for a 128-bit seed, there is a 4 bit checksum yielding 132 bits of data that needs to be encoded.
+This exceeds the 130-bits of room that we have for storing 128 bit seeds.
+We would have to compromise on the 48 character size, or the size of the headers, or the size of the checksum in order to add room for an additional character of data.
+
+This approach would also eliminate our short cut generation of a fresh master secret from generating random shares.
+One would be required to first generate BIP-0039 entropy, and then add a BIP-0039 checksum, before adding a Codex32 checksum and then generate other shares.
+In particular, this process could no longer be performed by hand since it is effectively impossible to hand compute a BIP-0039 checksum.
+
+An alternative approach is to discard the BIP-0039 checksum, since it is inadequate for error correction anyways, and rely on the Codex32 checksum.
+However, this approach ends up eliminating the benefits of BIP-0039 compatibility.
+While it is now possible to hand generate fresh shares, it is impossible to recover compatible BIP-0039 words by hand because, again, the BIP-0039 checksum is not hand computable.
+The only way of generating the compatible BIP-0039 mnemonic is to use wallet software.
+But if the wallet software is need to support this approach to decoding entropy, we may as well bypass all of the overhead of BIP-0039 and directly encode the entropy of a BIP-0032 master seed, which is what we do in our Codex32 proposal.
+
+Beyond the problems above, BIP-0039 does not define a single transformation from entropy to BIP-0032 master seed.
+Instead every different language has it own word list (or word lists) and each choice of word list yields a different transformation from entropy to master seed.
+We would need to encode the choice of word list in our share's meta-data, which takes up even more room, and is difficult to specify due to the ever-evolving choice of word lists.
+
+Alternatively we could standardize on the choice of the English word list, something that is nearly a de facto standard, and simply be incompatible with BIP-0039 wallets of other languages.
+Such a choice also risks users of BIP-0039 recovering their entropy from their language, encoding it in Codex32 and then failing to recover their wallet because the English word lists has replaced their language's word list.
+
+The main advantage of this alternative approach would be that wallets could give users an option switch between backing up their entropy as a BIP-0039 mnemonic and in Codex32 format, but again, only if their language choice happens to be the English word list.
+In practice, we do not expect users in switch back and forth between backup formats, and instead just generate a fresh master seed using Codex32.
+
+Seeing little value with BIP-0039 compatibility (English-only), all the difficulties with BIP-0039 language choice, not to mention the PBKDF2 overhead of using BIP-0039, we think it is best to abandon BIP-0039 and encode BIP-0032 master seeds directly.
+Our approach is semi-convertible with BIP-0039's 512-bit master seeds (in all languages, see Backwards Compatibility) and fully interconvertible with SLIP-39 encoded master seeds or any other encoding of BIP-0032 master seeds.
+
+==Backwards Compatibility==
+
+codex32 is an alternative to BIP-0039 and SLIP-0039.
+It is technically possible to derive the BIP32 master seed from seed words encoded in one of these schemes, and then to encode this seed in codex32.
+For BIP-0039 this process is irreversible, since it involves hashing the original words.
+Furthermore, the resulting seed will be 512 bits long, which may be too large to be safely and conveniently handled.
+
+SLIP-0039 seed words can be reversibly converted to master seeds, so it is possible to interconvert between SLIP-0039 and codex32.
+However, SLIP-0039 '''shares''' cannot be converted to codex32 shares because the two schemes use a different underlying field.
+
+The authors of this BIP do not recommend interconversion.
+Instead, users who wish to switch to codex32 should generate a fresh seed and sweep their coins.
+
+==Reference Implementation==
+
+Our [https://github.com/BlockstreamResearch/codex32 reference implementation repository] contains implementations in Rust and PostScript.
+The inline code in this BIP text can be used as a Python reference.
+
+==Test Vectors==
+
+===Test vector 1===
+
+This example shows the codex32 format, when used without splitting the secret into any shares.
+The payload contains 26 bech32 characters, which corresponds to 130 bits. We truncate the last two bits in order to obtain a 128-bit master seed.
+
+codex32 secret (bech32): ms10testsxxxxxxxxxxxxxxxxxxxxxxxxxx4nzvca9cmczlw
+
+Master secret (hex): 318c6318c6318c6318c6318c6318c631
+
+* human-readable part: ms
+* separator: 1
+* k value: 0 (no secret splitting)
+* identifier: test
+* share index: s (the secret)
+* payload: xxxxxxxxxxxxxxxxxxxxxxxxxx
+* checksum: 4nzvca9cmczlw
+* master node xprv: xprv9s21ZrQH143K3taPNekMd9oV5K6szJ8ND7vVh6fxicRUMDcChr3bFFzuxY8qP3xFFBL6DWc2uEYCfBFZ2nFWbAqKPhtCLRjgv78EZJDEfpL
+
+===Test vector 2===
+
+This example shows generating a new master seed using "random" codex32 shares, as well as deriving an additional codex32 share, using ''k''=2 and an identifier of NAME.
+Although codex32 strings are canonically all lowercase, it's also valid to use all uppercase.
+
+Share with index A: MS12NAMEA320ZYXWVUTSRQPNMLKJHGFEDCAXRPP870HKKQRM
+
+Share with index C: MS12NAMECACDEFGHJKLMNPQRSTUVWXYZ023FTR2GDZMPY6PN
+
+* Derived share with index D: MS12NAMEDLL4F8JLH4E5VDVULDLFXU2JHDNLSM97XVENRXEG
+* Secret share with index S: MS12NAMES6XQGUZTTXKEQNJSJZV4JV3NZ5K3KWGSPHUH6EVW
+* Master secret (hex): d1808e096b35b209ca12132b264662a5
+* master node xprv: xprv9s21ZrQH143K2NkobdHxXeyFDqE44nJYvzLFtsriatJNWMNKznGoGgW5UMTL4fyWtajnMYb5gEc2CgaKhmsKeskoi9eTimpRv2N11THhPTU
+
+Note that per BIP-0173, the lowercase form is used when determining a character's value for checksum purposes.
+In particular, given an all uppercase codex32 string, we still use lowercase ms as the human-readable part during checksum construction.
+
+===Test vector 3===
+
+This example shows splitting an existing 128-bit master seed into "random" codex32 shares, using ''k''=3 and an identifier of cash.
+We appended two zero bits in order to obtain 26 bech32 characters (130 bits of data) from the 128-bit master seed.
+
+Master secret (hex): ffeeddccbbaa99887766554433221100
+
+Secret share with index s: ms13cashsllhdmn9m42vcsamx24zrxgs3qqjzqud4m0d6nln
+
+Share with index a: ms13casha320zyxwvutsrqpnmlkjhgfedca2a8d0zehn8a0t
+
+Share with index c: ms13cashcacdefghjklmnpqrstuvwxyz023949xq35my48dr
+
+* Derived share with index d: ms13cashd0wsedstcdcts64cd7wvy4m90lm28w4ffupqs7rm
+* Derived share with index e: ms13casheekgpemxzshcrmqhaydlp6yhms3ws7320xyxsar9
+* Derived share with index f: ms13cashf8jh6sdrkpyrsp5ut94pj8ktehhw2hfvyrj48704
+* master node xprv: xprv9s21ZrQH143K266qUcrDyYJrSG7KA3A7sE5UHndYRkFzsPQ6xwUhEGK1rNuyyA57Vkc1Ma6a8boVqcKqGNximmAe9L65WsYNcNitKRPnABd
+
+Any three of the five shares among acdef can be used to recover the secret.
+
+Note that the choice to append two zero bits was arbitrary, and any of the following four secret shares would have been valid choices.
+However, each choice would have resulted in a different set of derived shares.
+
+* ms13cashsllhdmn9m42vcsamx24zrxgs3qqjzqud4m0d6nln
+* ms13cashsllhdmn9m42vcsamx24zrxgs3qpte35dvzkjpt0r
+* ms13cashsllhdmn9m42vcsamx24zrxgs3qzfatvdwq5692k6
+* ms13cashsllhdmn9m42vcsamx24zrxgs3qrsx6ydhed97jx2
+
+===Test vector 4===
+
+This example shows converting a 256-bit secret into a codex32 secret, without splitting the secret into any shares.
+We appended four zero bits in order to obtain 52 bech32 characters (260 bits of data) from the 256-bit secret.
+
+256-bit secret (hex): ffeeddccbbaa99887766554433221100ffeeddccbbaa99887766554433221100
+
+* codex32 secret: ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqqtum9pgv99ycma
+* master node xprv: xprv9s21ZrQH143K3s41UCWxXTsU4TRrhkpD1t21QJETan3hjo8DP5LFdFcB5eaFtV8x6Y9aZotQyP8KByUjgLTbXCUjfu2iosTbMv98g8EQoqr
+
+Note that the choice to append four zero bits was arbitrary, and any of the following sixteen codex32 secrets would have been valid:
+
+* ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqqtum9pgv99ycma
+* ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqpj82dp34u6lqtd
+* ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqzsrs4pnh7jmpj5
+* ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqrfcpap2w8dqezy
+* ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqy5tdvphn6znrf0
+* ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyq9dsuypw2ragmel
+* ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqx05xupvgp4v6qx
+* ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyq8k0h5p43c2hzsk
+* ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqgum7hplmjtr8ks
+* ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqf9q0lpxzt5clxq
+* ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyq28y48pyqfuu7le
+* ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqt7ly0paesr8x0f
+* ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqvrvg7pqydv5uyz
+* ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqd6hekpea5n0y5j
+* ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyqwcnrwpmlkmt9dt
+* ms10leetsllhdmn9m42vcsamx24zrxgs3qrl7ahwvhw4fnzrhve25gvezzyq0pgjxpzx0ysaam
+
+===Test vector 5===
+
+This example shows generating a new 512-bit master seed using "random" codex32 characters and appending a checksum.
+The payload contains 103 bech32 characters, which corresponds to 515 bits. The last three bits are discarded when converting to a 512-bit master seed.
+
+This is an example of a '''Long codex32 String'''.
+
+* Secret share with index S: MS100C8VSM32ZXFGUHPCHTLUPZRY9X8GF2TVDW0S3JN54KHCE6MUA7LQPZYGSFJD6AN074RXVCEMLH8WU3TK925ACDEFGHJKLMNPQRSTUVWXY06FHPV80UNDVARHRAK
+* Master secret (hex): dc5423251cb87175ff8110c8531d0952d8d73e1194e95b5f19d6f9df7c01111104c9baecdfea8cccc677fb9ddc8aec5553b86e528bcadfdcc201c17c638c47e9
+* master node xprv: xprv9s21ZrQH143K4UYT4rP3TZVKKbmRVmfRqTx9mG2xCy2JYipZbkLV8rwvBXsUbEv9KQiUD7oED1Wyi9evZzUn2rqK9skRgPkNaAzyw3YrpJN
+
+===Invalid test vectors===
+
+These examples have incorrect checksums.
+
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxve740yyge2ghq
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxve740yyge2ghp
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxlk3yepcstwr
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxx6pgnv7jnpcsp
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxx0cpvr7n4geq
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxm5252y7d3lr
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxrd9sukzl05ej
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxc55srw5jrm0
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxgc7rwhtudwc
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxx4gy22afwghvs
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxe8yfm0
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxvm597d
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxme084q0vpht7pe0
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxme084q0vpht7pew
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxqyadsp3nywm8a
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxzvg7ar4hgaejk
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxcznau0advgxqe
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxch3jrc6j5040j
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx52gxl6ppv40mcv
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx7g4g2nhhle8fk
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx63m45uj8ss4x8
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy4r708q7kg65x
+
+These examples use the wrong checksum for their given data sizes.
+
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxurfvwmdcmymdufv
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxcsyppjkd8lz4hx3
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxu6hwvl5p0l9xf3c
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwqey9rfs6smenxa
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxv70wkzrjr4ntqet
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx3hmlrmpa4zl0v
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxrfggf88znkaup
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxpt7l4aycv9qzj
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxus27z9xtyxyw3
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxcwm4re8fs78vn
+
+These examples have improper lengths.
+They are either too short, too long, or would decode to byte sequence with an incomplete group greater than 4 bits.
+
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxw0a4c70rfefn4
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxk4pavy5n46nea
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxx9lrwar5zwng4w
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxr335l5tv88js3
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxvu7q9nz8p7dj68v
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxpq6k542scdxndq3
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxkmfw6jm270mz6ej
+* ms12fauxxxxxxxxxxxxxxxxxxxxxxxxxxzhddxw99w7xws
+* ms12fauxxxxxxxxxxxxxxxxxxxxxxxxxxxx42cux6um92rz
+* ms12fauxxxxxxxxxxxxxxxxxxxxxxxxxxxxxarja5kqukdhy9
+* ms12fauxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxky0ua3ha84qk8
+* ms12fauxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx9eheesxadh2n2n9
+* ms12fauxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx9llwmgesfulcj2z
+* ms12fauxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx02ev7caq6n9fgkf
+
+This example uses a "0" threshold with a non-"s" index
+
+* ms10fauxxxxxxxxxxxxxxxxxxxxxxxxxxxx0z26tfn0ulw3p
+
+This example has a threshold that is not a digit.
+
+* ms1fauxxxxxxxxxxxxxxxxxxxxxxxxxxxxxda3kr3s0s2swg
+
+These examples do not begin with the required "ms" or "MS" prefix and/or are missing the "1" separator.
+
+* 0fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2
+* 10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2
+* ms0fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2
+* m10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2
+* s10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2
+* 0fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxhkd4f70m8lgws
+* 10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxhkd4f70m8lgws
+* m10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxx8t28z74x8hs4l
+* s10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxh9d0fhnvfyx3x
+
+These examples all incorrectly mix upper and lower case characters.
+
+* Ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2
+* mS10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2
+* MS10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2
+* ms10FAUXsxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2
+* ms10fauxSxxxxxxxxxxxxxxxxxxxxxxxxxxuqxkk05lyf3x2
+* ms10fauxsXXXXXXXXXXXXXXXXXXXXXXXXXXuqxkk05lyf3x2
+* ms10fauxsxxxxxxxxxxxxxxxxxxxxxxxxxxUQXKK05LYF3X2
+
+==Appendix==
+
+===Mathematical Companion===
+
+Below we use the bech32 character set to denote values in GF[32].
+In bech32, the letter Q denotes zero and the letter P denotes one.
+The digits 0 and 2 through 9 do ''not'' denote their numeric values.
+They are simply elements of GF[32].
+
+The generating polynomial for our BCH code is as follows.
+
+We extend GF[32] to GF[1024] by adjoining a primitive cube root of unity, ζ, satisfying ζ^2 = ζ + P.
+
+We select β := G ζ which has order 93, and construct the product (x - β^i) for i in {17, 20, 46, 49, 52, 77, 78, 79, 80, 81, 82, 83, 84}.
+The resulting polynomial is our generating polynomial for our 13 character checksum:
+
+ x^13 + E x^12 + M x^11 + 3 x^10 + G x^9 + Q x^8 + E x^7 + E x^6 + E x^5 + L x^4 + M x^3 + C x^2 + S x + S
+
+For our long checksum, we select γ := E + X ζ, which has order 1023, and construct the product (x - γ^i) for i in {32, 64, 96, 895, 927, 959, 991, 1019, 1020, 1021, 1022, 1023, 1024, 1025, 1026}.
+The resulting polynomial is our generating polynomial for our 15 character checksum for long strings:
+
+ x^15 + 0 x^14 + 2 x^13 + E x^12 + 6 x^11 + F x^10 + E x^9 + 4 x^8 + X x^7 + H x^6 + 4 x^5 + X x^4 + 9 x^3 + K x^2 + Y x^1 + H
+
+(Reminder: the character 0 does ''not'' denote the zero of the field.)
diff --git a/bip-0094.mediawiki b/bip-0094.mediawiki
new file mode 100644
index 0000000000..d7e436d56d
--- /dev/null
+++ b/bip-0094.mediawiki
@@ -0,0 +1,120 @@
+
+
+== Abstract ==
+
+A new test network with the goal to replace Testnet 3. This network comes with small but important improvements of the consensus rules, that should make it impractical to attack the network using only CPU mining.
+
+== Motivation ==
+
+Quoting the original mailing list post from Jameson Lopphttps://gnusha.org/pi/bitcoindev/CADL_X_eXjbRFROuJU0b336vPVy5Q2RJvhcx64NSNPH-3fDCUfw@mail.gmail.com/:
+
+
+Testnet3 has been running for 13 years. It's on block 2.5 million something and the block reward is down to ~0.014 TBTC, so mining is not doing a great job at distributing testnet coins anymore.
+
+The reason the block height is insanely high is due to a rather amusing edge case bug that causes the difficulty to regularly get reset to 1, which causes a bit of havoc. If you want a deep dive into the quirk: https://blog.lopp.net/the-block-storms-of-bitcoins-testnet/
+
+Testnet3 is being actively used for scammy airdrops; those of us who tend to be generous with our testnet coins are getting hounded by non-developers chasing cheap gains.
+
+As a result, TBTC is being actively bought and sold; one could argue that the fundamental principle of testnet coins having no value has been broken.
+
+
+Since then the issue with block storms has been further demonstrated on Testnet 3 when three years' worth of blocks were mined in a few weeks while rendering the network practically unusable at the same time.
+
+== Specification ==
+
+Consensus of Testnet 4 follows the same rules as mainnet with the exception of the three rules detailed below. Additionally all soft forks that are active on mainnet as of May 2024 are enforced from genesis.
+
+=== 20-minute Exception ===
+
+This rule was already previously implemented and active in Testnet 3https://github.com/bitcoin/bitcoin/pull/686.
+
+A block with a timestamp that is more than 20 minutes past the timestamp of the previous block must have a minimum difficulty of 1 (the network's minimum difficulty) instead of whatever the actual difficulty level currently is. This applies to all blocks in a difficulty period except for the first block. This means the blocks must change their nBits field from the actual difficulty level to the minimum difficulty value 0x1d00ffff.
+
+This rule also led to the block stormshttps://blog.lopp.net/the-block-storms-of-bitcoins-testnet/ which the following rule seeks to fix.
+
+=== Block Storm Fix ===
+
+The work required for a new difficulty period is calculated as multiplication factor to the difficulty of the previous period (but no less than 1/4th and no more than 4x), depending on the duration of the previous difficulty period. On Mainnet and Testnet 3, this factor is applied to the difficulty value of the last block.
+
+Block storms happen organically whenever the 20-minute exception is applied to a difficulty period’s last block, causing the block to be mined at a difficulty of 1. The difficulty adjustment rules then limit the subsequent period’s difficulty to a value between 1 (the minimum) and 4. Blocks will be generated rapidly in the subsequent low-difficulty periods while the difficulty climbs back to an adequate range. An arbitrarily large number of blocks can be generated quickly by repeatedly using the 20-minute exception on every last block of difficulty periods. The block storm is then bounded only by miner hash rate, the need for last blocks to have a timestamp 20 minutes after the second to last block, the Median-Time-Past nTime rule, and the requirement that blocks can't be more than 2 hours in the future. Overall a sustained attack would eventually be limited to a maximum cadence of six blocks per second.
+
+A block storm does not require a time warp attack, but one can be used to amplifyA perpetual block storm attack with entire difficulty periods being authored in less than 3.5 days that resets the difficulty to the minimum in the last block of every difficulty period would adjust to a new actual difficulty of 4 every period. An attacker that additionally leverages a time warp attack would start their attack by holding back timestamps until the latest block’s timestamp is at least two weeks in the past, and then limiting their block rate to six blocks per second, incrementing the timestamp on every sixth block. Only on the last block they would use the current time, which both resets the difficulty to one per the 20-minute exception and would result in a difficulty adjustment keeping the difficulty at the minimum due to the elapsed time exceeding the target. This would allow lower the difficulty for all blocks to difficulty 1 instead of difficulty 4 it.
+
+The mitigation consists of no longer applying the adjustment factor to the last block of the previous difficulty period. Instead, the first block of the difficulty period is used as the base.
+
+The first block must contain the actual difficulty of the network and can therefore be used as the base for the calculation of the new difficulty level. Note that the first block in new difficulty period does not allow usage of the 20-minute exception (this is prior behavior). This means that in each difficulty period the first block should always have the actual difficulty even if all other blocks were mined with the 20-minute exception.
+
+=== Time Warp Fix ===
+
+In addition to a time warp attack potentially exacerbating the perpetual block storm attack, a time warp attack provides an alternative way to increase the block production rate even if the unintended reset of the actual difficulty due to the 20-minute exception was mitigated.
+
+To protect against the time warp attack, the following rule proposed as part of The Great Consensus Cleanuphttps://github.com/TheBlueMatt/bips/blob/cleanup-softfork/bip-XXXX.mediawiki is enforced: "The nTime field of each block whose height, mod 2016, is 0 must be greater than or equal to the nTime field of the immediately prior block minus 600. For the avoidance of doubt, such blocks must still comply with existing Median-Time-Past nTime restrictions."
+
+== Rationale ==
+
+The applied changes were the result of discussions on the mailing list and the PR. The selected changes try to strike a balance between minimal changes to the network (keeping it as close to mainnet as possible) while making it more robust against attackers that try to disrupt the network. Several alternative designs were considered:
+
+* For the block storm fix an alternative fix could have been to prevent the last block in a difficulty period from applying the existing difficulty exception. Both solutions were deemed acceptable and there was no clear preference among reviewers.
+* Removal of the 20-minute exception was discussed but dismissed since several reviewers insisted that it was a useful feature allowing non-standard transactions to be mined with just a CPU. The 20-minute exception also allows CPU users to move the chain forward (except on the first block that needs to be mined at actual difficulty) in case a large amount of hash power suddenly leaves the network. This would allow the chain to recover to a normal difficulty level faster if left stranded at high difficulty.
+* Increase of minimum difficulty was discussed but dismissed as it would categorically prevent participation in the network using a CPU miner (utilizing the 20-minute exception).
+* Increase of the delay in the 20-minute exception was suggested but did not receive significant support.
+* Re-enabling acceptnonstdtxn in bitcoin core by default was dismissed as it had led to confusion among layer-2s that had used testnet for transaction propagation tests and expected it to behave similar to mainnet.
+* Motivating miners to re-org min difficulty blocks was suggested, but was considered out of scope for this BIP, since adoption of such a mining policy remains available after Testnet 4 is deployed. As 20-minute exception blocks only contribute work corresponding to difficulty one to the chaintip, and actual difficulty blocks should have a difficulty magnitudes higher, a block mined at actual difficulty could easily replace even multiple 20-minute exception blocks.
+* Persisting the real difficulty in the version field was suggested to robustly prevent exploits of the 20-minute exception while allowing it to be used on any block, but did not receive a sufficient level of support to justify the more invasive change.
+
+One known downside of the chosen approach is that if the difficulty is gradually raised by a miner with significant hash rate, and this miner disappears, then each difficulty adjustment period requires one block at the actual difficulty.
+
+This would cause the network to stall once per difficulty adjustment period until the real difficulty is adjusted downwards enough for the remaining hash rate to find this block in reasonable time.
+
+== Network Parameters ==
+
+=== Consensus Rules ===
+
+All consensus rules active on mainnet at the time of this proposal are enforced from block 1, the newest of these rules being the Taproot softfork.
+
+=== Genesis Block ===
+
+* Message: 03/May/2024 000000000000000000001ebd58c244970b3aa9d783bb001011fbe8ea8e98e00e
+* Pubkey: 000000000000000000000000000000000000000000000000000000000000000000
+* Time stamp: 1714777860
+* Nonce: 393743547
+* Difficulty: 0x1d00ffff
+* Version: 1
+
+The resulting genesis block hash is 00000000da84f2bafbbc53dee25a72ae507ff4914b867c565be350b0da8bf043, and the block hex is 0100000000000000000000000000000000000000000000000000000000000000000000004e7b2b9128fe0291db0693af2ae418b767e657cd407e80cb1434221eaea7a07a046f3566ffff001dbb0c78170101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff5504ffff001d01044c4c30332f4d61792f323032342030303030303030303030303030303030303030303165626435386332343439373062336161396437383362623030313031316662653865613865393865303065ffffffff0100f2052a010000002321000000000000000000000000000000000000000000000000000000000000000000ac00000000.
+
+=== Message Start ===
+
+The message start is defined as 0x1c163f28. These four bytes were randomly generated and have no special meaning.
+
+== Backwards Compatibility ==
+
+The rules used by Testnet 4 are backwards compatible to the rules of Testnet 3. Existing software that implements support for Testnet 3 would only require addition of the network parameters (magic number, genesis block, etc.) to be able to follow Testnet 4.
+
+However, implementations that only implement Testnet 3’s rules would accept a chain that violates Testnet 4’s rules and are therefore susceptible to being forked off. It is recommended that any implementations check blocks in regard to all the new rules of Testnet 4 and reject blocks that fail to comply.
+
+== Reference implementation ==
+
+Pull request at https://github.com/bitcoin/bitcoin/pull/29775
+
+== References ==
+
+
+
+== Copyright ==
+
+This document is licensed under the Creative Commons CC0 1.0 Universal license.
diff --git a/bip-0098.mediawiki b/bip-0098.mediawiki
new file mode 100644
index 0000000000..8cf8106935
--- /dev/null
+++ b/bip-0098.mediawiki
@@ -0,0 +1,308 @@
+
+ BIP: 98
+ Layer: Consensus (soft fork)
+ Title: Fast Merkle Trees
+ Author: Mark Friedenbach
+ Kalle Alm
+ BtcDrak
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0098
+ Status: Draft
+ Type: Standards Track
+ Created: 2017-08-24
+ License: CC-BY-SA-4.0
+ License-Code: MIT
+
+
+==Abstract==
+
+In many applications it is useful to prove membership of a data element in a set without having to reveal the entire contents of that set.
+The Merkle hash-tree, where inner/non-leaf nodes are labeled with the hash of the labels or values of its children, is a cryptographic tool that achieves this goal.
+Bitcoin uses a Merkle hash-tree construct for committing the transactions of a block into the block header.
+This particular design, created by Satoshi, suffers from a serious flaw related to duplicate entries documented in the National Vulnerability Database as CVE-2012-2459[1], and also suffers from less than optimal performance due to unnecessary double-hashing.
+
+This Bitcoin Improvement Proposal describes a more efficient Merkle hash-tree construct that is not vulnerable to CVE-2012-2459
+and achieves an approximate 55% decrease in hash-tree construction and validation times as compared with fully optimized implementations of the Satoshi Merkle hash-tree construct.
+
+==Copyright==
+
+This BIP is licensed under a Creative Commons Attribution-ShareAlike license. All provided source code is licensed under the MIT license.
+
+==Motivation==
+
+A Merkle hash-tree is a directed acyclic graph data structure where all non-terminal nodes are labeled with the hash of combined labels or values of the node(s) it is connected to.
+Bitcoin uses a unique Merkle hash-tree construct invented by Satoshi for calculating the block header commitment to the list of transactions in a block.
+While it would be convenient for new applications to make use of this same data structure so as to share implementation and maintenance costs, there are three principle drawbacks to reuse.
+
+First, Satoshi's Merkle hash-tree has a serious vulnerability[1] related to duplicate tree entries that can cause bugs in protocols that use it.
+While it is possible to secure protocols and implementations against exploit of this flaw, it requires foresight and it is a bit more tricky to design secure protocols that work around this vulnerability.
+Designers of new protocols ought avoid using the Satoshi Merkle hash-tree construct where at all possible in order to responsibly decrease the likelihood of downstream bugs in naïve implementations.
+
+Second, Satoshi's Merkle hash-tree performs an unnecessary number of cryptographic hash function compression rounds, resulting in construction and validation times that are approximately three (3) times more computation than is strictly necessary in a naïve implementation, or 2.32x more computation in an implementation specialized for this purpose only[2].
+New implementations that do not require backwards compatibility ought to consider hash-tree implementations that do not carry this unnecessary performance hit.
+
+Third, Satoshi's algorithm presumes construction of a tree index from an ordered list, and therefore is designed to support balanced trees with a uniform path length from root to leaf for all elements in the tree.
+Many applications, on the other hand, benefit from having unbalanced trees, particularly if the shorter path is more likely to be used.
+While it is possible to make a few elements of a Satoshi hash-tree have shorter paths than the others, the tricks for doing so are dependent on the size of the tree and not very flexible.
+
+Together these three reasons provide justification for specifying a standard Merkle hash-tree structure for use in new protocols that fixes these issues.
+This BIP describes such a structure, and provides an example implementation.
+
+==Specification==
+
+A Merkle hash-tree as defined by this BIP is an arbitrarily-balanced binary tree whose terminal/leaf nodes are labelled with the double-SHA256 hashes of data, whose format is outside the scope of this BIP, and inner nodes with labels constructed from the fast-SHA256 hash of its children's labels.
+The following image depicts an example unbalanced hash-tree:
+
+:: [[File:bip-0098/unbalanced-hash-tree.png]]
+
+'''A''', '''B''', and '''C''' are leaf labels, 32-byte double-SHA256 hashes of the data associated with the leaf.
+'''Node''' and '''Root''' are inner nodes, whose labels are fast-SHA256 (defined below) hashes of their respective children's labels.
+'''Node''' is labelled with the fast-SHA256 hash of the concatenation of '''B''' and '''C'''.
+'''Root''' is labelled with the fast-SHA256 hash of the concatenation of '''A''' and '''Node''', and is the ''Merkle root'' of the tree.
+Nodes with single children are not allowed.
+
+The ''double-SHA256'' cryptographic hash function takes an arbitrary-length data as input and produces a 32-byte hash by running the data through the SHA-256 hash function as specified in FIPS 180-4[3], and then running the same hash function again on the 32-byte result, as a protection against length-extension attacks.
+
+The ''fast-SHA256'' cryptographic hash function takes two 32-byte hash values, concatenates these to produce a 64-byte buffer, and applies a single run of the SHA-256 hash function with a custom 'initialization vector' (IV) and without message padding.
+The result is a 32-byte 'midstate' which is the combined hash value and the label of the inner node.
+The changed IV protects against path-length extension attacks (grinding to interpret a hash as both an inner node and a leaf).
+fast-SHA256 is only defined for two 32-byte inputs.
+The custom IV is the intermediate hash value generated after performing a standard SHA-256 of the following hex-encoded bytes and extracting the midstate:
+
+ cbbb9d5dc1059ed8 e7730eaff25e24a3 f367f2fc266a0373 fe7a4d34486d08ae
+ d41670a136851f32 663914b66b4b3c23 1b9e3d7740a60887 63c11d86d446cb1c
+
+This data is the first 512 fractional bits of the square root of 23, the 9th prime number.
+The resulting midstate is used as IV for the fast-SHA256 cryptographic hash function:
+
+ static unsigned char _MidstateIV[32] =
+ { 0x89, 0xcc, 0x59, 0xc6, 0xf7, 0xce, 0x43, 0xfc,
+ 0xf6, 0x12, 0x67, 0x0e, 0x78, 0xe9, 0x36, 0x2e,
+ 0x76, 0x8f, 0xd2, 0xc9, 0x18, 0xbd, 0x42, 0xed,
+ 0x0e, 0x0b, 0x9f, 0x79, 0xee, 0xf6, 0x8a, 0x24 };
+
+As fast-SHA256 is only defined for two (2) 32-byte hash inputs, there are necessarily two special cases:
+an empty Merkle tree is not allowed, nor is any root hash defined for such a "tree";
+and a Merkle tree with a single value has a root hash label equal to that self-same value of the leaf branch, the only node in the tree (a passthrough operation with no hashing).
+
+===Rationale===
+
+The fast-SHA256 hash function can be calculated 2.32x faster than a specialized double-SHA256 implementation[2], or three (3) times faster than an implementation applying a generic SHA-256 primitive twice,
+as hashing 64 bytes of data with SHA-256 as specified by FIPS 180-4[3] takes two compression runs (because of message padding) and then a third compression run for the double-SHA256 construction.
+Validating a fast-SHA256 Merkle root is therefore more than twice as fast as the double-SHA256 construction used by Satoshi in bitcoin.
+Furthermore the fastest fast-SHA256 implementation ''is'' the generic SHA-256 implementation, enabling generic circuitry and code reuse without a cost to performance.
+
+The application of fast-SHA256 to inner node label updates is safe in this limited domain because the inputs are hash values and fixed in number and in length,
+so the sorts of attacks prevented by message padding and double-hashing do not apply.
+
+The 'initialization vector' for fast-SHA256 is changed in order to prevent a category of attacks on higher level protocols where a partial collision can serve as both a leaf hash and as an inner node commitment to another leaf hash.
+The IV is computed using standard SHA-256 plus midstate extraction so as to preserve compatibility with cryptographic library interfaces that do not support custom IVs, at the cost of a 2x performance hit if neither custom IVs nor resuming from midstate are supported.
+The data hashed is a nothing-up-my-sleeve number that is unlikely to have a known hash preimage.
+The prime 23 was chosen as the leading fractional bits of the first eight (8) primes, two (2) through nineteen (19), are constants used in the setup of SHA-256 itself.
+Using the next prime in sequence reduces the likelihood of introducing weakness due to reuse of a constant factor.
+
+The Merkle root hash of a single element tree is a simple pass-through of the leaf hash without modification so as to allow for chained validation of split proofs.
+This is particularly useful when the validation environment constrains proof sizes, such as push limits in Bitcoin script.
+Chained validation allows a verifier to split one proof into two or more, where the leaf is shown to be under an inner node, and that inner node is shown to be under the root.
+Without pass-through hashing in a single-element tree, use of chained validation would unnecessarily introduce a minimum path length requirement equal to the number of chain links.
+Pass-through hashing of single elements allows instead for one or more of the chained validations to use a "NOP" proof consisting of a zero-length path,
+thereby allowing, for example, a fixed series of four (4) chained validations to verify a length three (3) or shorter path.
+
+==Inclusion Proofs==
+
+An important use of Merkle hash-trees is the ability to compactly prove membership with log-sized proofs.
+This section specifies a standard encoding for a multi-element inclusion proof.
+
+To prove that a set of hashes is contained within a Merkle tree with a given root requires four pieces of information:
+
+# The root hash of the Merkle tree;
+# The hash values to be verified, a set usually consisting of the double-SHA256 hash of data elements, but potentially the labels of inner nodes instead, or both;
+# The paths from the root to the nodes containing the values under consideration, expressed as a serialized binary tree structure; and
+# The hash values of branches not taken along those paths.
+
+Typically the last two elements, the paths and the elided branch hashes, are lumped together and referred to as the ''proof''.
+
+Serialization begins with a variable-length integer (VarInt) used to encode N, the number of internal nodes in the proof.
+Next the structure of the tree is traversed using depth-first, left-to-right, pre-order algorithm to visit each internal nodes, which are serialized using a packed 3-bit representation for the configuration of each node, consuming (3*N + 7) / 8 bytes.
+Then the number skipped hashes (those included in the proof, not verified by the proof) is serialized as a variable-length integer (VarInt),
+followed by the hashes themselves in the order previously traversed.
+
+There are eight possible configurations of internal nodes, as given in the following diagram:
+
+:: [[File:bip-0098/node-variants.png]]
+
+In this diagram, DESCEND means the branch links to another internal node, as indicated by its child graph elements labeled "...";
+SKIP means the branch contains a hash of an elided subtree or element, and the fast-SHA256 root hash of this subtree or double-SHA256 hash of the element is included in the proof structure; and
+VERIFY means the branch contains an externally provided hash that is needed as witness for the verification of the proof.
+In tabular form, these code values are:
+
+{| class="wikitable"
+|-
+| scope="col"| Code
+| scope="col"| Left
+| scope="col"| Right
+|-
+| scope="row"| 000
+| VERIFY
+| SKIP
+|-
+| scope="row"| 001
+| VERIFY
+| VERIFY
+|-
+| scope="row"| 010
+| VERIFY
+| DESCEND
+|-
+| scope="row"| 011
+| DESCEND
+| SKIP
+|-
+| scope="row"| 100
+| DESCEND
+| VERIFY
+|-
+| scope="row"| 101
+| DESCEND
+| DESCEND
+|-
+| scope="row"| 110
+| SKIP
+| VERIFY
+|-
+| scope="row"| 111
+| SKIP
+| DESCEND
+|}
+
+These 3-bit codes are packed into a byte array such that eight (8) codes would fit in every three (3) bytes.
+The order of filling a byte begins with the most significant bit 0x80 and ends with the least significant bit 0x01.
+Unless the number of inner nodes is a multiple of eight (8), there will be excess low-order bits in the final byte of serialization.
+These excess bits must be zero.
+
+Note that the tree serialization is self-segmenting.
+By tracking tree structure a proof reader will know when the parser has reached the last internal node.
+The number of inner nodes serialized in the proof MUST equal the number of nodes inferred from the tree structure itself.
+Similarly, the number of SKIP hashes can also be inferred from the tree structure as serialized, and MUST equal the number of hashes provided within the proof.
+
+The single-hash proof has N=0 (the number of inner nodes),
+the tree structure is not serialized (as there are no inner nodes),
+and the number of SKIP hashes can be either 0 or 1.
+
+===Example===
+
+Consider the following Merkle tree structure:
+
+:: [[File:bip-0098/traversal-example.png]]
+
+There are six (6) internal nodes.
+The depth-first, left-to-right, pre-order traversal of the tree visits these nodes in the following order: A, B, D, F, C, then E.
+There are three (3) skipped hashes, visited in the following order: 0x00..., 0x66..., and 0x22...
+The remaining four (4) hashes are provided at runtime to be verified by the proof.
+
+{|
+| scope="col"|
+| scope="col"| Byte 1
+| scope="col"| Byte 2
+| scope="col"| Byte 3
+|-
+| scope="row"| Bits
+| 76543210
+| 76543210
+| 76543210
+|-
+| scope="row"| Nodes
+| AAABBBDD
+| DFFFCCCE
+| EE------
+|-
+| scope="row"| Code
+| 10111101
+| 10000100
+| 01000000
+|}
+
+The serialization begins with the VarInt encoded number of inner nodes, 0x06, followed by the tree serialization itself, 0xbd8440.
+Next the number of SKIP hashes is VarInt encoded, 0x03, followed by the three (3) hashes in sequence.
+The resulting 101 byte proof, encoded in base64:.
+
+ Br2EQAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGZmZmZmZmZmZmZmZmZmZmZmZmZm
+ ZmZmZmZmZmZmZmZmREREREREREREREREREREREREREREREREREREREREREQ=
+
+===Rationale===
+
+The 3-bit encoding for inner nodes allows encoding all relevant configurations of the nodes where the left and right branches can each be one of {DESCEND, SKIP, VERIFY}.
+The excluded 9th possibility would have both branches as SKIP:
+
+:: [[File:bip-0098/skip-skip.png]]
+
+This possibility is not allowed as for verification purposes it is entirely equivalent to the shorter proof where the branch to that node was SKIP'ed.
+Disallowing a node with two SKIP branches eliminates what would otherwise be a source of proof malleability.
+
+The number of hashing operations required to verify a proof is one less than the number of hashes (SKIP and VERIFY combined),
+and is exactly equal to the number of inner nodes serialized as the beginning of the proof as N.
+The variable-length integer encoding has the property that serialized integers, sorted lexicographically, will also be sorted numerically.
+Since the first serialized item is the number of inner nodes, sorting proofs lexicographically has the effect of sorting the proofs by the amount of work required to verify.
+
+The number of hashes required as input for verification of a proof is N+1 minus the number of SKIP hashes,
+and can be quickly calculated without parsing the tree structure.
+
+The coding and packing rules for the serialized tree structure were also chosen to make lexicographical comparison useful (or at least not meaningless).
+If we consider a fully-expanded tree (no SKIP hashes, all VERIFY) to be encoding a list of elements in the order traversed depth-first from left-to-right,
+then we can extract proofs for subsets of the list by SKIP'ing the hashes of missing values and recursively pruning any resulting SKIP,SKIP nodes.
+Lexicographically comparing the resulting serialized tree structures is the same as lexicographically comparing lists of indices from the original list verified by the derived proof.
+
+Because the number of inner nodes and the number of SKIP hashes is extractible from the tree structure,
+both variable-length integers in the proof are redundant and could have been omitted.
+However that would require either construction and storage of the explicit tree in memory at deserialization time,
+or duplication of the relatively complicated tree parsing code in both the serialization and verification methods.
+For that reason (as well as to handle the single-hash edge case) the redundant inner node and SKIP hash counts are made explicit in the serialization,
+and the two values must match what is inferred from the tree structure for a proof to be valid.
+This makes deserialization trivial and defers tree construction until verification time,
+which has the additional benefit of enabling log-space verification algorithms.
+
+==Fast Merkle Lists==
+
+Many applications use a Merkle tree to provide indexing of, or compact membership proofs about the elements in a list.
+This addendum specifies an algorithm that constructs a canonical balanced tree structure for lists of various lengths.
+It differs in a subtle but important way from the algorithm used by Satoshi so as to structurally prevent the vulnerability described in [1].
+
+# Begin with a list of arbitrary data strings.
+# Pre-process the list by replacing each element with its double-SHA256 hash.
+# If the list is empty, return the zero hash.
+# While the list has 2 or more elements,
+#* Pass through the list combining adjacent entries with the fast-SHA256 hash. If the list has an odd number of elements, leave the last element as-is (this fixes [1]). This step reduces a list of N elements to ceil(N/2) entries.
+# The last remaining item in the list is the Merkle root.
+
+This algorithm differs from Merkle lists used in bitcoin in two ways.
+First, fast-SHA256 is used instead of double-SHA256 for inner node labels.
+Second, final entries on an odd-length list are not duplicated and hashed, which is the mistake that led to CVE-2012-2459[1].
+
+==Implementation==
+
+An implementation of this BIP for extraction of Merkle branches and fast, log-space Merkle branch validation is available at the following Github repository:
+
+[https://github.com/maaku/bitcoin/tree/fast-merkle-tree]
+
+Also included in this repo is a 'merklebranch' RPC for calculating root values and extracting inclusion proofs for both arbitrary trees and trees constructed from lists of values using the algorithm in this BIP,
+and a 'mergemerklebranch' RPC for unifying two or more fast Merkle tree inclusion proofs--replacing SKIP hashes in one proof with a subtree extracted from another.
+
+==Deployment==
+
+This BIP is used by BIP116 (MERKLEBRANCHVERIFY)[4] to add Merkle inclusion proof verification to script by means of a soft-fork NOP expansion opcode.
+Deployment of MERKLEBRANCHVERIFY would make the contents of this BIP consensus critical.
+The deployment plan for BIP116 is covered in the text of that BIP.
+
+==Compatibility==
+
+This BIP on its own does not cause any backwards incompatibility.
+
+==References==
+
+[1] [https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-2459 National Vulnerability Database: CVE-2012-2459]
+
+[2] [https://github.com/sipa/bitcoin/tree/201709_dsha256_64 github.com:sipa/bitcoin 201709_dsha256_64] Pieter Wuille, September 2017, personal communication. By making use of knowledge that the inputs at each stage are fixed length, Mr. Wuille was able to achieve a 22.7% reduction in the time it takes to compute the double-SHA256 hash of 64 bytes of data, the hash aggregation function of the Satoshi Merkle tree construction.
+
+[3] [http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf Secure Hash Standard]
+
+[4] [https://github.com/bitcoin/bips/blob/master/bip-0116.mediawiki BIP 116 MERKLEBRANCHVERIFY]
diff --git a/bip-0098/build.sh b/bip-0098/build.sh
new file mode 100755
index 0000000000..a8a3155e95
--- /dev/null
+++ b/bip-0098/build.sh
@@ -0,0 +1,6 @@
+#!/bin/sh
+
+dot -Tpng -o node-variants.png node-variants.dot
+dot -Tpng -o skip-skip.png skip-skip.dot
+dot -Tpng -o traversal-example.png traversal-example.dot
+dot -Tpng -o unbalanced-hash-tree.png unbalanced-hash-tree.dot
diff --git a/bip-0098/node-variants.dot b/bip-0098/node-variants.dot
new file mode 100644
index 0000000000..7171346125
--- /dev/null
+++ b/bip-0098/node-variants.dot
@@ -0,0 +1,85 @@
+digraph G {
+ row1 [shape=none, label=""]
+
+ A [label="000"]
+ A -> Al [label="L"]
+ Al [label="VERIFY"]
+ A -> Ar [label="R"]
+ Ar [label="SKIP"]
+
+ B [label="001"]
+ B -> Bl [label="L"]
+ Bl [label="VERIFY"]
+ B -> Br [label="R"]
+ Br [label="VERIFY"]
+
+ { rank = same; row1; A; B; }
+
+ C [label="010"]
+ C -> Cl [label="L"]
+ Cl [label="VERIFY"]
+ C -> Cr [label="R"]
+ Cr [label="DESCEND"]
+ Cr -> Crl
+ Crl [label="..."]
+ Cr -> Crr
+ Crr [label="..."]
+
+ D [label="011"]
+ D -> Dl [label="L"]
+ Dl [label="DESCEND"]
+ Dl -> Dll
+ Dll [label="..."]
+ Dl -> Dlr
+ Dlr [label="..."]
+ D -> Dr [label="R"]
+ Dr [label="SKIP"]
+
+ E [label="100"]
+ E -> El [label="L"]
+ El [label="DESCEND"]
+ El -> Ell
+ Ell [label="..."]
+ El -> Elr
+ Elr [label="..."]
+ E -> Er [label="R"]
+ Er [label="VERIFY"]
+
+ row1 -> invis [style=invis]
+ invis [shape=none, label=""]
+ invis -> C [style=invis]
+ { rank = same; C; D; E; }
+
+ F [label="101"]
+ F -> Fl [label="L"]
+ Fl [label="DESCEND"]
+ Fl -> Fll
+ Fll [label="..."]
+ Fl -> Flr
+ Flr [label="..."]
+ F -> Fr [label="R"]
+ Fr [label="DESCEND"]
+ Fr -> Frl
+ Frl [label="..."]
+ Fr -> Frr
+ Frr [label="..."]
+
+ G [label="110"]
+ G -> Gl [label="L"]
+ Gl [label="SKIP"]
+ G -> Gr [label="R"]
+ Gr [label="VERIFY"]
+
+ H [label="111"]
+ H -> Hl [label="L"]
+ Hl [label="SKIP"]
+ H -> Hr [label="R"]
+ Hr [label="DESCEND"]
+ Hr -> Hrl
+ Hrl [label="..."]
+ Hr -> Hrr
+ Hrr [label="..."]
+
+ Crl -> F [style=invis]
+ { rank = same; F; G; H; }
+}
diff --git a/bip-0098/node-variants.png b/bip-0098/node-variants.png
new file mode 100644
index 0000000000..991d7bc2a1
Binary files /dev/null and b/bip-0098/node-variants.png differ
diff --git a/bip-0098/skip-skip.dot b/bip-0098/skip-skip.dot
new file mode 100644
index 0000000000..5e633d6498
--- /dev/null
+++ b/bip-0098/skip-skip.dot
@@ -0,0 +1,7 @@
+digraph G {
+ A [label="???"]
+ A -> Al [label="L"]
+ Al [label="SKIP"]
+ A -> Ar [label="R"]
+ Ar [label="SKIP"]
+}
\ No newline at end of file
diff --git a/bip-0098/skip-skip.png b/bip-0098/skip-skip.png
new file mode 100644
index 0000000000..d3e7c454e2
Binary files /dev/null and b/bip-0098/skip-skip.png differ
diff --git a/bip-0098/traversal-example.dot b/bip-0098/traversal-example.dot
new file mode 100644
index 0000000000..29936428c1
--- /dev/null
+++ b/bip-0098/traversal-example.dot
@@ -0,0 +1,32 @@
+digraph G {
+ a [label="A\n101"]
+ a -> b
+ a -> c
+
+ b [label="B\n111"]
+ b -> s0
+ s0 [label="SKIP\n0x00..."]
+ b -> d
+
+ d [label="D\n011"]
+ d -> f
+ d -> s1
+ s1 [label="SKIP\n0x22..."]
+
+ f [label="F\n000"]
+ f -> v1
+ v1 [label="VERIFY\n0x55..."]
+ f -> s2
+ s2 [label="SKIP\n0x66..."]
+
+ c [label="C\n010"]
+ c -> v2
+ v2 [label="VERIFY\n0x11..."]
+ c -> e
+
+ e [label="E\n001"]
+ e -> v3
+ v3 [label="VERIFY\n0x33..."]
+ e -> v4
+ v4 [label="VERIFY\n0x44..."]
+}
diff --git a/bip-0098/traversal-example.png b/bip-0098/traversal-example.png
new file mode 100644
index 0000000000..a6a7954ec3
Binary files /dev/null and b/bip-0098/traversal-example.png differ
diff --git a/bip-0098/unbalanced-hash-tree.dot b/bip-0098/unbalanced-hash-tree.dot
new file mode 100644
index 0000000000..c6376525c8
--- /dev/null
+++ b/bip-0098/unbalanced-hash-tree.dot
@@ -0,0 +1,11 @@
+digraph G {
+ 0 [label="Root\nH(A || H(B || C))"]
+ 0 -> A
+ A [label="A\nskip"]
+ 0 -> 1
+ 1 [label="Node\nH(B || C)"]
+ 1 -> B
+ B [label="B\nskip"]
+ 1 -> C
+ C [label="C\nverify"]
+}
diff --git a/bip-0098/unbalanced-hash-tree.png b/bip-0098/unbalanced-hash-tree.png
new file mode 100644
index 0000000000..339bb2276c
Binary files /dev/null and b/bip-0098/unbalanced-hash-tree.png differ
diff --git a/bip-0099.mediawiki b/bip-0099.mediawiki
index c40bacb6a4..6889252bba 100644
--- a/bip-0099.mediawiki
+++ b/bip-0099.mediawiki
@@ -2,9 +2,12 @@
BIP: 99
Title: Motivation and deployment of consensus rule changes ([soft/hard]forks)
Author: Jorge Timón
- Status: Draft
- Type: Informational | Process
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0099
+ Status: Rejected
+ Type: Informational
Created: 2015-06-20
+ License: PD
Post-History: http://lists.linuxfoundation.org/pipermail/bitcoin-dev/2015-June/008936.html
@@ -20,7 +23,7 @@ not always well-understood, and the best upgrade mechanisms to the
consensus validation rules may vary depending on the type of change being deployed.
Discussing such changes without a uniform view on the deployment
paths often leads to misunderstandings and unnecessarily delays the
-deployment of changes.
+deployment of changes.
==Definitions==
@@ -40,7 +43,7 @@ deployment of changes.
: a theoretical piece of software that contains the specifications that define the validity of a block for a given state and chain parameters (ie it may act differently on, for example, regtest).
;Libbitcoinconsensus
-: the existing implementation is a library that is compiled by default with Bitcoin Core master and exposes a single C function named bitcoinconsensus_verify_script(). Although it has a deterministic build and implements the most complex rules (most of the cryptography, which is itself heavily based on libsecp256k1 after #REPLACE_libsecp256k1_PR), it is still not a complete specification of the consensus rules. Since libconsensus doesn't manage the current state but only the validation of the next block given that state, it is known that this long effort of encapsulation and decoupling will eventually finish, and that the person who moves the last line
+: the existing implementation is a library that is compiled by default with Bitcoin Core master and exposes a single C function named bitcoinconsensus_verify_script(). Although it has a deterministic build and implements the most complex rules (most of the cryptography, which is itself heavily based on libsecp256k1 after #REPLACE_libsecp256k1_PR), it is still not a complete specification of the consensus rules. Since libconsensus doesn't manage the current state but only the validation of the next block given that state, it is known that this long effort of encapsulation and decoupling will eventually finish, and that the person who moves the last line
==Taxonomy of consensus forks==
@@ -53,7 +56,7 @@ development, diversity, etc) to fork the Bitcoin Core software and it's good
that there's many alternative implementations of the protocol (forks
of Bitcoin Core or written from scratch).
-But sometimes a bug in the reimplementaion of the consensus
+But sometimes a bug in the reimplementation of the consensus
validation rules can prevent users of alternative implementation from
following the longest (most work) valid chain. This can result in
those users losing coins or being defrauded, making reimplementations
@@ -73,14 +76,14 @@ without burdening them with specific design choices made by Bitcoin
Core. It is to be noted that sharing the same code for consensus
validation doesn't prevent alternative implementations from
independently changing their consensus rules: they can always fork
-the libbitcoinconsensus project (once it is in a separate repository).
+the libbitcoinconsensus project (once it is in a separate repository).
Hopefully libbitcoinconsensus will remove this type of consensus fork
which - being accidental - obviously doesn't need a deployment plan.
====11/12 March 2013 Chain Fork====
-There is a precedent of an accidental consensus fork at height 225430.
+There is a precedent of an accidental consensus fork at height 225430.
Without entering into much detail (see [2]), the situation was different from
what's being described from the alternative implementation risks (today alternative implementation
still usually rely in different degrees on Bitcoin Core trusted proxies, which
@@ -101,7 +104,7 @@ rapidly by the whole worldwide community and nobody is unhappy about
the solution.
But there's some philosophical disagreements on the terms of what the
-solution was: we can add a pedantic note on that.
+solution was: we can add a pedantic note on that.
If "the implementation is the specification", then those
levelDB-specific limitations were part of the consensus rules.
Then additional rules were necessary and any alternative
@@ -110,7 +113,7 @@ planned consensus fork to migrate all Bitcoin-qt 0.7- users could
remove those additional consensus restrictions.
Had libconsensus being implemented without depending on levelDB,
those additional restrictions wouldn't have been part of "the specification"
- and this would just have been a bug in the
+and this would just have been a bug in the
consensus rules, just a consensus-critical bug in a set of
implementations, concretely all satoshi-bitcoin-0.7-or-less (which
happened to be a huge super majority of the users), but other
@@ -123,7 +126,7 @@ another consensus fork to remove them. Two theoretical consensus forks
instead of one but the first one deployed practically for free. The
practical result would have been identical and only the definitions
change. This means discussing something that went uncontroversially
-well further is "philosophical bike-shed" (TM).
+well further is "philosophical bike-shed" (TM).
===Unilateral softforks===
@@ -141,7 +144,7 @@ unnecessary.
Fundamental disagreements and controversies are part of social
systems, like the one defined as the human participants in the Bitcoin
network. Without judging the motivation of the rule discrepancies or
-what rules were in place first, we're definining schism[1] hardforks as
+what rules were in place first, we're defining schism[1] hardforks as
those in which - for whatever reason - users are consiously going to validate 2
different sets of consensus rules. Since they will validate different
rulesets, they will end up following 2 different chains for at least
@@ -154,17 +157,17 @@ that this must always be the case.
While 2 chains cohexist, they can be considered two different
currencies.
We could say that bitcoin becomes bitcoinA and bitcoinB. The implications for market
-capitalization are completely unpredictable,
+capitalization are completely unpredictable,
-maybe mc(bitcoinA) = mc(bitcoinB) = mc(old_bitcoin),
+maybe mc(bitcoinA) = mc(bitcoinB) = mc(old_bitcoin),
-maybe mc(bitcoinA) + mc(bitcoinB) = mc(old_bitcoin),
+maybe mc(bitcoinA) + mc(bitcoinB) = mc(old_bitcoin),
maybe mc(bitcoinA) + mc(bitcoinB) = 1000 * mc(old_bitcoin),
maybe mc(bitcoinA) + mc(bitcoinB) = 0,
-...
+...
Schism hardforks have been compared to one type of altcoins called
"spinoffs"[spinoffs] that distribute all or part of its initial seigniorage to
@@ -221,7 +224,7 @@ Let's imagine BIP66 had a crypto backdoor
that nobody noticed and allows an evil developer cabal to steal
everyone's coins. The users and non-evil developers could join, fork
libconsensus and use the forked version in their respective bitcoin
-implementations.
+implementations.
Should miner's "vote" be required to express their consent? What if some miners
are part of the cabal? In the unlikely event that most miners are
part of such an evil cabal, changing the pow function may be
@@ -265,7 +268,7 @@ that's why the voting mechanism and first used for BIP30 and BIP66.
The current voting threshold for softfork enforcement is 95%. There's
also a 75% threshold for miners to activate it as a policy rule, but
it should be safe for miners to activate such a policy from the start
-or later than 75%, as long as they enforce it as consensus rule after 95%.
+or later than 75%, as long as they enforce it as consensus rule after 95%.
The current miners' voting mechanism can be modified to allow for
changes to be deployed in parallel, the rejection of a concrete
@@ -352,12 +355,12 @@ worth of blocks).
[5] Original references:
https://bitcointalk.org/index.php?topic=114751.0
https://bitcointalk.org/index.php?topic=43692.msg521772#msg521772
-Rebased patch:
+Rebased patch:
https://github.com/freicoin/freicoin/commit/beb2fa54745180d755949470466cbffd1cd6ff14
==Attribution==
-Incorporated corrections and suggestions from: Andy Chase, Bryan Bishop,
+Incorporated corrections and suggestions from: Andy Chase, Bryan Bishop,
Btcdrak, Gavin Andresen, Gregory Sanders, Luke Dashjr, Marco Falke.
==Copyright==
diff --git a/bip-0100.mediawiki b/bip-0100.mediawiki
new file mode 100644
index 0000000000..aaf6beb603
--- /dev/null
+++ b/bip-0100.mediawiki
@@ -0,0 +1,77 @@
+
+ BIP: 100
+ Layer: Consensus (hard fork)
+ Title: Dynamic maximum block size by miner vote
+ Author: Jeff Garzik
+ Tom Harding
+ Dagur Valberg Johannsson
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0100
+ Status: Rejected
+ Type: Standards Track
+ Created: 2015-06-11
+ License: BSD-2-Clause
+
+
+==Abstract==
+
+Replace the static 1M block size hard limit with a hard limit set by coinbase vote, conducted on the same schedule as difficulty retargeting.
+
+==Motivation==
+
+Miners directly feel the effects, both positive and negative, of any maximum block size change imposed by their peers. Larger blocks allow more growth in the on-chain ecosystem, while smaller blocks reduce resource requirements network-wide. Miners also act as an efficient proxy for the rest of the ecosystem, since they are paid in the tokens collected for the blocks they create.
+
+A simple deterministic system is specified, whereby a 75% mining supermajority may activate a change to the maximum block size each 2016 blocks. Each change is limited to a 5% increase from the previous block size hard limit, or a decrease of similar magnitude. Among adopting nodes, there will be no disagreement on the evolution of the maximum block size.
+
+The system is compatible with emergent consensus, but whereas under that system a miner may choose to accept any size block, a miner following BIP100 observes the 75% supermajority rule, and the 5% change limit rule. Excessive-block values signaled by emergent consensus blocks are considered in the calculation of the BIP100 block size hard limit, and the BIP100 calculated maximum block size is signaled as an excessive-block value for the benefit of all observers.
+
+==Specification==
+
+===Dynamic Maximum Block Size===
+# Initial value of hardLimit is 1000000 bytes, preserving current system.
+# Changing hardLimit is accomplished by encoding a proposed value, a vote, within a block's coinbase scriptSig, and by processing the votes contained in the previous retargeting period.
+## Vote encoding
+### A vote is represented as a megabyte value using the BIP100 pattern
/BIP100/B[0-9]+/
Example: /BIP100/B8/ is a vote for a 8000000-byte hardLimit.
+### If the block height is encoded at the start of the coinbase scriptSig, as per BIP34, it is ignored.
+### Only the first BIP100 pattern match is processed in "Maximum block size recalculation" below.
+### A megabyte value is represented by consecutive base-ten digits.
+### If no BIP100 pattern is matched, the first matching emergent consensus pattern /EB[0-9]+/, if any, is accepted as the megabyte vote.
+## Maximum block size recalculation
+### A new hardLimit is calculated after each difficulty adjustment period of 2016 blocks, and applies to the next 2016 blocks.
+### Absent/zero-valued votes are counted as votes for the current hardLimit.
+### The votes of the previous 2016 blocks are sorted by megabyte vote.
+### Raising hardLimit
+#### The raise value is defined as the vote of the 1512th highest block, converted to bytes.
+#### If the resultant raise value is greater than (current hardLimit * 1.05) rounded down, it is set to that value.
+#### If the resultant raise value is greater than current hardLimit, the raise value becomes the new hardLimit and the recalculation is complete.
+### Lowering hardLimit
+#### The lower value is defined as the vote of the 1512th lowest block, converted to bytes.
+#### If the resultant lower value is less than (current hardLimit / 1.05) rounded down, it is set to that value.
+#### If the resultant lower value is less than current hardLimit, the lower value becomes the new hardLimit and the recalculation is complete.
+### Otherwise, new hardLimit remains the same as current hardLimit.
+
+===Signature Hashing Operations Limits===
+# The per-block signature hashing operations limit is scaled to (actual block size, fractional megabyte rounded to next higher megabyte) / 50.
+# A maximum serialized transaction size of 1000000 bytes is imposed.
+
+==Recommendations==
+
+===Publication of hardLimit===
+# For the benefit of all observers, it is recommended that hardLimit be published. Example: a complete coinbase string might read
/BIP100/B8/EB2.123456/
which indicates a vote for 8M maximum block size, and an enforced hardLimit of 2.123456 megabytes for the block containing the coinbase string.
+
+==Deployment==
+
+This BIP is presumed deployed and activated as of block height 449568 by implementing nodes on the bitcoin mainnet. It has no effect until a raise value different from 1M is observed, which requires at least 1512 of 2016 blocks to vote differently from 1M.
+
+==Backward compatibility==
+
+The first block larger than 1M will create a network partition, as nodes with a fixed 1M hard limit reject that block.
+
+==Implementations==
+https://github.com/bitcoinxt/bitcoinxt/pull/188
+https://github.com/bitcoinxt/bitcoin/pull/1
+https://github.com/BitcoinUnlimited/BitcoinUnlimited/pull/398
+
+==Copyright==
+This document is licensed under the BSD 2-clause license.
+
diff --git a/bip-0101.mediawiki b/bip-0101.mediawiki
index a76db0f949..03215697bc 100644
--- a/bip-0101.mediawiki
+++ b/bip-0101.mediawiki
@@ -1,8 +1,11 @@
@@ -13,28 +16,29 @@ Simple, one-time increase in total amount of transaction data permitted in a blo
==Motivation==
-# Enable network growth.
-# Continue current economic policy of low fee pressure on average.
-# Exercise network upgrade procedure.
+# Continue current economic policy.
+# Exercise hard fork network upgrade.
==Specification==
-# Maximum block size permitted to be valid is 1MB.
-# Increase this maximum to 2MB as soon as 75% of the last 1,000 blocks have signaled support.
+# MAX_BLOCK_SIZE increased to 2,000,000 bytes at trigger point.
# Increase maximum block sigops by similar factor, preserving SIZE/50 formula.
+# Trigger: (1) Block time 00:00:00 on flag day, AND (2) 95% of the last 1,000 blocks have signaled support.
==Backward compatibility==
-Older clients are not compatible with this change. The first block exceeding 1,000,000 bytes will partition older clients off the new network.
+Fully validating older clients are not compatible with this change.
+The first block exceeding 1,000,000 bytes will partition older clients
+off the new network.
==Discussion==
-In the short term, an increase is needed to continue to facilitate
-network growth, and buy time for more comprehensive solutions to be
-developed. This continues the current economic policies with regards to
-fees, matching market expectations and preventing market disruption.
+In the short term, an increase is needed to continue to current
+economic policies with regards to fees and block space, matching
+market expectations and preventing market disruption.
-In the long term, continued direct management of this limit is a moral hazard that clouds free market input and prevents a healthy fee market from developing. This area of code should be transitioned away from direct management.
+In the long term, this limit should focus on reflecting the maximum
+network engineering limit.
==Implementation==
diff --git a/bip-0103.mediawiki b/bip-0103.mediawiki
index 39e8a3f644..3a8bab5aea 100644
--- a/bip-0103.mediawiki
+++ b/bip-0103.mediawiki
@@ -1,16 +1,24 @@
==Abstract==
This BIP proposes a block size growth intended to accommodate for hardware and other technological improvements for the foreseeable future.
+==Copyright==
+
+This BIP is licensed under the 2-clause BSD license.
+
==Motivation==
Many people want to see Bitcoin scale over time, allowing an increasing number of transactions on the block chain. It would come at an increased cost for the ecosystem (bandwidth, processing, and storage for relay nodes, as well as an impact on propagation speed of blocks on the network), but technology also improves over time. When all technologies depended on have improved as well as their availability on the market, there is no reason why Bitcoin's fundamental transaction rate cannot improve proportionally.
@@ -65,7 +73,7 @@ Using a time-based check is very simple to implement, needs little context, is e
==Compatibility==
-This is a hard forking change, thus breaks compatbility with old fully-validating node. It should not be deployed without widespread consensus.
+This is a hard forking change, thus breaks compatibility with old fully-validating node. It should not be deployed without widespread consensus.
==Acknowledgements==
diff --git a/bip-0104.mediawiki b/bip-0104.mediawiki
new file mode 100644
index 0000000000..4d81110af7
--- /dev/null
+++ b/bip-0104.mediawiki
@@ -0,0 +1,78 @@
+
+
+==Abstract==
+
+Automatic adjustment of max block size with the target of keeping blocks 75% full, based on the average block size of the previous 2016 blocks. This would be done on the same schedule as difficulty.
+
+==Motivation==
+
+Blocks are already too full and cannot support further transaction growth. While SegWit and Lightning (and other off-chain solutions) will help, they will not solve this problem.
+
+Bitcoin needs a reasonably effective and predictable way of managing the maximum block size which allows moderate growth, keeps max block size as small as possible, and prevents wild swings in transaction fees.
+
+The every two-week and automatic adjustment of difficulty has proven to be a reasonably effective and predictable way of managing how quickly blocks are mined. It works well because humans aren’t involved (except for setting the original target of a 10 minute per block average), and therefore it isn’t political or contentious. It’s simply a response to changing network resources.
+
+It’s clear at this point that human beings should not be involved in the determination of max block size, just as they’re not involved in deciding the difficulty. Therefore, it is logical and consistent with Bitcoin’s design to implement a permanent solution which, as with the difficulty adjustment, is simply an automatic response to changing transaction volumes. With the target of keeping blocks 75% full on average, this is the goal of Block75.
+
+
+==Specification==
+
+The max block size will be recalculated every 2016 blocks, along with difficulty, using Block75’s simple algorithm:
+
+
+new max block size = x + (x * (AVERAGE_CAPACITY - TARGET_CAPACITY))
+
+
+* TARGET_CAPACITY = 0.75 //Block75's target of keeping blocks 75% full
+* AVERAGE_CAPACITY = average percentage full of the last 2016 blocks, as a decimal
+* x = current max block size
+
+
+All code which generates/validates blocks or uses/references the current hardcoded limits will need to be changed to support Block75.
+
+==Rationale==
+
+The 75% full block target was selected because:
+* it is the middle ground between blocks being too small (average 100% full) and blocks being unnecessarily large (average 50% full)
+* it can handle short-term spikes in transaction volume of up to 33%
+* it limits the growth of max block size to less than 25% over the previous period
+* it will maintain average transaction fees at a stable level similar to that of May/June 2016
+
+The 2016 block (~2 weeks) period was selected because:
+* it has been shown to be reasonably adaptive to changing network resources (re: difficulty)
+* the frequent and gradual adjustments that result will be relatively easy for miners and node operators to predict and adapt to, as any unforeseen consequences will be visible well in advance
+* it minimizes any effect a malicious party could have in an attempt to manipulate max block size
+
+The Block75 algorithm will adjust the max block size up and down in response to transaction volume, including changes brought on by SegWit and Lightning. This is important as it will keep average transaction fees stable, thereby allowing miners and businesses using Bitcoin more certainty regarding future income/expenses.
+
+==Other solutions considered==
+A hardcoded increase to max block size (2MB, 8MB, etc.), rejected because:
+* only a temporary solution, whatever limit was chosen would inevitably become a problem again
+* would cause transaction fees to vary wildly over time
+
+Allow miners to vote for max block size, rejected because:
+* overly complex and political
+* human involvement makes this slow to respond to changing transaction volumes
+* focuses power over max block size to a relatively small group of people
+* unpredictable transaction fees caused by this would create uncertainty in the ecosystem
+
+==Backward Compatibility==
+This BIP is not backward compatible (hard fork). Any code which fully validates blocks must be upgraded prior to activation, as failure to do so will result in rejection of blocks over the current 1MB limit.
+
+==Activation==
+To help negate some of the risks associated with a hard fork and to prevent a single relatively small mining pool from preventing Block75's adoption, activation would occur at the next difficulty adjustment once 900 of the last 1,000 blocks mined signal support and a grace period of 4,032 blocks (~1 month) has elapsed.
+
+==Copyright==
+This BIP is dual-licensed under the BSD 2-clause license and the GNU All-Permissive License.
diff --git a/bip-0105.mediawiki b/bip-0105.mediawiki
index c4f0a09982..af416910df 100644
--- a/bip-0105.mediawiki
+++ b/bip-0105.mediawiki
@@ -1,29 +1,33 @@
==Abstract==
-A method of altering the maximum allowed block size of the Bitcoin protocol
+A method of altering the maximum allowed block size of the Bitcoin protocol
using a consensus based approach.
==Motivation==
-There is a belief that Bitcoin cannot easily respond to raising the
-blocksize limit if popularity was to suddenly increase due to a mass adoption
-curve, because co-ordinating a hard fork takes considerable time, and being
-unable to respond in a timely manner would irreparably harm the credibility of
+There is a belief that Bitcoin cannot easily respond to raising the
+blocksize limit if popularity was to suddenly increase due to a mass adoption
+curve, because co-ordinating a hard fork takes considerable time, and being
+unable to respond in a timely manner would irreparably harm the credibility of
bitcoin.
Additionally, predetermined block size increases are problematic because they
-attempt to predict the future, and if too large could have unintended
-consequences like damaging the possibility for a fee market to develop
-as block subsidy decreases substantially over the next 9 years; introducing
+attempt to predict the future, and if too large could have unintended
+consequences like damaging the possibility for a fee market to develop
+as block subsidy decreases substantially over the next 9 years; introducing
or exacerbating mining attack vectors; or somehow affect the network in unknown
or unpredicted ways. Since fixed changes are hard to deploy, the damage could be
extensive.
@@ -32,14 +36,14 @@ Dynamic block size adjustments also suffer from the potential to be gamed by the
larger hash power.
Free voting as suggested by BIP100 allows miners to sell their votes out of band
-at no risk, and enable the sponsor the ability to manipulate the blocksize.
+at no risk, and enable the sponsor the ability to manipulate the blocksize.
It also provides a cost free method or the larger pools to vote in ways to
manipulate the blocksize such to disadvantage or attack smaller pools.
==Rationale==
-By introducing a cost to increase the block size ensures the mining community
+By introducing a cost to increase the block size ensures the mining community
will collude to increase it only when there is a clear necessity, and reduce it
when it is unnecessary. Larger miners cannot force their wishes so easily
because not only will they have to pay extra a difficulty target, then can be
@@ -59,7 +63,7 @@ honest.
The initial block size limit shall be 1MB.
Each time a miner creates a block, they may vote to increase or decrease the
-blocksize by a maximum of 10% of the current block size limit. These votes will
+blocksize by a maximum of 10% of the current block size limit. These votes will
be used to recalculate the new block size limit every 2016 blocks.
Votes are cast using the block's coinbase transaction scriptSig.
@@ -73,7 +77,7 @@ If a miner votes for an increase, the block hash must meet a difficulty target
which is proportionally larger than the standard difficulty target based on the
percentage increase they voted for.
-Votes proposing decreasing the block size limit do not need to meet a higher
+Votes proposing decreasing the block size limit do not need to meet a higher
difficulty target.
Miners can vote for no change by voting for the current block size.
diff --git a/bip-0106.mediawiki b/bip-0106.mediawiki
index e9018fac9f..84b04980f2 100644
--- a/bip-0106.mediawiki
+++ b/bip-0106.mediawiki
@@ -1,8 +1,11 @@
@@ -33,13 +36,13 @@ https://blockchain.info/charts/avg-block-size?timespan=all&showDataPoints=false&
Keep the same MaxBlockSize
===Proposal 2 : Depending on previous block size calculation and previous Tx fee collected by miners===
-
+
TotalBlockSizeInLastButOneDifficulty = Sum of all Block size of first 2008 blocks in last 2 difficulty period
TotalBlockSizeInLastDifficulty = Sum of all Block size of second 2008 blocks in last 2 difficulty period (This actually includes 8 blocks from last but one difficulty)
-
+
TotalTxFeeInLastButOneDifficulty = Sum of all Tx fees of first 2008 blocks in last 2 difficulty period
TotalTxFeeInLastDifficulty = Sum of all Tx fees of second 2008 blocks in last 2 difficulty period (This actually includes 8 blocks from last but one difficulty)
-
+
If ( ( (Sum of first 4016 block size in last 2 difficulty period)/4016 > 50% MaxBlockSize) AND (TotalTxFeeInLastDifficulty > TotalTxFeeInLastButOneDifficulty) AND (TotalBlockSizeInLastDifficulty > TotalBlockSizeInLastButOneDifficulty) )
MaxBlockSize = TotalBlockSizeInLastDifficulty * MaxBlockSize / TotalBlockSizeInLastButOneDifficulty
Else If ( ( (Sum of first 4016 block size in last 2 difficulty period)/4016 < 50% MaxBlockSize) AND (TotalTxFeeInLastDifficulty < TotalTxFeeInLastButOneDifficulty) AND (TotalBlockSizeInLastDifficulty < TotalBlockSizeInLastButOneDifficulty) )
@@ -49,7 +52,7 @@ https://blockchain.info/charts/avg-block-size?timespan=all&showDataPoints=false&
==Rationale==
-These two proposals have been derived after discussion on [https://bitcointalk.org/index.php?topic=1154536.0 BitcoinTalk] and [http://lists.linuxfoundation.org/pipermail/bitcoin-dev/2015-August/010285.html bitcoin-dev mailing list]. The original idea and its evolution in the light of various arguements can be found [http://upalc.com/maxblocksize.php here].
+These two proposals have been derived after discussion on [https://bitcointalk.org/index.php?topic=1154536.0 BitcoinTalk] and [http://lists.linuxfoundation.org/pipermail/bitcoin-dev/2015-August/010285.html bitcoin-dev mailing list]. The original idea and its evolution in the light of various arguments can be found [http://upalc.com/maxblocksize.php here].
===Proposal 1 : Depending only on previous block size calculation===
diff --git a/bip-0107.mediawiki b/bip-0107.mediawiki
new file mode 100644
index 0000000000..915657aa70
--- /dev/null
+++ b/bip-0107.mediawiki
@@ -0,0 +1,87 @@
+
+ BIP: 107
+ Layer: Consensus (hard fork)
+ Title: Dynamic limit on the block size
+ Author: Washington Y. Sanchez
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0107
+ Status: Rejected
+ Type: Standards Track
+ Created: 2015-09-11
+ License: PD
+
+
+==Abstract==
+
+This BIP proposes a dynamic limit to the block size based on transaction volume.
+
+==Motivation==
+
+Over the next few years, large infrastructure investments will be made into:
+
+# Improving global network connectivity
+# Improving block propagation across the Bitcoin network
+# Layer 2 services and networks for off-chain transactions
+# General efficiency improvements to transactions and the blockchain
+
+* While there is a consensus between Bitcoin developers, miners, businesses and users that the block size needs to be increased, there is a lingering concern over the potential unintended consequences that may augment the trend towards network and mining centralization (largely driven by mining hardware such as ASICs) and thereby threaten the security of the network.
+* In contrast, failing to respond to elevated on-chain transaction volume may lead to a consumer-failure of Bitcoin, where ordinary users - having enjoyed over 6 years of submitting transactions on-chain at relatively low cost - will be priced out of blockchain with the emergence of a prohibitive 'fee market'.
+* These two concerns must be delicately balanced so that all users can benefit from a robust, scalable, and neutral network.
+
+==Specification==
+
+* Increases in the block size will occur in 2 phases
+* '''Phase 1'''
+** The block size will be increased similar to [[https://twitter.com/adam3us/status/636410827969421312|Adam Back's proposal]], as a safe runway prior to switching to Phase 2, while network and protocol infrastructure is improved
+** The schedule:
+*** ''2016-2017:'' 2 MB
+*** ''2018-2019:'' 4 MB
+*** ''2020:'' 6 MB
+* '''Phase 2'''
+** In 2020, the maximum block size will be increased dynamically according to sustained increases in transaction volume
+** Every 4032 blocks (~4 weeks), a CHECK will be performed to determine if a raise in the maximum block size should occur
+*** This calculates to a theoretical maximum of 13 increases per year
+** IF of the last >= 3025 blocks were >=60% full, the maximum block size will be increased by 10%
+** The maximum block size can only ever be increased, not decreased
+* The default limitfreerelay will also be raised in proportion to maximum block size increases
+** Transactions without fees can continue to be submitted and relayed on the network as per normal
+** limitfreerelay also helps counter attempts to trigger a block size increase by 'penny-flooding'
+
+For example:
+* When the dynamic rules for increasing the block size go live on January 1st 2020, the starting maximum block size will be 6 MB
+* IF >=3025 blocks are >= 3.6 MB, the new maximum block size become 6.6 MB.
+* The theoretical maximum block size at the end of 2020 would be ~20.7 MB, assuming all 13 increases are triggered every 4 weeks by the end of the year.
+
+==Rationale==
+
+* '''Phase 1'''
+** This runway has a schedule for conservative increases to the block size in order to relieve transaction volume pressure while allowing network and protocol infrastructure improvements to be made, as well as layer 2 services to emerge
+* '''Phase 2'''
+** Why 60% full blocks?
+*** IF blocks are 60% full, they count as a ''vote'' towards increasing the block size
+*** If this parameter is too low, the trigger sensitivity may be too high and vulnerable to spam attacks or miner collusion
+*** Setting the parameter too high may set the trigger sensitivity too low, causing transaction delays that are trying to be avoided in the first place
+*** Between September 2013-2015, the standard deviation measured from average block size (n=730 data points from blockchain.info) was ~ 0.13 MB or 13% of the maximum block size
+**** If blocks needed to be 90% full before an increase were triggered, normal variance in the average block size would mean some blocks would be full before an increase could be triggered
+*** Therefore, we need a ''safe distance'' away from the maximum block size to avoid normal block size variance hitting the limit. The 60% level represents a 3 standard deviation distance from the limit.
+** Why 3025 blocks?
+*** The assessment period is 4032 blocks or ~ 4 weeks, with the threshold set as 4032 blocks/0.75 + 1
+*** Increases in the maximum block size should only occur after a sustained trend can be observed in order to:
+***# Demonstrate a market-driven secular elevation in the transaction volume
+***# Increase the cost to trigger an increase by spam attacks or miner collusion with zero fee transactions
+*** In other words, increases to the maximum block size must be conservative but meaningful to relieve transaction volume pressure in response to true market demand
+** Why 10% increase in the block size?
+*** Increases in the block size are designed to be conservative and in balance with the number of theoretical opportunities to increase the block size per year
+*** Makes any resources spent for spam attacks or miner collusion relatively expensive to achieve a minor increase in the block size. A sustained attack would need to be launched that may be too costly, and ideally detectable by the community
+
+==Deployment==
+Similar deployment model to BIP101:
+
Activation is achieved when 750 of 1,000 consecutive blocks in the best chain have a version number with the first, second, third, and thirtieth bits set (0x20000007 in hex). The activation time will be the timestamp of the 750'th block plus a two week (1,209,600 second) grace period to give any remaining miners or services time to upgrade to support larger blocks.
+
+==Acknowledgements==
+
+Thanks to Austin Williams, Brian Hoffman, Angel Leon, Bulukani Mlalazi, Chris Pacia, and Ryan Shea for their comments.
+
+==Copyright==
+
+This work is placed in the public domain.
diff --git a/bip-0109.mediawiki b/bip-0109.mediawiki
new file mode 100644
index 0000000000..ec1d7e5bc6
--- /dev/null
+++ b/bip-0109.mediawiki
@@ -0,0 +1,86 @@
+
+ BIP: 109
+ Layer: Consensus (hard fork)
+ Title: Two million byte size limit with sigop and sighash limits
+ Author: Gavin Andresen
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0109
+ Status: Rejected
+ Type: Standards Track
+ Created: 2016-01-28
+ License: PD
+
+
+==Abstract==
+
+One-time increase in total amount of transaction data permitted in a block from 1MB to 2MB, with limits on signature operations and hashing.
+
+==Motivation==
+
+# Continue current economic policy.
+# Exercise hard fork network upgrade.
+# Mitigate potential CPU exhaustion attacks
+
+==Specification==
+
+=== MAX_BLOCK_SIZE increased to 2,000,000 bytes ===
+
+The maximum number of bytes in a canonically serialized block shall be increased from
+1,000,000 bytes to 2,000,000 bytes.
+
+=== Switch to accurately-counted sigop limit of 20,000 per block ===
+
+The existing MAX_SIGOPS limit of 20,000 signature operations per block shall be retained,
+but only ECDSA verifications actually performed to validate the block shall be counted.
+
+In particular:
+
+* The coinbase scriptSig is not counted
+* Signature operations in un-executed branches of a Script are not counted
+* OP_CHECKMULTISIG evaluations are counted accurately; if the signature for a 1-of-20 OP_CHECKMULTISIG is satisfied by the public key nearest the top of the execution stack, it is counted as one signature operation. If it is satisfied by the public key nearest the bottom of the execution stack, it is counted as twenty signature operations.
+* Signature operations involving invalidly encoded signatures or public keys are not counted towards the limit
+
+=== Add a new limit of 1,300,000,000 bytes hashed to compute transaction signatures per block ===
+
+The amount of data hashed to compute signature hashes is limited to 1,300,000,000 bytes per block. The same rules for counting are used as for counting signature operations.
+
+=== Activation: 75% hashpower support trigger, followed by 28-day 'grace period' ===
+
+Solo miners or mining pool operators express their support for this BIP by setting the fourth-highest-bit in the block's 32-bit version number (0x10000000 in hex). The first block with that bit set, a timestamp less than or equal to the expiration time, and with at least 750 out of 1000 blocks preceding it (with heights H-1000..H-1) with that bit set, shall define the beginning of a grace period. Blocks with timestamps greater than or equal to the triggering block's timestamp plus 28 days (60*60*24*28 seconds) shall be subject to the new limits.
+
+As always, miners are expected to use their best judgement for what is best for the entire Bitcoin ecosystem when making decisions about what consensus-level changes to support.
+
+=== Expiration: 1-Jan-2018 ===
+
+If this BIP is not triggered before 1-Jan-2018 00:00:00 GMT it should be considered withdrawn.
+
+Miners that support this BIP should set bit 0x10000000 in the block version until 1-Jan-2018. After that date, that bit can be safely re-used for future consensus rule upgrades.
+
+==Backward compatibility==
+
+Fully validating older clients are not compatible with this change.
+The first block exceeding the old limits on block size or inaccurately counted signature operations will partition older clients off the new network.
+
+SPV (simple payment validation) wallets are compatible with this change.
+
+==Rationale==
+
+In the short term, an increase is needed to handle increasing transaction volume.
+
+The limits on signature operations and amount of signature hashing done prevent possible CPU exhaustion attacks by "rogue miners" producing very expensive-to-validate two megabyte blocks. The signature hashing limit is chosen to be impossible to reach with any non-attack transaction or block, to minimize the impact on existing mining or wallet software.
+
+The choices of constants for the deployment scheme were motivated by prior experience with upgrades to the Bitcoin consensus rules:
+
+* 0x10000000 was chosen to be compatible with the BIP 9 proposal for parallel deployment of soft forks
+* 75% was chosen instead of 95% to minimize the opportunity for a single large mining pool or miner to be able to veto an increase, either because of ideological opposition or threat of violence or extortion.
+* A four-week grace period after the voting period was chosen as a balance between giving people sufficient time to upgrade and keeping people's attention on the urgent need to upgrade.
+
+==Implementation==
+
+https://github.com/gavinandresen/bitcoin-git/tree/two_mb_bump
+
+See also http://gavinandresen.ninja/a-guided-tour-of-the-2mb-fork
+
+==Copyright==
+
+This work is placed in the public domain.
diff --git a/bip-0111.mediawiki b/bip-0111.mediawiki
index d3bd630b8e..cb5028f5e0 100644
--- a/bip-0111.mediawiki
+++ b/bip-0111.mediawiki
@@ -1,10 +1,15 @@
BIP: 111
+ Layer: Peer Services
Title: NODE_BLOOM service bit
- Author: Matt Corallo , Peter Todd
- Status: Draft
+ Author: Matt Corallo
+ Peter Todd
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0111
+ Status: Proposed
Type: Standards Track
Created: 2015-08-20
+ License: PD
BIP: 112
+ Layer: Consensus (soft fork)
Title: CHECKSEQUENCEVERIFY
- Authors: BtcDrak
- Mark Friedenbach
- Eric Lombrozo
- Status: Draft
+ Author: BtcDrak
+ Mark Friedenbach
+ Eric Lombrozo
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0112
+ Status: Final
Type: Standards Track
Created: 2015-08-10
+ License: PD
==Abstract==
@@ -22,16 +26,17 @@ being spent.
CHECKSEQUENCEVERIFY redefines the existing NOP3 opcode.
When executed, if any of the following conditions are true, the script interpreter will terminate with an error:
+* the stack is empty; or
* the top item on the stack is less than 0; or
* the top item on the stack has the disable flag (1 << 31) unset; and
** the transaction version is less than 2; or
-** the transaction input sequence number disable flag (1 << 31) is set; and
+** the transaction input sequence number disable flag (1 << 31) is set; or
** the relative lock-time type is not the same; or
-** the top stack item is greater than the transaction sequence (when masked according to the BIP68);
+** the top stack item is greater than the transaction input sequence (when masked according to the BIP68);
Otherwise, script execution will continue as if a NOP had been executed.
-BIP 68 prevents a non-final transaction from being selected for inclusion in a block until the corresponding input has reached the specified age, as measured in block-height or block-time. By comparing the argument to CHECKSEQUENCEVERIFY against the nSequence field, we indirectly verify a desired minimum age of the
+BIP 68 prevents a non-final transaction from being selected for inclusion in a block until the corresponding input has reached the specified age, as measured in block-height or block-time. By comparing the argument to CHECKSEQUENCEVERIFY against the nSequence field, we indirectly verify a desired minimum age of
the output being spent; until that relative age has been reached any script execution pathway including the CHECKSEQUENCEVERIFY will fail to validate, causing the transaction not to be selected for inclusion in a block.
@@ -58,19 +63,19 @@ established in the following way. Alice, Bob and Escrow create a 2-of-3
address with the following redeemscript.
IF
- 2 3 CHECKMULTISIGVERIFY
+ 2 3 CHECKMULTISIG
ELSE
"30d" CHECKSEQUENCEVERIFY DROP
- CHECKSIGVERIFY
+ CHECKSIG
ENDIF
-At any time funds can be spent using signatures from any two of Alice,
+At any time funds can be spent using signatures from any two of Alice,
Bob or the Escrow.
After 30 days Alice can sign alone.
The clock does not start ticking until the payment to the escrow address
-confirms.
+confirms.
===Retroactive Invalidation===
@@ -137,10 +142,10 @@ A simple output, paying to Alice might then look like:
HASH160 EQUAL
IF
-
+
ELSE
"24h" CHECKSEQUENCEVERIFY DROP
-
+
ENDIF
CHECKSIG
@@ -152,10 +157,10 @@ With CHECKLOCKTIMEVERIFY, this would look like:
HASH160 EQUAL
IF
-
+
ELSE
"2015/12/15" CHECKLOCKTIMEVERIFY DROP
-
+
ENDIF
CHECKSIG
@@ -180,13 +185,13 @@ Alice might look like the following in Alice's commitment transaction:
IF
"24h" CHECKSEQUENCEVERIFY
2DROP
-
+
ELSE
EQUAL
NOTIF
- "24h" CHECKLOCKTIMEVERIFY DROP
+ "2015/10/20 10:33" CHECKLOCKTIMEVERIFY DROP
ENDIF
-
+
ENDIF
CHECKSIG
@@ -195,12 +200,12 @@ and correspondingly in Bob's commitment transaction:
HASH160 DUP EQUAL
SWAP EQUAL ADD
IF
-
+
ELSE
"2015/10/20 10:33" CHECKLOCKTIMEVERIFY
"24h" CHECKSEQUENCEVERIFY
2DROP
-
+
ENDIF
CHECKSIG
@@ -225,134 +230,129 @@ The 2-way pegged sidechain requires a new REORGPROOFVERIFY opcode, the semantics
==Specification==
-Refer to the reference implementation, reproduced below, for the precise
+Refer to the reference implementation, reproduced below, for the precise
semantics and detailed rationale for those semantics.
-
- /* If this flag set, CTxIn::nSequence is NOT interpreted as a
- * relative lock-time. */
- static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG = (1 << 31);
-
- /* If CTxIn::nSequence encodes a relative lock-time and this flag
- * is set, the relative lock-time has units of 512 seconds,
- * otherwise it specifies blocks with a granularity of 1. */
- static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG = (1 << 22);
-
- /* If CTxIn::nSequence encodes a relative lock-time, this mask is
- * applied to extract that lock-time from the sequence field. */
- static const uint32_t SEQUENCE_LOCKTIME_MASK = 0x0000ffff;
-
- case OP_NOP3:
- {
- if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
- // not enabled; treat as a NOP3
- if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
- return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
- }
- break;
+
+/* Below flags apply in the context of BIP 68 */
+/* If this flag set, CTxIn::nSequence is NOT interpreted as a
+ * relative lock-time. */
+static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG = (1 << 31);
+
+/* If CTxIn::nSequence encodes a relative lock-time and this flag
+ * is set, the relative lock-time has units of 512 seconds,
+ * otherwise it specifies blocks with a granularity of 1. */
+static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG = (1 << 22);
+
+/* If CTxIn::nSequence encodes a relative lock-time, this mask is
+ * applied to extract that lock-time from the sequence field. */
+static const uint32_t SEQUENCE_LOCKTIME_MASK = 0x0000ffff;
+
+case OP_NOP3:
+{
+ if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
+ // not enabled; treat as a NOP3
+ if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
+ return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
}
-
- if (stack.size() < 1)
- return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
-
- // Note that elsewhere numeric opcodes are limited to
- // operands in the range -2**31+1 to 2**31-1, however it is
- // legal for opcodes to produce results exceeding that
- // range. This limitation is implemented by CScriptNum's
- // default 4-byte limit.
- //
- // Thus as a special case we tell CScriptNum to accept up
- // to 5-byte bignums, which are good until 2**39-1, well
- // beyond the 2**32-1 limit of the nSequence field itself.
- const CScriptNum nSequence(stacktop(-1), fRequireMinimal, 5);
-
- // In the rare event that the argument may be < 0 due to
- // some arithmetic being done first, you can always use
- // 0 MAX CHECKSEQUENCEVERIFY.
- if (nSequence < 0)
- return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
-
- // To provide for future soft-fork extensibility, if the
- // operand has the disabled lock-time flag set,
- // CHECKSEQUENCEVERIFY behaves as a NOP.
- if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
- break;
-
- // Compare the specified sequence number with the input.
- if (!checker.CheckSequence(nSequence))
- return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
-
break;
}
-
- bool TransactionSignatureChecker::CheckSequence(const CScriptNum& nSequence) const
- {
- // Relative lock times are supported by comparing the passed
- // in operand to the sequence number of the input.
- const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
-
- // Fail if the transaction's version number is not set high
- // enough to trigger BIP 68 rules.
- if (static_cast(txTo->nVersion) < 2)
- return false;
-
- // Sequence numbers with their most significant bit set are not
- // defined by BIP68. Testing that the transaction's sequence
- // number do not have this bit set prevents using this property
- // to get around a CHECKSEQUENCEVERIFY check.
- if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
- return false;
-
- // Mask off any bits that do not have BIP68 consensus-enforced meaning
- // before doing the integer comparisons of ::VerifySequence.
- const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG
- | CTxIn::SEQUENCE_LOCKTIME_MASK;
-
- if (!::VerifySequence(txToSequence & nLockTimeMask,
- CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG,
- nSequence & nLockTimeMask))
- return false;
-
- return true;
- }
-
- static bool VerifySequence(int64_t txToSequence, int64_t nThreshold, const CScriptNum& nSequence)
- {
- // There are two kinds of nLockTime: lock-by-blockheight
- // and lock-by-blocktime, distinguished by whether
- // nSequence < nThreshold (CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG).
- //
- // We want to compare apples to apples, so fail the script
- // unless the type of nSequence being tested is the same as
- // the nSequence in the transaction.
- if (!(
- (txToSequence < nThreshold && nSequence < nThreshold) ||
- (txToSequence >= nThreshold && nSequence >= nThreshold)
- ))
- return false;
-
- // Now that we know we're comparing apples-to-apples, the
- // comparison is a simple numeric one.
- if (nSequence > txToSequence)
- return false;
-
- return true;
- }
+ if (stack.size() < 1)
+ return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
+
+ // Note that elsewhere numeric opcodes are limited to
+ // operands in the range -2**31+1 to 2**31-1, however it is
+ // legal for opcodes to produce results exceeding that
+ // range. This limitation is implemented by CScriptNum's
+ // default 4-byte limit.
+ //
+ // Thus as a special case we tell CScriptNum to accept up
+ // to 5-byte bignums, which are good until 2**39-1, well
+ // beyond the 2**32-1 limit of the nSequence field itself.
+ const CScriptNum nSequence(stacktop(-1), fRequireMinimal, 5);
+
+ // In the rare event that the argument may be < 0 due to
+ // some arithmetic being done first, you can always use
+ // 0 MAX CHECKSEQUENCEVERIFY.
+ if (nSequence < 0)
+ return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
+
+ // To provide for future soft-fork extensibility, if the
+ // operand has the disabled lock-time flag set,
+ // CHECKSEQUENCEVERIFY behaves as a NOP.
+ if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
+ break;
+
+ // Compare the specified sequence number with the input.
+ if (!checker.CheckSequence(nSequence))
+ return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
+
+ break;
+}
+
+bool TransactionSignatureChecker::CheckSequence(const CScriptNum& nSequence) const
+{
+ // Relative lock times are supported by comparing the passed
+ // in operand to the sequence number of the input.
+ const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
+
+ // Fail if the transaction's version number is not set high
+ // enough to trigger BIP 68 rules.
+ if (static_cast(txTo->nVersion) < 2)
+ return false;
+
+ // Sequence numbers with their most significant bit set are not
+ // consensus constrained. Testing that the transaction's sequence
+ // number do not have this bit set prevents using this property
+ // to get around a CHECKSEQUENCEVERIFY check.
+ if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
+ return false;
+
+ // Mask off any bits that do not have consensus-enforced meaning
+ // before doing the integer comparisons
+ const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK;
+ const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
+ const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
+
+ // There are two kinds of nSequence: lock-by-blockheight
+ // and lock-by-blocktime, distinguished by whether
+ // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
+ //
+ // We want to compare apples to apples, so fail the script
+ // unless the type of nSequenceMasked being tested is the same as
+ // the nSequenceMasked in the transaction.
+ if (!(
+ (txToSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
+ (txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG)
+ ))
+ return false;
+
+ // Now that we know we're comparing apples-to-apples, the
+ // comparison is a simple numeric one.
+ if (nSequenceMasked > txToSequenceMasked)
+ return false;
+
+ return true;
+}
+
==Reference Implementation==
A reference implementation is provided by the following pull request:
-https://github.com/bitcoin/bitcoin/pull/6564
+https://github.com/bitcoin/bitcoin/pull/7524
==Deployment==
-This BIP is to be deployed by either version-bits BIP9 or by isSuperMajority(). Exact details TDB.
+This BIP is to be deployed by "versionbits" BIP9 using bit 0.
-It is recommended to deploy BIP68 and BIP113 at the same time as this BIP.
+For Bitcoin '''mainnet''', the BIP9 '''starttime''' will be midnight 1st May 2016 UTC (Epoch timestamp 1462060800) and BIP9 '''timeout''' will be midnight 1st May 2017 UTC (Epoch timestamp 1493596800).
+For Bitcoin '''testnet''', the BIP9 '''starttime''' will be midnight 1st March 2016 UTC (Epoch timestamp 1456790400) and BIP9 '''timeout''' will be midnight 1st May 2017 UTC (Epoch timestamp 1493596800).
+
+This BIP must be deployed simultaneously with BIP68 and BIP113 using the same deployment mechanism.
==Credits==
@@ -370,6 +370,8 @@ Thanks to Eric Lombrozo and Anthony Towns for contributing example use cases.
==References==
+[https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki BIP 9] Versionbits
+
[https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki BIP 68] Relative lock-time through consensus-enforced sequence numbers
[https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki BIP 65] OP_CHECKLOCKTIMEVERIFY
@@ -386,7 +388,7 @@ Thanks to Eric Lombrozo and Anthony Towns for contributing example use cases.
[http://lists.linuxfoundation.org/pipermail/bitcoin-dev/2015-August/010396.html Softfork deployment considerations]
-[https://gist.github.com/sipa/bf69659f43e763540550 Version bits]
+[https://web.archive.org/web/20210925124425/https://gist.github.com/sipa/bf69659f43e763540550 Version bits]
[https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2013-April/002433.html Jeremy Spilman Micropayment Channels]
diff --git a/bip-0113.mediawiki b/bip-0113.mediawiki
index 190fb4cc13..d736280931 100644
--- a/bip-0113.mediawiki
+++ b/bip-0113.mediawiki
@@ -1,11 +1,15 @@
BIP: 113
+ Layer: Consensus (soft fork)
Title: Median time-past as endpoint for lock-time calculations
Author: Thomas Kerin
- Mark Friedenbach
- Status: Draft
+ Mark Friedenbach
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0113
+ Status: Final
Type: Standards Track
Created: 2015-08-10
+ License: PD
@@ -34,19 +38,20 @@ value to monotonically advance, thereby removing the capability for
miners to claim more transaction fees by lying about the timestamps of
their block.
-This proposal seeks to ensure reliable behaviour in locktime calculations as
-required by BIP65 (CHECKLOCKTIMEVERIFY), BIP68 (sequence numbers), and BIP112 (CHECKSEQUENCEVERIFY).
+This proposal seeks to ensure reliable behaviour in locktime calculations
+as required by BIP65 (CHECKLOCKTIMEVERIFY) and matching the behavior of
+BIP68 (sequence numbers) and BIP112 (CHECKSEQUENCEVERIFY).
==Specification==
-The values for transaction locktime remain unchanged. The difference is only in
-the calculation determining whether a transaction can be included. Instead of
-an unreliable timestamp, the following function is used to determine the current
+The values for transaction locktime remain unchanged. The difference is only in
+the calculation determining whether a transaction can be included. Instead of
+an unreliable timestamp, the following function is used to determine the current
block time for the purpose of checking lock-time constraints:
enum { nMedianTimeSpan=11 };
-
+
int64_t GetMedianTimePast(const CBlockIndex* pindex)
{
int64_t pmedian[nMedianTimeSpan];
@@ -58,11 +63,12 @@ block time for the purpose of checking lock-time constraints:
return pbegin[(pend - pbegin)/2];
}
-Lock-time constraints are checked by the consensus method IsFinalTx(),
-or LockTime() under BIP68. These methods take the block time as one
-parameter. This BIP proposes that after activation calls to
-IsFinalTx() or LockTime() within consensus code use the return value
-of `GetMedianTimePast(pindexPrev)` instead.
+Lock-time constraints are checked by the consensus method IsFinalTx().
+This method takes the block time as one parameter. This BIP proposes
+that after activation calls to IsFinalTx() within consensus code use
+the return value of `GetMedianTimePast(pindexPrev)` instead.
+
+The new rule applies to all transactions, including the coinbase transaction.
A reference implementation of this proposal is provided by the
following pull request:
@@ -72,33 +78,13 @@ https://github.com/bitcoin/bitcoin/pull/6566
==Deployment==
-We reuse the double-threshold switchover mechanism from BIPs 34 and
-66, with the same thresholds, but for nVersion = 8. The new rules are
-in effect for every block (at height H) with nVersion = 8 and at least
-750 out of 1000 blocks preceding it (with heights H-1000..H-1) also
-have nVersion = 8. Furthermore, when 950 out of the 1000 blocks
-preceding a block do have nVersion = 8, nVersion = 3 blocks become
-invalid, and all further blocks enforce the new rules.
-
-When assessing the block version as mask of ~0x20000007 must be applied
-to work around the complications caused by
-[http://lists.linuxfoundation.org/pipermail/bitcoin-dev/2015-August/010396.html BIP101's premature use]
-of the [https://gist.github.com/sipa/bf69659f43e763540550 undecided version bits proposal].
-
-By applying ~0x20000007 with nVersion = 8, the thresholds should be tested
-comparing block nVersion >= 4 as this will save a bit for future use.
+This BIP is to be deployed by "versionbits" BIP9 using bit 0.
-It is recommended that this soft-fork deployment trigger include other related
-proposals for improving Bitcoin's lock-time capabilities, including:
+For Bitcoin '''mainnet''', the BIP9 '''starttime''' will be midnight 1st May 2016 UTC (Epoch timestamp 1462060800) and BIP9 '''timeout''' will be midnight 1st May 2017 UTC (Epoch timestamp 1493596800).
-[https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki BIP 65]:
-CHECKLOCKTIMEVERIFY,
+For Bitcoin '''testnet''', the BIP9 '''starttime''' will be midnight 1st March 2016 UTC (Epoch timestamp 1456790400) and BIP9 '''timeout''' will be midnight 1st May 2017 UTC (Epoch timestamp 1493596800).
-[https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki BIP 68]:
-Consensus-enforced transaction replacement signalled via sequence numbers,
-
-and [https://github.com/bitcoin/bips/blob/master/bip-0112.mediawiki BIP 112]:
-CHECKSEQUENCEVERIFY.
+This BIP must be deployed simultaneously with BIP68 and BIP112 using the same deployment mechanism.
==Acknowledgements==
@@ -121,6 +107,9 @@ concerns with existing protocols.
==References==
+
+[https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki BIP9: Versionbits]
+
[https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki BIP65: OP_CHECKLOCKTIMEVERIFY]
[https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki BIP68: Consensus-enforced transaction replacement signaled via sequence numbers]
diff --git a/bip-0114.mediawiki b/bip-0114.mediawiki
new file mode 100644
index 0000000000..5b0713747e
--- /dev/null
+++ b/bip-0114.mediawiki
@@ -0,0 +1,380 @@
+
+ BIP: 114
+ Layer: Consensus (soft fork)
+ Title: Merkelized Abstract Syntax Tree
+ Author: Johnson Lau
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0114
+ Status: Rejected
+ Type: Standards Track
+ Created: 2016-04-02
+ License: PD
+
+
+==Abstract==
+This BIP defines a new witness program type that uses a Merkle tree to encode mutually exclusive branches in a script. This enables complicated redemption conditions that are currently not possible, improves privacy by hiding unexecuted scripts, and allows inclusion of non-consensus enforced data with very low or no additional cost.
+
+==Motivation==
+===Evolution of Bitcoin script system===
+Bitcoin uses a script system to specify the conditions for redemption of transaction outputs. In its original design, the conditions for redemption are directly recorded in the scriptPubKey by the sender of the funds. This model has several drawbacks, particularly for complicated scripts:
+# It could be difficult for the receiver to specify the conditions;
+# Large scripts take up more UTXO space;
+# The sender will pay for the additional block space;
+# To prevent DoS attack, scripts are limited to 10,000 bytes and 201 op codes;
+# Any unexecuted branches and non-consensus enforced data in the script are visible to the public, consuming block space while damaging privacy.
+
+The [[bip-0016.mediawiki|BIP16]] (Pay-to-script-hash, "P2SH") fixes the first 3 problems by using a fixed-length 20-byte script hash in the scriptPubKey, and moving the responsibility for supplying the script to the redeemer. However, due to the data push size limit in script, a P2SH script may not be bigger than 520 bytes. Also, P2SH still requires the redeemer to publish all unexecuted branches of the script.
+
+The [[bip-0141.mediawiki|BIP141]] defines 2 new types of scripts that support segregated witness. The pay-to-witness-script-hash (P2WSH) is similar to P2SH is many ways. By supplying the script in witness, P2WSH restores the original 10,000 byte script limit. However, it still requires publishing of unexecuted branches.
+
+===Merkelized Abstract Syntax Tree===
+The idea of Merkelized Abstract Syntax Tree (MAST) is to use a Merkle tree to encode branches in a script. When spending, users may provide only the branches they are executing, and hashes that connect the branches to the fixed size Merkel root. This reduces the size of redemption stack from O(n) to O(log n) (n as the number of branches). This enables complicated redemption conditions that is currently not possible due to the script size and opcode limit, improves privacy by hiding unexecuted branches, and allows inclusion of non-consensus enforced data with very low or no additional cost.
+
+==Specification==
+In [[bip-0141.mediawiki|BIP141]], witness programs with a version byte of 1 or larger are considered to be anyone-can-spend scripts. The following new validation rules are applied if the witness program version byte is 1 and the program size is 32 bytes.If the version byte is 1, but the witness program is not 32 bytes, no further interpretation of the witness program or witness stack happens. This is reserved for future extensions. The witness program is the MAST Root.
+
+To redeem an output of this kind, the witness must consist of the following items:
+
+
+ Script_stack_1
+ Script_stack_2
+ .
+ .
+ Script_stack_X (X ≥ 0)
+ Subscript_1
+ Subscript_2
+ .
+ .
+ Subscript_Y (1 ≤ Y ≤ 255)
+ Position
+ Path
+ Metadata (Y|MAST Version)
+
+
+Metadata is the last witness item. It is a vector of 1 to 5 bytes. The first byte is an unsigned integer between 1 to 255 denoting the number of Subscript (defined hereinafter). The following 0 to 4 byte(s) is an unsigned little-endian integer denoting the MAST version. MAST Version must be minimally encoded (the most significant byte must not be 0).
+
+Path is the second last witness item. It is a serialized Merkle path of the Script Hash (defined hereinafter). Size of Path must be a multiple of 32 bytes, and not more than 1024 bytes. Each 32 byte word is a double-SHA256 merkle node in the merkle branch connecting to the Script Root (defined hereinafter). Depth of the tree (0 to 32) is the size of Path divided by 32.
+
+Position is the third last witness item. It indicates the location of the Script Hash in the Merkle tree, with zero indicating the leftmost position. It is an unsigned little-endian integer with not more than 4 bytes. It must be minimally encoded: the value must not be larger than the maximum number of items allowed by the Depth of the tree, and the most significant byte must not be 0. For example, if Depth is 4, the valid range of Position is 0 to 15 (24-1).
+
+Depends on the first byte of Metadata, there should be 1 to 255 Subscript witness item(s) before Position.
+
+Script Hash is defined as:
+
+ Script Hash = H(Y|H(Subscript_1)|H(Subscript_2)|...|H(Subscript_Y))
+ H() = SHA256(SHA256())
+
+where Y is a 1-byte value denoting number of Subscript, followed by the hash of each Subscript
+
+Script Root is the Merkle root calculated by the ComputeMerkleRootFromBranch function, using Script Hash, Path and Position.
+
+MAST Root is H(MAST Version|Script Root). The pre-image has a fixed size of 36 bytes: 4 bytes for MAST Version (unsigned little-endian integer) and 32 bytes for Script Root.
+
+The script evaluation fails if MAST Root does not match the witness program.
+
+If the MAST Root matches the witness program and MAST Version is greater than 0, the script returns a success without further evaluation. SigOpsCost is counted as 0. This is reserved for future script upgrades.
+
+If the MAST Version is 0, the Subscript(s) are serialized to form the final MAST Script, beginning with Subscript_1. The unused witness item(s) before the Subscript_1 are used as Input Stack to feed to the MASTScript. (Similar to P2WSH in BIP141)
+
+The script fails with one of the following conditions:
+* MAST Script is malformed (i.e. not enough data provided for the last push operation). Individual Subscript might be malformed, as long as they are serialized into a valid MAST Script
+* Size of MAST Script is larger than 10,000 bytes
+* Size of any one of the Input Stack item is larger than 520 bytes
+* Number of non-push operations (nOpCount) is more than 201. nOpCount is the sum of the number of non-push operations in MAST Script (counted in the same way as P2WSH witnessScript), number of Subscript (Y), and Depth of the Merkle tree.
+
+The MAST Script is then evaluated with the Input Stack (with some new or redefined opcodes described in BIPXXX). The evaluation must not fail, and result in an exactly empty stack.
+
+Counting of SigOpsCost is based on the MAST Script, described in BIPYYY.
+
+== Rationale ==
+=== MAST Structure ===
+This proposal is a restricted case of more general MAST. In a general MAST design, users may freely assign one or more script branches for execution. In this proposal, only one branch is allowed for execution, and users are required to transform a complicated condition into several mutually exclusive branches. For example, if the desired redeem condition is:
+
+ (A or B) and (C or D or E) and (F or G)
+
+In a general MAST design, the 7 branches (A to G) will form a 3-level Merkle tree, plus an "overall condition" describing the relationship of different branches. In redemption, the "overall condition", executed branches (e.g. B, D, F), and Merkle path data will be provided for validation.
+
+In the current proposal, the user has to transform the redeem condition into 12 mutually exclusive branches and form a 4-level Merkle tree, and present only one branch in redemption:
+
+
+ A and C and F
+ B and C and F
+ A and D and F
+ .
+ .
+ B and E and G
+
+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.
+
+The advantages of the current proposal are:
+* Subscript are located at a fixed position in the witness stack. This allows static program analysis, such as static SigOpsCost counting and early termination of scripts with disabled opcodes.
+* If different parties in a contract do not want to expose their scripts to each other, they may provide only H(Subscript) and keep the Subscript private until redemption.
+* If they are willing to share the actual scripts, they may combine them into one Subscript for each branch, saving some nOpCount and a few bytes of witness space.
+
+There are some disadvantages, but only when the redemption condition is very complicated:
+* It may require more branches than a general MAST design (as shown in the previous example) and take more witness space in redemption
+* Creation and storage of the MAST structure may take more time and space. However, such additional costs affect only the related parties in the contract but not any other Bitcoin users.
+
+=== MAST Version ===
+This proposal allows users to indicate the version of scripting language in the witness, which is cheaper than doing that in scriptPubKey or scriptSig. Undefined versions remain anyone-can-spend and are reserved for future expansions. A new version could be used for relaxing constraints (e.g. the 10,000 bytes size limit of MAST Script), adding or redefining opcodes, or even introducing a completely novel scripting system.
+
+=== nOpCount limit ===
+In version 0 MAST, the extra hashing operations in calculating the MAST Root are counted towards the 201 nOpCount limit to prevent abusive use. This limitation is not applied to undefined MAST Version for flexibility, but it is constrained by the 255 Subscript and 32 Depth limits.
+
+=== Script evaluation ===
+This proposal requires script evaluation resulting in an empty stack, instead of a single TRUE value as in P2WSH. This allows each party in a contract to provide its own Subscript, and demonstrate the required Input Stack to clean up its own Subscript. In this case, order of the Subscript is not important since the overall objective is to clean up the stack after evaluation.
+
+== Examples ==
+=== Calculation of MAST Root ===
+
+
+
+
+ Subscript:
+ SA = 1 EQUALVERIFY (0x5188)
+ SB = 2 EQUALVERIFY (0x5288)
+ SC = 3 EQUALVERIFY (0x5388)
+ SD = 4 EQUALVERIFY (0x5488)
+ SE = 5 EQUALVERIFY (0x5588)
+ SF = 6 EQUALVERIFY (0x5688)
+ SG = 7 EQUALVERIFY (0x5788)
+ SH = 8 EQUALVERIFY (0x5888)
+ M = RETURN "Hello" (0x6a0548656c6c6f)
+ Hash:
+ HA = H(0x01|H(SA)) = H(0x015acb54166e0db370cd1b05a29120373568dacea2abc3748459ec3da2106e4b4e) = 0xd385d7268ad7e1ec51660f833d54787d2d8d79b6b1809d9c1d06c9e71f7be204
+ HB = H(0x02|H(SB)|H(SC)) = 0x7cbfa08e44ea9f4f996873be95d9bffd97d4b91a5af32cc5f64efb8461727cdd
+ HF = H(0x03|H(SD)|H(SE)|H(SF)) = 0x4611414355945a7c2fcc62a53a0004821b87e68f93048ffba7a55a3cb1e9783b
+ HG = H(0x01|H(SG)) = 0xaa5fbdf58264650eadec33691ba1e7606d0a62f570eea348a465c55bc86ffc10
+ HC = H(0x01|H(M)) = 0x70426d480d5b28d93c5be54803681f99abf4e8df4eab4dc87aaa543f0d138159
+ HD = H(0x0x|H(SH)) = 0x8482f6c9c3fe90dd4d533b4efedb6a241b95ec9267d1bd5aaaee36d2ce2dd6da
+ HE = H(HA|HB) = 0x049b9f2f94f0a9bdea624e39cd7d6b27a365c6a0545bf0e9d88d86eff4894210
+ HH = H(HC|HD) = 0xc709fdc632f370f3367da45378d1cf430c5fda6805e731ad5761c213cf2d276e
+ HI = H(HE|HF) = 0xead5e1a1e7e41b77b794f091df9be3f0e9f41d47304eb43dece90688f69843b7
+ HJ = H(HG|HH) = 0xd00fc690c4700d0f983f9700740066531ea826b21a4cbc62f80317261723d477
+ Script Root = H(HI|HJ) = 0x26d5235d20daf1440a15a248f5b5b4f201392128072c55afa64a26ccc6f56bd9
+ MAST Root = H(MAST Version|Script Root) = H(0x0000000026d5235d20daf1440a15a248f5b5b4f201392128072c55afa64a26ccc6f56bd9) = 0xb4b706e0c02eab9aba58419eb7ea2a286fb1c01d7406105fc12742bf8a3f97c9
+
+
+The scriptPubKey with native witness program is:
+
+ 1 <0xb4b706e0c02eab9aba58419eb7ea2a286fb1c01d7406105fc12742bf8a3f97c9>
+ (0x5120b4b706e0c02eab9aba58419eb7ea2a286fb1c01d7406105fc12742bf8a3f97c9)
+
+
+To redeem with the SD|SE|SF branch, the witness is
+
+ Script_stack_1: 0x06
+ Script_stack_2: 0x05
+ Script_stack_3: 0x04
+ Subscript_1: 0x5488
+ Subscript_2: 0x5588
+ Subscript_3: 0x5688
+ Position: 0x01 (HF is the second hash in its level)
+ Path (HE|HJ): 0x049b9f2f94f0a9bdea624e39cd7d6b27a365c6a0545bf0e9d88d86eff4894210d00fc690c4700d0f983f9700740066531ea826b21a4cbc62f80317261723d477
+ Metadata: 0x03 (3 Subscript)
+
+
+
+=== Imbalance MAST ===
+When constructing a MAST, if the user believes that some of the branches are more likely to be executed, they may put them closer to the Script Root. It will save some witness space when the preferred branches are actually executed.
+
+=== Escrow with Timeout ===
+The following is the "Escrow with Timeout" example in [[bip-0112.mediawiki|BIP112]]:
+ IF
+ 2 3 CHECKMULTISIG
+ ELSE
+ "30d" CHECKSEQUENCEVERIFY DROP
+ CHECKSIG
+ ENDIF
+
+Using compressed public key, the size of this script is 150 bytes.
+
+With MAST, this script could be broken down into 2 mutually exclusive branches:In BIPXXX, it is proposed that CHECKLOCKTIMEVERIFY and CHECKSEQUENCEVERIFY will pop the top stack item
+ 2 3 CHECKMULTISIGVERIFY (105 bytes)
+ "30d" CHECKSEQUENCEVERIFY CHECKSIGVERIFY (42 bytes)
+
+Since only one branch will be published, it is more difficult for a blockchain analyst to determine the details of the escrow.
+
+=== Hashed Time-Lock Contract ===
+The following is the "Hashed TIme-Lock Contract" example in [[bip-0112.mediawiki|BIP112]]:
+ HASH160 DUP EQUAL
+ IF
+ "24h" CHECKSEQUENCEVERIFY
+ 2DROP
+
+ ELSE
+ EQUAL
+ NOTIF
+ "Timestamp" CHECKLOCKTIMEVERIFY DROP
+ ENDIF
+
+ ENDIF
+ CHECKSIG
+
+To create a MAST Root, it is flattened to 3 mutually exclusive branches:
+ HASH160 EQUALVERIFY "24h" CHECKSEQUENCEVERIFY CHECKSIGVERIFY
+ HASH160 EQUALVERIFY CHECKSIGVERIFY
+ "Timestamp" CHECKLOCKTIMEVERIFY CHECKSIGVERIFY
+
+which significantly improves readability and reduces the witness size when it is redeemed.
+
+=== Large multi-signature constructs ===
+The current CHECKMULTISIG supports up to 20 public keys. Although it is possible to extend it beyond 20 keys by using multiple CHECKSIGs and IF/ELSE conditions, the construction could be very complicated and soon use up the 10,000 bytes and 201 nOpCount limit.
+
+With MAST, large and complex multi-signature constructs could be flattened to many simple CHECKMULTISIGVERIFY conditions. For example, a 3-of-2000 multi-signature scheme could be expressed as 1,331,334,000 3-of-3 CHECKMULTISIGVERIFY, which forms a 31-level MAST. The scriptPubKey still maintains a fixed size of 34 bytes, and the redemption witness will be very compact, with less than 1,500 bytes.
+
+=== Commitment of non-consensus enforced data ===
+Currently, committing non-consensus enforced data in the scriptPubKey requires the use of OP_RETURN which occupies additional block space. With MAST, users may commit such data as a branch. Depends on the number of executable branches, inclusion of such a commitment may incur no extra witness space, or 32 bytes at most.
+
+An useful case would be specifying "message-signing keys", which are not valid for spending, but allow users to sign any message without touching the cold storage "funding key".
+
+== Backward compatibility ==
+As a soft fork, older software will continue to operate without modification. Non-upgraded nodes, however, will consider MAST programs as anyone-can-spend scripts. Wallets should always be wary of anyone-can-spend scripts and treat them with suspicion.
+
+== Deployment ==
+This BIP depends on [[bip-0141.mediawiki|BIP141]] and will be deployed by version-bits [[bip-0009.mediawiki|BIP9]] after BIP141 is enforced. Exact details TBD.
+
+== Credits ==
+The idea of MAST originates from Russell O’Connor, Pieter Wuille, and [https://bitcointalk.org/index.php?topic=255145.msg2757327#msg2757327 Peter Todd].
+
+== Reference Implementation ==
+https://github.com/jl2012/bitcoin/tree/bip114v2 (WIP)
+
+
+
+Copying from src/consensus/merkle.cpp:
+
+
+
+== References ==
+*[[bip-0141.mediawiki|BIP141 Segregated Witness (Consensus layer)]]
+
+== Copyright ==
+This document is placed in the public domain.
diff --git a/bip-0114/mastexample.png b/bip-0114/mastexample.png
new file mode 100644
index 0000000000..9bff7b9939
Binary files /dev/null and b/bip-0114/mastexample.png differ
diff --git a/bip-0115.mediawiki b/bip-0115.mediawiki
new file mode 100644
index 0000000000..042d0570ec
--- /dev/null
+++ b/bip-0115.mediawiki
@@ -0,0 +1,117 @@
+
+
+==Abstract==
+
+This BIP describes a new opcode (OP_CHECKBLOCKATHEIGHT) for the Bitcoin scripting system that allows construction of transactions which are valid only on specific blockchains.
+
+==Copyright==
+
+This BIP is licensed under the BSD 2-clause license.
+
+==Specification==
+
+OP_CHECKBLOCKATHEIGHT redefines the existing OP_NOP5 opcode.
+
+When this opcode is executed:
+
+* If the stack has fewer than 2 elements, the script fails.
+* If the top item on the stack cannot be interpreted as a minimal-length 32-bit CScriptNum, the script fails.
+* The top item on the stack is interpreted as a block height (ParamHeight).
+* If the blockchain (in the context of the execution) does not have ParamHeight blocks prior to the one including this transaction, the script fails (this failure must not be cached across blocks; it is equivalent to non-final status).
+* If ParamHeight specifies a block deeper than 52596 blocks in the chain (including negative values), the opcode completes successfully and script continues as normal.
+* The second-to-top item on the stack is interpreted as a block hash (ParamBlockHash).
+* If ParamBlockHash is longer than 28 bytes, the script fails.
+* If ParamBlockHash does not match the equivalent ending bytes of the block hash specified by ParamHeight, the script fails.
+
+Otherwise, script execution will continue as if a NOP had been executed.
+
+===Deployment===
+
+This BIP will be deployed by "version bits" [[bip-0009.mediawiki|BIP9]] with the '''name''' "cbah" and using '''bit''' TBD.
+
+For Bitcoin '''mainnet''', the BIP9 '''starttime''' will be TBD (Epoch timestamp TBD) and BIP9 '''timeout''' will be TBD (Epoch timestamp TBD).
+
+For Bitcoin '''mainnet''', the BIP9 '''starttime''' will be TBD (Epoch timestamp TBD) and BIP9 '''timeout''' will be TBD (Epoch timestamp TBD).
+
+==Motivation==
+
+===Securely recovering from double spends===
+
+In some circumstances, users may wish to spend received bitcoins before they have confirmed on the blockchain (Tx B1).
+However, if the transaction sending them those bitcoins (Tx A1) is double-spent, the wallet must re-issue their own transaction spending them (Tx B2).
+So long as the double-spend of the incoming transaction (Tx A2) also pays the wallet, this can be managed by simply updating the outgoing transaction with the new outpoint and resigning.
+However, if the double-spend does not pay the wallet, the situation is presently irrecoverable:
+it must spend different, non-conflicting TXOs in Tx B2, which allows an attacker to then reorganise the chain (reversing the incoming transaction's double-spend) and confirm both of his transactions Tx B1 and Tx B2.
+
+By adding OP_CHECKBLOCKATHEIGHT, the wallet can issue Tx B2 with a condition that the block confirming Tx A2 is in the history, thus eliminating this risk.
+
+===Replay protection in the event of a persistent blockchain split===
+
+In the event of a persistent blockchain split, some mechanism is desired by which the UTXOs valid in either chain may be spent without the transaction being validly replayable on the other chain.
+
+This can be guaranteed by choosing a block which exists only on either side of the split, and pinning (using OP_CHECKBLOCKATHEIGHT) common UTXOs to be spent only on chains based on that block.
+
+==Best practices for wallets==
+
+To avoid unnecessary conflicts when a chain is reorganized, wallets should always avoid specifying the last 100 blocks when practical.
+Wallets that use recent blocks when unavoidable SHOULD actively monitor the network and re-create transactions that are reorganised out with updated block hashes.
+Unless it conflicts with local/user security policies, wallets SHOULD retain the private key in memory to re-sign such transactions until the pinned block is at least 100 blocks deep into the chain.
+
+For ordinary usage, wallets SHOULD specify the ParamBlockHash as 16 bytes.
+
+==Rationale==
+
+How is this different from the transaction's lock-time?
+
+* The lock-time specifies a time or block height before a transaction becomes valid. OP_CHECKBLOCKATHEIGHT, on the other hand, specifies a specific block's hash.
+
+Why are block heights required to be absolute, rather than relative?
+
+* A relative block height would allow for creation of transactions which are valid at block N, but not N+1. This is carefully avoided by Bitcoin to ensure that if any given block is reorganised out, non-malicious transactions can be simply re-confirmed in a later block.
+
+Why are blocks older than 52596 deep in the chain not verified?
+
+* This is to avoid creating an infinite storage requirement from all full nodes which would be necessary to maintain all the block headers indefinitely. 52596 block headers requires a fixed size of approximately 4 MB.
+* In any case where you might want to specify a deeper block, you can also just as well specify a more recent one that descends from it.
+* It is assumed that 1 year is sufficient time to double-spend any common UTXOs on all blockchains of interest.
+* If a deeper check is needed, it can be softforked in. Making the check more shallow, on the other hand, is a hardfork.
+
+Why is ParamBlockHash allowed to match less than the full block hash?
+
+* In a chain split, it is sufficient to check only a few bytes to avoid replay.
+* In all scenarios, it is likely sufficient to check only a minority of the full hash to avoid any realistic chance of replay.
+* Allowing less than the full hash to be specified saves space in transaction data.
+* Using a single byte can be combined with other opcodes (such as OP_LESSTHAN) to enable on-chain gambling logic.
+
+What if ParamBlockHash has leading zeros? Should this be prevented?
+
+* If leading zeros are included, they should be compared to the actual block hash. (If they were truncated, fewer bytes would be compared.)
+* It is unlikely that the leading zeros will ever be necessary for sufficient precision, so the additional space is not a concern.
+* Since all block hashes are in principle shorter than 29 bytes, ParamBlockHash may not be larger than 28 bytes.
+
+Why is it safe to allow checking blocks as recently as the immediate previous block?
+
+* This should only be used when necessary (ie, the deeper block is not sufficient), and when the wallet can actively issue updates should the blockchain reorganise.
+* While this allows intentionally creating a transaction which may be invalid in a reorganization, the same can already be accomplished by creating double spends.
+
+==Backwards Compatibility==
+
+OP_NOP5 ought to be forbidden by policy by all miners for future extensions such as this, so old miners will under no circumstances produce blocks which would now be considered invalid under the new rules.
+However, miners must still upgrade to avoid accepting and building on top of such a possible invalid block as part of an attack.
+
+Old nodes will likely also not relay transactions using this opcode for the same extensibility reasons, but this is not important since the rule cannot be verified deterministically outside the context of a block.
+
+==Reference Implementation==
+
+https://github.com/bitcoin/bitcoin/compare/master...luke-jr:cbah
diff --git a/bip-0116.mediawiki b/bip-0116.mediawiki
new file mode 100644
index 0000000000..70b340f575
--- /dev/null
+++ b/bip-0116.mediawiki
@@ -0,0 +1,145 @@
+
+
+==Abstract==
+
+A general approach to bitcoin contracts is to fully enumerate the possible spending conditions and then program verification of these conditions into a single script.
+At redemption, the spending condition used is explicitly selected, e.g. by pushing a value on the witness stack which cascades through a series if if/else constructs.
+
+This approach has significant downsides, such as requiring all program pathways to be visible in the scriptPubKey or redeem script, even those which are not used at validation.
+This wastes space on the block chain, restricts the size of possible scripts due to push limits, and impacts both privacy and fungibility as details of the contract can often be specific to the user.
+
+This BIP proposes a new soft-fork upgradeable opcode, MERKLEBRANCHVERIFY, which allows script writers to commit to a set of data elements and have one or more of these elements be provided at redemption without having to reveal the entire set.
+As these data elements can be used to encode policy, such as public keys or validation subscripts, the MERKLEBRANCHVERIFY opcode can be used to overcome these limitations of existing bitcoin script.
+
+==Copyright==
+
+This BIP is licensed under a Creative Commons Attribution-ShareAlike license. All provided source code is licensed under the MIT license.
+
+==Specification==
+
+MERKLEBRANCHVERIFY redefines the existing NOP4 opcode.
+When executed, if any of the following conditions are true, the script interpreter will terminate with an error:
+
+# the stack contains less than three (3) items;
+# the first item on the stack is more than 2 bytes;
+# the first item on the stack, interpreted as an integer, N, is negative or not minimally encoded;
+# the second item on the stack is not exactly 32 bytes;
+# the third item on the stack is not a serialized Merkle tree inclusion proof as specified by BIP98[1] and requiring exactly floor(N/2) VERIFY hashes; or
+# the remainder of the stack contains less than floor(N/2) additional items, together referred to as the input stack elements.
+
+If the low-order bit of N is clear, N&1 == 0, each input stack element is hashed using double-SHA256.
+Otherwise, each element must be exactly 32 bytes in length and are interpreted as serialized hashes.
+These are the VERIFY hashes.
+
+If the fast Merkle root computed from the Merkle tree inclusion proof, the third item on the stack,
+with the VERIFY hashes in the order as presented on the stack, from top to bottom,
+does not exactly match the second item on the stack,
+the script interpreter will terminate with an error.
+
+Otherwise, script execution will continue as if a NOP had been executed.
+
+==Motivation==
+
+Although BIP16 (Pay to Script Hash)[2] and BIP141 (Segregated Witness)[3] both allow the redeem script to be kept out of the scriptPubKey and therefore out of the UTXO set, the entire spending conditions for a coin must nevertheless be revealed when that coin is spent.
+This includes execution pathways or policy conditions which end up not being needed by the redemption.
+Not only is it inefficient to require this unnecessary information to be present on the blockchain, albeit in the witness, it also impacts privacy and fungibility as some unused script policies may be identifying.
+Using a Merkle hash tree to commit to the policy options, and then only forcing revelation of the policy used at redemption minimizes this information leakage.
+
+Using Merkle hash trees to commit to policy allows for considerably more complex contracts than would otherwise be possible, due to various built-in script size and runtime limitations.
+With Merkle commitments to policy these size and runtime limitations constrain the complexity of any one policy that can be used rather than the sum of all possible policies.
+
+==Rationale==
+
+The MERKLEBRANCHVERIFY opcode uses fast Merkle hash trees as specified by BIP98[1] rather than the construct used by Satoshi for committing transactions to the block header as the later has a known vulnerability relating to duplicate entries that introduces a source of malleability to downstream protocols[4].
+A source of malleability in Merkle proofs could potentially lead to spend vulnerabilities in protocols that use MERKLEBRANCHVERIFY.
+For example, a compact 2-of-N policy could be written by using MERKLEBRANCHVERIFY to prove that two keys are extracted from the same tree, one at a time, then checking the proofs for bitwise equality to make sure the same entry wasn't used twice.
+With the vulnerable Merkle tree implementation there are privledged positions in unbalanced Merkle trees that allow multiple proofs to be constructed for the same, single entry.
+
+BIP141 (Segregated Witness)[3] provides support for a powerful form of script upgrades called script versioning, which is able to achieve the sort of upgrades which would previously have been hard-forks.
+If script versioning were used for deployment then MERKLEBRANCHVERIFY could be written to consume its inputs, which would provide a small 2-byte savings for many anticipated use cases.
+However the more familiar NOP-expansion soft-fork mechanism used by BIP65 (CHECKLOCKTIMEVERIFY)[5] and BIP112 (CHECKSEQUENCEVERIFY)[6] was chosen over script versioning for the following two reasons:
+
+# '''Infrastructure compatibility.''' Using soft-fork NOP extensions allows MERKLEBRANCHVERIFY to be used by any existing software able to consume custom scripts, and results in standard P2SH or P2WSH-nested-in-P2SH addresses without the need for BIP143[7] signing code. This allows MERKLEBRANCHVERIFY to be used immediately by services that need it rather than wait on support for script versioning and/or BIP-143[7] signatures in tools and libraries.
+# '''Delayed decision on script upgrade protocol.''' There are unresolved issues with respect to how script versioning should be used for future script upgrades. There are only 16 available script versions reserved for future use, and so they should be treated as a scarce resource. Additionally, script feature versioning should arguably be specified in the witness and the BIP141 script versioning only be used to specify the structure of the witness, however no such protocol exists as of yet. Using the NOP-expansion space prevents MERKLEBRANCHVERIFY from being stalled due to waiting on script upgrade procedure to be worked out, while making use of expansion space that is already available.
+
+The MERKLEBRANCHVERIFY opcode allows for VERIFY hashes to be presented directly, or calculated from the leaf values using double-SHA256.
+In most cases the latter approach is expected to be used so that the leaf value(s) can be used for both branch validation and other purposes without any explicit preprocessing.
+However allowing already-calculated hash values as inputs enables using chained MERKLEBRANCHVERIFY opcodes to verify branches of trees with proofs large enough that they would not fit in the 520 byte script push limitation.
+As specified, a 30-branch path can be verified by proving the path from the leaf to the 15th interior node as the 'root', then proving that node's hash to be a child of the actual Merkle tree root hash.
+Validation of a 256-branch path (e.g. a binary prefix tree with a hash value as key) would require 18 chained validations, which would fit within current script limitations.
+
+==Applications==
+
+===1-of-N for large N===
+
+Here is a redeem script that allows a coin to be spent by any key from a large set, without linear scaling in script size:
+
+ redeemScript: 2 MERKLEBRANCHVERIFY 2DROP DROP CHECKSIG
+ witness:
+
+The redeem script looks very similar to the standard pay-to-pubkey-hash, except instead of showing that the pubkey's hash is the same as the commitment given, we demonstrate that the pubkey is one of potentially many pubkeys included in the Merkle tree committed to in the redeem script.
+The low-order bit of the first parameter, 2, is clear, meaning that there is one input ((2>>1) == 1), the serialized pubkey, and its VERIFY hash needs to be calculated by MERKLEBRANCHVERIFY using double-SHA256.
+
+===Honeypots===
+
+As described by Pieter Wuille[8] the 1-of-N scheme is particularly useful for constructing honeypots.
+The desire is to put a large bounty on a server, larger than the value of the server itself so that if the server is compromised it is highly likely that the hacker will claim the bitcoin, thereby revealing the intrusion.
+However if there are many servers, e.g. 1,000, it becomes excessively expensive to lock up separate bounties for each server.
+It would be desirable if the same bounty was shared across multiple servers in such a way that the spend would reveal which server was compromised.
+
+This is accomplished by generating 1,000 different keys, building a hash tree of these public keys, and placing each key and associated Merkle path on separate servers.
+When the honeypot is claimed, the (previous) owner of the coins can tell which server was compromised from the key and path used to claim the funds.
+
+==Implementation==
+
+An implementation of this BIP, including both consensus code updates and tests is available at the following Github repository:
+
+[https://github.com/maaku/bitcoin/tree/merkle-branch-verify]
+
+==Deployment==
+
+This BIP will be deployed by BIP8 (Version bits with lock-in by height)[9] with the name "merklebranchverify" and using bit 2.
+
+For Bitcoin mainnet, the BIP8 startheight will be at height M to be determined and BIP8 timeout activation will occur on height M + 50,400 blocks.
+
+For Bitcoin testnet, the BIP8 startheight will be at height T to be determined and BIP8 timeout activation will occur on height T + 50,400 blocks.
+
+We note that DISCOURAGE_UPGRADABLE_NOPS means that transactions which use this feature are already considered non-standard by the rules of the network, making deployment easier than was the case with, for example, with BIP68 (Relative lock-time using consensus-enforced sequence numbers)[9].
+
+==Compatibility==
+
+Old clients will consider the OP_MERKLEBRANCHVERIFY as a NOP and ignore it. Proof will not be verified, but the transaction will be accepted.
+
+==References==
+
+[1] [https://github.com/bitcoin/bips/blob/master/bip-0098.mediawiki BIP98: Fast Merkle Trees (Consensus layer)]
+
+[2] [https://github.com/bitcoin/bips/blob/master/bip-0016.mediawiki BIP16: Pay to Script Hash]
+
+[3] [https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki BIP141: Segregated Witness (Consensus layer)]
+
+[4] [https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-2459 National Vulnerability Database: CVE-2012-2459]
+
+[5] [https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki BIP65: OP_CHECKLOCKTIMEVERIFY]
+
+[6] [https://github.com/bitcoin/bips/blob/master/bip-0112.mediawiki BIP112: CHECKSEQUENCEVERIFY]
+
+[7] [https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki BIP143: Transaction Signature Verification for Version 0 Witness Program]
+
+[8] [https://blockstream.com/2015/08/24/treesignatures.html Multisig on steroids using tree signatures]
+
+[9] [https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki BIP68: Relative lock-time using consensus-enforced sequence numbers]
diff --git a/bip-0117.mediawiki b/bip-0117.mediawiki
new file mode 100644
index 0000000000..4b5706ef16
--- /dev/null
+++ b/bip-0117.mediawiki
@@ -0,0 +1,196 @@
+
+
+==Abstract==
+
+BIP16 (Pay to Script Hash)[1] and BIP141 (Segregated Witness)[2] provide mechanisms by which script policy can be revealed at spend time as part of the execution witness.
+In both cases only a single script can be committed to by the construct.
+While useful for achieving the goals of these proposals, they still require that all policies be specified within the confine of a single script, regardless of whether the policies are needed at the time of spend.
+
+This BIP, in conjunction with BIP116 (MERKLEBRANCHVERIFY)[3] allows for a script to commit to a practically unbounded number of code pathways, and then reveal the actual code pathway used at spend time.
+This achieves a form of generalized MAST[4] enabling decomposition of complex branching scripts into a set of non-branching flat execution pathways, committing to the entire set of possible pathways, and then revealing only the path used at spend time.
+
+==Copyright==
+
+This BIP is licensed under a Creative Commons Attribution-ShareAlike license. All provided source code is licensed under the MIT license.
+
+==Specification==
+
+If, at the end of script execution:
+
+* the execution state is non-clean, meaning
+*# the main stack has more than one item on it, or
+*# the main stack has exactly one item and the alt-stack is not empty;
+* the top-most element of the main stack evaluates as true when interpreted as a bool; and
+* the top-most element is not a single byte or is outside the inclusive range of 0x51 to 0x60,
+
+then that top-most element of the main stack is popped and interpreted as a serialized script and executed,
+while the remaining elements of both stacks remain in place as inputs.
+
+If the above conditions hold except for the last one, such that:
+
+* the top-most element ''is'' a single byte within the inclusive range of 0x51 (OP_1, meaning N=2) to 0x60 (OP_16, meaning N=17); and
+* other than this top-most element there are at least N additional elements on the main stack and alt stack combined,
+
+then the top-most element of the main stack is dropped,
+and the N=2 (0x51) to 17 (0x60) further elements are popped from the main stack,
+continuing from the alt stack if the main stack is exhausted,
+and concatenated together in reverse order to form a serialized script,
+which is then executed with the remaining elements of both stacks remaining in place as inputs.
+
+The presence of CHECKSIG or CHECKMULTISIG within the subscript do not count towards the global MAX_BLOCK_SIGOPS_COST limit,
+and the number of non-push opcodes executed in the subscript is not limited by MAX_OPS_PER_SCRIPT.
+Execution state, other than the above exceptions, carries over into the subscript,
+and termination of the subscript terminates execution of the script as a whole.
+This is known as execution with tail-call semantics.
+
+Only one such tail-call of a subscript is allowed per script execution context, and only from within a segwit redeem script.
+Alternatively stated, neither evaluation of witness stack nor execution of the scriptPubKey or scriptSig or P2SH redeem script results in tail-call semantics.
+
+==Motivation==
+
+BIP16 (Pay to Script Hash)[1] and BIP141 (Segregated Witness)[2] allow delayed revelation of a script's policy until the time of spend.
+However these approaches are limited in that only a single policy can be committed to in a given transaction output.
+It is not possible to commit to multiple policies and then choose, at spend time, which to reveal.
+
+BIP116 (MERKLEBRANCHVERIFY)[3] allows multiple data elements to be committed to while only revealing those necessary at the time of spend.
+The MERKLEBRANCHVERIFY opcode is only able to provide commitments to a preselected set of data values, and does not by itself allow for executing code.
+
+This BIP generalizes the approach of these prior methods by allowing the redeem script to perform any type of computation necessary to place the policy script on the stack.
+The policy script is then executed from the top of the data stack in a way similar to how BIP16 and BIP141 enable redeem scripts to be executed from the top of the witness stack.
+In particular, using MERKLEBRANCHVERIFY[3] in the scriptPubKey or redeem script allows selection of the policy script that contains only the necessary conditions for validation of the spend.
+This is a form of generalized MAST[4] where a stage of precomputation splits a syntax tree into possible execution pathways, which are then enumerated and hashed into a Merkle tree of policy scripts.
+At spend time membership in this tree of the provided policy script is proven before execution recurses into the policy script.
+
+==Rationale==
+
+This proposal is a soft-fork change to bitcoin's consensus rules because leaving a script that data-wise evaluates as true from its serialized form on the stack as execution terminates would result in the script validation returning true anyway.
+Giving the subscript a chance to terminate execution is only further constraining the validation rules.
+The only scripts which would evaluate as false are the empty script, or a script that does nothing more than push empty/zero values to the stack.
+None of these scripts have any real-world utility, so excluding them to achieve soft-fork compatibility doesn't come with any downsides.
+
+By restricting ourselves to tail-call evaluation instead of a more general EVAL opcode we greatly simplify the implementation.
+Tail-call semantics means that execution never returns to the calling script's context, and therefore no state needs to be saved or later restored.
+The implementation is truly as simple as pulling the subscript off the stack, resetting a few state variables, and performing a jump back to the beginning of the script interpreter.
+
+The restriction to allow only one layer of tail-call recursion is admittedly limiting, however the technical challenges to supporting multi-layer tail-call recursion are significant.
+A new metric would have to be developed to track script resource usage, for which transaction data witness size are only two factors.
+This new weight would have to be relayed with transactions, used as the basis for fee calculation, validated in-line with transaction execution, and policy decided upon for DoS-banning peers that propagate violating transactions.
+
+However should these problems be overcome, dropping the single recursion constraint is itself a soft-fork for the same reason, applied inductively.
+Allowing only one layer of tail-call recursion allows us to receive the primary benefit of multi-policy commitments / generalized MAST,
+while leaving the door open to future generalized tail-call recursion if and when the necessary changes are made to resource accounting and p2p transaction distribution.
+
+The global SIGOP limit and per-script opcode limits do not apply to the policy script
+because dynamic selection of the policy script makes it not possible for static analysis tools to verify these limits in general,
+and because performance improvements to libsecp256k1 and Bitcoin Core have made these limits no longer necessary as they once were.
+The validation costs are still limited by the number of signature operations it is possible to encode within block size limits,
+and the maximum script size per input is limited to 10,000 + 17*520 = 18,840 bytes.
+
+To allow for this drop of global and per-script limits,
+tail-call evaluation cannot be allowed for direct execution of the scriptPubKey,
+as such scripts are fetched from the UTXO and do not count towards block size limits of the block being validated.
+Likewise tail-call from P2SH redeem scripts is not supported due to quadratic blow-up vulnerabilities that are fixed in segwit.
+
+==Generalized MAST==
+
+When combined with BIP116 (MERKLEBRANCHVERIFY)[3], tail-call semantics allows for generalized MAST capabilities[4].
+The script author starts with a full description of the entire contract they want to validate at the time of spend.
+The possible execution pathways through the script are then enumerated, with conditional branches replaced by a validation of the condition and the branch taken.
+The list of possible execution pathways is then put into a Merkle tree, with the flattened policy scripts as the leaves of this tree.
+The final redeem script which funds are sent to is as follows:
+
+ redeemScript: 2 MERKLEBRANCHVERIFY 2DROP DROP
+ witness: ...
+
+Where policyScript is the flattened execution pathway, proof is the serialized Merkle branch and path that proves the policyScript is drawn from the set used to construct the Merkle tree root, and arg1 through argN are the arguments required by policyScript.
+The 2 indicates that a single leaf (1 << 1) follows, and the leaf value is not pre-hashed.
+The 2DROP DROP is necessary to remove the arguments to MERKLEBRANCHVERIFY from the stack.
+
+The above example was designed for clarity, but actually violates the CLEANSTACK rule of segwit v0 script execution.
+Unless the CLEANSTACK rule is dropped or modified in a new segwit output version, this would script would have to be modified to use the alt-stack, as follows:
+
+ redeemScript: [TOALTSTACK]*N 2 MERKLEBRANCHVERIFY 2DROP DROP
+ witness: ...
+
+Where [TOALTSTACK]*N is the TOALTSTACK opcode repeated N times.
+This moves arg1 through argN to the alt-stack in reverse order, such that arg1 is on the top of the alt-stack when execution of policyScript begins.
+The policyScript would also have to be modified to fetch its arguments from the alt-stack, of course.
+
+If the total set of policy scripts includes scripts that take a varying number of parameters, that too can be supported, within reasonable limits.
+The following redeem script allows between 1 and 3 witness arguments in addition to the policy script and Merkle proof:
+
+ witness: ... // N is between 1 and 3
+ redeemScript: DEPTH TOALTSTACK // Save number of witness elements to alt-stack
+ TOALTSTACK // Save 1st element (required) to alt-stack
+ DEPTH 2 SUB // Calculate number of optional elements, ignoring policyScript and proof
+ DUP IF SWAP TOALTSTACK 1SUB ENDIF // Save 2nd element (optional) to alt-stack, if it is present
+ IF TOALTSTACK ENDIF // Save 3rd element (optional) to alt-stack, if it is present; consume counter
+ 2 MERKLEBRANCHVERIFY 2DROP DROP
+ alt-stack: ...
+
+Because the number of witness elements is pushed onto the alt-stack, this enables policy scripts to verify the number of arguments passed, even though the size of the alt-stack is not usually accessible to script.
+The following policy script for use with the above redeem script will only accept 2 witness elements on the alt-stack, preventing witness malleability:
+
+ policyScript: FROMALTSTACK ...check arg1... FROMALTSTACK ...check&consume arg2/arg1&2... FROMALTSTACK 4 EQUAL
+
+The number 4 is expected as that includes the policyScript and proof.
+
+The verbosity of this example can be prevented by using a uniform number of witness elements as parameters for all policy subscripts, eliminating the conditionals and stack size counts.
+Future script version upgrades should also consider relaxing CLEANSTACK rules to allow direct pass-through of arguments from the witness/redeem script to the policy script on the main stack.
+
+===Comparison with BIP114===
+
+BIP114 (Merkelized Abstract Syntax Tree)[5] specifies an explicit MAST scheme activated by BIP141 script versioning[2].
+Unlike BIP114, the scheme proposed by this BIP in conjunction with BIP116 (MERKLEBRANCHVERIFY)[3] implicitly enables MAST constructs using script itself to validate membership of the policy script in the MAST.
+This has the advantage of requiring vastly fewer consensus code changes, as well as potentially enabling future script-based innovation without requiring any further consensus code changes at all, as the MAST scheme itself is programmable.
+
+Furthermore, by adding MERKLEBRANCHVERIFY and tail-call semantics to all script using the NOP-expansion space, BIP141 style script versioning is not required.
+This removes a potentially significant hurdle to deployment by making this feature not dependent on resolving outstanding issues over address formats, how script version upgrades should be deployed, and consensus over what other features might go into a v1 upgrade.
+
+==Implementation==
+
+An implementation of this BIP, including both consensus code changes and tests are available at the following Github repository:
+
+[https://github.com/maaku/bitcoin/tree/tail-call-semantics]
+
+==Deployment==
+
+This BIP will be deployed by BIP8 (Version bits with lock-in by height)[9] with the name "tailcall" and using bit 3.
+
+For Bitcoin mainnet, the BIP8 startheight will be at height M to be determined and BIP8 timeout activation will occur on height M + 50,400 blocks.
+
+For Bitcoin testnet, the BIP8 startheight will be at height T to be determined and BIP8 timeout activation will occur on height T + 50,400 blocks.
+
+We note that CLEANSTACK means that transactions which use this feature are already considered non-standard by the rules of the network, making deployment easier than was the case with, for example, with BIP68 (Relative lock-time using consensus-enforced sequence numbers)[6].
+
+==Compatibility==
+
+The v0 segwit rules prohibit leaving anything on the stack, so for v0 parameters have to be passed on the alt stack for compatibility reasons.
+
+==References==
+
+[1] [https://github.com/bitcoin/bips/blob/master/bip-0016.mediawiki BIP16: Pay to Script Hash]
+
+[2] [https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki BIP141: Segregated Witness (Consensus Layer)]
+
+[3] [https://github.com/bitcoin/bips/blob/master/bip-0116.mediawiki BIP116: MERKLEBRANCHVERIFY]
+
+[4] "[https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2017-September/015028.html An explanation and justification of the tail-call and MBV approach to MAST]", Mark Friedenbach, Bitcoin Development Mailing List, 20 September 2017.
+
+[5] [https://github.com/bitcoin/bips/blob/master/bip-0114.mediawiki BIP114: Merkelized Abstract Syntax Tree]
+
+[6] [https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki BIP68: Relative lock-time using consensus-enforced sequence numbers]
diff --git a/bip-0118.mediawiki b/bip-0118.mediawiki
new file mode 100644
index 0000000000..93e0578bad
--- /dev/null
+++ b/bip-0118.mediawiki
@@ -0,0 +1,205 @@
+
+
+== Introduction ==
+
+=== Abstract ===
+
+This BIP describes a new type of public key for tapscript ([[bip-0342.mediawiki|BIP 342]]) transactions.
+It allows signatures for these public keys to not commit to the exact UTXO being spent.
+This enables dynamic binding of transactions to different UTXOs, provided they have compatible scripts.
+
+=== Copyright ===
+
+This document is licensed under the 3-clause BSD license.
+
+=== Motivation ===
+
+Off-chain protocols make use of transactions that are not yet broadcast to the Bitcoin network in order to renegotiate the final state that should be settled on-chain.
+In a number of cases it is desirable to respond to a given transaction being seen on-chain with a predetermined reaction in the form of another transaction.
+Often the same reaction is desired for a variety of different transactions that may be seen on-chain, but because the input signatures in the response transaction commit to the exact transaction that is being reacted to, this means a new signature must be created for every possible transaction one wishes to be able to react to.
+
+This proposal introduces a new public key type'''Why a new public key type?'''
+New public key types for tapscript can be introduced in a soft fork by specifying new rules for ''unknown public key types'' as specified in [[bip-0342.mediawiki|BIP 342]], as this only requires adding restrictions to the pre-existing signature opcodes.
+Possible alternative approaches would be to define new script opcodes, to use a different taproot leaf version, or to use a different set of SegWit outputs than those specified by [[bip-0341.mediawiki|BIP 341]]; however all of these approaches are more complicated, and are better reserved for other upgrades where the additional flexibility is actually needed.
+In this case, we specify a new transaction digest, but retain the same elliptic curve and signature algorithm (ie, secp256k1 and [[bip-0340.mediawiki|BIP 340]]).
+that modifies the behavior of the transaction digest algorithm used in the signature creation and verification, by excluding the commitment to the previous output (and, optionally, the witness script'''Why (and why not) commit to the witness script?'''
+The [https://blockstream.com/eltoo.pdf eltoo] paper provides an example of why committing to the witness script is not always appropriate.
+It uses script and the transaction nLockTime to make signatures asymmetric, so that a transaction with an earlier signature can be spent by a transaction with a later signature, but a transaction with a later signature cannot be spent by a transaction with an earlier signature.
+As a result, a single signature for a third, even later transaction must be able to spend both the prior transactions, even though they have a different tapscript.
+On the other hand, these cases also provide a good reason to have the option to commit to the script: because each transaction has a new script, committing to the script allows you to produce a signature that applies to precisely one of these transactions.
+In the eltoo case, this allows you to have a signature for an update transaction that can be applied to any prior update, and a signature for a settlement transaction that applies only to the corresponding update transaction, while using the same key for both, which in turn allows for a more compact script.
+ and value '''Why (and why not) commit to the input value?'''
+Committing to the input value may provide additional safety that a signature can't be maliciously reused to claim funds that the signer does not intend to spend, so by default it seems sensible to commit to it. However, doing so prevents being able to use a single signature to consolidate a group of UTXOs with the same spending condition into a single UTXO which may be useful for some protocols, such as the proposal for [https://lists.linuxfoundation.org/pipermail/lightning-dev/2020-January/002448.html layered commitments with eltoo].).
+Removing this commitment allows dynamic rebinding of a signed transaction to another previous output that requires authorisation by the same key.
+
+The dynamic rebinding is opt-in due to using a separate public key type, and the breadth of transactions the signature can be rebound to can be further restricted by using different keys, committing to the script being spent in the signature, using different amounts between UTXOs, using different nSequence values in the spending transaction, or using the codeseparator opcode to commit to the position in the script.
+
+== Specification ==
+
+This BIP modifies the behaviour of the [[bip-0342.mediawiki|BIP 342]] signature opcodes'''What about key path spends?'''
+This proposal only supports ANYPREVOUT signatures via script path spends, and does not support ANYPREVOUT signatures for key path spends.
+This is for two reasons: first, not supporting key path spends allows this proposal to be independent of the core changes included in [[bip-0341.mediawiki|BIP 341]] and [[bip-0342.mediawiki|BIP 342]]; second, it allows addresses to opt-in or opt-out of ANYPREVOUT support while remaining indistinguishable prior to being spent.
+ (CHECKSIG, CHECKSIGVERIFY, and CHECKSIGADD) for public keys that have a length of 33 bytes and a first byte of 0x01 or the public key which is precisely the single byte vector 0x01'''Use of 0x01 public key type'''
+Because OP_0 leaves an empty vector on the stack it would not satisfy [[bip-0342.mediawiki|BIP 342]]'s rules for unknown public key types. As such, it is convenient to use one of OP_1..OP_16 or OP_1NEGATE as a way to reference the taproot internal key.
+To keep things as simple as possible, we use the first of these, and add the same byte as a prefix to allow ANYPREVOUT signatures for explicitly specified keys.
+.
+These keys are termed '''BIP 118 public keys'''.
+
+==== Rules for signature opcodes ====
+
+The [[bip-0342.mediawiki|BIP 342]] rules for signature opcodes are modified by removing keys with the first byte 0x01 and length of either 1-byte or 33-bytes from the list of unknown public key types, and adding the following rule prior to the handling of unknown public key types:
+
+* If the public key is the single byte 0x01, or if the public key is 33 bytes and the first byte of the public key is 0x01, it is considered to be a BIP 118 public key:
+** If the signature is not the empty vector, the signature is validated according to the [[bip-0341.mediawiki|BIP 341]] signing validation rules with the public key, allowable hash_type values, and transaction digest modified as defined below.
+
+==== Public key ====
+
+To convert the 1-byte BIP 118 public key for use with [[bip-0340.mediawiki|BIP 340]], use the 32-byte taproot internal key, p, as defined in [[bip-0341.mediawiki|BIP 341]].
+
+To convert a 33-byte BIP 118 public key for use with [[bip-0340.mediawiki|BIP 340]], remove the 0x01 prefix and use the remaining 32 bytes.
+
+==== Signature message ====
+
+We define the functions ''Msg118(hash_type)'' and ''Ext118(hash_type)'' which compute the message being signed as a byte array.
+
+The parameter ''hash_type'' is an 8-bit unsigned value, reusing values defined in [[bip-0341.mediawiki|BIP 341]], with the addition that the values 0x41, 0x42, 0x43, 0xc1, 0xc2, and 0xc3 are also valid for BIP 118 public keys.
+
+We define the following constants using bits 6 and 7 of hash_type:
+
+* SIGHASH_ANYPREVOUT = 0x40
+* SIGHASH_ANYPREVOUTANYSCRIPT = 0xc0
+
+The following restrictions apply and cause validation failure if violated:
+* Using any undefined ''hash_type'' (not ''0x00'', ''0x01'', ''0x02'', ''0x03'', ''0x41'', ''0x42'', ''0x43'', ''0x81'', ''0x82'', ''0x83'', ''0xc1'', ''0xc2'', or ''0xc3'').
+* Using SIGHASH_SINGLE without a "corresponding output" (an output with the same index as the input being verified).
+
+If these restrictions are not violated, ''Msg118(hash_type)'' evaluates as follows.
+
+If ''hash_type & 0x40 == 0'', then ''Msg118(hash_type) = SigMsg(hash_type, 1)'', where ''SigMsg'' is as defined in [[bip-0341.mediawiki|BIP 341]].
+
+If ''hash_type & 0x40 != 0'', then ''Msg118(hash_type)'' is the concatenation of the following data, in order (with byte size of each item listed in parentheses). Numerical values in 2, 4, or 8-byte items are encoded in little-endian.
+
+* Control:
+** ''hash_type'' (1).
+* Transaction data:
+** ''nVersion'' (4): the ''nVersion'' of the transaction.
+** ''nLockTime'' (4): the ''nLockTime'' of the transaction.
+** If ''hash_type & 3'' does not equal SIGHASH_NONE or SIGHASH_SINGLE:
+*** ''sha_outputs'' (32): the SHA256 of the serialization of all outputs in CTxOut format.
+* Data about this input:
+** ''spend_type'' (1): equal to 2 if no annex is present, or 3 otherwise (the original witness stack has two or more witness elements, and the first byte of the last element is ''0x50'')
+** If ''hash_type & 0xc0'' is SIGHASH_ANYPREVOUT:
+*** ''amount'' (8): value of the previous output spent by this input.
+*** ''scriptPubKey'' (35): ''scriptPubKey'' of the previous output spent by this input, serialized as script inside CTxOut. Its size is always 35 bytes.
+** ''nSequence'' (4): ''nSequence'' of this input.
+** If an annex is present (the lowest bit of ''spend_type'' is set):
+*** ''sha_annex'' (32): the SHA256 of ''(compact_size(size of annex) || annex)'', where ''annex'' includes the mandatory ''0x50'' prefix.
+* Data about this output:
+** If ''hash_type & 3'' equals SIGHASH_SINGLE:
+*** ''sha_single_output'' (32): the SHA256 of the corresponding output in CTxOut format.
+
+Similarly, ''Ext118(hash_type)'' evaluates to the concatenation of the following data, in order:
+
+* Extension:
+** If ''hash_type & 0xc0'' is not SIGHASH_ANYPREVOUTANYSCRIPT:
+*** ''tapleaf_hash'' (32): the tapleaf hash as defined in [[bip-0341.mediawiki|BIP 341]]
+** ''key_version'' (1): a constant value ''0x01'' representing that this is a signature for a BIP 118 public key.
+** ''codesep_pos'' (4): the opcode position of the last executed OP_CODESEPARATOR before the currently executed signature opcode, with the value in little endian (or ''0xffffffff'' if none executed). The first opcode in a script has a position of 0. A multi-byte push opcode is counted as one opcode, regardless of the size of data being pushed.
+
+To verify a signature ''sig'' for a BIP 118 public key ''p'':
+
+* If the ''sig'' is 64 bytes long, return ''Verify(p, hashTapSigHash(0x00 || Msg118(0x00) || Ext118(0x00)), sig)''
+* If the ''sig'' is 65 bytes long, return ''sig[64] ≠ 0x00 and Verify(p, hashTapSighash(0x00 || Msg118(sig[64]) || Ext118(sig[64])), sig[0:64])''.
+* Otherwise, fail.
+
+''Verify'' is as defined in [[bip-0340.mediawiki|BIP 340]].
+
+The key differences from [[bip-0342.mediawiki|BIP 342]] signature verification are:
+
+* In all cases, key_version is set to the constant value 0x01 instead of 0x00.'''Why change key_version?''' Changing key_version ensures that if the same private key is used to generate both a [[bip-0342.mediawiki|BIP 342]] key and a BIP 118 public key, that a signature for the [[bip-0342.mediawiki|BIP 342]] key is not also valid for the BIP 118 public key (and vice-versa).
+* If SIGHASH_ANYPREVOUT is set, the digest is calculated as if SIGHASH_ANYONECANPAY was set, except outpoint is not included in the digest.
+* If SIGHASH_ANYPREVOUTANYSCRIPT is set, the digest is calculated as if SIGHASH_ANYONECANPAY was set, except outpoint, amount, scriptPubKey and tapleaf_hash are not included in the digest.
+
+== Security ==
+
+==== Signature replay ====
+
+By design, SIGHASH_ANYPREVOUT and SIGHASH_ANYPREVOUTANYSCRIPT introduce additional potential for signature replay (that is they allow the same signature to be reused on a different transaction) when compared to SIGHASH_ALL and SIGHASH_ANYONECANPAY signatures.
+
+Both SIGHASH_ALL and SIGHASH_ANYONECANPAY signatures prevent signature replay by committing to one or more inputs, so replay of the signature is only possible if the same input can be spent multiple times, which is not possible on the Bitcoin blockchain (due to enforcement of [[bip-0030.mediawiki|BIP 30]]).
+With SIGHASH_ANYPREVOUT signature replay is possible for different UTXOs with the same scriptPubKey and the same value, while with SIGHASH_ANYPREVOUTANYSCRIPT signature replay is possible for any UTXOs that reuse the same BIP 118 public key in one of their potential scripts.
+
+As a consequence, implementors MUST ensure that BIP 118 public keys are only reused when signature replay cannot cause loss of funds (eg due to other features of the protocol or other constraints on the transaction), or when such a loss of funds is acceptable.
+
+==== Malleability ====
+
+Use of SIGHASH_ANYPREVOUT or SIGHASH_ANYPREVOUTANYSCRIPT may introduce additional malleability vectors.
+
+In particular, a transaction authenticated using only ANYPREVOUT signatures is malleable to anyone able to provide an alternate input satisfied by the signature -- an input changed in this way would produce a new, valid transaction paying the same recipient, but with a different txid.
+Depending on the changes to the inputs, this might conflict with the original transaction (if some inputs remain shared) or might result in a double-payment to the recipient (if they do not).
+
+Further, for a chain of transactions using the same scriptPubKey and value, and only authenticated via ANYPREVOUT signatures (as envisioned in eltoo for failure cases), it may be possible for any third party to malleate the transactions (and their txids) without having access to any of the private keys, particularly by omitting intermediate transactions.
+
+This form of malleation can be dealt with by the child transactions also using ANYPREVOUT signatures -- when a parent transaction is malleated, its children can be adjusted to reference the new txid as the input and the ANYPREVOUT signatures remain valid.
+
+However child transactions that are authorised by a SIGHASH_ALL or SIGHASH_ANYONECANPAY signature will need new signatures if their inputs are malleated in this way.
+This risk may be mitigated somewhat by using [[bip-0068.mediawiki|BIP 68]]/[[bip-0112.mediawiki|BIP 112]] relative time locks before spending a UTXO that had been authorised via an ANYPREVOUT signature with SIGHASH_ALL or SIGHASH_ANYONECANPAY: a relative timelock can ensure that the inputs have enough confirmations that they can only be replaced in the event of a large block reorg.
+Note that this approach has drawbacks: relative timelocks prevent fee-bumping via child-pays-for-parent, and have the obvious drawback of making the funds temporarily unusable until the timelock expires.
+
+==== Privacy considerations ====
+
+It is expected that ANYPREVOUT signatures will only be rarely used in practice.
+Protocol and wallet designers should aim to have their transactions use Taproot key path spends whenever possible, both for efficiency reasons due to the lower transaction weight, but also for privacy reasons to avoid third parties being able to distinguish their transactions from those of other protocols.
+
+Transactions that do use ANYPREVOUT signatures will therefore reveal information about the transaction, potentially including that cooperation was impossible, or what protocol or software was used (due to the details of the script).
+
+In order to maximise privacy, it is therefore recommended that protocol designers only use BIP 118 public keys in scripts that will be spent using at least one ANYPREVOUT signature, and either use key path spends or alternate scripts in the taproot merkle tree for any spends that can be authorised without ANYPREVOUT signatures.
+Following this recommendation may require additional script branches, which may mean disregarding this recommendation may result in a better tradeoff between cost and privacy in some circumstances.
+
+== Rationale ==
+
+
+
+== Deployment ==
+
+TODO
+
+This may be deployed as a soft-fork either concurrent with, or subsequent to the deployment of [[bip-0340.mediawiki|BIP 340]], [[bip-0341.mediawiki|BIP 341]] and [[bip-0342.mediawiki|BIP 342]].
+
+== Backwards compatibility ==
+
+As a soft fork, older software will continue to operate without modification.
+Nodes that have not upgraded to support [[bip-0341.mediawiki|BIP 341]] will see all taproot witness programs as anyone-can-spend scripts, and nodes that have upgraded to support [[bip-0341.mediawiki|BIP 341]] and [[bip-0342.mediawiki|BIP 342]] but not BIP 118 will simply treat any non-empty signature against a BIP 118 public key as valid.
+As such, nodes are strongly encourage to upgrade in order to fully validate signatures for the new public key type.
+
+Non-upgraded wallets can receive and send bitcoin from non-upgraded and upgraded wallets using SegWit version 0 programs, traditional pay-to-pubkey-hash, etc.
+Depending on the implementation, non-upgraded wallets may be able to send to SegWit version 1 programs if they support sending to [[bip-0350.mediawiki|BIP350]] Bech32m addresses and do not prevent the transaction from being broadcast due to considering the outputs non-standard.
+
+== Revisions ==
+
+Apart from being based on Taproot rather than SegWit v0, the main differences to prior revisions of this BIP are:
+
+* The sighash flag has been renamed from "NOINPUT" to "ANYPREVOUT" to reflect that while any prevout may potentially be used with the signature, some aspects of the input are still committed to, namely the input nSequence value, and (optionally) the spending conditions and amount.
+* Previously NOINPUT would have worked for direct public key spends (assuming deployment was fleshed out in a way similar to BIP 141 P2WPKH and P2WSH), however this proposal only applies to signatures via tapscript, and not direct key path spends. This means that addresses must opt-in to the ability to be spent by a SIGHASH_ANYPREVOUT or SIGHASH_ANYPREVOUTANYSCRIPT signature by including an appropriate tapscript path when the address is created.
+* NOINPUT signatures do not commit to the output's spending conditions either via scriptPubKey or the redeem/witness script. This behaviour is preserved when SIGHASH_ANYPREVOUTANYSCRIPT is used, but when SIGHASH_ANYPREVOUT is used, the signature now commits to scriptPubKey and the tapscript.
+* NOINPUT signatures did commit to the input's amount. This behaviour is preserved when SIGHASH_ANYPREVOUT is used, but not when SIGHASH_ANYPREVOUTANYSCRIPT is used.
+* OP_CODESEPARATOR in script will affect both SIGHASH_ANYPREVOUT and SIGHASH_ANYPREVOUTANYSCRIPT signatures, whereas it would not have in the previous draft.
+
+== Acknowledgements ==
+
+The SIGHASH_NOINPUT flag was first proposed by Joseph Poon in [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2016-February/012460.html February 2016], after being mentioned in the original [http://lightning.network/lightning-network-paper.pdf Lightning paper] by Joseph Poon and Thaddeus Dryja.
+This document is the result of discussions with many people and had direct input from Greg Maxwell, Jonas Nick, Pieter Wuille and others.
+
diff --git a/bip-0119.mediawiki b/bip-0119.mediawiki
new file mode 100644
index 0000000000..4ab3f5547e
--- /dev/null
+++ b/bip-0119.mediawiki
@@ -0,0 +1,695 @@
+
+
+==Abstract==
+
+This BIP proposes a new opcode, OP_CHECKTEMPLATEVERIFY, to be activated
+as a change to the semantics of OP_NOP4.
+
+The new opcode has applications for transaction congestion control and payment
+channel instantiation, among others, which are described in the Motivation
+section of this BIP.
+
+==Summary==
+
+OP_CHECKTEMPLATEVERIFY uses opcode OP_NOP4 (0xb3) as a soft fork upgrade.
+
+OP_CHECKTEMPLATEVERIFY does the following:
+
+* There is at least one element on the stack, fail otherwise
+* The element on the stack is 32 bytes long, NOP otherwise
+* The DefaultCheckTemplateVerifyHash of the transaction at the current input index is equal to the element on the stack, fail otherwise
+
+The DefaultCheckTemplateVerifyHash commits to the serialized version, locktime, scriptSigs hash (if any
+non-null scriptSigs), number of inputs, sequences hash, number of outputs, outputs hash, and
+currently executing input index.
+
+The recommended standardness rules additionally:
+
+* Reject non-32 byte as SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS.
+
+==Motivation==
+
+Covenants are restrictions on how a coin may be spent beyond key ownership.
+This is a general definition based on the legal definition which even simple
+scripts using CSV would satisfy. Covenants in Bitcoin transactions usually
+refer to restrictions on where coins can be transferred. Covenants can be
+useful to construct smart contracts. Covenants have historically been widely
+considered to be unfit for Bitcoin because they are too complex to implement
+and risk reducing the fungibility of coins bound by them.
+
+This BIP introduces a simple covenant called a *template* which enables a
+limited set of highly valuable use cases without significant risk. BIP-119
+templates allow for '''non-recursive''' fully-enumerated covenants with no dynamic
+state. CTV serves as a replacement for a pre-signed transaction oracle, which
+eliminates the trust and interactivity requirements. Examples of uses include
+vaults, non-interactive payment channel creation, congestion controlled
+batching, efficient to construct discreet log contracts, and payment pools,
+among many others. For more details on these applications, please see the
+references.
+
+
+==Detailed Specification==
+
+The below code is the main logic for verifying CHECKTEMPLATEVERIFY, described
+in pythonic pseudocode. The canonical specification for the semantics of
+OP_CHECKTEMPLATEVERIFY as implemented in C++ in the context of Bitcoin Core can
+be seen in the reference implementation.
+
+The execution of the opcode is as follows:
+
+
+The computation of this hash can be implemented as specified below (where self
+is the transaction type). Care must be taken that in any validation context,
+the precomputed data must be initialized to prevent Denial-of-Service attacks.
+Any implementation *must* cache these parts of the hash computation to avoid
+quadratic hashing DoS. All variable length computations must be precomputed
+including hashes of the scriptsigs, sequences, and outputs. See the section
+"Denial of Service and Validation Costs" below. This is not a performance
+optimization.
+
+
+
+== Abstract ==
+
+A new type of test network where signatures are used in addition to proof of work for block progress, enabling much better coordination and robustness (be reliably unreliable), for persistent, longer-term testing scenarios involving multiple independent parties.
+
+== Motivation ==
+
+Testnet is a great place to try out new things without risking real money, but it is notoriously unreliable. Huge block reorgs, long gaps in between blocks being mined or sudden bursts of blocks in rapid succession mean that realistic testing of software, especially involving multiple independent parties running software over an extended period of time, becomes infeasible in practice.
+
+A new type of test network would be more suitable for integration testing by organizations such as exchanges, or testing of next generation Layer-2 protocols like Eltoo or sidechain pegs. The goal is not to be perfectly reliable but rather to have a predictable amount of unreliability. You want a test network to behave like mainnet (i.e. no thousands of block reorgs) while also making it easier to trigger expected but rare events like a 6-block reorg. Regtest is not suitable for longer-term scenarios involving multiple independent parties because creating blocks costs nothing, so any party can completely control the test network.
+
+== Specification ==
+
+A new type of network ("signet"), which takes an additional consensus parameter called the challenge (scriptPubKey). The challenge can be a simple pubkey (P2PKH style), or a k-of-n multisig, or any other script you would want.
+
+Signet requires all blocks to have a BIP 141 commitment in the coinbase transaction. In order to provide a non-empty solution to the block challenge the block's BIP 141 commitment's optional data must include an additional commitment of the signature/solution for the block:
+
+ 1-5 bytes - Push the following (4 + x + y) bytes
+ 4 bytes - Signet header (0xecc7daa2)
+ x bytes - scriptSig
+ y bytes - scriptWitness
+
+In the special case where an empty solution is valid (ie scriptSig and scriptWitness are both empty) this additional commitment can optionally be left out. This special case is to allow non-signet-aware block generation code to be used to test a custom signet chain where the challenge is trivially true.
+
+The scriptSig is serialized by first encoding its length as CompactSize. The scriptWitness stack is serialized as described in BIP 141.
+
+Any push operations that do not start with the 4 byte Signet header are ignored. Multiple push operations with the 4 byte Signet header are ignored except for the first instance of the header.
+
+To sign the block or verify a block signature, two virtual transactions, each with a single input and output are constructed from the block as follows.
+
+The "to_spend" transaction is:
+
+ nVersion = 0
+ nLockTime = 0
+ vin[0].prevout.hash = 0000...000
+ vin[0].prevout.n = 0xFFFFFFFF
+ vin[0].nSequence = 0
+ vin[0].scriptSig = OP_0 PUSH72[ block_data ]
+ vin[0].scriptWitness = []
+ vout[0].nValue = 0
+ vout[0].scriptPubKey = signet_challenge
+
+where block_data is the serialization of the block's nVersion, hashPrevBlock, signet_merkle_root, and nTime. The signet_merkle_root is obtained by generating the merkle root of the block transactions, after modifying the coinbase witness commitment by replacing the signet solution with an empty solution (that is, the witness commitment includes a four byte push of the Signet header with no additional solution data, and no prior pushes beginning with the Signet header). This means the merkle root of the block is different from the merkle root in the signet commitment. This is needed, because the signature can never be included in the very message (in this case, a block) that is being signed.
+
+The "to_sign" transaction is:
+
+ nVersion = 0
+ nLockTime = 0
+ vin[0].prevout.hash = to_spend.txid
+ vin[0].prevout.n = 0
+ vin[0].nSequence = 0
+ vin[0].sigScript = [ signet_solution sigScript (x bytes), if any ]
+ vin[0].scriptWitness = [ signet_solution scriptWitness (y bytes), if any ]
+ vout[0].nValue = 0
+ vout[0].scriptPubKey = OP_RETURN
+
+The scriptSig and/or scriptWitness for vin[0] are filled in from the Signet header push above.
+
+To simplify block generation (mining), the signature also does not commit to the block nonce value, so that rolling the nonce to generate proof-of-work does not also require regenerating signatures. When grinding proof of work, the extended nonce cannot be used as it would invalidate the signature. Instead, simply resigning the same (or an updated) block will give a new search space.
+
+A block is considered fully validated only if the to_sign transaction is a valid spend of the to_spend transaction. It is recommended that this verification is done directly before or after the witness commitment verification, as the data required to do both is approximately the same.
+
+There is one other acceptable special case: if a block's challenge is e.g. `OP_TRUE` (`0x51`), where an empty solution would result in success, the block is also considered valid if the signet commitment is absent.
+
+== Genesis Block and Message Start ==
+
+The genesis block is the same for all signet networks, whereas the message start is defined as the first four bytes of the sha256d of the challenge script as a single data push (see below).
+
+=== Genesis Block ===
+
+* Time stamp: 1598918400
+* Nonce: 52613770
+* Difficulty: 0x1e0377ae
+* Version: 1
+
+The resulting genesis block hash is 00000008819873e925422c1ff0f99f7cc9bbb232af63a077a480a3633bee1ef6, and the block hex is 0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a008f4d5fae77031e8ad222030101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4d04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73ffffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000.
+
+=== Message Start ===
+
+The message start is defined as the first four bytes of the sha256d of the challenge script, as a single push (i.e. prefixed with the challenge script length). Example:
+
+* Challenge script = 512103ad5e0edad18cb1f0fc0d28a3d4f1f3e445640337489abb10404f2d1e086be43051ae
+* Sha256d(len || challenge script) = sha256d(25512103ad...51ae) = 7ec653a59b1912f9db10da2c461ed827d48f9404d5ef0346a6c94aadd4203646
+* First four bytes = the message start = 7ec653a5
+
+== Compatibility ==
+
+This specification is backwards compatible in the sense that existing software can use Signet out of the box.
+
+Simply by adding the network parameters for signet (magic number, etc), a client can connect to and use any signet network without further modifications. The block headers have valid proof of work, so clients can trivially check that blocks are "probably" valid.
+
+However, anyone can mine blocks that are accepted by the client for any given signet network. These blocks do not contain the required signatures, however, so any fully validating node will promptly reject them. As such, clients need to either validate the block signature inside the coinbase transaction, or connect to trusted peers.
+
+Other software need not add block signature validation code that they will not use in production. This is adequate for non-production test purposes where the goal is to have a network behave as much like mainnet as possible.
+
+== Reference implementation ==
+
+Pull request at https://github.com/bitcoin/bitcoin/pull/18267
+
+== References ==
+
+# Original mailing list thread: https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2019-March/016734.html
+# Bitcoin Wiki entry: https://en.bitcoin.it/wiki/Signet
+
+== Copyright ==
+
+This document is licensed under the Creative Commons CC0 1.0 Universal license.
diff --git a/bip-0326.mediawiki b/bip-0326.mediawiki
new file mode 100644
index 0000000000..526ab5fa96
--- /dev/null
+++ b/bip-0326.mediawiki
@@ -0,0 +1,124 @@
+
+
+
+== Abstract ==
+
+This document proposes a certain type of wallet behaviour which uses BIP341 taproot[1]. It provides a greater anonymity set for off-chain protocols which will make use of point-time-locked contracts (PTLCs) such as CoinSwap, Lightning and Discrete Log Contracts.
+
+== Motivation ==
+
+With taproot recently added to bitcoin, and wallet software about to implement taproot wallets, we are in a unique position to improve the privacy of off-chain protocols if we act soon.
+
+Taproot allows for point-time-locked contracts (PTLCs) as a more private replacement for hash-time-locked contracts (HTLCs). If an off-chain contract (for example a Lightning channel) is closed using a PTLC instead of an HTLC, then the blockchain will just see a regular taproot script instead of a hash value and preimage. However, if a contract is closed using the timelock path, then the blockchain will either see a OP_CHECKSEQUENCEVERIFY opcode or a nSequence value in the transaction, neither of which are very common today, and this would mark the closing transaction as something special and unusual.
+
+This BIP proposes to improve the privacy and fungibility of off-chain protocols by having on-chain wallets like Bitcoin Core also set the nSequence field in their taproot transactions as in BIP68[5]. This would be in place of their regular nLockTime anti-fee-sniping protection. The end result is that, if an observer of the blockchain sees a taproot spend with an nSequence value, then that could be either: a regular spend from a wallet, or an off-chain settlement transaction spent with a timelock. The two cases would be indistinguishable, and this could greatly improve the privacy and fungibility of bitcoin. The community and wallet developers should act now to implement this so that the anonymity set of nSequence transactions starts to be built up as soon as taproot itself becomes adopted by wallets.
+
+== Background ==
+
+=== Fee sniping ===
+
+Fee sniping is a hypothetical outcome of bad incentives to bitcoin mining in the low-inflation future. For a large miner the value of the transactions in the best block and the mempool can be exceeded by the cost of deliberately attempting to mine two blocks to orphan the best block. However with anti-fee-sniping protection using nLockTime or nSequence the bad miner will soon run out of transactions that can be put in the first block, which means they now need to go in the second. Anti-fee-sniping adds to the incentive to move the blockchain forward.
+
+The nLockTime field is being used this way today. It is implemented in Bitcoin Core[2] and Electrum[3], and adopted by approximately 20% of all recent transactions[4].
+
+=== Absolute vs relative locktime ===
+
+nLockTime is an absolute lock time, it allows the transaction to only be mined after a certain block height or unix time. The widespread adoption of it might have provided a good anonymity set for off-chain protocols. Unfortunately those protocols also commonly use relative lock times, because it allows contracts (for example Lightning payment channels or CoinSwaps) to remain open indefinitely as the countdown clock only starts ticking when the closing transaction is confirmed.
+
+Absolute locktimes are also still used, so we should keep using nLockTime, but also often use nSequence.
+
+=== Transaction pinning ===
+
+Transaction pinning[8] is a method for making fee bumping prohibitively expensive by abusing node protections against attacks that can waste bandwidth, CPU, and memory. This can make fee management more difficult in multipart contract protocols (such as Lightning Network or CoinSwap). One possible way of solving the problem is to include a 1-block relative timelock `1 OP_CSV` to all spend paths, making it impossible to spend the unconfirmed UTXO. Such a 1-block locktime can also be created with an nSequence value of 1. Many on-chain transactions in bitcoin spend inputs that were created just one or two blocks ago, following this BIP such transactions with `nSequence=1` would also provide cover traffic for off-chain transactions which disable transaction pinning.
+
+== Specifications ==
+
+When wallets create transactions spending UTXOs protected by BIP341 taproot, they should set either an nLockTime value or nSequence values to discourage fee sniping, by allowing the transaction to only be mined in the next block after the tip, not the current block. This BIP suggests 50% probability for using nLockTime and 50% for nSequence. If nSequence is set it should apply to at least one of the inputs of the transaction, if it has multiple inputs. It is suggested that on-chain wallets pick an input randomly.
+
+Wallets should also have a second random branch which sets the nLockTime or nSequence value even further back, so that transactions that are delayed after signing for whatever reason (e.g. high-latency mix networks) have better privacy. Existing behaviour is that with a probability of 10%, choose a random number between 0 and 99, and subtract it from the current block height. See the Bitcoin Core and Electrum source codes linked in the references for an example.
+
+nSequence can only encode up to 65535 for the block distance[5] so if the UTXOs being spent have more than 65535 confirmations, then the wallet should use nLockTime instead.
+
+=== Pseudocode ===
+
+
+def apply_anti_fee_sniping_fields(transaction, rbf_set):
+ # bip68 requires v=2
+ transaction.version = 2
+ # Initialize all nsequence to indicate the requested RBF state
+ # nsequence can not be 2**32 - 1 in order for nlocktime to take effect
+ for input in transaction.inputs:
+ if rbf_set:
+ input.nsequence = 2**32 - 3
+ else:
+ input.nsequence = 2**32 - 2
+ # always set nlocktime if any of the transaction inputs have more
+ # confirmations than 65535 or are not taproot inputs, or have
+ # unconfirmed inputs
+ # otherwise choose either nlocktime or nsequence with 50% probability
+ if not rbf_set || any(map(lambda input: input.confirmations() > 65535
+ || !input.is_taproot() || input.confirmations() == 0,
+ transaction.inputs)) || randint(2) == 0:
+ transaction.nlocktime = blockchain.height()
+ if randint(10) == 0:
+ transaction.nlocktime = max(0, transaction.nlocktime
+ - randint(0, 99))
+ # nsequence must be set in order for nlocktime to take effect
+ else:
+ transaction.nlocktime = 0
+ input_index = randint(len(transaction.inputs))
+ transaction.inputs[input_index].nsequence = transaction.inputs\
+ [input_index].confirmations()
+ if randint(10) == 0:
+ transaction.inputs[input_index].nsequence = max(1,
+ transaction.inputs[input_index].nsequence - randint(0, 99))
+
+
+== Compatibility ==
+
+This BIP doesn't need any consensus changes. It can be adopted unilaterally and gradually by wallets. Although for greater privacy it would be good for software to adopt it as soon as possible. Ideally during the process of developers implementing their taproot wallets, so that when taproot starts to be used it will already include the nSequence code.
+
+All wallet software already keeps track of how many confirmations its UTXOs have, so the information required to set the nSequence field is already available.
+
+== Acknowledgements ==
+
+Originally suggested by David Harding[6] and mentioned to me by ZmnSCPxj.
+
+Thanks to craigraw for suggesting a new value for input nsequence in the absolute locktime case[7].
+
+== Copyright ==
+
+This BIP is licensed under the Creative Commons CC0 1.0 Universal licence.
+
+== References ==
+
+[1] https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki
+
+[2] https://github.com/bitcoin/bitcoin/pull/2340
+
+[3]
+https://github.com/spesmilo/electrum/blob/7e6d65ec11c0dccfc24478471c5951d3ae586937/electrum/wallet.py#L211-L224
+
+[4]
+https://txstats.com/dashboard/db/blocks-statistics?panelId=4&fullscreen&orgId=1
+
+[5] https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki
+
+[6]
+https://lists.linuxfoundation.org/pipermail/lightning-dev/2020-January/002412.html
+
+[7] https://github.com/sparrowwallet/sparrow/issues/161#issuecomment-925003231
+
+[8] https://bitcoinops.org/en/topics/transaction-pinning/
diff --git a/bip-0327.mediawiki b/bip-0327.mediawiki
new file mode 100644
index 0000000000..7eb8d1a6ab
--- /dev/null
+++ b/bip-0327.mediawiki
@@ -0,0 +1,830 @@
+
+ BIP: 327
+ Title: MuSig2 for BIP340-compatible Multi-Signatures
+ Author: Jonas Nick
+ Tim Ruffing
+ Elliott Jin
+ Status: Active
+ License: BSD-3-Clause
+ Type: Informational
+ Created: 2022-03-22
+ Post-History: 2022-04-05: https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2022-April/020198.html [bitcoin-dev] MuSig2 BIP
+ 2022-10-11: https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2022-October/021000.html [bitcoin-dev] MuSig2 BIP
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0327
+
+
+== Introduction ==
+
+=== Abstract ===
+
+This document proposes a standard for the [https://eprint.iacr.org/2020/1261.pdf MuSig2] multi-signature scheme.
+The standard is compatible with [https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki BIP340] public keys and signatures.
+It supports ''tweaking'', which allows deriving [https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki BIP32] child keys from aggregate public keys and creating [https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki BIP341] Taproot outputs with key and script paths.
+
+=== Copyright ===
+
+This document is licensed under the 3-clause BSD license.
+
+=== Motivation ===
+
+MuSig2 is a multi-signature scheme that allows multiple signers to create a single aggregate public key and cooperatively create ordinary Schnorr signatures valid under the aggregate public key.
+Signing requires interaction between ''all'' signers involved in key aggregation.
+(MuSig2 is a ''n-of-n'' multi-signature scheme and not a ''t-of-n'' threshold-signature scheme.)
+
+The primary motivation is to create a standard that allows users of different software projects to jointly control Taproot outputs ([https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki BIP341]).
+Such an output contains a public key which, in this case, would be the aggregate of all users' individual public keys.
+It can be spent using MuSig2 to produce a signature for the key-based spending path.
+
+The on-chain footprint of a MuSig2 Taproot output is essentially a single BIP340 public key, and a transaction spending the output only requires a single signature cooperatively produced by all signers. This is '''more compact''' and has '''lower verification cost''' than each signer providing an individual public key and signature, as would be required by an ''n-of-n'' policy implemented using OP_CHECKSIGADD as introduced in ([https://github.com/bitcoin/bips/blob/master/bip-0342.mediawiki BIP342]).
+As a side effect, the number ''n'' of signers is not limited by any consensus rules when using MuSig2.
+
+Moreover, MuSig2 offers a '''higher level of privacy''' than OP_CHECKSIGADD: MuSig2 Taproot outputs are indistinguishable for a blockchain observer from regular, single-signer Taproot outputs even though they are actually controlled by multiple signers. By tweaking an aggregate public key, the shared Taproot output can have script spending paths that are hidden unless used.
+
+There are multi-signature schemes other than MuSig2 that are fully compatible with Schnorr signatures.
+The MuSig2 variant proposed below stands out by combining all the following features:
+* '''Simple Key Setup''': Key aggregation is non-interactive and fully compatible with BIP340 public keys.
+* '''Two Communication Rounds''': MuSig2 is faster in practice than previous three-round multi-signature schemes such as [https://eprint.iacr.org/2018/068.pdf MuSig1], particularly when signers are connected through high-latency anonymous links. Moreover, the need for fewer communication rounds simplifies the algorithms and reduces the probability that implementations and users make security-relevant mistakes.
+* '''Provable security''': MuSig2 has been [https://eprint.iacr.org/2020/1261.pdf proven existentially unforgeable] under the algebraic one-more discrete logarithm (AOMDL) assumption (instead of the discrete logarithm assumption required for single-signer Schnorr signatures). AOMDL is a falsifiable and weaker variant of the well-studied OMDL problem.
+* '''Low complexity''': MuSig2 has a substantially lower computational and implementation complexity than alternative schemes like [https://eprint.iacr.org/2020/1057 MuSig-DN]. However, this comes at the cost of having no ability to generate nonces deterministically and the requirement to securely handle signing state.
+
+=== Design ===
+
+* '''Compatibility with BIP340''': In this proposal, the aggregate public key is a BIP340 X-only public key, and the signature output at the end of the signing protocol is a BIP340 signature that passes BIP340 verification for the aggregate public key and a message. The individual public keys that are input to the key aggregation algorithm are ''plain'' public keys in compressed format.
+* '''Tweaking for BIP32 derivations and Taproot''': This proposal supports tweaking aggregate public keys and signing for tweaked aggregate public keys. We distinguish two modes of tweaking: ''Plain'' tweaking can be used to derive child aggregate public keys per [https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki BIP32]. ''X-only'' tweaking, on the other hand, allows creating a [https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki BIP341] tweak to add script paths to a Taproot output. See [[#tweaking-the-aggregate-public-key|below]] for details.
+* '''Non-interactive signing with preprocessing''': The first communication round, exchanging the nonces, can happen before the message or the exact set of signers is determined. Once the parameters of the signing session are finalized, the signers can send partial signatures without additional interaction.
+* '''Key aggregation optionally independent of order''': The output of the key aggregation algorithm depends on the order in which the individual public keys are provided as input. Key aggregation does not sort the individual public keys by default because applications often already have a canonical order of signers. Nonetheless, applications can mandate sorting before aggregation,Applications that sort individual public keys before aggregation should ensure that the implementation of sorting is reasonably efficient, and in particular does not degenerate to quadratic runtime on pathological inputs. and this proposal specifies a canonical order to sort the individual public keys before key aggregation. Sorting will ensure the same output, independent of the initial order.
+* '''Third-party nonce and partial signature aggregation''': Instead of every signer sending their nonce and partial signature to every other signer, it is possible to use an untrusted third-party ''aggregator'' in order to reduce the communication complexity from quadratic to linear in the number of signers. In each of the two rounds, the aggregator collects all signers' contributions (nonces or partial signatures), aggregates them, and broadcasts the aggregate back to the signers. A malicious aggregator can force the signing session to fail to produce a valid Schnorr signature but cannot negatively affect the unforgeability of the scheme.
+* '''Partial signature verification''': If any signer sends a partial signature contribution that was not created by honestly following the signing protocol, the signing session will fail to produce a valid Schnorr signature. This proposal specifies a partial signature verification algorithm to identify disruptive signers. It is incompatible with third-party nonce aggregation because the individual nonce is required for partial verification.
+* '''MuSig2* optimization''': This proposal uses an optimized scheme MuSig2*, which allows saving a point multiplication in key aggregation as compared to MuSig2. MuSig2* is proven secure in the appendix of the [https://eprint.iacr.org/2020/1261 MuSig2 paper]. The optimization consists of assigning the constant key aggregation coefficient ''1'' to the second distinct key in the list of individual public keys to be aggregated (as well as to any key identical to this key).
+* '''Size of the nonce and security''': In this proposal, each signer's nonce consists of two elliptic curve points. The [https://eprint.iacr.org/2020/1261 MuSig2 paper] gives distinct security proofs depending on the number of points that constitute a nonce. See section [[#choosing-the-size-of-the-nonce|Choosing the Size of the Nonce]] for a discussion.
+
+== Overview ==
+
+Implementers must make sure to understand this section thoroughly to avoid subtle mistakes that may lead to catastrophic failure.
+
+=== Optionality of Features ===
+
+The goal of this proposal is to support a wide range of possible application scenarios.
+Given a specific application scenario, some features may be unnecessary or not desirable, and implementers can choose not to support them.
+Such optional features include:
+* Applying plain tweaks after x-only tweaks.
+* Applying tweaks at all.
+* Dealing with messages that are not exactly 32 bytes.
+* Identifying a disruptive signer after aborting (aborting itself remains mandatory).
+* Dealing with duplicate individual public keys in key aggregation.
+If applicable, the corresponding algorithms should simply fail when encountering inputs unsupported by a particular implementation. (For example, the signing algorithm may fail when given a message which is not 32 bytes.)
+Similarly, the test vectors that exercise the unimplemented features should be re-interpreted to expect an error, or be skipped if appropriate.
+
+=== General Signing Flow ===
+
+The signers start by exchanging their individual public keys and computing an aggregate public key using the ''KeyAgg'' algorithm.
+Whenever they want to sign a message, the basic order of operations to create a multi-signature is as follows:
+
+'''First broadcast round:'''
+The signers start the signing session by running ''NonceGen'' to compute ''secnonce'' and ''pubnonce''.We treat the ''secnonce'' and ''pubnonce'' as grammatically singular even though they include serializations of two scalars and two elliptic curve points, respectively. This treatment may be confusing for readers familiar with the MuSig2 paper. However, serialization is a technical detail that is irrelevant for users of MuSig2 interfaces.
+Then, the signers broadcast their ''pubnonce'' to each other and run ''NonceAgg'' to compute an aggregate nonce.
+
+'''Second broadcast round:'''
+At this point, every signer has the required data to sign, which, in the algorithms specified below, is stored in a data structure called [[#session-context|Session Context]].
+Every signer computes a partial signature by running ''Sign'' with the secret signing key, the ''secnonce'' and the session context.
+Then, the signers broadcast their partial signatures to each other and run ''PartialSigAgg'' to obtain the final signature.
+If all signers behaved honestly, the result passes [https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki BIP340] verification.
+
+Both broadcast rounds can be optimized by using an aggregator who collects all signers' nonces or partial signatures, aggregates them using ''NonceAgg'' or ''PartialSigAgg'', respectively, and broadcasts the aggregate result back to the signers. A malicious aggregator can force the signing session to fail to produce a valid Schnorr signature but cannot negatively affect the unforgeability of the scheme, i.e., even a malicious aggregator colluding with all but one signer cannot forge a signature.
+
+'''IMPORTANT''': The ''Sign'' algorithm must '''not''' be executed twice with the same ''secnonce''.
+Otherwise, it is possible to extract the secret signing key from the two partial signatures output by the two executions of ''Sign''.
+To avoid accidental reuse of ''secnonce'', an implementation may securely erase the ''secnonce'' argument by overwriting it with 64 zero bytes after it has been read by ''Sign''.
+A ''secnonce'' consisting of only zero bytes is invalid for ''Sign'' and will cause it to fail.
+
+To simplify the specification of the algorithms, some intermediary values are unnecessarily recomputed from scratch, e.g., when executing ''GetSessionValues'' multiple times.
+Actual implementations can cache these values.
+As a result, the [[#session-context|Session Context]] may look very different in implementations or may not exist at all.
+However, computation of ''GetSessionValues'' and storage of the result must be protected against modification from an untrusted third party.
+This party would have complete control over the aggregate public key and message to be signed.
+
+=== Public Key Aggregation ===
+
+We distinguish between two public key types, namely ''plain public keys'', the key type traditionally used in Bitcoin, and ''X-only public keys''.
+Plain public keys are byte strings of length 33 (often called ''compressed'' format).
+In contrast, X-only public keys are 32-byte strings defined in [https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki BIP340].
+
+The individual public keys of signers as input to the key aggregation algorithm ''KeyAgg'' (and to ''GetSessionValues'' and ''PartialSigVerify'') are plain public keys.
+The output of ''KeyAgg'' is a [[#keyagg-context|KeyAgg Context]] which stores information required for tweaking the aggregate public key (see [[#tweaking-the-aggregate-public-key|below]]),
+and it can be used to produce an X-only aggregate public key, or a plain aggregate public key.
+In order to obtain an X-only public key compatible with BIP340 verification, implementations call the ''GetXonlyPubkey'' function with the KeyAgg Context.
+To get the plain aggregate public key, which is required for some applications of [[#tweaking-the-aggregate-public-key|tweaking]], implementations call ''GetPlainPubkey'' instead.
+
+The aggregate public key produced by ''KeyAgg'' (regardless of the type) depends on the order of the individual public keys.
+If the application does not have a canonical order of the signers, the individual public keys can be sorted with the ''KeySort'' algorithm to ensure that the aggregate public key is independent of the order of signers.
+
+The same individual public key is allowed to occur more than once in the input of ''KeyAgg'' and ''KeySort''.
+This is by design: All algorithms in this proposal handle multiple signers who (claim to) have identical individual public keys properly,
+and applications are not required to check for duplicate individual public keys.
+In fact, applications are recommended to omit checks for duplicate individual public keys in order to simplify error handling.
+Moreover, it is often impossible to tell at key aggregation which signer is to blame for the duplicate, i.e., which signer came up with an individual public key honestly and which disruptive signer copied it.
+In contrast, MuSig2 is designed to identify disruptive signers at signing time (see [[#identifying-disruptive-signers|Identifying Disruptive Signers]]).
+
+While the algorithms in this proposal are able to handle duplicate individual public keys, there are scenarios where applications may choose to abort when encountering duplicates.
+For example, we can imagine a scenario where a single entity creates a MuSig2 setup with multiple signing devices.
+In that case, duplicates may not result from a malicious signing device copying an individual public key of another signing device but from accidental initialization of two devices with the same seed.
+Since MuSig2 key aggregation would accept the duplicate keys and not error out, which would in turn reduce the security compared to the intended key setup, applications may reject duplicate individual public keys before passing them to MuSig2 key aggregation and ask the user to investigate.
+
+=== Nonce Generation ===
+
+'''IMPORTANT''': ''NonceGen'' must have access to a high-quality random generator to draw an unbiased, uniformly random value ''rand' ''.
+In contrast to BIP340 signing, the values ''k1'' and ''k2'' '''must not be derived deterministically''' from the session parameters because otherwise active adversaries can [https://medium.com/blockstream/musig-dn-schnorr-multisignatures-with-verifiably-deterministic-nonces-27424b5df9d6#e3b6 trick the victim into reusing a nonce].
+
+The optional arguments to ''NonceGen'' enable a defense-in-depth mechanism that may prevent secret key exposure if ''rand' '' is accidentally not drawn uniformly at random.
+If the value ''rand' '' was identical in two ''NonceGen'' invocations, but any other argument was different, the ''secnonce'' would still be guaranteed to be different as well (with overwhelming probability), and thus accidentally using the same ''secnonce'' for ''Sign'' in both sessions would be avoided.
+Therefore, it is recommended to provide the optional arguments ''sk'', ''aggpk'', and ''m'' if these session parameters are already determined during nonce generation.
+The auxiliary input ''extra_in'' can contain additional contextual data that has a chance of changing between ''NonceGen'' runs,
+e.g., a supposedly unique session id (taken from the application), a session counter wide enough not to repeat in practice, any nonces by other signers (if already known), or the serialization of a data structure containing multiple of the above.
+However, the protection provided by the optional arguments should only be viewed as a last resort.
+In most conceivable scenarios, the assumption that the arguments are different between two executions of ''NonceGen'' is relatively strong, particularly when facing an active adversary.
+
+In some applications, it is beneficial to generate and send a ''pubnonce'' before the other signers, their individual public keys, or the message to sign is known.
+In this case, only the available arguments are provided to the ''NonceGen'' algorithm.
+After this preprocessing phase, the ''Sign'' algorithm can be run immediately when the message and set of signers is determined.
+This way, the final signature is created quicker and with fewer round trips.
+However, applications that use this method presumably store the nonces for a longer time and must therefore be even more careful not to reuse them.
+Moreover, this method is not compatible with the defense-in-depth mechanism described in the previous paragraph.
+
+Instead of every signer broadcasting their ''pubnonce'' to every other signer, the signers can send their ''pubnonce'' to a single aggregator node that runs ''NonceAgg'' and sends the ''aggnonce'' back to the signers.
+This technique reduces the overall communication.
+A malicious aggregator can force the signing session to fail to produce a valid Schnorr signature but cannot negatively affect the unforgeability of the scheme.
+
+In general, MuSig2 signers are stateful in the sense that they first generate ''secnonce'' and then need to store it until they receive the other signers' ''pubnonces'' or the ''aggnonce''.
+However, it is possible for one of the signers to be stateless.
+This signer waits until it receives the ''pubnonce'' of all the other signers and until session parameters such as a message to sign, individual public keys, and tweaks are determined.
+Then, the signer can run ''NonceGen'', ''NonceAgg'' and ''Sign'' in sequence and send out its ''pubnonce'' along with its partial signature.
+Stateless signers may want to consider signing deterministically (see [[#modifications-to-nonce-generation|Modifications to Nonce Generation]]) to remove the reliance on the random number generator in the ''NonceGen'' algorithm.
+
+=== Identifying Disruptive Signers ===
+
+The signing protocol makes it possible to identify malicious signers who send invalid contributions to a signing session in order to make the signing session abort and prevent the honest signers from obtaining a valid signature.
+This property is called "identifiable aborts" and ensures that honest parties can assign blame to malicious signers who cause an abort in the signing protocol.
+
+Aborts are identifiable for an honest party if the following conditions hold in a signing session:
+* The contributions received from all signers have not been tampered with (e.g., because they were sent over authenticated connections).
+* Nonce aggregation is performed honestly (e.g., because the honest signer performs nonce aggregation on its own or because the aggregator is trusted).
+* The partial signatures received from all signers are verified using the algorithm ''PartialSigVerify''.
+
+If these conditions hold and an honest party (signer or aggregator) runs an algorithm that fails due to invalid protocol contributions from malicious signers, then the algorithm run by the honest party will output the index of exactly one malicious signer.
+Additionally, if the honest parties agree on the contributions sent by all signers in the signing session, all the honest parties who run the aborting algorithm will identify the same malicious signer.
+
+==== Further Remarks ====
+
+Some of the algorithms specified below may also assign blame to a malicious aggregator.
+While this is possible for some particular misbehavior of the aggregator, it is not guaranteed that a malicious aggregator can be identified.
+More specifically, a malicious aggregator (whose existence violates the second condition above) can always make signing abort and wrongly hold honest signers accountable for the abort (e.g., by claiming to have received an invalid contribution from a particular honest signer).
+
+The only purpose of the algorithm ''PartialSigVerify'' is to ensure identifiable aborts, and it is not necessary to use it when identifiable aborts are not desired.
+In particular, partial signatures are ''not'' signatures.
+An adversary can forge a partial signature, i.e., create a partial signature without knowing the secret key for the claimed individual public key.Assume an adversary wants to forge a partial signature for individual public key ''P''. It joins the signing session pretending to be two different signers, one with individual public key ''P'' and one with another individual public key. The adversary can then set the second signer's nonce such that it will be able to produce a partial signature for ''P'' but not for the other claimed signer. An explanation of the individual steps required to create a partial signature forgery can be found in [https://gist.github.com/AdamISZ/ca974ed67889cedc738c4a1f65ff620b a write up by Adam Gibson].
+However, if ''PartialSigVerify'' succeeds for all partial signatures then ''PartialSigAgg'' will return a valid Schnorr signature.Given a list of individual public keys, it is an open question whether a BIP-340 signature valid under the corresponding aggregate public key is a proof of knowledge of all secret keys of the individual public keys.
+
+=== Tweaking the Aggregate Public Key ===
+
+The aggregate public key can be ''tweaked'', which modifies the key as defined in the [[#tweaking-definition|Tweaking Definition]] subsection.
+In order to apply a tweak, the KeyAgg Context output by ''KeyAgg'' is provided to the ''ApplyTweak'' algorithm with the ''is_xonly_t'' argument set to false for plain tweaking and true for X-only tweaking.
+The resulting KeyAgg Context can be used to apply another tweak with ''ApplyTweak'' or obtain the aggregate public key with ''GetXonlyPubkey'' or ''GetPlainPubkey''.
+
+The purpose of supporting tweaking is to ensure compatibility with existing uses of tweaking, i.e., that the result of signing is a valid signature for the tweaked public key.
+The MuSig2 algorithms take arbitrary tweaks as input but accepting arbitrary tweaks may negatively affect the security of the scheme.It is an open question whether allowing arbitrary tweaks from an adversary affects the unforgeability of MuSig2.
+Instead, signers should obtain the tweaks according to other specifications.
+This typically involves deriving the tweaks from a hash of the aggregate public key and some other information.
+Depending on the specific scheme that is used for tweaking, either the plain or the X-only aggregate public key is required.
+For example, to do [https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki BIP32] derivation, you call ''GetPlainPubkey'' to be able to compute the tweak, whereas [https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki BIP341] TapTweaks require X-only public keys that are obtained with ''GetXonlyPubkey''.
+
+The tweak mode provided to ''ApplyTweak'' depends on the application:
+Plain tweaking can be used to derive child public keys from an aggregate public key using [https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki BIP32].
+On the other hand, X-only tweaking is required for Taproot tweaking per [https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki BIP341].
+A Taproot-tweaked public key commits to a ''script path'', allowing users to create transaction outputs that are spendable either with a MuSig2 multi-signature or by providing inputs that satisfy the script path.
+Script path spends require a control block that contains a parity bit for the tweaked X-only public key.
+The bit can be obtained with ''GetPlainPubkey(keyagg_ctx)[0] & 1''.
+
+== Algorithms ==
+
+The following specification of the algorithms has been written with a focus on clarity.
+As a result, the specified algorithms are not always optimal in terms of computation and space.
+In particular, some values are recomputed but can be cached in actual implementations (see [[#general-signing-flow|General Signing Flow]]).
+
+=== Notation ===
+
+The following conventions are used, with constants as defined for [https://www.secg.org/sec2-v2.pdf secp256k1]. We note that adapting this proposal to other elliptic curves is not straightforward and can result in an insecure scheme.
+* Lowercase variables represent integers or byte arrays.
+** The constant ''p'' refers to the field size, ''0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F''.
+** The constant ''n'' refers to the curve order, ''0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141''.
+* Uppercase variables refer to points on the curve with equation ''y2 = x3 + 7'' over the integers modulo ''p''.
+** ''is_infinite(P)'' returns whether ''P'' is the point at infinity.
+** ''x(P)'' and ''y(P)'' are integers in the range ''0..p-1'' and refer to the X and Y coordinates of a point ''P'' (assuming it is not infinity).
+** The constant ''G'' refers to the base point, for which ''x(G) = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798'' and ''y(G) = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8''.
+** Addition of points refers to the usual [https://en.wikipedia.org/wiki/Elliptic_curve#The_group_law elliptic curve group operation].
+** [https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication Multiplication (⋅) of an integer and a point] refers to the repeated application of the group operation.
+* Functions and operations:
+** ''||'' refers to byte array concatenation.
+** The function ''x[i:j]'', where ''x'' is a byte array and ''i, j ≥ 0'', returns a ''(j - i)''-byte array with a copy of the ''i''-th byte (inclusive) to the ''j''-th byte (exclusive) of ''x''.
+** The function ''bytes(n, x)'', where ''x'' is an integer, returns the n-byte encoding of ''x'', most significant byte first.
+** The constant ''empty_bytestring'' refers to the empty byte array. It holds that ''len(empty_bytestring) = 0''.
+** The function ''xbytes(P)'', where ''P'' is a point for which ''not is_infinite(P)'', returns ''bytes(32, x(P))''.
+** The function ''len(x)'' where ''x'' is a byte array returns the length of the array.
+** The function ''has_even_y(P)'', where ''P'' is a point for which ''not is_infinite(P)'', returns ''y(P) mod 2 == 0''.
+** The function ''with_even_y(P)'', where ''P'' is a point, returns ''P'' if ''is_infinite(P)'' or ''has_even_y(P)''. Otherwise, ''with_even_y(P)'' returns ''-P''.
+** The function ''cbytes(P)'', where ''P'' is a point for which ''not is_infinite(P)'', returns ''a || xbytes(P)'' where ''a'' is a byte that is ''2'' if ''has_even_y(P)'' and ''3'' otherwise.
+** The function ''cbytes_ext(P)'', where ''P'' is a point, returns ''bytes(33, 0)'' if ''is_infinite(P)''. Otherwise, it returns ''cbytes(P)''.
+** The function ''int(x)'', where ''x'' is a 32-byte array, returns the 256-bit unsigned integer whose most significant byte first encoding is ''x''.
+** The function ''lift_x(x)'', where ''x'' is an integer in range ''0..2256-1'', returns the point ''P'' for which ''x(P) = x''
+ Given a candidate X coordinate ''x'' in the range ''0..p-1'', there exist either exactly two or exactly zero valid Y coordinates. If no valid Y coordinate exists, then ''x'' is not a valid X coordinate either, i.e., no point ''P'' exists for which ''x(P) = x''. The valid Y coordinates for a given candidate ''x'' are the square roots of ''c = x3 + 7 mod p'' and they can be computed as ''y = ±c(p+1)/4 mod p'' (see [https://en.wikipedia.org/wiki/Quadratic_residue#Prime_or_prime_power_modulus Quadratic residue]) if they exist, which can be checked by squaring and comparing with ''c''. and ''has_even_y(P)'', or fails if ''x'' is greater than ''p-1'' or no such point exists. The function ''lift_x(x)'' is equivalent to the following pseudocode:
+*** Fail if ''x > p-1''.
+*** Let ''c = x3 + 7 mod p''.
+*** Let ''y' = c(p+1)/4 mod p''.
+*** Fail if ''c ≠ y'2 mod p''.
+*** Let ''y = y' '' if ''y' mod 2 = 0'', otherwise let ''y = p - y' ''.
+*** Return the unique point ''P'' such that ''x(P) = x'' and ''y(P) = y''.
+** The function ''cpoint(x)'', where ''x'' is a 33-byte array (compressed serialization), sets ''P = lift_x(int(x[1:33]))'' and fails if that fails. If ''x[0] = 2'' it returns ''P'' and if ''x[0] = 3'' it returns ''-P''. Otherwise, it fails.
+** The function ''cpoint_ext(x)'', where ''x'' is a 33-byte array (compressed serialization), returns the point at infinity if ''x = bytes(33, 0)''. Otherwise, it returns ''cpoint(x)'' and fails if that fails.
+** The function ''hashtag(x)'' where ''tag'' is a UTF-8 encoded tag name and ''x'' is a byte array returns the 32-byte hash ''SHA256(SHA256(tag) || SHA256(tag) || x)''.
+* Other:
+** Tuples are written by listing the elements within parentheses and separated by commas. For example, ''(2, 3, 1)'' is a tuple.
+
+=== Key Generation and Aggregation ===
+
+==== Key Generation of an Individual Signer ====
+
+
+Algorithm ''IndividualPubkey(sk)'':The ''IndividualPubkey'' algorithm matches the key generation procedure traditionally used for ECDSA in Bitcoin
+* Inputs:
+** The secret key ''sk'': a 32-byte array, freshly generated uniformly at random
+* Let ''d' = int(sk)''.
+* Fail if ''d' = 0'' or ''d' ≥ n''.
+* Return ''cbytes(d'⋅G)''.
+
+
+==== KeyAgg Context ====
+
+The KeyAgg Context is a data structure consisting of the following elements:
+* The point ''Q'' representing the potentially tweaked aggregate public key: an elliptic curve point
+* The accumulated tweak ''tacc'': an integer with ''0 ≤ tacc < n''
+* The value ''gacc'' : 1 or -1 mod n
+
+We write "Let ''(Q, gacc, tacc) = keyagg_ctx''" to assign names to the elements of a KeyAgg Context.
+
+
+Algorithm ''KeySort(pk1..u)'':
+* Inputs:
+** The number ''u'' of individual public keys with ''0 < u < 2^32''
+** The individual public keys ''pk1..u'': ''u'' 33-byte arrays
+* Return ''pk1..u'' sorted in lexicographical order.
+
+
+==== Key Aggregation ====
+
+
+Algorithm ''KeyAgg(pk1..u)'':
+* Inputs:
+** The number ''u'' of individual public keys with ''0 < u < 2^32''
+** The individual public keys ''pk1..u'': ''u'' 33-byte arrays
+* Let ''pk2 = GetSecondKey(pk1..u)''
+* For ''i = 1 .. u'':
+** Let ''Pi = cpoint(pki)''; fail if that fails and blame signer ''i'' for invalid individual public key.
+** Let ''ai = KeyAggCoeffInternal(pk1..u, pki, pk2)''.
+* Let ''Q = a1⋅P1 + a2⋅P2 + ... + au⋅Pu''
+* Fail if ''is_infinite(Q)''.
+* Let ''gacc = 1''
+* Let ''tacc = 0''
+* Return ''keyagg_ctx = (Q, gacc, tacc)''.
+
+Internal Algorithm ''KeyAggCoeffInternal(pk1..u, pk', pk2)'':
+* Let ''L = HashKeys(pk1..u)''
+* If ''pk' = pk2'':
+** Return 1
+* Return ''int(hashKeyAgg coefficient(L || pk')) mod n''The key aggregation coefficient is computed by hashing the individual public key instead of its index, which requires one more invocation of the SHA-256 compression function. However, it results in significantly simpler implementations because signers do not need to translate between public key indices before and after sorting.
+
+
+==== Applying Tweaks ====
+
+
+Algorithm ''ApplyTweak(keyagg_ctx, tweak, is_xonly_t)'':
+* Inputs:
+** The ''keyagg_ctx'': a [[#keyagg-context|KeyAgg Context]] data structure
+** The ''tweak'': a 32-byte array
+** The tweak mode ''is_xonly_t'': a boolean
+* Let ''(Q, gacc, tacc) = keyagg_ctx''
+* If ''is_xonly_t'' and ''not has_even_y(Q)'':
+** Let ''g = -1 mod n''
+* Else:
+** Let ''g = 1''
+* Let ''t = int(tweak)''; fail if ''t ≥ n''
+* Let ''Q' = g⋅Q + t⋅G''
+** Fail if ''is_infinite(Q')''
+* Let ''gacc' = g⋅gacc mod n''
+* Let ''tacc' = t + g⋅tacc mod n''
+* Return ''keyagg_ctx' = (Q', gacc', tacc')''
+
+
+=== Nonce Generation ===
+
+
+Algorithm ''NonceGen(sk, pk, aggpk, m, extra_in)'':
+* Inputs:
+** The secret signing key ''sk'': a 32-byte array (optional argument)
+** The individual public key ''pk'': a 33-byte array (see [[#signing-with-tweaked-individual-keys|Signing with Tweaked Individual Keys]] for the reason that this argument is mandatory)
+** The x-only aggregate public key ''aggpk'': a 32-byte array (optional argument)
+** The message ''m'': a byte array (optional argument)In theory, the allowed message size is restricted because SHA256 accepts byte strings only up to size of 2^61-1 bytes (and because of the 8-byte length encoding).
+** The auxiliary input ''extra_in'': a byte array with ''0 ≤ len(extra_in) ≤ 232-1'' (optional argument)
+* Let ''rand' '' be a 32-byte array freshly drawn uniformly at random
+* If the optional argument ''sk'' is present:
+** Let ''rand'' be the byte-wise xor of ''sk'' and ''hashMuSig/aux(rand')''The random data is hashed (with a unique tag) as a precaution against situations where the randomness may be correlated with the secret signing key itself. It is xored with the secret key (rather than combined with it in a hash) to reduce the number of operations exposed to the actual secret key.
+* Else:
+** Let ''rand = rand' ''
+* If the optional argument ''aggpk'' is not present:
+** Let ''aggpk = empty_bytestring''
+* If the optional argument ''m'' is not present:
+** Let ''m_prefixed = bytes(1, 0)''
+* Else:
+** Let ''m_prefixed = bytes(1, 1) || bytes(8, len(m)) || m''
+* If the optional argument ''extra_in'' is not present:
+** Let ''extra_in = empty_bytestring''
+* Let ''ki = int(hashMuSig/nonce(rand || bytes(1, len(pk)) || pk || bytes(1, len(aggpk)) || aggpk || m_prefixed || bytes(4, len(extra_in)) || extra_in || bytes(1, i - 1))) mod n'' for ''i = 1,2''
+* Fail if ''k1 = 0'' or ''k2 = 0''
+* Let ''R⁎,1 = k1⋅G, R⁎,2 = k2⋅G''
+* Let ''pubnonce = cbytes(R⁎,1) || cbytes(R⁎,2)''
+* Let ''secnonce = bytes(32, k1) || bytes(32, k2) || pk''The algorithms as specified here assume that the ''secnonce'' is stored as a 97-byte array using the serialization ''secnonce = bytes(32, k1) || bytes(32, k2) || pk''. The same format is used in the reference implementation and in the test vectors. However, since the ''secnonce'' is (obviously) not meant to be sent over the wire, compatibility between implementations is not a concern, and this method of storing the ''secnonce'' is merely a suggestion.
+The ''secnonce'' is effectively a local data structure of the signer which comprises the value triple ''(k1, k2, pk)'', and implementations may choose any suitable method to carry it from ''NonceGen'' (first communication round) to ''Sign'' (second communication round). In particular, implementations may choose to hide the ''secnonce'' in internal state without exposing it in an API explicitly, e.g., in an effort to prevent callers from reusing a ''secnonce'' accidentally.
+* Return ''(secnonce, pubnonce)''
+
+
+=== Nonce Aggregation ===
+
+
+Algorithm ''NonceAgg(pubnonce1..u)'':
+* Inputs:
+** The number ''u'' of ''pubnonces'' with ''0 < u < 2^32''
+** The public nonces ''pubnonce1..u'': ''u'' 66-byte arrays
+* For ''j = 1 .. 2'':
+** For ''i = 1 .. u'':
+*** Let ''Ri,j = cpoint(pubnoncei[(j-1)*33:j*33])''; fail if that fails and blame signer ''i'' for invalid ''pubnonce''.
+** Let ''Rj = R1,j + R2,j + ... + Ru,j''
+* Return ''aggnonce = cbytes_ext(R1) || cbytes_ext(R2)''
+
+
+=== Session Context ===
+
+The Session Context is a data structure consisting of the following elements:
+* The aggregate public nonce ''aggnonce'': a 66-byte array
+* The number ''u'' of individual public keys with ''0 < u < 2^32''
+* The individual public keys ''pk1..u'': ''u'' 33-byte arrays
+* The number ''v'' of tweaks with ''0 ≤ v < 2^32''
+* The tweaks ''tweak1..v'': ''v'' 32-byte arrays
+* The tweak modes ''is_xonly_t1..v'' : ''v'' booleans
+* The message ''m'': a byte array
+
+We write "Let ''(aggnonce, u, pk1..u, v, tweak1..v, is_xonly_t1..v, m) = session_ctx''" to assign names to the elements of a Session Context.
+
+
+Algorithm ''GetSessionValues(session_ctx)'':
+* Let ''(aggnonce, u, pk1..u, v, tweak1..v, is_xonly_t1..v, m) = session_ctx''
+* Let ''keyagg_ctx0 = KeyAgg(pk1..u)''; fail if that fails
+* For ''i = 1 .. v'':
+** Let ''keyagg_ctxi = ApplyTweak(keyagg_ctxi-1, tweaki, is_xonly_ti)''; fail if that fails
+* Let ''(Q, gacc, tacc) = keyagg_ctxv''
+* Let ''b = int(hashMuSig/noncecoef(aggnonce || xbytes(Q) || m)) mod n''
+* Let ''R1 = cpoint_ext(aggnonce[0:33]), R2 = cpoint_ext(aggnonce[33:66])''; fail if that fails and blame nonce aggregator for invalid ''aggnonce''.
+* Let ''R' = R1 + b⋅R2''
+* If ''is_infinite(R'):
+** Let final nonce ''R = G'' (see [[#dealing-with-infinity-in-nonce-aggregation|Dealing with Infinity in Nonce Aggregation]])
+* Else:
+** Let final nonce ''R = R' ''
+* Let ''e = int(hashBIP0340/challenge(xbytes(R) || xbytes(Q) || m)) mod n''
+* Return ''(Q, gacc, tacc, b, R, e)''
+
+
+
+Algorithm ''GetSessionKeyAggCoeff(session_ctx, P)'':
+* Let ''(_, u, pk1..u, _, _, _, _) = session_ctx''
+* Let ''pk = cbytes(P)''
+* Fail if ''pk'' not in ''pk1..u''
+* Return ''KeyAggCoeff(pk1..u, pk)''
+
+
+=== Signing ===
+
+
+Algorithm ''Sign(secnonce, sk, session_ctx)'':
+* Inputs:
+** The secret nonce ''secnonce'' that has never been used as input to ''Sign'' before: a 97-byte array
+** The secret key ''sk'': a 32-byte array
+** The ''session_ctx'': a [[#session-context|Session Context]] data structure
+* Let ''(Q, gacc, _, b, R, e) = GetSessionValues(session_ctx)''; fail if that fails
+* Let ''k1' = int(secnonce[0:32]), k2' = int(secnonce[32:64])''
+* Fail if ''ki' = 0'' or ''ki' ≥ n'' for ''i = 1..2''
+* Let ''k1 = k1', k2 = k2' '' if ''has_even_y(R)'', otherwise let ''k1 = n - k1', k2 = n - k2' ''
+* Let ''d' = int(sk)''
+* Fail if ''d' = 0'' or ''d' ≥ n''
+* Let ''P = d'⋅G''
+* Let ''pk = cbytes(P)''
+* Fail if ''pk ≠ secnonce[64:97]''
+* Let ''a = GetSessionKeyAggCoeff(session_ctx, P)''; fail if that failsFailing ''Sign'' when ''GetSessionKeyAggCoeff(session_ctx, P)'' fails is not necessary for unforgeability. It merely indicates to the caller that the scheme is not being used correctly.
+* Let ''g = 1'' if ''has_even_y(Q)'', otherwise let ''g = -1 mod n''
+* Let ''d = g⋅gacc⋅d' mod n'' (See [[#negation-of-the-secret-key-when-signing|Negation Of The Secret Key When Signing]])
+* Let ''s = (k1 + b⋅k2 + e⋅a⋅d) mod n''
+* Let ''psig = bytes(32, s)''
+* Let ''pubnonce = cbytes(k1'⋅G) || cbytes(k2'⋅G)''
+* If ''PartialSigVerifyInternal(psig, pubnonce, pk, session_ctx)'' (see below) returns failure, failVerifying the signature before leaving the signer prevents random or adversarially provoked computation errors. This prevents publishing invalid signatures which may leak information about the secret key. It is recommended but can be omitted if the computation cost is prohibitive.
+* Return partial signature ''psig''
+
+
+=== Partial Signature Verification ===
+
+
+Algorithm ''PartialSigVerify(psig, pubnonce1..u, pk1..u, tweak1..v, is_xonly_t1..v, m, i)'':
+* Inputs:
+** The partial signature ''psig'': a 32-byte array
+** The number ''u'' of public nonces and individual public keys with ''0 < u < 2^32''
+** The public nonces ''pubnonce1..u'': ''u'' 66-byte arrays
+** The individual public keys ''pk1..u'': ''u'' 33-byte arrays
+** The number ''v'' of tweaks with ''0 ≤ v < 2^32''
+** The tweaks ''tweak1..v'': ''v'' 32-byte arrays
+** The tweak modes ''is_xonly_t1..v'' : ''v'' booleans
+** The message ''m'': a byte array
+** The index of the signer ''i'' in the of public nonces and individual public keys with ''0 < i ≤ u''
+* Let ''aggnonce = NonceAgg(pubnonce1..u)''; fail if that fails
+* Let ''session_ctx = (aggnonce, u, pk1..u, v, tweak1..v, is_xonly_t1..v, m)''
+* Run ''PartialSigVerifyInternal(psig, pubnoncei, pki, session_ctx)''
+* Return success iff no failure occurred before reaching this point.
+
+
+
+Internal Algorithm ''PartialSigVerifyInternal(psig, pubnonce, pk, session_ctx)'':
+* Let ''(Q, gacc, _, b, R, e) = GetSessionValues(session_ctx)''; fail if that fails
+* Let ''s = int(psig)''; fail if ''s ≥ n''
+* Let ''R⁎,1 = cpoint(pubnonce[0:33]), R⁎,2 = cpoint(pubnonce[33:66])''
+* Let ''Re⁎' = R⁎,1 + b⋅R⁎,2''
+* Let effective nonce ''Re⁎ = Re⁎' '' if ''has_even_y(R)'', otherwise let ''Re⁎ = -Re⁎' ''
+* Let ''P = cpoint(pk)''; fail if that fails
+* Let ''a = GetSessionKeyAggCoeff(session_ctx, P)''''GetSessionKeyAggCoeff(session_ctx, P)'' cannot fail when called from ''PartialSigVerifyInternal''.
+* Let ''g = 1'' if ''has_even_y(Q)'', otherwise let ''g = -1 mod n''
+* Let ''g' = g⋅gacc mod n'' (See [[#negation-of-the-individual-public-key-when-partially-verifying|Negation Of The Individual Public Key When Partially Verifying]])
+* Fail if ''s⋅G ≠ Re⁎ + e⋅a⋅g'⋅P''
+* Return success iff no failure occurred before reaching this point.
+
+
+=== Partial Signature Aggregation ===
+
+
+Algorithm ''PartialSigAgg(psig1..u, session_ctx)'':
+* Inputs:
+** The number ''u'' of signatures with ''0 < u < 2^32''
+** The partial signatures ''psig1..u'': ''u'' 32-byte arrays
+** The ''session_ctx'': a [[#session-context|Session Context]] data structure
+* Let ''(Q, _, tacc, _, _, R, e) = GetSessionValues(session_ctx)''; fail if that fails
+* For ''i = 1 .. u'':
+** Let ''si = int(psigi)''; fail if ''si ≥ n'' and blame signer ''i'' for invalid partial signature.
+* Let ''g = 1'' if ''has_even_y(Q)'', otherwise let ''g = -1 mod n''
+* Let ''s = s1 + ... + su + e⋅g⋅tacc mod n''
+* Return ''sig = ''xbytes(R) || bytes(32, s)''
+
+
+=== Test Vectors and Reference Code ===
+
+We provide a naive, highly inefficient, and non-constant time [[bip-0327/reference.py|pure Python 3 reference implementation of the key aggregation, partial signing, and partial signature verification algorithms]].
+
+Standalone JSON test vectors are also available in the [[bip-0327|same directory]], to facilitate porting the test vectors into other implementations.
+
+The reference implementation is for demonstration purposes only and not to be used in production environments.
+
+== Remarks on Security and Correctness ==
+
+=== Signing with Tweaked Individual Keys ===
+
+The scheme in this proposal has been designed to be secure
+even if signers tweak their individual secret keys with tweaks known to the adversary (e.g., as in BIP32 unhardened derivation)
+before providing the corresponding individual public keys as input to key aggregation.
+In particular, the scheme as specified above requires each signer to provide a final individual public key ''pk'' already to ''NonceGen'',
+which writes it into the ''secnonce'' array
+so that it can be checked against ''IndividualPubkey(sk)'' in the ''Sign'' algorithm.
+The purpose of this check in ''Sign'' is to ensure that ''pk'',
+and thus the secret key ''sk'' that will be provided to ''Sign'',
+is determined before the signer sends out the ''pubnonce''.
+
+If the check in ''Sign'' was omitted,
+and a signer supported signing with at least two different secret keys ''sk1'' and ''sk2''
+which have been obtained via tweaking another secret key with tweaks known to the adversary,
+then the adversary could, after having seen the ''pubnonce'',
+influence whether ''sk1'' or ''sk2'' is provided to ''Sign''.
+This degree of freedom may allow the adversary to perform a generalized birthday attack and thereby forge a signature
+(see [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2022-October/021000.html bitcoin-dev mailing list post] and [https://github.com/jonasnick/musig2-tweaking writeup] for details).
+
+Checking ''pk'' against ''IndividualPubkey(sk)'' is a simple way to ensure
+that the secret key provided to ''Sign'' is fully determined already when ''NonceGen'' is invoked.
+This removes the adversary's ability to influence the secret key after having seen the ''pubnonce''
+and thus rules out the attack.Ensuring that the secret key provided to ''Sign'' is fully determined already when ''NonceGen'' is invoked is a simple policy to rule out the attack,
+but more flexible polices are conceivable.
+In fact, if the signer uses nothing but the message to be signed and the list of the individual public keys of all signers to decide which secret key to use,
+then it is not a problem that the adversary can influence this decision after having seen the ''pubnonce''.
+More formally, consider modified algorithms ''NonceGen' '' and ''Sign' '', where ''NonceGen' '' does not take the individual public key of the signer as input and does not store it in pubnonce, and Sign' does not check read the individual public key from pubnonce and does not check it against the secret key taken as input.
+Then it suffices that for each invocation of ''NonceGen' '' with output ''(secnonce, pubnonce)'',
+a function ''fsk'' is determined before sending out ''pubnonce'',
+where ''fsk'' maps a pair consisting of a list of individual public keys and a message to a secret key,
+such that the secret key ''sk'' and the session context ''session_ctx = (_, _, pk1..u, _, _, _, m)''
+provided to the corresponding invocation of ''Sign'(secnonce, sk, session_ctx)'',
+adhere to the condition ''fsk(pk1..u, m) = sk''.
+However, this requirement is complex and hard to enforce in implementations.
+The algorithms ''NonceGen'' and ''Sign'' specified in this BIP are effectively restricted to constant functions ''fsk(_, _) = sk''.
+In other words, their usage ensure that the secret key ''sk'' of the signers is determined entirely when invoking ''NonceGen'',
+which is enforced easily by letting ''NonceGen'' take the corresponding individual public key ''pk'' as input and checking ''pk'' against ''IndividualPubKey(sk)'' in ''Sign''.
+Note that the scheme as given in the [https://eprint.iacr.org/2020/1261 MuSig2 paper] does not perform the check in ''Sign''.
+However, the security model in the paper does not cover tweaking at all and assumes a single fixed secret key.
+
+=== Modifications to Nonce Generation ===
+
+Implementers must avoid modifying the ''NonceGen'' algorithm without being fully aware of the implications.
+We provide two modifications to ''NonceGen'' that are secure when applied correctly and may be useful in special circumstances, summarized in the following table.
+
+{| class="wikitable" style="margin:auto"
+! !! needs secure randomness !! needs secure counter !! needs to keep state securely !! needs aggregate nonce of all other signers (only possible for one signer)
+|-
+! NonceGen || ✓ || || ✓ ||
+|-
+! CounterNonceGen || || ✓ || ✓ ||
+|-
+! DeterministicSign || || || || ✓
+|}
+
+First, on systems where obtaining uniformly random values is much harder than maintaining a global atomic counter, it can be beneficial to modify ''NonceGen''.
+The resulting algorithm ''CounterNonceGen'' does not draw ''rand' '' uniformly at random but instead sets ''rand' '' to the value of an atomic counter that is incremented whenever it is read.
+With this modification, the secret signing key ''sk'' of the signer generating the nonce is '''not''' an optional argument and must be provided to ''NonceGen''.
+The security of the resulting scheme then depends on the requirement that reading the counter must never yield the same counter value in two ''NonceGen'' invocations with the same ''sk''.
+
+Second, if there is a unique signer who is supposed to send the ''pubnonce'' last, it is possible to modify nonce generation for this single signer to not require high-quality randomness.
+Such a nonce generation algorithm ''DeterministicSign'' is specified below.
+Note that the only optional argument is ''rand'', which can be omitted if randomness is entirely unavailable.
+''DeterministicSign'' requires the argument ''aggothernonce'' which should be set to the output of ''NonceAgg'' run on the ''pubnonce'' value of '''all''' other signers (but can be provided by an untrusted party).
+Hence, using ''DeterministicSign'' is only possible for the last signer to generate a nonce and makes the signer stateless, similar to the stateless signer described in the [[#nonce-generation|Nonce Generation]] section.
+
+==== Deterministic and Stateless Signing for a Single Signer ====
+
+
+Algorithm ''DeterministicSign(sk, aggothernonce, pk1..u, tweak1..v, is_xonly_t1..v, m, rand)'':
+* Inputs:
+** The secret signing key ''sk'': a 32-byte array
+** The aggregate public nonce ''aggothernonce'' (see [[#modifications-to-nonce-generation|above]]): a 66-byte array
+** The number ''u'' of individual public keys with ''0 < u < 2^32''
+** The individual public keys ''pk1..u'': ''u'' 32-byte arrays
+** The number ''v'' of tweaks with ''0 ≤ v < 2^32''
+** The tweaks ''tweak1..v'': ''v'' 32-byte arrays
+** The tweak methods ''is_xonly_t1..v'': ''v'' booleans
+** The message ''m'': a byte array
+** The auxiliary randomness ''rand'': a 32-byte array (optional argument)
+* If the optional argument ''rand'' is present:
+** Let ''sk' '' be the byte-wise xor of ''sk'' and ''hashMuSig/aux(rand)''
+* Else:
+** Let ''sk' = sk''
+* Let ''keyagg_ctx0 = KeyAgg(pk1..u)''; fail if that fails
+* For ''i = 1 .. v'':
+** Let ''keyagg_ctxi = ApplyTweak(keyagg_ctxi-1, tweaki, is_xonly_ti)''; fail if that fails
+* Let ''aggpk = GetXonlyPubkey(keyagg_ctxv)''
+* Let ''ki = int(hashMuSig/deterministic/nonce(sk' || aggothernonce || aggpk || bytes(8, len(m)) || m || bytes(1, i - 1))) mod n'' for ''i = 1,2''
+* Fail if ''k1 = 0'' or ''k2 = 0''
+* Let ''R⁎,1 = k1⋅G, R⁎,2 = k2⋅G''
+* Let ''pubnonce = cbytes(R⁎,2) || cbytes(R⁎,2)''
+* Let ''d = int(sk)''
+* Fail if ''d = 0'' or ''d ≥ n''
+* Let ''pk = cbytes(d⋅G)''
+* Let ''secnonce = bytes(32, k1) || bytes(32, k2) || pk''
+* Let ''aggnonce = NonceAgg((pubnonce, aggothernonce))''; fail if that fails and blame nonce aggregator for invalid ''aggothernonce''.
+* Let ''session_ctx = (aggnonce, u, pk1..u, v, tweak1..v, is_xonly_t1..v, m)''
+* Return ''(pubnonce, Sign(secnonce, sk, session_ctx))''
+
+
+=== Tweaking Definition ===
+
+Two modes of tweaking the aggregate public key are supported. They correspond to the following algorithms:
+
+
+Algorithm ''ApplyPlainTweak(P, t)'':
+* Inputs:
+** ''P'': a point
+** The tweak ''t'': an integer with ''0 ≤ t < n ''
+* Return ''P + t⋅G''
+
+
+==Abstract==
+
+This document specifies how BIP 32 extended public keys can be constructed from a BIP 327 MuSig2
+aggregate public key and how such keys should be used for key derivation.
+
+==Copyright==
+
+This BIP is licensed under the Creative Commons CC0 1.0 Universal license.
+
+==Motivation==
+
+Multiple signers can create a single aggregate public key with MuSig2 that is indistinguishable
+from a random public key. The cosigners need a method for generating additional aggregate pubkeys
+to follow the best practice of using a new address for every payment.
+
+The obvious method is for the cosigners to generate multiple public keys and produce a
+new aggregate pubkey every time one is needed. This is similar to how multisig using Bitcoin script
+works where all of the cosigners share their extended public keys and do derivation to produce
+the multisig script. The same could be done with MuSig2 and instead of producing a multisig script,
+the result would be a MuSig2 aggregate pubkey.
+
+However, it is much simpler to be able to derive from a single extended public key instead of having
+to derive from many extended public keys and aggregate them. As MuSig2 produces a normal looking
+public key, the aggregate public can be used in this way. This reduces the storage and computation
+requirements for generating new aggregate pubkeys.
+
+==Specification==
+
+A synthetic xpub can be created from a BIP 327 MuSig2 plain aggregate public key by setting
+the depth to 0, the child number to 0, and attaching a chaincode with the byte string
+868087ca02a6f974c4598924c36b57762d32cb45717167e300622c7167e38965'''Where does this
+constant chaincode come from?''' It is the SHA256 of the text MuSig2MuSig2MuSig2.
+This fixed chaincode should be used by all such synthetic xpubs following this specification.
+Unhardened child public keys can be derived from the synthetic xpub as with any other xpub. Since
+the aggregate public key is all that is necessary to produce the synthetic xpub, any aggregate
+public key that will be used in this way shares the same privacy concerns as typical xpubs.
+
+Furthermore, as there is no aggregate private key, only unhardened derivation from the aggregate
+public key is possible.
+
+When signing, all signers must compute the tweaks used in the BIP 32 derivation for the child key
+being signed for. The IL value computed in ''CKDpub'' is the tweak used at each
+derivation step. These are provided in the session context, each with a tweak mode of plain
+(''is_xonly_t = false''). When the ''Sign'' algorithm is used, the tweaks will be applied to the
+partial signatures.
+
+==Test Vectors==
+
+TBD
+
+==Backwards Compatibility==
+
+Once a synthetic xpub is created, it is fully backwards compatible with BIP 32 - only unhardened
+derivation can be done, and the signers will be able to produce a signature for any derived children.
+
+==Rationale==
+
+
+
+==Reference Implementation==
+
+TBD
+
+==Acknowledgements==
+
+Thanks to Pieter Wuille, Andrew Poelstra, Sanket Kanjalkar, Salvatore Ingala, and all others who
+participated in discussions on this topic.
diff --git a/bip-0329.mediawiki b/bip-0329.mediawiki
new file mode 100644
index 0000000000..13b332b0cc
--- /dev/null
+++ b/bip-0329.mediawiki
@@ -0,0 +1,145 @@
+
+
+==Abstract==
+
+This document specifies a format for the export of labels that may be attached to various common types of records in a wallet.
+
+==Copyright==
+
+This BIP is licensed under the BSD 2-clause license.
+
+==Motivation==
+
+The export and import of funds across different Bitcoin wallet applications is well defined through standards such as BIP39, BIP32, BIP44 etc.
+These standards are well supported and allow users to move easily between different wallets.
+There is, however, no defined standard to transfer any labels the user may have applied to the transactions, addresses, public keys, inputs, outputs or xpubs in their wallet.
+The UTXO model that Bitcoin uses makes these labels particularly valuable as they may indicate the source of funds, whether received externally or as a result of change from a prior transaction.
+In both cases, care must be taken when spending to avoid undesirable leaks of private information.
+
+Labels provide valuable guidance in this regard, and have even become mandatory when spending in several Bitcoin wallets.
+Allowing users to import and export their labels in a standardized way ensures that they do not experience lock-in to a particular wallet application.
+In addition, many wallets allow unspent outputs to be frozen or made unspendable within the wallet. Since this wallet-related metadata is similar to labels and not captured elsewhere, it is also included in this format.
+
+==Rationale==
+
+While there is currently no widely accepted format for exporting and importing labels, there are existing formats in use.
+SLIP-0015[https://github.com/satoshilabs/slips/blob/master/slip-0015.md SLIP-0015] defines a format for exporting address and output labels, but requires encryption using a private key associated with the wallet seed, and thus cannot be used independently by coordinator wallets which cannot access private keys.
+The Electrum wallet imports and exports address and transaction labels in a JSON format which could be used with other record types, but the format used is not self describing making record type identification difficult.
+
+==Specification==
+
+In order to be lightweight, human readable and well structured, this BIP uses a JSON format.
+Further, the JSON Lines format is used (also called newline-delimited JSON)[https://jsonlines.org/ jsonlines.org].
+This allows a document to be split, streamed, or incrementally added to, and limits the potential for formatting errors to invalidate an entire import.
+It is also a convenient format for command-line processing, which is often line-oriented.
+
+Further to the JSON Lines specification, an export of labels from a wallet must be a UTF-8 encoded text file, containing one record per line consisting of a valid JSON object.
+Lines are separated by \n. Multiline values are not permitted.
+Each JSON object must contain 3 or 4 key/value pairs, defined as follows:
+
+{| class="wikitable"
+|-
+! Key
+! Description
+|-
+| type
+| One of tx, addr, pubkey, input, output or xpub
+|-
+| ref
+| Reference to the transaction, address, public key, input, output or extended public key
+|-
+| label
+| The label applied to the reference
+|-
+| origin
+| Optional key origin information referencing the wallet associated with the label
+|-
+| spendable
+| One of true or false, denoting if an output should be spendable by the wallet
+|}
+
+The reference is defined for each type as follows:
+
+{| class="wikitable"
+|-
+! Type
+! Description
+! Example
+|-
+| tx
+| Transaction id in hexadecimal format
+| f91d0a8a78462bc59398f2c5d7a84fcff491c26ba54c4833478b202796c8aafd
+|-
+| addr
+| Address in base58 or bech32 format
+| bc1q34aq5drpuwy3wgl9lhup9892qp6svr8ldzyy7c
+|-
+| pubkey
+| 32, 33 or 65 byte public key in hexadecimal format
+| 0283409659355b6d1cc3c32decd5d561abaac86c37a353b52895a5e6c196d6f448
+|-
+| input
+| Transaction id and input index separated by a colon
+| f91d0a8a78462bc59398f2c5d7a84fcff491c26ba54c4833478b202796c8aafd:0
+|-
+| output
+| Transaction id and output index separated by a colon
+| f91d0a8a78462bc59398f2c5d7a84fcff491c26ba54c4833478b202796c8aafd:1
+|-
+| xpub
+| Extended public key as defined by BIP32
+| xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8Nq...
+|}
+
+Each JSON object must contain both type and ref properties. The label, origin and spendable properties are optional. If the label or spendable properties are omitted, the importing wallet should not alter these values. The origin property should only appear where type is tx, and the spendable property only where type is output.
+
+If present, the optional origin property must contain an abbreviated output descriptor (as defined by BIP380[https://github.com/bitcoin/bips/blob/master/bip-0380.mediawiki BIP-0380]) describing a BIP32 compatible originating wallet, including all key origin information but excluding any actual keys, any child path elements, or a checksum.
+This property should be used to disambiguate transaction labels from different wallets contained in the same export, particularly when exporting multiple accounts derived from the same seed.
+
+Care should be taken when exporting due to the privacy sensitive nature of the data.
+Encryption in transit over untrusted networks is highly recommended, and encryption at rest should also be considered.
+Unencrypted exports should be deleted as soon as possible.
+For security reasons no private key types are defined.
+
+==Importing==
+
+* An importing wallet may ignore records it does not store, and truncate labels if necessary. A suggested default for maximum label length is 255 characters, and an importing wallet should consider warning the user if truncation is applied.
+* Wallets importing public key records may derive addresses from them to match against known wallet addresses.
+* Wallets importing extended public keys may match them against signers, for example in a multisig setup.
+
+==Backwards Compatibility==
+
+The nature of this format makes it naturally extensible to handle other record types.
+However, importing wallets complying to this specification may ignore types not defined here.
+
+==Test Vectors==
+
+The following fragment represents a wallet label export:
+
+
+==Abstract==
+
+This document specifies a P2P protocol extension for reconciliation of transaction announcements between 2 nodes, which is a building block for efficient transaction relay protocols (e.g., [https://arxiv.org/pdf/1905.10518.pdf Erlay]). This is a step towards increasing the connectivity of the network for almost no bandwidth cost.
+
+==Motivation==
+
+Currently in the Bitcoin network, every 32-byte transaction ID is announced in at least one direction between every pair of connected peers, via INV messages. This results in high cost of announcing transactions: ''O(nodes * connections_per_node)''.
+
+A reconciliation-based protocol which uses the technique suggested in this document can have better scaling properties than INV-based flooding.
+
+Increasing the connectivity of the network makes the network more robust to partitioning attacks; thus, improving the bandwidth scaling of transaction relay to ''O(nodes)'' (and without a high constant overhead) would allow us to improve the security of the network by increasing connectivity. It would also reduce the bandwidth required to run a Bitcoin node and potentially enable more users to run full nodes.
+
+===Erlay===
+
+[https://arxiv.org/pdf/1905.10518.pdf Erlay] is an example of a high-level transaction relay protocol which employs set reconciliation for bandwidth efficiency.
+
+Note that what we are going to describe here is a modified version from the protocol (it is different from what is presented in the paper).
+
+Erlay uses both flooding (announcing using INV messages to all peers) and reconciliation to announce transactions.
+Flooding is expensive, so Erlay seeks to use it only when necessary to facilitate rapid relay over a small subset of connections.
+
+Efficient set reconciliation is meant to deliver transactions to those nodes which didn't receive a transaction via flooding, and also just make sure remaining connections are in sync (directly connected pairs of nodes are aware they have nothing to learn from each other).
+
+Efficient set reconciliation works as follows:
+1) every node keeps a reconciliation set for each peer, in which transactions are placed which would have been announced using INV messages absent this protocol
+2) once in a while every node chooses a peer from its reconciliation queue to reconcile with, resulting in both sides learning the transactions known to the other side
+3) after every reconciliation round, the corresponding reconciliation set is cleared
+
+A more detailed description of a set reconciliation round can be found below.
+
+Erlay allows us to:
+* save a significant portion of the bandwidth consumed by a node
+* increase network connectivity for almost no bandwidth or latency cost
+* keep transaction propagation latency at the same level
+
+This document proposes a P2P-layer extension which is required to enable efficient reconciliation-based protocols (like Erlay) for transaction relay.
+
+==Specification==
+
+===New data structures===
+
+Several new data structures are introduced to the P2P protocol first, to aid with efficient transaction relay.
+
+====32-bit short transaction IDs====
+=
+Short IDs are computed as follows:
+* Let ''salt1'' and ''salt2'' be the entropy contributed by both sides; see the "sendtxrcncl" message further for details how they are exchanged.
+* Sort the two salts such that ''salt1 ≤ salt2'' (which side sent what doesn't matter).
+* Compute ''h = TaggedHash("Tx Relay Salting", salt1, salt2)'', where the two salts are encoded in 64-bit little-endian byte order, and TaggedHash is specified by [https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki BIP-340].
+* Let ''k0'' be the 64-bit integer obtained by interpreting the first 8 bytes of ''h'' in little-endian byte order.
+* Let ''k1'' be the 64-bit integer obtained by interpreting the second 8 bytes of ''h'' in little-endian byte order.
+* Let ''s = SipHash-2-4((k0,k1),wtxid)'', where ''wtxid'' is the transaction hash including witness data as defined by BIP141.
+* The short ID is equal to ''1 + (s mod 0xFFFFFFFF)''.
+
+This results in approximately uniformly distributed IDs in the range ''[1..0xFFFFFFFF]'', which is a requirement for using them as elements in 32-bit sketches. See the next paragraph for details.
+
+====Short transaction ID sketches====
+
+Reconciliation-based relay uses [https://www.cs.bu.edu/~reyzin/code/fuzzy.html PinSketch] BCH-based secure sketches as introduced by the [https://www.cs.bu.edu/~reyzin/fuzzy.html Fuzzy Extractors paper]. They are a form of set checksums with the following properties:
+* Sketches have a predetermined capacity, and when the number of elements in the set does not exceed the capacity, it is always possible to recover the entire set from the sketch by decoding the sketch. A sketch of nonzero b-bit elements with capacity c can be stored in bc bits.
+* A sketch of the [https://en.wikipedia.org/wiki/Symmetric_difference symmetric difference] between the two sets (i.e., all elements that occur in one but not both input sets), can be obtained by combining the sketches of those sets.
+
+The sketches used here consists of elements of the [https://en.wikipedia.org/wiki/Finite_field finite field] ''GF(232)''. Specifically, we represent finite field elements as polynomials in ''x'' over ''GF(2)'' modulo ''x327 + x3 + x2 + 1''. To map integers to finite field elements, simply treat each bit ''i'' (with value ''2i'') in the integer as the coefficient of ''xi'' in the polynomial representation. For example the integer ''101 = 26 + 25 + 22 + 1'' is mapped to field element ''x6 + x5 + x2 + 1''. These field elements can be added and multiplied together, but the specifics of that are out of scope for this document.
+
+A short ID sketch with capacity ''c'' consists of a sequence of ''c'' field elements. The first is the sum of all short IDs in the set, the second is the sum of the 3rd powers of all short IDs, the third is the sum of the 5th powers etc., up to the last element with is the sum of the ''(2c-1)''th powers. These elements are then encoded as 32-bit integers in little endian byte order, resulting in a ''4c''-byte serialization.
+
+The following Python 3.2+ code implements the creation of sketches:
+FIELD_BITS = 32
+FIELD_MODULUS = (1 << FIELD_BITS) + 0b10001101
+
+def mul2(x):
+ """Compute 2*x in GF(2^FIELD_BITS)"""
+ return (x << 1) ^ (FIELD_MODULUS if x.bit_length() >= FIELD_BITS else 0)
+
+def mul(x, y):
+ """Compute x*y in GF(2^FIELD_BITS)"""
+ ret = 0
+ for bit in [(x >> i) & 1 for i in range(x.bit_length())]:
+ ret, y = ret ^ bit * y, mul2(y)
+ return ret
+
+def create_sketch(shortids, capacity):
+ """Compute the bytes of a sketch for given shortids and given capacity."""
+ odd_sums = [0 for _ in range(capacity)]
+ for shortid in shortids:
+ squared = mul(shortid, shortid)
+ for i in range(capacity):
+ odd_sums[i] ^= shortid
+ shortid = mul(shortid, squared)
+ return b''.join(elem.to_bytes(4, 'little') for elem in odd_sums)
+
+
+The [https://github.com/sipa/minisketch/ minisketch] library implements the construction, merging, and decoding of these sketches efficiently.
+
+===Intended Protocol Flow===
+
+Set reconciliation primarily consists of the transmission and decoding of a reconciliation set sketch upon request.
+
+Since sketches are based on the WTXIDs, the negotiation and support of Erlay should be enabled only if both peers signal [https://github.com/bitcoin/bips/blob/master/bip-0339.mediawiki BIP-339] support.
+
+[[File:bip-0330/recon_scheme_merged.png|framed|center|Protocol flow]]
+
+====Sketch extension====
+
+If a node is unable to reconstruct the set difference from the received sketch, the node then makes a request for sketch extension. The peer would then send an extension, which is a sketch of a higher capacity (allowing to decode more differences) over the same transactions minus the sketch part which was already sent initially (to save bandwidth).
+To allow this optimization, the initiator is supposed to locally store a sketch received initially.
+This optimization is possible because extending a sketch is just concatenating new elements to an array.
+
+===New messages===
+Several new protocol messages are added: sendtxrcncl, reqrecon, sketch, reqsketchext, reconcildiff. This section describes their serialization, contents, and semantics.
+
+In what follows, all integers are serialized in little-endian byte order. Boolean values are encoded as a single byte that must be 0 or 1 exactly. Arrays are serialized with the CompactSize prefix that encodes their length, as is common in other P2P messages.
+
+====sendtxrcncl====
+The sendtxrcncl message announces support for the reconciliation protocol. It is expected to be only sent once, and ignored by nodes that don't support it.
+
+Should be sent before "verack" and accompanied by "wtxidrelay" (in any order).
+
+If "sendtxrcncl" was sent after "verack", the sender should be disconnected.
+
+If "sendtxrcncl" was sent before "verack", but by "verack" the "wtxidrelay" message was not received,
+"sendtxrcncl" should be ignored. The connection should proceed normally, but as if reconciliation
+was not supported.
+
+Must not be sent if peer specified no support for transaction relay (fRelay=0) in "version".
+Otherwise, the sender should be disconnected.
+
+Its payload consists of:
+{|class="wikitable"
+! Data type !! Name !! Description
+|-
+| uint32 || version || Sender must set this to 1 currently, otherwise receiver should ignore the message. v1 is the lowest protocol version, everything below that is a protocol violation.
+|-
+| uint64 || salt || The salt used in the short transaction ID computation.
+|}
+
+After both peers have confirmed support by sending "sendtxrcncl", the initiator of the P2P connection assumes the role of reconciliation initiator (will send "reqrecon" messages) and the other peer assumes the role of reconciliation responder (will respond to "reqrecon" messages).
+"reqrecon" messages can only be sent by the reconciliation initiator.
+
+====reqrecon====
+The reqrecon message initiates a reconciliation round.
+
+{|class="wikitable"
+! Data type !! Name !! Description
+|-
+| uint16 || set_size || Size of the sender's reconciliation set, used to estimate set difference.
+|-
+| uint16 || q || Coefficient used to estimate set difference. Multiplied by PRECISION=(2^15) - 1 and rounded up by the sender and divided by PRECISION by the receiver.
+|}
+
+Upon receipt of a "reqrecon" message, the receiver:
+* Constructs and sends a "sketch" message (see below), with a sketch of certain ''capacity=f(set_size, local_set_size, q)'' (the exact function is suggested below), where ''local_set_size'' represents size of the receiver's reconciliation set.
+* Makes a snapshot of their current reconciliation set, and clears the set itself. The snapshot is kept until a "reconcildiff" message is received by the node.
+
+No new "reqrecon" message can be sent until a "reconcildiff" message is sent.
+
+====sketch====
+The sketch message is used to communicate a sketch required to perform set reconciliation.
+
+{|class="wikitable"
+! Data type !! Name !! Description
+|-
+| byte[] || skdata || The sketch of the sender's reconciliation snapshot
+|}
+
+The sketch message may be received in two cases.
+
+1. Initial sketch. Upon receipt of a "sketch" message, a node computes the difference sketch by combining the received sketch with a sketch computed locally for a corresponding reconciliation set. The receiving node then tries to decode the difference sketch and based on the result:
+* If the decoding failed, the receiving node requests an extension sketch by sending a "reqsketchext" message. Alternatively, the node may terminate the reconciliation right away by sending a "reconcildiff" message is sent with the failure flag set (success=false).
+* If the decoding succeeded, a "reconcildiff" message with success=true.
+The receiver also makes snapshot of their current reconciliation set, and clears the set itself. The snapshot is kept until a "reconcildiff" message is sent by the node. It is needed to enable sketch extension.
+
+2. Sketch extension. By combining the sketch extension with the initially received sketch, an extended sketch is obtained. The receiving node then computes the extended difference sketch by combining the received extended sketch with an extended sketch computed locally over a corresponding reconciliation set snapshot. The receiving node then tries to decode the extended difference sketch and based on the result:
+* If the decoding failed, the receiving node terminates the reconciliation right away by sending a "reconcildiff" message is sent with the failure flag set (success=false).
+* If the decoding succeeded, a "reconcildiff" message with success=true.
+
+In either cases, a "reconcildiff" with success=false should also be accompanied with announcing all transactions from the reconciliation set (or set snapshot if failed after extension) as a fallback to flooding.
+A "reconcildiff" with success=true should contain unknown short IDs of the transactions from the decoded difference, corresponding to the transactions missing on the sender's side. Known short IDs from the difference correspond to what the receiver of the message is missing, and they should be announced via an "inv" message.
+
+====reqsketchext====
+The reqsketchext message is used by reconciliation initiator to signal that initial set reconciliation has failed and a sketch extension is needed to find set difference.
+
+It has an empty payload.
+
+Upon receipt of a "reqsketchext" message, a node responds to it with a "sketch" message, which contains a sketch extension: a sketch (of the same transactions sketched initially) of higher capacity without the part sent initially.
+
+====reconcildiff====
+The reconcildiff message is used by reconciliation initiator to announce transactions which are found to be missing during set reconciliation on the sender's side.
+
+{|class="wikitable"
+! Data type !! Name !! Description
+|-
+| uint8 || success || Indicates whether sender of the message succeeded at set difference decoding.
+|-
+| uint32[] || ask_shortids || The short IDs that the sender did not have.
+|}
+
+Upon receipt a "reconcildiff" message with ''success=1'' (reconciliation success), a node sends an "inv" message for the transactions requested by 32-bit IDs (first vector) containing their wtxids (with parent transactions occurring before their dependencies).
+If ''success=0'' (reconciliation failure), receiver should announce all transactions from the reconciliation set via an "inv" message.
+In both cases, transactions the sender of the message thinks the receiver is missing are announced via an "inv" message.
+The regular "inv" deduplication should apply.
+
+The snapshot of the corresponding reconciliation set is cleared by the sender and the receiver of the message.
+
+The sender should also send their own "inv" message along with the reconcildiff message to announce transactions which are missing on the receiver's side.
+
+==Local state==
+
+This BIP suggests a stateful protocol and it requires storing several variables at every node to operate properly.
+
+====Reconciliation salt====
+When negotiating reconciliation support, peers send each other their contribution to the reconciliation salt (see how we construct short IDs above). These salts (or just the resulting salt) should be stored on both sides of the connection.
+
+====Reconciliation sets====
+Every node stores a set of wtxids for every peer which supports transaction reconciliation, representing the transactions which would have been sent according to the regular flooding protocol.
+Incoming transactions are added to sets when those transactions are received (if they satisfy the policies such as minimum fee set by a peer).
+A reconciliation set is moved to the corresponding set snapshot after the transmission of the initial sketch.
+
+====Reconciliation set snapshot====
+After transmitting the initial sketch (either sending or receiving of the reconcildiff message), every node should store the snapshot of the current reconciliation set, and clear the set.
+This is important to make sketch extension more stable (extension should be computed over the set snapshot). Otherwise, extension would contain transactions received after sending out the initial sketch.
+The snapshot is cleared after the end of the reconciliation round (sending or receiving of the reconcildiff message).
+
+====Sketch capacity estimation and q-coefficient====
+
+Earlier we suggested that upon receiving a reconciliation request, a node should estimate the sketch capacity it should send: ''capacity=f(set_size, local_set_size, q)''.
+
+We suggest the following function: ''capacity=|set_size - local_set_size| + q * min(set_size, local_set_size) + c''.
+
+Intuitively, ''q'' represents the discrepancy in sets: the closer the sets are, the lower optimal ''q'' is.
+Per the Erlay paper, ''q'' should be derived as an optimal ''q'' value for the previous reconciliation with a given peer, once the actual set sizes and set difference are known.
+For example, if in previous round ''set_size=30'' and ''local_set_size=20'', and the *actual* difference was ''12'', then a node should compute ''q'' as following:
+''q=(12 - |30-20|) / min(30, 20)=0.1''
+
+The derivation of ''q'' can be changed according to the version of the protocol. For example, a static value could be chosen for simplicity. However, we suggest that ''q'' remains a parameter sent in every reconciliation request to enable future compatibility with more sophisticated (non-static) choices of this parameter.
+
+As for the ''c'' parameter, it is suggested to use ''c=1'' to avoid sending empty sketches and reduce the overhead caused by under-estimations.
+
+==Backward compatibility==
+
+Older clients remain fully compatible and interoperable after this change.
+
+Clients which do not implement this protocol remain fully compatible after this change using existing protocols, because transaction announcement reconciliation is used only for peers that negotiate support for it.
+
+==Rationale==
+
+====Why use PinSketch for set reconciliation?====
+
+PinSketch is more bandwidth efficient than IBLT, especially for the small differences in sets we expect to operate over.
+PinSketch is as bandwidth efficient as CPISync, but PinSketch has quadratic decoding complexity, while CPISync have cubic decoding complexity. This makes PinSketch significantly faster.
+
+====Why use 32-bit short transaction IDs?====
+
+To use Minisketch in practice, transaction IDs should be shortened (ideally, not more than 64 bits per element).
+A small number of bits per transaction also allows saving extra bandwidth and make operations over sketches faster.
+According to our estimates, 32 bits provides low collision rate in a non-adversarial model (which is enabled by using independent salts per-link).
+
+====Why use sketch extensions instead of bisection?====
+
+Bisection is an alternative to sketch extensions, per which a second sketch with the same initial capacity is computed over half of the txID space.
+Due to the linearity of sketches, transmitting just this one allows a reconciliation initiator to compute the sketch of the same capacity of another half. Two sketches allow the initiator to reconstruct twice as many differences as was allowed by an initial sketch.
+
+In practice this allows the initiator to amortize the bandwidth overhead of initial reconciliation failure, similarly to extension sketches, making the overhead negligible.
+
+The main benefit of sketch extensions is a much simpler implementation. Implementing bisection is hard (see [https://github.com/naumenkogs/bitcoin/commit/b5c92a41e4cc0599504cf838d20212f1a403e573 implementation]) because, in the end, we have to operate with two sketches and handle scenarios where one sketch decoded and another sketch failed.
+
+It becomes even more difficult if in the future we decide to allow more than one extension/bisection. Bisection in this case have to be recursive (and spawn 4/8/16/... sketches), while for extensions we always end up with one extended sketch.
+
+Sketch extensions are also more flexible: extending a sketch of capacity 10 with 4 more means just computing a sketch of capacity 14 and sending the extension, while for bisection increasing the capacity to something different than 10*2/10*4/10*8/... is sophisticated implementation-wise.
+
+The only advantage of bisection is that it doesn't require computing sketches of higher capacities (exponential cost). We believe that since
+the protocol is currently designed to operate in the conditions where sketches usually have at most the capacity of 20, this efficiency is not crucial.
+
+==Implementation==
+
+https://github.com/bitcoin/bitcoin/pull/21515
+
+==Acknowledgments==
+
+A large fraction of this proposal was done during designing Erlay with Gregory Maxwell, Sasha Fedorova and Ivan Beschastnikh.
+We would like to thank Suhas Daftuar for contributions to the design and BIP structure.
+We would like to thank Ben Woosley for contributions to the high-level description of the idea.
+
+==Copyright==
+
+This document is licensed under the Creative Commons CC0 1.0 Universal license.
diff --git a/bip-0330/minisketch.py b/bip-0330/minisketch.py
new file mode 100755
index 0000000000..5e3977935d
--- /dev/null
+++ b/bip-0330/minisketch.py
@@ -0,0 +1,157 @@
+#!/usr/bin/env python3
+
+######## ENCODING and DECODING ########
+
+FIELD_BITS = 32
+FIELD_MODULUS = (1 << FIELD_BITS) + 0b10001101
+
+def mul2(x):
+ """Compute 2*x in GF(2^FIELD_BITS)"""
+ return (x << 1) ^ (FIELD_MODULUS if x.bit_length() >= FIELD_BITS else 0)
+
+def mul(x, y):
+ """Compute x*y in GF(2^FIELD_BITS)"""
+ ret = 0
+ for bit in [(x >> i) & 1 for i in range(x.bit_length())]:
+ ret ^= bit * y
+ y = mul2(y)
+ return ret
+
+######## ENCODING only ########
+
+def sketch(shortids, capacity):
+ """Compute the bytes of a sketch for given shortids and given capacity."""
+ odd_sums = [0 for _ in range(capacity)]
+ for shortid in shortids:
+ squared = mul(shortid, shortid)
+ for i in range(capacity):
+ odd_sums[i] ^= shortid
+ shortid = mul(shortid, squared)
+ return b''.join(elem.to_bytes(4, 'little') for elem in odd_sums)
+
+######## DECODING only ########
+
+import random
+
+def inv(x):
+ """Compute 1/x in GF(2^FIELD_BITS)"""
+ t = x
+ for i in range(FIELD_BITS - 2):
+ t = mul(mul(t, t), x)
+ return mul(t, t)
+
+
+def berlekamp_massey(s):
+ """Given a sequence of LFSR outputs, find the coefficients of the LFSR."""
+ C, B, L, m, b = [1], [1], 0, 1, 1
+ for n in range(len(s)):
+ d = s[n]
+ for i in range(1, L + 1):
+ d ^= mul(C[i], s[n - i])
+ if d == 0:
+ m += 1
+ else:
+ T = list(C)
+ while len(C) <= len(B) + m:
+ C += [0]
+ t = mul(d, inv(b))
+ for i in range(len(B)):
+ C[i + m] ^= mul(t, B[i])
+ if 2 * L <= n:
+ L, B, b, m = n + 1 - L, T, d, 1
+ else:
+ m += 1
+ return C[0:L + 1]
+
+def poly_monic(p):
+ """Return the monic multiple of p, or 0 if the input is 0."""
+ if len(p) == 0:
+ return []
+ i = inv(p[-1])
+ return [mul(v, i) for v in p]
+
+def poly_divmod(m, p):
+ """Compute the polynomial quotient p/m, and replace p with p mod m."""
+ assert(len(m) > 0 and m[-1] == 1)
+ div = [0 for _ in range(len(p) - len(m) + 1)]
+ while len(p) >= len(m):
+ div[len(p) - len(m)] = p[-1]
+ for i in range(len(m)):
+ p[len(p) - len(m) + i] ^= mul(p[-1], m[i])
+ assert(p[-1] == 0)
+ p.pop()
+ while (len(p) > 0 and p[-1] == 0):
+ p.pop()
+ return div
+
+def poly_gcd(a, b):
+ """Compute the GCD of a and b (destroys the inputs)."""
+ if len(a) < len(b):
+ a, b = b, a
+ while len(b):
+ if len(b) == 1:
+ return [1]
+ b = poly_monic(b)
+ poly_divmod(b, a)
+ a, b = b, a
+ return a
+
+def poly_sqr(p):
+ """Compute the coefficients of the square of polynomial with coefficients p."""
+ return [0 if i & 1 else mul(p[i // 2], p[i // 2]) for i in range(2 * len(p))]
+
+def poly_trace(m, a):
+ """Compute the coefficients of the trace polynomial of (a*x) mod m."""
+ out = [0, a]
+ for i in range(FIELD_BITS - 1):
+ out = poly_sqr(out)
+ while len(out) < 2:
+ out += [0]
+ out[1] = a
+ poly_divmod(m, out)
+ return out
+
+def find_roots_inner(p, a):
+ """Recursive helper function for find_roots (destroys p). a is randomizer."""
+ # p must be monic
+ assert(len(p) > 0 and p[-1] == 1)
+ # Deal with degree 0 and degree 1 inputs
+ if len(p) == 1:
+ return []
+ elif len(p) == 2:
+ return [p[0]]
+ # Otherwise, split p in left*right using parameter a_vals[0].
+ t = poly_monic(poly_trace(p, a))
+ left = poly_gcd(list(p), t)
+ right = poly_divmod(list(left), p)
+ # Invoke recursion with the remaining a_vals.
+ ret_right = find_roots_inner(right, mul2(a))
+ ret_left = find_roots_inner(left, mul2(a))
+ # Concatenate roots
+ return ret_left + ret_right
+
+def find_roots(p):
+ """Find the roots of polynomial with coefficients p."""
+ # Compute x^(2^FIELD_BITS)+x mod p in a roundabout way.
+ t = poly_trace(p, 1)
+ t2 = poly_sqr(t)
+ for i in range(len(t)):
+ t2[i] ^= t[i]
+ poly_divmod(p, t2)
+ # If distinct from 0, p is not fully factorizable into non-repeating roots.
+ if len(t2):
+ return None
+ # Invoke the recursive splitting algorithm
+ return find_roots_inner(list(p), random.randrange(1, 2**32-1))
+
+def decode(sketch):
+ """Recover the shortids from a sketch."""
+ odd_sums = [int.from_bytes(sketch[i*4:(i+1)*4], 'little') for i in range(len(sketch) // 4)]
+ sums = []
+ for i in range(len(odd_sums) * 2):
+ if i & 1:
+ sums.append(mul(sums[(i-1)//2], sums[(i-1)//2]))
+ else:
+ sums.append(odd_sums[(i+1)//2])
+ return find_roots(list(reversed(berlekamp_massey(sums))))
+
diff --git a/bip-0330/recon_scheme_merged.png b/bip-0330/recon_scheme_merged.png
new file mode 100644
index 0000000000..546b4170c4
Binary files /dev/null and b/bip-0330/recon_scheme_merged.png differ
diff --git a/bip-0331.mediawiki b/bip-0331.mediawiki
new file mode 100644
index 0000000000..08927a23fb
--- /dev/null
+++ b/bip-0331.mediawiki
@@ -0,0 +1,430 @@
+
+
+==Abstract==
+
+Peer-to-peer protocol messages enabling nodes to request and relay the unconfirmed ancestor package
+of a given transaction, and to request and relay transactions in batches.
+
+==Motivation==
+
+===Propagate High Feerate Transactions===
+
+Since v0.13, Bitcoin Core has used ancestor packages instead of individual transactions to evaluate
+the incentive compatibility of transactions in the mempool
+[https://github.com/bitcoin/bitcoin/pull/7594 Add tracking of ancestor packages] and
+selecting them for inclusion in blocks
+[https://github.com/bitcoin/bitcoin/pull/7600 Select transactions using feerate-with-ancestors].
+Incentive-compatible mempool and miner policies help create a fair, fee-based market for block
+space. While miners maximize transaction fees in order to earn higher block rewards, non-mining
+users participating in transaction relay reap many benefits from employing policies that result in a
+mempool with similar contents, including faster compact block relay and more accurate fee
+estimation. Additionally, users may take advantage of mempool and miner policy to bump the priority
+of their transactions by attaching high-fee descendants (Child Pays for Parent or CPFP).
+
+Only individually considering transactions for submission to the mempool creates a limitation in
+the node's ability to determine which transactions to include in the mempool, since it cannot take
+into account descendants until all the transactions are in the mempool. Similarly, it cannot use a
+transaction's descendants when considering which of two conflicting transactions to keep (Replace by
+Fee or RBF).
+
+When a user's transaction does not meet a mempool's minimum feerate and they cannot create a
+replacement transaction directly, their transaction will simply be rejected by this mempool or
+evicted if already included. They also cannot attach a descendant to pay for replacing a conflicting
+transaction; it would be rejected for spending inputs that do not exist.
+
+This limitation harms users' ability to fee-bump their transactions. Further, it presents security and complexity
+issues in contracting protocols which rely on presigned, time-sensitive transactions'''Examples of time-sensitive pre-signed transactions in L2 protocols.'''
+* [https://github.com/lightning/bolts/blob/master/03-transactions.md#htlc-timeout-and-htlc-success-transactions HTCL-Timeout in LN Penalty]
+* [https://github.com/revault/practical-revault/blob/master/transactions.md#cancel_tx Unvault Cancel in Revault]
+* [https://github.com/discreetlogcontracts/dlcspecs/blob/master/Transactions.md#refund-transaction Refund Transaction in Discreet Log Contracts]
+* [https://gist.github.com/instagibbs/60264606e181451e977e439a49f69fe1 Updates in Eltoo]
+* [https://github.com/ElementsProject/peerswap/blob/master/docs/peer-protocol.md#claim-transaction Claim Transactions in PeerSwap]
+ to prevent cheating.
+In other words, a key security assumption of many contracting protocols is that all parties can
+propagate and confirm transactions in a timely manner. Increasing attention has been brought to
+"pinning attacks," a type of censorship in which the attacker uses mempool policy restrictions to
+prevent a transaction from being relayed or getting mined.
+'''Concerns for pinning attacks in L2 protocols'''
+* [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2022-May/020458.html Greg Sanders, "Bringing a nuke to a knife fight: Transaction introspection to stop RBF pinning"]
+* [https://lists.linuxfoundation.org/pipermail/lightning-dev/2020-April/002639.html Matt Corallo, "RBF Pinning with Counterparties and Competing Interest"]
+* [https://lists.linuxfoundation.org/pipermail/lightning-dev/2020-June/002758.html Antoine Riard, "Pinning : The Good, The Bad, The Ugly"]
+* [https://github.com/t-bast/lightning-docs/blob/master/pinning-attacks.md Bastien Teinturier, "Pinning Attacks"]
+* [https://gist.github.com/instagibbs/60264606e181451e977e439a49f69fe1 Greg Sanders, "Eltoo Pinning"]
+
+
+These transactions must meet a certain confirmation target to be effective, but their feerates
+are negotiated well ahead of broadcast time. If the forecast feerate was too low and no
+fee-bumping options are available, attackers can steal money from their counterparties. Always
+overestimating fees may sidestep this issue (but only while mempool traffic is low and
+predictable), but this solution is not guaranteed to work and wastes users' money. For some attacks,
+the available defenses require nodes to have a bird's-eye view of Bitcoin nodes' mempools, which is
+an unreasonable security requirement.
+
+Part of the solution is to enable nodes to consider packages of transactions as a unit, e.g. one or
+more low-fee ancestor transactions with a high-fee descendant, instead of separately. A package-aware
+mempool policy can help determine if it would actually be economically rational to accept a
+transaction to the mempool if it doesn't meet fee requirements individually. Network-wide adoption
+of these policies would create a more purely-feerate-based market for block space and allow
+contracting protocols to adjust fees (and therefore mining priority) at broadcast time.
+
+Theoretically, developing a safe and incentive-compatible package mempool acceptance policy is
+sufficient to solve this issue. Nodes could opportunistically accept packages (e.g. by trying
+combinations of transactions rejected from their mempools), but this practice would likely be
+inefficient at best and open new Denial of Service attacks at worst. As such, this proposal
+suggests adding new p2p messages enabling nodes to request and share package-validation-related
+information with one another, resulting in a more efficient and reliable way to propagate packages.
+
+===Handle Orphans Better===
+
+Txid-based transaction relay is problematic since a transaction's witness may be malleated without
+changing its txid; a node cannot use txid to deduplicate transactions it has already downloaded
+or validated. Ideally, two nodes that both support BIP339 wtxid-based transaction relay shouldn't
+ever need to use txid-based transaction relay.
+
+A single use case of txid-based relay remains: handling "orphan" transactions that spend output(s)
+from an unconfirmed transaction the receiving node is unaware of. Orphan transactions are very
+common for new nodes that have just completed Initial Block Download and do not have an up-to-date
+mempool. Nodes also download transactions from multiple peers. If the peer from which a child
+transaction was requested responds faster than the peer from which its parent was requested, that
+child is seen as an orphan transaction.
+
+Nodes may handle orphans by storing them in a cache and requesting any missing parent(s) by txid
+(prevouts specify txid, not wtxid). These parents may end up being orphans as well, if they also
+spend unconfirmed inputs that the node is unaware of. This method of handling orphans is problematic
+for two reasons: it requires nodes to allocate memory for unvalidated data received on the p2p
+network and it relies on txid-based relay between two wtxid-relay peers.
+
+This proposal makes orphan resolution more efficient and no longer require txid-based relay.
+
+==Definitions==
+
+Given any two transactions Tx0 and Tx1 where Tx1 spends an output of Tx0, Tx0 is a '''parent''' of
+Tx1 and Tx1 is a '''child''' of Tx0.
+
+A transaction's '''ancestors''' include, recursively, its parents, the parents of its parents, etc.
+A transaction's '''descendants''' include, recursively, its children, the children of its children,
+etc. A transaction's parent is its ancestor, but an ancestor is not necessarily a parent.
+
+A '''package''' is a list of transactions, representable by a connected Directed Acyclic
+Graph (a directed edge exists between a transaction that spends the output of another transaction).
+In this proposal, a package is limited to unconfirmed transactions.
+
+An '''ancestor package''' consists of an unconfirmed transaction with all of its unconfirmed
+ancestors.
+
+In a '''topologically sorted''' package, each parent appears somewhere in the list before its child.
+
+==Specification==
+
+Ancestor Package Relay includes two parts: a package information round and a transaction data
+download round.
+The package information round is used to help a receiver learn what transactions are in a package and
+decide whether they want to download them. The transaction data round is used to help a node download
+multiple transactions in one message instead of as separate messages.
+'''Why are package information and transaction data rounds both necessary?'''
+
+Several alternative designs were considered. One should measure alternative solutions based on the
+resources used to communicate (not necessarily trustworthy) information: We would like to minimize
+network bandwidth, avoid downloading a transaction more than once, avoid downloading transactions
+that are eventually rejected, and minimize storage allocated for not-yet-validated transactions.
+
+
+
+'''No Package Information Round:''' One proposal is to just use the child's wtxid to refer to the
+package and always send the entire package together, skipping the package information round.
+However, this protocol would make it very likely for honest nodes to redownload duplicate
+transactions. See the following example, where the high-feerate ancestors were already downloaded
+and accepted individually.
+
+[[File:./bip-0331/no_package_info.png|600px]]
+
+
+'''Package Information Only:''' Just having package information gives enough information for the
+receiver to accept the packages. That is, rather than using "getpkgtxns" and "pkgtxns" messages,
+send "getdata" and download the transactions individually. While this option is a potential fallback
+if batched transaction download fails for some reason, it shouldn't be used as the default because
+it always requires storage of unvalidated transactions.
+[[File:./bip-0331/package_info_only.png|1000px]]
+
+
+Package relay is negotiated between two peers during the version handshake using a "sendpackages"
+message. The versions field within "sendpackages" is interpreted as a bitfield; peers may relay
+multiple versions of packages. Package relay requires both peers to support wtxid-based relay
+because package transactions are referenced by their wtxids.
+'''Why do we need multiple versions? Why can't we just support arbitrary packages?'''
+Attempting to support arbitrary packages in mempool validation may result in very complex logic, new
+Denial of Service attack vectors, and policy limitations that could be leveraged to censor
+transactions (aka "pinning attacks"). This protocol is extensible to support other types of
+packages based on future desired use cases. Future package information messages may describe
+different types of packages and/or contain more information than a list of wtxids, e.g. feerate or
+relationships between transactions.
+'''Why use a bitfield instead of a numbering system?'''
+It should be possible to support some subset of the existing package types.
+
+[[File:./bip-0331/version_negotiation.png|400px]]
+
+Nodes indicate support for batched transaction data round ("getpkgtxns", "pkgtxns", and
+"MSG_PKGTXNS") using the PKG_RELAY_PKGTXNS = (1 << 0) bit in their "sendpackages"
+messages during version handshake. They indicate support for the ancestor package information
+round ("ancpkginfo", "MSG_ANCPKGINFO") using the PKG_RELAY_ANC = (1 << 1) bit in their
+"sendpackages" messages during version handshake.
+
+===Protocol Flow Examples===
+
+This package relay protocol satisfies both use cases (orphan transaction handling and high-feerate
+transaction paying for low-feerate ancestors).
+
+====Orphan Transaction Handling====
+
+Upon receiving an orphan transaction, a node may request ancestor package information delineating
+the wtxids of the transaction's unconfirmed ancestors. This is done without using txid-based relay.
+The package information can be used to request transaction data. As these transactions are dependent
+upon one another to be valid, the transactions can be requested and sent as a batch.
+
+Contrast this protocol with legacy orphan handling, which requires requesting the missing
+transactions by their txids and may require new round trips for each generation of missing parents.
+[[File:./bip-0331/orphan_handling_flow.png|1000px]]
+
+====Fee-Bumped Transactions====
+
+Too-low-feerate transactions (i.e. below the node's minimum mempool feerate) with high-feerate
+descendants can also be relayed this way. If the peers are using BIP133 fee filters and a
+low-feerate transaction is below the node's fee filter, the sender will not announce it. The
+high-feerate transaction will be sent by the sender, and received and handled as an orphan by the
+receiver, the transactions are validated as a package, and so the protocol naturally works for this
+use case.
+
+This does not mean BIP133 is required for package relay to work, provided that nodes do not
+immediately reject transactions previously found to be too low feerate. If the low-feerate
+transaction was sent and rejected, the receiver should later re-request and accept it after learning
+that it is the ancestor of another transaction, and that they meet the receiver's mempool policy
+requirements when validated together.
+
+[[File:./bip-0331/package_cpfp_flow.png|600px]]
+
+This protocol is receiver-initiated only; nodes do not proactively announce packages to their peers.
+'''Why no sender-initiated protocol?''' Sender-initiated package
+relay can, theoretically, save a round trip by notifying the receiver ahead of time that they will
+probably need to request and validate a group of transactions together in order for them to be
+accepted. As with any proactive communication, there is a chance that the receiver already knows
+this information, so this network bandwidth may be wasted. Shortened latency is less significant
+than wasted bandwidth.
+
+The logic used to decide when to announce a package proactively determines whether it is a net
+increase or decrease for overall bandwidth usage. However, it is difficult to design anything to
+save bandwidth without any idea of what its bandwidth usage actually looks like in practice. No
+historical data is available, as one of the primary goals of this protocol is to enable
+currently-rejected transactions to propagate. After deploying receiver-initiated package relay, we
+can observe its usage and then introduce a sender-initiated package relay protocol informed by data
+collected from the p2p network.
+
+===Combined Hash===
+
+A "combined hash" serves as a unique "package id" for some list of transactions and helps provide a
+meaningful but short "notfound" response to "getpkgtxns."
+
+The combined hash of a package of transactions is equal to the sha256 hash of each transaction's
+wtxid concatenated in lexicographical order.
+
+===New Messages===
+
+Four new protocol messages and two inv types are added.
+
+====sendpackages====
+
+{|
+| Field Name || Type || Size || Purpose
+|-
+|versions || uint64_t || 4 || Bit field that is 64 bits wide, denoting the package versions supported by the sender.
+|-
+|}
+
+# The "sendpackages" message has the structure defined above, with pchCommand == "sendpackages".
+
+# During version handshake, nodes should send one "sendpackages" message indicating they support package relay, with the versions field indicating which versions they support.
+
+# The "sendpackages" message MUST be sent before sending a "verack" message. If a "sendpackages" message is received after "verack", the sender may be disconnected.
+
+# Upon successful connection ("verack" sent by both peers), a node may relay packages with the peer if they did not set "fRelay" to false in the "version" message, both peers sent "wtxidrelay", and both peers sent "sendpackages" for matching version bit(s). Unknown bits (including versions==0) should be ignored. Peers should relay packages corresponding to versions that both sent "sendpackages" for.'''Is it ok to send "sendpackages" to a peer that specified fRelay=false in their "version" message?'''
+Yes, this is allowed in order to reduce the number of negotiation steps. This means nodes can
+announce features without first checking what the other peer has sent, and then apply negotiation
+logic at the end based on what was sent and received. See [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2022-May/020510.html this discussion].
+
+
+====ancpkginfo====
+{|
+| Field Name || Type || Size || Purpose
+|-
+|txns_length||CompactSize||1 or 3 bytes|| The number of transactions provided.
+|-
+|txns||List of wtxids||txns_length * 32|| The wtxids of each transaction in the package.
+|}
+
+# The "ancpkginfo" message has the structure defined above, with pchCommand == "ancpkginfo".
+
+# The "txns" field should contain a list of wtxids which constitute the ancestor package of the last wtxid. For the receiver's convenience, the sender should - but is not required to - sort the wtxids in topological order. The topological sort can be achieved by sorting the transactions by mempool acceptance order (if parents are always accepted before children). Apart from the last wtxid which is used to learn which transaction the message corresponds to, there is no enforced ordering. Nodes should not disconnect or punish a peer who provides a list not sorted in topological order.'''Why not include feerate information to help the receiver decide whether these transactions are worth downloading?'''
+A simple feerate is typically insufficient; the receiver must also know the dependency
+relationships between transactions and their respective sizes.
+'''Should a peer be punished if they provide incorrect package info, e.g. a list of unrelated transactions?'''
+Ideally, there should be a way to enforce that peers are providing correct information to each
+other. However, two peers may have different views of what a transaction's unconfirmed ancestors
+are based on their chainstate. For example, during a reorg or when two blocks are found at the same
+time, one peer may see a transaction as confirmed while the other peer does not.
+As such, it is impossible to accurately enforce this without also knowing the peer's chainstate.
+It was [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2022-May/020493.html originally proposed]
+to include a block hash in "ancpkginfo" to avoid unwarranted disconnections. However, it does not
+make much sense to stop or delay transaction data requests due to mismatched chainstates, and the
+chainstate may change again between package information and transaction data rounds. Instead,
+differences in chainstate should be handled at the validation level. The node has already spent
+network bandwidth downloading these transactions; it should make a best effort to validate them.
+See [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2022-June/020558.html discussion].
+'''Why not require topological order?'''
+It is not possible to determine whether a list of transactions is topologically sorted without first
+establishing that the list contains a full ancestor package. It is not possible to determine whether
+a list of transactions contains a full ancestor package without knowing what the chainstate is.
+
+
+# Upon receipt of a "ancpkginfo" message, the node may use it to request the transactions it does not already have (e.g. using "getpkgtxns" or "tx").
+
+# Upon receipt of a malformed "ancpkginfo" message, the sender may be disconnected. An "ancpkginfo" message is malformed if it contains duplicate wtxids or conflicting transactions (spending the same inputs). The receiver may learn that a package info was malformed after downloading the transactions.
+
+# A node MUST NOT send a "ancpkginfo" message that has not been requested by the recipient. Upon receipt of an unsolicited "ancpkginfo", a node may disconnect the sender.
+
+# This message must only be used if both peers set PKG_RELAY_ANC in their "sendpackages" message. If an "ancpkginfo" message is received from a peer with which this type of package relay was not negotiated, no response should be sent and the sender may be disconnected.
+
+====MSG_ANCPKGINFO====
+
+# A new inv type (MSG_ANCPKGINFO == 0x7) is added, for use only in getdata requests pertaining to ancestor packages.
+
+# As a getdata request type, it indicates that the sender wants an "ancpkginfo" containing all of the unconfirmed ancestors of a transaction, referenced by wtxid.
+
+# Upon receipt of a "getdata(MSG_ANCPKGINFO)" request, the node should respond with an "ancpkginfo" message corresponding to the transaction's unconfirmed ancestor package, or with "notfound". The wtxid of the requested transaction must be the last item in the "ancpkginfo" response list, as the last item is used to determine which transaction the "ancpkginfo" pertains to.
+
+# The inv type must only be used in a "getdata" message. An "inv(MSG_ANCPKGINFO)" must never be sent. If an "inv(MSG_ANCPKGINFO)" is received, the sender may be disconnected.
+
+# This inv type must only be used if both peers set PKG_RELAY_ANC in their "sendpackages" message. If a "getdata" message with type MSG_ANCPKGINFO is received from a peer with which this type of package relay was not negotiated, no response should be sent and the sender may be disconnected.
+
+====getpkgtxns====
+
+{|
+| Field Name || Type || Size || Purpose
+|-
+|txns_length||CompactSize||1 or 3 bytes|| The number of transactions requested.
+|-
+|txns||List of wtxids||txns_length * 32|| The wtxids of each transaction in the package.
+|}
+
+# The "getpkgtxns" message has the structure defined above, with pchCommand == "getpkgtxns".
+
+# A "getpkgtxns" message should be used to request some list of transactions specified by witness transaction id. It indicates that the node wants to receive either all the specified transactions or none of them. This message is intended to allow nodes to avoid downloading and storing transactions that cannot be validated without each other. The list of transactions does not need to correspond to a previously-received ancpkginfo message.
+
+# Upon receipt of a "getpkgtxns" message, a node should respond with either a "pkgtxns" containing all of the requested transactions in the same order specified in the "getpkgtxns" request or one "notfound" message of type MSG_PKGTXNS and combined hash of all of the wtxids in the "getpkgtxns" request (only one "notfound" message and nothing else), indicating one or more of the transactions is unavailable.
+
+# A "getpkgtxns" message must contain at most 100 wtxids. Upon receipt of a "getpkgtxns" message with more than 100 wtxids, a node may ignore the message (to avoid calculating the combined hash) and disconnect the sender.
+
+# This message must only be used if both peers set PKG_RELAY_PKGTXNS in their "sendpackages" message. If a "getpkgtxns" message is received from a peer with which this type of package relay was not negotiated, no response should be sent and the sender may be disconnected.
+
+====pkgtxns====
+
+{|
+| Field Name || Type || Size || Purpose
+|-
+|txns_length||CompactSize||1 or 3 bytes|| The number of transactions provided.
+|-
+|txns||List of transactions||variable|| The transactions in the package.
+|}
+
+# The "pkgtxns" message has the structure defined above, with pchCommand == "pkgtxns".
+
+# A "pkgtxns" message should contain the transaction data requested using "getpkgtxns".
+
+# A "pkgtxns" message should only be sent to a peer that requested the package using "getpkgtxns". If a node receives an unsolicited package, it may choose to validate the transactions or not, and the sender may be disconnected.
+
+# This message must only be used if both peers set PKG_RELAY_PKGTXNS in their "sendpackages" message. If a "pkgtxns" message is received from a peer with which this type of package relay was not negotiated, no response should be sent and the sender may be disconnected.
+
+====MSG_PKGTXNS====
+
+# A new inv type (MSG_PKGTXNS == 0x6) is added, for use only in "notfound" messages pertaining to package transactions.
+
+# As a "notfound" type, it indicates that the sender is unable to send all the transactions requested in a prior "getpkgtxns" message. The hash used is equal to the combined hash of the wtxids in the getpkgtxns request.
+
+# This inv type should only be used in "notfound" messages, i.e. "inv(MSG_PKGTXNS)" and "getdata(MSG_PKGTXNS)" must never be sent. Upon receipt of an "inv" or "getdata" message of this type, the sender may be disconnected.
+
+# This inv type must only be used if both peers set PKG_RELAY_PKGTXNS in their "sendpackages" message.
+
+==Compatibility==
+
+Older clients remain fully compatible and interoperable after this change. Clients implementing this
+protocol will only attempt to send and request packages if agreed upon during the version handshake.
+'''Will package relay cause non-package relay nodes to waste bandwidth on low-feerate transactions?'''
+If a node supports package relay, it may accept low-feerate transactions (e.g. paying zero fees)
+into its mempool, but non-package relay nodes would most likely reject them. To mitigate bandwidth
+waste, a package relay node should not announce descendants of below-fee-filter transactions to
+non-package relay peers.
+
+'''Is Package Erlay possible?'''
+A client using BIP330 reconciliation-based transaction relay (Erlay) is able to use package relay
+without interference. After reconciliation, any transaction with unconfirmed ancestors may have
+those ancestors resolved using ancestor package relay.
+[[File:./bip-0331/package_erlay.png|700px]]
+
+
+==Extensibility==
+
+This protocol can be extended to include more types of package information in the future, while
+continuing to use the same messages for transaction data download. One would define a new package
+information message (named "*pkginfo" in the diagram below), allocate its corresponding inv
+type (named "*PKGINFO" in the diagram below), and specify how to signal support using the
+versions field of "sendpackages" (an additional bit named "PKG_RELAY_*" in the diagram below). A
+future version of package relay may allow a sender-initiated dialogue by specifying that the package
+info type inv type can be used in an "inv" message.
+
+[[File:./bip-0331/sender_init_future_version.png|700px]]
+
+==Implementation==
+
+Sample implementation for Bitcoin Core: https://github.com/bitcoin/bitcoin/pull/27742
+
+A prerequisite for implementing a safe
+package relay protocol is a mempool acceptance policy that safely validates packages of
+transactions.
+'''Package Mempool Acceptance Policy'''
+Accepting packages from peers should not significantly increase a node's DoS attack surface;
+processing packages should not permit waste or exhaustion of the node and network's resources.
+Additionally, a sensible mempool acceptance policy should result in the most incentive-compatible
+subset of the package in the mempool in order to avoid adding more pinning attacks or censorship
+vectors. For example, It should not be assumed that packages are CPFPs. An ancestor package may
+include a high-feerate parent and low-feerate child; the policy may choose to accept the parent but
+not the child. If one or more transactions are policy-invalid, other transactions that are not
+dependent upon them should still be considered.
+
+
+==Acknowledgements==
+
+Thank you to Suhas Daftuar, John Newbery, Anthony Towns, Martin Zumsande, and others for input on the design.
+
+Thank you to Will Clark, Sergi Delgado, Fabian Jahr, John Newbery, Greg Sanders, Stéphan Vuylsteke, Pieter Wuille, and others for input on this document.
+
+Much of this work is inspired by ideas and code by Suhas Daftuar and Antoine Riard.
+'''Prior Work on Package Relay'''
+* [https://gist.github.com/sdaftuar/8756699bfcad4d3806ba9f3396d4e66a Strawman Proposal]
+* [https://github.com/bitcoin/bitcoin/issues/14895 Package relay design questions]
+* [https://github.com/bitcoin/bitcoin/pull/16401 Add package acceptance logic to mempool]
+* [https://github.com/bitcoin/bitcoin/pull/19621 [RFC] Package-relay: sender-initiated]
+
+
+==References and Rationale==
+
+
+
diff --git a/bip-0331/no_package_info.png b/bip-0331/no_package_info.png
new file mode 100644
index 0000000000..54b20f97dd
Binary files /dev/null and b/bip-0331/no_package_info.png differ
diff --git a/bip-0331/orphan_handling_flow.png b/bip-0331/orphan_handling_flow.png
new file mode 100644
index 0000000000..4588de84b1
Binary files /dev/null and b/bip-0331/orphan_handling_flow.png differ
diff --git a/bip-0331/package_cpfp_flow.png b/bip-0331/package_cpfp_flow.png
new file mode 100644
index 0000000000..6b48c5da65
Binary files /dev/null and b/bip-0331/package_cpfp_flow.png differ
diff --git a/bip-0331/package_erlay.png b/bip-0331/package_erlay.png
new file mode 100644
index 0000000000..fd3661ff5d
Binary files /dev/null and b/bip-0331/package_erlay.png differ
diff --git a/bip-0331/package_info_only.png b/bip-0331/package_info_only.png
new file mode 100644
index 0000000000..2bd0272606
Binary files /dev/null and b/bip-0331/package_info_only.png differ
diff --git a/bip-0331/sender_init_future_version.png b/bip-0331/sender_init_future_version.png
new file mode 100644
index 0000000000..d4a21050ec
Binary files /dev/null and b/bip-0331/sender_init_future_version.png differ
diff --git a/bip-0331/version_negotiation.png b/bip-0331/version_negotiation.png
new file mode 100644
index 0000000000..5b2f48cb60
Binary files /dev/null and b/bip-0331/version_negotiation.png differ
diff --git a/bip-0337.mediawiki b/bip-0337.mediawiki
new file mode 100644
index 0000000000..e87c5bc2c4
--- /dev/null
+++ b/bip-0337.mediawiki
@@ -0,0 +1,301 @@
+
+
+== Introduction ==
+
+=== Abstract ===
+This document proposes a serialization scheme for compressing Bitcoin transactions. The compressed Bitcoin transactions can reach a serialized size of less than 50% of the original serialized transaction. One method for compressing involves reducing the transaction outpoints in a potentially lossy way. Therefore, it is an optional path for compression. Compressing the outpoints is necessary for compressed transactions to reach less than 70% of the original size.
+
+=== Motivation ===
+Typical Bitcoin transactions usually contain a large amount of white space and padding due to specific fields that are often one of a minimal number of possibilities. We can use this fact and a few similar methods to create an encoding for 90% of Bitcoin transactions that are roughly 25-50% smaller.
+
+There exists a working-in-progress app that allows the use of steganography to encode data in images to be passed around via various social media groups. When used in conjunction with this compression scheme and an elligator squared encryption, this would allow for a very secure and private form of broadcasting bitcoin transactions.
+
+=== Rationale ===
+
+The four main methods to achieve a lower transaction size are:
+
+1. Packing transaction metadata before it and each of its inputs and outputs to determine the following data structure.
+
+2. Replacing 32-bit numeric values with either variable-length integers (VarInts) or compact integers (CompactSizes).
+
+3. Using compressed signatures and public key recovery upon decompression.
+
+4. Replacing the 36-byte Outpoint txid/vout pair with a block height and index.
+
+
+=== Backwards Compatibility ===
+
+There are no concerns with backwards compatibility.
+
+=== Specification ===
+
+==== Primitives ====
+
+{| class="wikitable" style="margin:auto"
+|-
+! Name !! Width !! Description
+|-
+| CompactSize || 1-5 Bytes || For 0-253, encode the value directly in one byte. For 254-65535, encode 254 followed by two little-endian bytes. For 65536-(2^32-1), encode 255 followed by four little-endian bytes.
+|-
+| CompactSize Flag || 2 Bits || 1, 2, or 3 indicate literal values. 0 indicates that a CompactSize encoding of the value will follow.
+|-
+| VarInt || 1+ Bytes || 7-bit little-endian encoding, with each 7-bit word encoded in a byte. The highest bit of each byte is one if more bytes follow, and 0 for the last byte.
+|-
+| VLP-Bytestream || 2+ Bytes || A VarInt Length Prefixed Bytestream. It uses the prefixed VarInt to determine the length of the following byte stream.
+|}
+
+==== General Schema ====
+
+{| class="wikitable" style="margin:auto"
+|-
+! Name !! Width !! Description
+|-
+| Transaction metadata || 1 Bytes || Information on the structure of the transaction. See [[#transaction-metadata|Transaction Metadata]]
+|-
+| Version || 0-5 Bytes || If present according to the metadata field, a CompactSize encoding of the transaction version.
+|-
+| Input Count || 0-5 Bytes || If present according to the metadata field, a CompactSize encoding of the transaction input count.
+|-
+| Output Count || 0-5 Bytes || If present according to the metadata field, a CompactSize encoding of the transaction output count.
+|-
+| LockTime || 0-5 Bytes || If present according to the metadata field, a CompactSize encoding of the transaction LockTime.
+|-
+| Minimum Blockheight || 1-5 Bytes || If present according to the metadata field, a VarInt encoding of the minimum block height for transaction compressed inputs and LockTime.
+|-
+| Input Metadata+Output Metadata || 1+ Bytes || An encoding containing the metadata for all the inputs followed by all the outputs of the transaction. For each input, see [[#input-metadata|Input Metadata]], and for each output, see [[#output-metadata|Output Metadata]].
+|-
+| Input Data || 66+ Bytes || See [[#input-data|Input Data]].
+|-
+| Output Data || 3+ Bytes || See [[#output-data|Output Data]].
+|}
+
+
+==== Transaction Metadata ====
+
+{| class="wikitable" style="margin:auto"
+|-
+! Name !! Width !! Description
+|-
+| Version || 2 Bits || A CompactSize flag for the transaction version.
+|-
+| Input Count || 2 Bits || A CompactSize flag for the transaction input count.
+|-
+| Output Count || 2 Bits || A CompactSize flag for the transaction output count.
+|-
+| LockTime || 1 Bit || A boolean to indicate if the transaction has a LockTime.
+|-
+| Minimum Blockheight || 1 Bit || A boolean to indicate if the transaction minimum block height is greater than zero.
+|}
+
+
+==== Input Metadata ====
+
+{| class="wikitable" style="margin:auto"
+|-
+! Name !! Width !! Description
+|-
+| Compressed Signature || 1 Bit || A Boolean do determine if this input's signature is compressed. The signature is only compressed for P2TR on a key spend and for P2SH when it is a wrapped P2SH-WPKH.
+|-
+| Standard Hash || 1 Bit || A Boolean to determine if this input's signature hash type is standard (0x00 for Taproot, 0x01 for Legacy/Segwit).
+|-
+| Standard Sequence || 2 Bits || A CompactSize flag for this input's sequence. Encode literal values as follows: 1 = 0x00000000, 2 = 0xFFFFFFFE, 3 = 0xFFFFFFFF.
+|-
+| Compressed OutPoint || 1 bit || A Boolean to determine if the input's outpoint is compressed.
+|}
+
+
+==== Output Metadata ====
+
+{| class="wikitable" style="margin:auto"
+|-
+! Name !! Width !! Description
+|-
+| Encoded Script Type || 3 Bits || [[#script-type-encoding|Encoded Script Type]].
+|}
+
+
+==== Script Type Encoding ====
+
+{| class="wikitable" style="margin:auto"
+|-
+! Script Type !! Value
+|-
+| Uncompressed Custom Script || 0b000
+|-
+| Uncompressed P2PK || 0b001
+|-
+| Compressed P2PK || 0b010
+|-
+| P2PKH || 0b011
+|-
+| P2SH || 0b100
+|-
+| P2WPKH || 0b101
+|-
+| P2WSH || 0b110
+|-
+| P2TR || 0b111
+|}
+
+
+==== Input Data ====
+
+{| class="wikitable" style="margin:auto"
+|-
+! Name !! Width !! Description
+|-
+| Outpoint || 2-37 Bytes || The Outpoint Txid/Vout are determined to be compressed or otherwise by the "Compressed Outpoint" Boolean in the input metadata. For each compressed outpoint see [[#compressed-outpoint|Compressed Outpoint]]. For each uncompressed signature see [[#uncompressed-outpoint|Uncompressed Outpoint]].
+|-
+| Signature || 64+ Bytes || The Signature is determined to be compressed or otherwise by the output script of the previous transaction. For each compressed signature see [[#compressed-signature|Compressed Signature]]. For each uncompressed signature see [[#uncompressed-signature|Uncompressed Signature]].
+|-
+| Sequence || 0-5 Bytes || If present due to a non-standard sequence, a VarInt encoding of the sequence.
+|}
+
+
+==== Compressed Outpoint ====
+
+{| class="wikitable" style="margin:auto"
+|-
+! Name !! Width !! Description
+|-
+| Txid Block Height || 1-5 Bytes || A VarInt containing the offset from Minimum Blockheight for this Txid.
+|-
+| Txid Block Index || 1-5 Bytes || A VarInt containing the flattened index from the Txid block height for the Vout.
+|}
+
+
+==== Uncompressed Outpoint ====
+
+{| class="wikitable" style="margin:auto"
+|-
+! Name !! Width !! Description
+|-
+| Txid || 32 Bytes || Contains the 32 Byte Txid.
+|-
+| Vout || 1-5 Bytes || A CompactSize Containing the Vout of the Txid.
+|}
+
+
+
+==== Compressed Signature ====
+
+{| class="wikitable" style="margin:auto"
+|-
+! Name !! Width !! Description
+|-
+| Signature || 64 Bytes || Contains the 64 Byte signature.
+|-
+| Pubkey Hash || 0-20 Bytes || If input is P2SH-P2WPKH contains the 20 byte hash of the public key.
+|-
+| Hash Type || 0-1 Bytes || An Optional Byte containing the Hash Type if it was non-standard.
+|}
+
+
+==== Uncompressed Signature ====
+
+{| class="wikitable" style="margin:auto"
+|-
+! Name !! Width !! Description
+|-
+| Signature || 2+ Bytes || A VLP-Bytestream containing the signature.
+|}
+
+
+==== Output Data ====
+
+{| class="wikitable" style="margin:auto"
+|-
+! Name !! Width !! Description
+|-
+| Output Script || 2+ Bytes || A VLP-Bytestream containing the output script.
+|-
+| Amount || 1-9 Bytes || A VarInt containing the output amount.
+|}
+
+==== Ideal Transaction ====
+
+The compression scheme was designed to be optimal for a "typical" transaction, spending a few close-in-age inputs and having one or two outputs. Here are size
+values for such a transaction, which demonstrate the effectiveness of the compression.
+
+{| class="wikitable" style="margin:auto"
+|-
+! Field !! Requirements !! Savings Up To
+|-
+| Version || Less than four || 30 Bits
+|-
+| Input Count || Less than four || 30 Bits
+|-
+| Output Count || Less than four || 30 Bits
+|-
+| LockTime || 0 || 30 Bits
+|-
+| Input Sequence || 0x00, 0xFFFFFFFE, or 0xFFFFFFFF || 62 Bits For Each Input
+|-
+| Input Txid || Compressed Outpoint || 23 - 31 Bytes For Each Input
+|-
+| Input Vout || Compressed Outpoint || (-1) - 3 Bytes For Each Input
+|-
+| Input Signature || Non-custom Script Signing || 40 - 72 Bytes For Each Legacy Input
+|-
+| Input Hash Type || 0x00 for Taproot, 0x01 for Legacy || 7 Bits For Each Input
+|-
+| Output Script || Non-custom Scripts || 2 - 5 Bytes For Each Output
+|-
+| Output Amount || No Restrictions || (-1) - 7 Bytes For Each Output
+|}
+
+=== Reference Implementation ===
+
+This reference implementation adds two new RPC endpoints, compressrawtransaction and decompressrawtransaction. The first accepts a raw hex-encoded transaction and returns a compact hex-encoded transaction; also included in the output is a list of warnings to help ensure there are no unexpected uncompressed values. The second accepts a compact hex transaction and returns the uncompressed raw hex-encoded transaction.
+
+https://github.com/bitcoin/bitcoin/pull/29134
+
+=== Test Vectors ===
+
+==== Taproot ====
+
+===== Uncompressed =====
+020000000001017ad1d0cc314504ec06f1b5c786c50cf3cda30bd5be88cf08ead571b0ce7481fb0000000000fdffffff0188130000000000001600142da377ed4978fefa043a58489912f8e28e16226201408ce65b3170d3fbc68e3b6980650514dc53565f915d14351f83050ff50c8609495b7aa96271c3c99cdac1a92b1b45e77a4a870251fc1673596793adf2494565e500000000
+
+===== Compressed =====
+96b1ec7f968001b0218ce65b3170d3fbc68e3b6980650514dc53565f915d14351f83050ff50c8609495b7aa96271c3c99cdac1a92b1b45e77a4a870251fc1673596793adf2494565e58efefefe7d2da377ed4978fefa043a58489912f8e28e162262a608
+
+==== P2WPKH ====
+
+===== Uncompressed =====
+0200000000010144bcf05ab48b8789268a7ca07133241ad654c0739ac7165015b2d669eadb10ea0000000000fdffffff0188130000000000001600142da377ed4978fefa043a58489912f8e28e16226202473044022043ab639a98dfbc704f16a35bf25b8b72acb4cb928fd772285f1fcf63725caa85022001c9ff354504e7024708bce61f30370c8db13da8170cef4e8e4c4cdad0f71bfe0121030072484c24705512bfb1f7f866d95f808d81d343e552bc418113e1b9a1da0eb400000000
+
+===== Compressed =====
+96b1ec71968001932643ab639a98dfbc704f16a35bf25b8b72acb4cb928fd772285f1fcf63725caa8501c9ff354504e7024708bce61f30370c8db13da8170cef4e8e4c4cdad0f71bfe8efefefe7d2da377ed4978fefa043a58489912f8e28e162262a608
+
+==== P2SH-P2WPKH ====
+
+===== Uncompressed =====
+0200000000010192fb2e4332b43dc9a73febba67f3b7d97ba890673cb08efde2911330f77bbdfc00000000171600147a1979232206857167b401fdac1ffbf33f8204fffdffffff0188130000000000001600142da377ed4978fefa043a58489912f8e28e16226202473044022041eb682e63c25b85a5a400b11d41cf4b9c25f309090a5f3e0b69dc15426da90402205644ddc3d5179bab49cce4bf69ebfaeab1afa34331c1a0a70be2927d2836b0e8012103c483f1b1bd24dd23b3255a68d87ef9281f9d080fd707032ccb81c1cc56c5b00200000000
+
+===== Compressed =====
+96b1ec7c9e8001981641eb682e63c25b85a5a400b11d41cf4b9c25f309090a5f3e0b69dc15426da9045644ddc3d5179bab49cce4bf69ebfaeab1afa34331c1a0a70be2927d2836b0e87a1979232206857167b401fdac1ffbf33f8204ff8efefefe7d2da377ed4978fefa043a58489912f8e28e162262a608
+
+==== P2PKH ====
+
+===== Uncompressed =====
+02000000015f5be26862482fe2fcc900f06ef26ee256fb205bc4773e5a402d0c1b88b82043000000006a473044022031a20f5d9212023b510599c9d53d082f8e07faaa2d51482e078f8e398cb50d770220635abd99220ad713a081c4f20b83cb3f491ed8bd032cb151a3521ed144164d9c0121027977f1b6357cead2df0a0a19570088a1eb9115468b2dfa01439493807d8f1294fdffffff0188130000000000001600142da377ed4978fefa043a58489912f8e28e16226200000000
+
+===== Compressed =====
+96b1ec7c968001981431a20f5d9212023b510599c9d53d082f8e07faaa2d51482e078f8e398cb50d77635abd99220ad713a081c4f20b83cb3f491ed8bd032cb151a3521ed144164d9c8efefefe7d2da377ed4978fefa043a58489912f8e28e162262a608
+
+
+== Acknowledgements ==
+Thank you to Andrew Poelstra, who helped invent and develop the ideas in the proposal and the code for reference implementation.
diff --git a/bip-0338.mediawiki b/bip-0338.mediawiki
new file mode 100644
index 0000000000..908aef63de
--- /dev/null
+++ b/bip-0338.mediawiki
@@ -0,0 +1,115 @@
+
+
+==Abstract==
+
+This BIP describes a change to the p2p protocol to allow a node to tell a peer
+that a connection will not be used for transaction relay, to support
+block-relay-only connections that are currently in use on the network.
+
+==Motivation==
+
+This proposal is part of an effort to increase the number of inbound
+connections that a peer can service, by distinguishing peers which will not
+relay transactions from those that do.
+
+Since 2019, software has been deployed[1] which initiates
+connections on the Bitcoin network and sets the transaction relay field
+(introduced by BIP 37 and also defined in BIP 60) to false, to prevent
+transaction relay from occurring on the connection. Additionally, addr messages
+received from the peer are ignored by this software.
+
+The purpose of these connections is two-fold: by making additional
+low-bandwidth connections on which blocks can propagate, the robustness of a
+node to network partitioning attacks is strengthened. Additionally, by not
+relaying transactions and ignoring received addresses, the ability of an
+adversary to learn the complete network graph (or a subgraph) is reduced[2],
+which in turn increases the cost or difficulty to an attacker seeking to carry
+out a network partitioning attack (when compared with having such knowledge).
+
+The low-bandwidth / minimal-resource nature of these connections is currently
+known only by the initiator of the connection; this is because the transaction
+relay field in the version message is not a permanent setting for the lifetime
+of the connection. Consequently, a node receiving an inbound connection with
+transaction relay disabled cannot distinguish between a peer that will never
+enable transaction relay (as described in BIP 37) and one that will. Moreover,
+the node also cannot determine that the incoming connection will ignore relayed
+addresses; with that knowledge a node would likely choose other peers to
+receive announced addresses instead.
+
+This proposal adds a new, optional message that a node can send a peer when
+initiating a connection to that peer, to indicate that connection should not be
+used for transaction relay for the connection's lifetime. In addition, without
+a current mechanism to negotiate whether addresses should be relayed on a
+connection, this BIP suggests that address messages not be sent on links where
+transaction relay has been disabled.
+
+After this BIP is deployed, nodes could more easily implement inbound
+connection limiting that differentiates low-resource nodes (such as those
+sending disabletx) from full-relay peers, potentially allowing for an increase
+in the number of block-relay-only connections that can be made on the network.
+
+==Specification==
+
+# A new disabletx message is added, which is defined as an empty message with message type set to "disabletx".
+# The protocol version of nodes implementing this BIP must be set to 70017 or higher.
+# If a node sets the transaction relay field in the version message to a peer to false, then the disabletx message MAY also be sent in response to a version message from that peer if the peer's protocol version is >= 70017. If sent, the disabletx message MUST be sent prior to sending a verack.
+# A node MUST NOT send the disabletx message if the transaction relay field in the version message is omitted or set to true.
+# A node that has sent or received a disabletx message to/from a peer MUST NOT send any of these messages to the peer:
+## inv messages for transactions
+## notfound messages for transactions
+## getdata messages for transactions
+## getdata messages for merkleblock (BIP 37)
+## filteradd/filterload/filterclear (BIP 37)
+## feefilter (BIP 133)
+## mempool (BIP 35)
+## tx message
+# It is RECOMMENDED that a node that has sent or received a disabletx message to/from a peer not send any of these messages to the peer:
+## addr/getaddr
+## addrv2 (BIP 155)
+# The behavior regarding sending or processing other message types is not specified by this BIP.
+# Nodes MAY decide to not remain connected to peers that send this message (for example, if trying to find a peer that will relay transactions).
+
+==Compatibility==
+
+Nodes with protocol version >= 70017 that do not implement this BIP, and nodes
+with protocol version < 70017, will continue to remain compatible with
+implementing software: transactions would not be relayed to peers sending the
+disabletx message (provided that BIP 37 or BIP 60 has been implemented), and while
+periodic address relay may still take place, software implementing this BIP
+should not be disconnecting such peers solely for that reason.
+
+Disabling address relay is suggested but not required by this BIP, to allow for
+future protocol extensions that might specify more carefully how address relay
+is to be negotiated. This BIP's recommendations for software to not relay
+addresses is intended to be interpreted as guidance in the absence of any such
+future protocol extension, to accommodate existing software behavior.
+
+Note that all messages specified in BIP 152, including blocktxn and
+getblocktxn, are permitted between peers that have sent/received a disabletx
+message, subject to the feature negotiation of BIP 152.
+
+This proposal is compatible with, but independent of, BIP 37.
+
+==Implementation==
+
+https://github.com/bitcoin/bitcoin/pull/20726
+
+==References==
+
+# Bitcoin Core has [https://github.com/bitcoin/bitcoin/pull/15759 implemented this functionality] since version 0.19.0.1, released in November 2019.
+# For example, see https://www.cs.umd.edu/projects/coinscope/coinscope.pdf and https://arxiv.org/pdf/1812.00942.pdf.
+
+==Copyright==
+
+This BIP is licensed under the 2-clause BSD license.
diff --git a/bip-0339.mediawiki b/bip-0339.mediawiki
new file mode 100644
index 0000000000..7fb6bc4eed
--- /dev/null
+++ b/bip-0339.mediawiki
@@ -0,0 +1,59 @@
+
+
+==Abstract==
+
+This BIP describes two changes to the p2p protocol to support transaction relay
+based on the BIP 141 wtxid of a transaction, rather than its txid.
+
+==Motivation==
+
+Historically, the inv messages sent on the Bitcoin peer-to-peer network to
+announce transactions refer to transactions by their txid, which is a hash of
+the transaction that does not include the witness (see BIP 141). This has been
+the case even since Segregated Witness (BIP 141/143/144) has been adopted by
+the network.
+
+Not committing to the witness in transaction announcements creates
+inefficiencies: because a transaction's witness can be malleated without
+altering the txid, a node in receipt of a witness transaction that the node
+does not accept will generally still download that same transaction when
+announced by other peers. This is because the alternative -- of not downloading
+a given txid after rejecting a transaction with that txid -- would allow a
+third party to interfere with transaction relay by malleating a transaction's
+witness and announcing the resulting invalid transaction to nodes, preventing
+relay of the valid version of the transaction as well.
+
+We can eliminate this concern by using the wtxid in place of the txid when
+announcing and fetching transactions.
+
+==Specification==
+
+# A new wtxidrelay message is added, which is defined as an empty message where pchCommand == "wtxidrelay".
+# The protocol version of nodes implementing this BIP must be set to 70016 or higher.
+# The wtxidrelay message MUST be sent in response to a version message from a peer whose protocol version is >= 70016 and prior to sending a verack. A wtxidrelay message received after a verack message MUST be ignored or treated as invalid.
+# A new inv type MSG_WTX (0x00000005) is added, for use in both inv messages and getdata requests, indicating that the hash being referenced is a transaction's wtxid. In the case of getdata requests, MSG_WTX implies that the transaction being requested should be serialized with witness as well, as described in BIP 144.
+# After a node has received a wtxidrelay message from a peer, the node MUST use the MSG_WTX inv type when announcing transactions to that peer.
+# After a node has received a wtxidrelay message from a peer, the node SHOULD use a MSG_WTX getdata message to request any announced transactions. A node MAY still request transactions from that peer using MSG_TX getdata messages, such as for transactions not recently announced by that peer (like the parents of recently announced transactions).
+
+==Backward compatibility==
+
+As wtxid-based transaction relay is only enabled between peers that both support it, older clients remain fully compatible and interoperable after this change.
+
+==Implementation==
+
+https://github.com/bitcoin/bitcoin/pull/18044
+
+==Copyright==
+
+This BIP is licensed under the 2-clause BSD license.
diff --git a/bip-0340.mediawiki b/bip-0340.mediawiki
new file mode 100644
index 0000000000..05b75ceb10
--- /dev/null
+++ b/bip-0340.mediawiki
@@ -0,0 +1,304 @@
+
+ BIP: 340
+ Title: Schnorr Signatures for secp256k1
+ Author: Pieter Wuille
+ Jonas Nick
+ Tim Ruffing
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0340
+ Status: Final
+ Type: Standards Track
+ License: BSD-2-Clause
+ Created: 2020-01-19
+ Post-History: 2018-07-06: https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-July/016203.html [bitcoin-dev] Schnorr signatures BIP
+
+
+== Introduction ==
+
+=== Abstract ===
+
+This document proposes a standard for 64-byte Schnorr signatures over the elliptic curve ''secp256k1''.
+
+=== Copyright ===
+
+This document is licensed under the 2-clause BSD license.
+
+=== Motivation ===
+
+Bitcoin has traditionally used
+[https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm ECDSA] signatures over the [https://www.secg.org/sec2-v2.pdf secp256k1 curve] with [https://en.wikipedia.org/wiki/SHA-2 SHA256] hashes for authenticating
+transactions. These are [https://www.secg.org/sec1-v2.pdf standardized], but have a number of downsides
+compared to [http://publikationen.ub.uni-frankfurt.de/opus4/files/4280/schnorr.pdf Schnorr signatures] over the same curve:
+
+* '''Provable security''': Schnorr signatures are provably secure. In more detail, they are ''strongly unforgeable under chosen message attack (SUF-CMA)''Informally, this means that without knowledge of the secret key but given valid signatures of arbitrary messages, it is not possible to come up with further valid signatures. [https://www.di.ens.fr/~pointche/Documents/Papers/2000_joc.pdf in the random oracle model assuming the hardness of the elliptic curve discrete logarithm problem (ECDLP)] and [http://www.neven.org/papers/schnorr.pdf in the generic group model assuming variants of preimage and second preimage resistance of the used hash function]A detailed security proof in the random oracle model, which essentially restates [https://www.di.ens.fr/~pointche/Documents/Papers/2000_joc.pdf the original security proof by Pointcheval and Stern] more explicitly, can be found in [https://eprint.iacr.org/2016/191 a paper by Kiltz, Masny and Pan]. All these security proofs assume a variant of Schnorr signatures that use ''(e,s)'' instead of ''(R,s)'' (see Design above). Since we use a unique encoding of ''R'', there is an efficiently computable bijection that maps ''(R,s)'' to ''(e,s)'', which allows to convert a successful SUF-CMA attacker for the ''(e,s)'' variant to a successful SUF-CMA attacker for the ''(R,s)'' variant (and vice-versa). Furthermore, the proofs consider a variant of Schnorr signatures without key prefixing (see Design above), but it can be verified that the proofs are also correct for the variant with key prefixing. As a result, all the aforementioned security proofs apply to the variant of Schnorr signatures proposed in this document.. In contrast, the [https://nbn-resolving.de/urn:nbn:de:hbz:294-60803 best known results for the provable security of ECDSA] rely on stronger assumptions.
+* '''Non-malleability''': The SUF-CMA security of Schnorr signatures implies that they are non-malleable. On the other hand, ECDSA signatures are inherently malleableIf ''(r,s)'' is a valid ECDSA signature for a given message and key, then ''(r,n-s)'' is also valid for the same message and key. If ECDSA is restricted to only permit one of the two variants (as Bitcoin does through a policy rule on the network), it can be [https://nbn-resolving.de/urn:nbn:de:hbz:294-60803 proven] non-malleable under stronger than usual assumptions.; a third party without access to the secret key can alter an existing valid signature for a given public key and message into another signature that is valid for the same key and message. This issue is discussed in [[bip-0062.mediawiki|BIP62]] and [[bip-0146.mediawiki|BIP146]].
+* '''Linearity''': Schnorr signatures provide a simple and efficient method that enables multiple collaborating parties to produce a signature that is valid for the sum of their public keys. This is the building block for various higher-level constructions that improve efficiency and privacy, such as multisignatures and others (see Applications below).
+
+For all these advantages, there are virtually no disadvantages, apart
+from not being standardized. This document seeks to change that. As we
+propose a new standard, a number of improvements not specific to Schnorr signatures can be
+made:
+
+* '''Signature encoding''': Instead of using [https://en.wikipedia.org/wiki/X.690#DER_encoding DER]-encoding for signatures (which are variable size, and up to 72 bytes), we can use a simple fixed 64-byte format.
+* '''Public key encoding''': Instead of using [https://www.secg.org/sec1-v2.pdf ''compressed''] 33-byte encodings of elliptic curve points which are common in Bitcoin today, public keys in this proposal are encoded as 32 bytes.
+* '''Batch verification''': The specific formulation of ECDSA signatures that is standardized cannot be verified more efficiently in batch compared to individually, unless additional witness data is added. Changing the signature scheme offers an opportunity to address this.
+* '''Completely specified''': To be safe for usage in consensus systems, the verification algorithm must be completely specified at the byte level. This guarantees that nobody can construct a signature that is valid to some verifiers but not all. This is traditionally not a requirement for digital signature schemes, and the lack of exact specification for the DER parsing of ECDSA signatures has caused problems for Bitcoin [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2015-July/009697.html in the past], needing [[bip-0066.mediawiki|BIP66]] to address it. In this document we aim to meet this property by design. For batch verification, which is inherently non-deterministic as the verifier can choose their batches, this property implies that the outcome of verification may only differ from individual verifications with negligible probability, even to an attacker who intentionally tries to make batch- and non-batch verification differ.
+
+By reusing the same curve and hash function as Bitcoin uses for ECDSA, we are able to retain existing mechanisms for choosing secret and public keys, and we avoid introducing new assumptions about the security of elliptic curves and hash functions.
+
+== Description ==
+
+We first build up the algebraic formulation of the signature scheme by
+going through the design choices. Afterwards, we specify the exact
+encodings and operations.
+
+=== Design ===
+
+'''Schnorr signature variant''' Elliptic Curve Schnorr signatures for message ''m'' and public key ''P'' generally involve a point ''R'', integers ''e'' and ''s'' picked by the signer, and the base point ''G'' which satisfy ''e = hash(R || m)'' and ''s⋅G = R + e⋅P''. Two formulations exist, depending on whether the signer reveals ''e'' or ''R'':
+# Signatures are pairs ''(e, s)'' that satisfy ''e = hash(s⋅G - e⋅P || m)''. This variant avoids minor complexity introduced by the encoding of the point ''R'' in the signature (see paragraphs "Encoding R and public key point P" and "Implicit Y coordinates" further below in this subsection). Moreover, revealing ''e'' instead of ''R'' allows for potentially shorter signatures: Whereas an encoding of ''R'' inherently needs about 32 bytes, the hash ''e'' can be tuned to be shorter than 32 bytes, and [http://www.neven.org/papers/schnorr.pdf a short hash of only 16 bytes suffices to provide SUF-CMA security at the target security level of 128 bits]. However, a major drawback of this optimization is that finding collisions in a short hash function is easy. This complicates the implementation of secure signing protocols in scenarios in which a group of mutually distrusting signers work together to produce a single joint signature (see Applications below). In these scenarios, which are not captured by the SUF-CMA model due its assumption of a single honest signer, a promising attack strategy for malicious co-signers is to find a collision in the hash function in order to obtain a valid signature on a message that an honest co-signer did not intend to sign.
+# Signatures are pairs ''(R, s)'' that satisfy ''s⋅G = R + hash(R || m)⋅P''. This supports batch verification, as there are no elliptic curve operations inside the hashes. Batch verification enables significant speedups.The speedup that results from batch verification can be demonstrated with the cryptography library [https://github.com/jonasnick/secp256k1/blob/schnorrsig-batch-verify/doc/speedup-batch.md libsecp256k1].
+
+Since we would like to avoid the fragility that comes with short hashes, the ''e'' variant does not provide significant advantages. We choose the ''R''-option, which supports batch verification.
+
+'''Key prefixing''' Using the verification rule above directly makes Schnorr signatures vulnerable to "related-key attacks" in which a third party can convert a signature ''(R, s)'' for public key ''P'' into a signature ''(R, s + a⋅hash(R || m))'' for public key ''P + a⋅G'' and the same message ''m'', for any given additive tweak ''a'' to the signing key. This would render signatures insecure when keys are generated using [[bip-0032.mediawiki#public-parent-key--public-child-key|BIP32's unhardened derivation]] and other methods that rely on additive tweaks to existing keys such as Taproot.
+
+To protect against these attacks, we choose ''key prefixed''A limitation of committing to the public key (rather than to a short hash of it, or not at all) is that it removes the ability for public key recovery or verifying signatures against a short public key hash. These constructions are generally incompatible with batch verification. Schnorr signatures which means that the public key is prefixed to the message in the challenge hash input. This changes the equation to ''s⋅G = R + hash(R || P || m)⋅P''. [https://eprint.iacr.org/2015/1135.pdf It can be shown] that key prefixing protects against related-key attacks with additive tweaks. In general, key prefixing increases robustness in multi-user settings, e.g., it seems to be a requirement for proving multiparty signing protocols (such as MuSig, MuSig2, and FROST) secure (see Applications below).
+
+We note that key prefixing is not strictly necessary for transaction signatures as used in Bitcoin currently, because signed transactions indirectly commit to the public keys already, i.e., ''m'' contains a commitment to ''pk''. However, this indirect commitment should not be relied upon because it may change with proposals such as SIGHASH_NOINPUT ([[bip-0118.mediawiki|BIP118]]), and would render the signature scheme unsuitable for other purposes than signing transactions, e.g., [https://bitcoin.org/en/developer-reference#signmessage signing ordinary messages].
+
+'''Encoding R and public key point P''' There exist several possibilities for encoding elliptic curve points:
+# Encoding the full X and Y coordinates of ''P'' and ''R'', resulting in a 64-byte public key and a 96-byte signature.
+# Encoding the full X coordinate and one bit of the Y coordinate to determine one of the two possible Y coordinates. This would result in 33-byte public keys and 65-byte signatures.
+# Encoding only the X coordinate, resulting in 32-byte public keys and 64-byte signatures.
+
+Using the first option would be slightly more efficient for verification (around 10%), but we prioritize compactness, and therefore choose option 3.
+
+'''Implicit Y coordinates''' In order to support efficient verification and batch verification, the Y coordinate of ''P'' and of ''R'' cannot be ambiguous (every valid X coordinate has two possible Y coordinates). We have a choice between several options for symmetry breaking:
+# Implicitly choosing the Y coordinate that is in the lower half.
+# Implicitly choosing the Y coordinate that is evenSince ''p'' is odd, negation modulo ''p'' will map even numbers to odd numbers and the other way around. This means that for a valid X coordinate, one of the corresponding Y coordinates will be even, and the other will be odd..
+# Implicitly choosing the Y coordinate that is a quadratic residue (i.e. has a square root modulo ''p'').
+
+The second option offers the greatest compatibility with existing key generation systems, where the standard 33-byte compressed public key format consists of a byte indicating the oddness of the Y coordinate, plus the full X coordinate. To avoid gratuitous incompatibilities, we pick that option for ''P'', and thus our X-only public keys become equivalent to a compressed public key that is the X-only key prefixed by the byte 0x02. For consistency, the same is done for ''R''An earlier version of this draft used the third option instead, based on a belief that this would in general trade signing efficiency for verification efficiency. When using Jacobian coordinates, a common optimization in ECC implementations, it is possible to determine if a Y coordinate is a quadratic residue by computing the Legendre symbol, without converting to affine coordinates first (which needs a modular inversion). As modular inverses and Legendre symbols have similar [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2020-August/018081.html performance] in practice, this trade-off is not worth it..
+
+Despite halving the size of the set of valid public keys, implicit Y coordinates are not a reduction in security. Informally, if a fast algorithm existed to compute the discrete logarithm of an X-only public key, then it could also be used to compute the discrete logarithm of a full public key: apply it to the X coordinate, and then optionally negate the result. This shows that breaking an X-only public key can be at most a small constant term faster than breaking a full one.This can be formalized by a simple reduction that reduces an attack on Schnorr signatures with implicit Y coordinates to an attack to Schnorr signatures with explicit Y coordinates. The reduction works by reencoding public keys and negating the result of the hash function, which is modeled as random oracle, whenever the challenge public key has an explicit Y coordinate that is odd. A proof sketch can be found [https://medium.com/blockstream/reducing-bitcoin-transaction-sizes-with-x-only-pubkeys-f86476af05d7 here]..
+
+'''Tagged Hashes''' Cryptographic hash functions are used for multiple purposes in the specification below and in Bitcoin in general. To make sure hashes used in one context can't be reinterpreted in another one, hash functions can be tweaked with a context-dependent tag name, in such a way that collisions across contexts can be assumed to be infeasible. Such collisions obviously can not be ruled out completely, but only for schemes using tagging with a unique name. As for other schemes collisions are at least less likely with tagging than without.
+
+For example, without tagged hashing a BIP340 signature could also be valid for a signature scheme where the only difference is that the arguments to the hash function are reordered. Worse, if the BIP340 nonce derivation function was copied or independently created, then the nonce could be accidentally reused in the other scheme leaking the secret key.
+
+This proposal suggests to include the tag by prefixing the hashed data with ''SHA256(tag) || SHA256(tag)''. Because this is a 64-byte long context-specific constant and the ''SHA256'' block size is also 64 bytes, optimized implementations are possible (identical to SHA256 itself, but with a modified initial state). Using SHA256 of the tag name itself is reasonably simple and efficient for implementations that don't choose to use the optimization. In general, tags can be arbitrary byte arrays, but are suggested to be textual descriptions in UTF-8 encoding.
+
+'''Final scheme''' As a result, our final scheme ends up using public key ''pk'' which is the X coordinate of a point ''P'' on the curve whose Y coordinate is even and signatures ''(r,s)'' where ''r'' is the X coordinate of a point ''R'' whose Y coordinate is even. The signature satisfies ''s⋅G = R + tagged_hash(r || pk || m)⋅P''.
+
+=== Specification ===
+
+The following conventions are used, with constants as defined for [https://www.secg.org/sec2-v2.pdf secp256k1]. We note that adapting this specification to other elliptic curves is not straightforward and can result in an insecure schemeAmong other pitfalls, using the specification with a curve whose order is not close to the size of the range of the nonce derivation function is insecure..
+* Lowercase variables represent integers or byte arrays.
+** The constant ''p'' refers to the field size, ''0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F''.
+** The constant ''n'' refers to the curve order, ''0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141''.
+* Uppercase variables refer to points on the curve with equation ''y2 = x3 + 7'' over the integers modulo ''p''.
+** ''is_infinite(P)'' returns whether or not ''P'' is the point at infinity.
+** ''x(P)'' and ''y(P)'' are integers in the range ''0..p-1'' and refer to the X and Y coordinates of a point ''P'' (assuming it is not infinity).
+** The constant ''G'' refers to the base point, for which ''x(G) = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798'' and ''y(G) = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8''.
+** Addition of points refers to the usual [https://en.wikipedia.org/wiki/Elliptic_curve#The_group_law elliptic curve group operation].
+** [https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication Multiplication (⋅) of an integer and a point] refers to the repeated application of the group operation.
+* Functions and operations:
+** ''||'' refers to byte array concatenation.
+** The function ''x[i:j]'', where ''x'' is a byte array and ''i, j ≥ 0'', returns a ''(j - i)''-byte array with a copy of the ''i''-th byte (inclusive) to the ''j''-th byte (exclusive) of ''x''.
+** The function ''bytes(x)'', where ''x'' is an integer, returns the 32-byte encoding of ''x'', most significant byte first.
+** The function ''bytes(P)'', where ''P'' is a point, returns ''bytes(x(P))''.
+** The function ''int(x)'', where ''x'' is a 32-byte array, returns the 256-bit unsigned integer whose most significant byte first encoding is ''x''.
+** The function ''has_even_y(P)'', where ''P'' is a point for which ''not is_infinite(P)'', returns ''y(P) mod 2 = 0''.
+** The function ''lift_x(x)'', where ''x'' is a 256-bit unsigned integer, returns the point ''P'' for which ''x(P) = x''
+ Given a candidate X coordinate ''x'' in the range ''0..p-1'', there exist either exactly two or exactly zero valid Y coordinates. If no valid Y coordinate exists, then ''x'' is not a valid X coordinate either, i.e., no point ''P'' exists for which ''x(P) = x''. The valid Y coordinates for a given candidate ''x'' are the square roots of ''c = x3 + 7 mod p'' and they can be computed as ''y = ±c(p+1)/4 mod p'' (see [https://en.wikipedia.org/wiki/Quadratic_residue#Prime_or_prime_power_modulus Quadratic residue]) if they exist, which can be checked by squaring and comparing with ''c''. and ''has_even_y(P)'', or fails if ''x'' is greater than ''p-1'' or no such point exists. The function ''lift_x(x)'' is equivalent to the following pseudocode:
+*** Fail if ''x ≥ p''.
+*** Let ''c = x3 + 7 mod p''.
+*** Let ''y = c(p+1)/4 mod p''.
+*** Fail if ''c ≠ y2 mod p''.
+*** Return the unique point ''P'' such that ''x(P) = x'' and ''y(P) = y'' if ''y mod 2 = 0'' or ''y(P) = p-y'' otherwise.
+** The function ''hashname(x)'' where ''x'' is a byte array returns the 32-byte hash ''SHA256(SHA256(tag) || SHA256(tag) || x)'', where ''tag'' is the UTF-8 encoding of ''name''.
+
+==== Public Key Generation ====
+
+Input:
+* The secret key ''sk'': a 32-byte array, freshly generated uniformly at random
+
+The algorithm ''PubKey(sk)'' is defined as:
+* Let ''d' = int(sk)''.
+* Fail if ''d' = 0'' or ''d' ≥ n''.
+* Return ''bytes(d'⋅G)''.
+
+Note that we use a very different public key format (32 bytes) than the ones used by existing systems (which typically use elliptic curve points as public keys, or 33-byte or 65-byte encodings of them). A side effect is that ''PubKey(sk) = PubKey(bytes(n - int(sk))'', so every public key has two corresponding secret keys.
+
+==== Public Key Conversion ====
+
+As an alternative to generating keys randomly, it is also possible and safe to repurpose existing key generation algorithms for ECDSA in a compatible way. The secret keys constructed by such an algorithm can be used as ''sk'' directly. The public keys constructed by such an algorithm (assuming they use the 33-byte compressed encoding) need to be converted by dropping the first byte. Specifically, [[bip-0032.mediawiki|BIP32]] and schemes built on top of it remain usable.
+
+==== Default Signing ====
+
+Input:
+* The secret key ''sk'': a 32-byte array
+* The message ''m'': a byte array
+* Auxiliary random data ''a'': a 32-byte array
+
+The algorithm ''Sign(sk, m)'' is defined as:
+* Let ''d' = int(sk)''
+* Fail if ''d' = 0'' or ''d' ≥ n''
+* Let ''P = d'⋅G''
+* Let ''d = d' '' if ''has_even_y(P)'', otherwise let ''d = n - d' ''.
+* Let ''t'' be the byte-wise xor of ''bytes(d)'' and ''hashBIP0340/aux(a)''The auxiliary random data is hashed (with a unique tag) as a precaution against situations where the randomness may be correlated with the private key itself. It is xored with the private key (rather than combined with it in a hash) to reduce the number of operations exposed to the actual secret key..
+* Let ''rand = hashBIP0340/nonce(t || bytes(P) || m)''Including the [https://moderncrypto.org/mail-archive/curves/2020/001012.html public key as input to the nonce hash] helps ensure the robustness of the signing algorithm by preventing leakage of the secret key if the calculation of the public key ''P'' is performed incorrectly or maliciously, for example if it is left to the caller for performance reasons..
+* Let ''k' = int(rand) mod n''Note that in general, taking a uniformly random 256-bit integer modulo the curve order will produce an unacceptably biased result. However, for the secp256k1 curve, the order is sufficiently close to ''2256'' that this bias is not observable (''1 - n / 2256'' is around ''1.27 * 2-128'')..
+* Fail if ''k' = 0''.
+* Let ''R = k'⋅G''.
+* Let ''k = k' '' if ''has_even_y(R)'', otherwise let ''k = n - k' ''.
+* Let ''e = int(hashBIP0340/challenge(bytes(R) || bytes(P) || m)) mod n''.
+* Let ''sig = bytes(R) || bytes((k + ed) mod n)''.
+* If ''Verify(bytes(P), m, sig)'' (see below) returns failure, abortVerifying the signature before leaving the signer prevents random or attacker provoked computation errors. This prevents publishing invalid signatures which may leak information about the secret key. It is recommended, but can be omitted if the computation cost is prohibitive..
+* Return the signature ''sig''.
+
+The auxiliary random data should be set to fresh randomness generated at signing time, resulting in what is called a ''synthetic nonce''. Using 32 bytes of randomness is optimal. If obtaining randomness is expensive, 16 random bytes can be padded with 16 null bytes to obtain a 32-byte array. If randomness is not available at all at signing time, a simple counter wide enough to not repeat in practice (e.g., 64 bits or wider) and padded with null bytes to a 32 byte-array can be used, or even the constant array with 32 null bytes. Using any non-repeating value increases protection against [https://moderncrypto.org/mail-archive/curves/2017/000925.html fault injection attacks]. Using unpredictable randomness additionally increases protection against other side-channel attacks, and is '''recommended whenever available'''. Note that while this means the resulting nonce is not deterministic, the randomness is only supplemental to security. The normal security properties (excluding side-channel attacks) do not depend on the quality of the signing-time RNG.
+
+==== Alternative Signing ====
+
+It should be noted that various alternative signing algorithms can be used to produce equally valid signatures. The 32-byte ''rand'' value may be generated in other ways, producing a different but still valid signature (in other words, this is not a ''unique'' signature scheme). '''No matter which method is used to generate the ''rand'' value, the value must be a fresh uniformly random 32-byte string which is not even partially predictable for the attacker.''' For nonces without randomness, this implies that the same inputs must not be presented in another context. This can be most reliably accomplished by not reusing the same private key across different signing schemes. For example, if the ''rand'' value was computed as per RFC6979 and the same secret key is used in deterministic ECDSA with RFC6979, the signatures can leak the secret key through nonce reuse.
+
+'''Nonce exfiltration protection''' It is possible to strengthen the nonce generation algorithm using a second device. In this case, the second device contributes randomness which the actual signer provably incorporates into its nonce. This prevents certain attacks where the signer's device is compromised and intentionally tries to leak the secret key through its nonce selection.
+
+'''Multisignatures''' This signature scheme is compatible with various types of multisignature and threshold schemes such as [https://eprint.iacr.org/2020/1261.pdf MuSig2], where a single public key requires holders of multiple secret keys to participate in signing (see Applications below).
+'''It is important to note that multisignature signing schemes in general are insecure with the ''rand'' generation from the default signing algorithm above (or any other deterministic method).'''
+
+'''Precomputed public key data''' For many uses, the compressed 33-byte encoding of the public key corresponding to the secret key may already be known, making it easy to evaluate ''has_even_y(P)'' and ''bytes(P)''. As such, having signers supply this directly may be more efficient than recalculating the public key from the secret key. However, if this optimization is used and additionally the signature verification at the end of the signing algorithm is dropped for increased efficiency, signers must ensure the public key is correctly calculated and not taken from untrusted sources.
+
+==== Verification ====
+
+Input:
+* The public key ''pk'': a 32-byte array
+* The message ''m'': a byte array
+* A signature ''sig'': a 64-byte array
+
+The algorithm ''Verify(pk, m, sig)'' is defined as:
+* Let ''P = lift_x(int(pk))''; fail if that fails.
+* Let ''r = int(sig[0:32])''; fail if ''r ≥ p''.
+* Let ''s = int(sig[32:64])''; fail if ''s ≥ n''.
+* Let ''e = int(hashBIP0340/challenge(bytes(r) || bytes(P) || m)) mod n''.
+* Let ''R = s⋅G - e⋅P''.
+* Fail if ''is_infinite(R)''.
+* Fail if ''not has_even_y(R)''.
+* Fail if ''x(R) ≠ r''.
+* Return success iff no failure occurred before reaching this point.
+
+For every valid secret key ''sk'' and message ''m'', ''Verify(PubKey(sk),m,Sign(sk,m))'' will succeed.
+
+Note that the correctness of verification relies on the fact that ''lift_x'' always returns a point with an even Y coordinate. A hypothetical verification algorithm that treats points as public keys, and takes the point ''P'' directly as input would fail any time a point with odd Y is used. While it is possible to correct for this by negating points with odd Y coordinate before further processing, this would result in a scheme where every (message, signature) pair is valid for two public keys (a type of malleability that exists for ECDSA as well, but we don't wish to retain). We avoid these problems by treating just the X coordinate as public key.
+
+==== Batch Verification ====
+
+Input:
+* The number ''u'' of signatures
+* The public keys ''pk1..u'': ''u'' 32-byte arrays
+* The messages ''m1..u'': ''u'' byte arrays
+* The signatures ''sig1..u'': ''u'' 64-byte arrays
+
+The algorithm ''BatchVerify(pk1..u, m1..u, sig1..u)'' is defined as:
+* Generate ''u-1'' random integers ''a2...u'' in the range ''1...n-1''. They are generated deterministically using a [https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator CSPRNG] seeded by a cryptographic hash of all inputs of the algorithm, i.e. ''seed = seed_hash(pk1..pku || m1..mu || sig1..sigu )''. A safe choice is to instantiate ''seed_hash'' with SHA256 and use [https://tools.ietf.org/html/rfc8439 ChaCha20] with key ''seed'' as a CSPRNG to generate 256-bit integers, skipping integers not in the range ''1...n-1''.
+* For ''i = 1 .. u'':
+** Let ''Pi = lift_x(int(pki))''; fail if it fails.
+** Let ''ri = int(sigi[0:32])''; fail if ''ri ≥ p''.
+** Let ''si = int(sigi[32:64])''; fail if ''si ≥ n''.
+** Let ''ei = int(hashBIP0340/challenge(bytes(ri) || bytes(Pi) || mi)) mod n''.
+** Let ''Ri = lift_x(ri)''; fail if ''lift_x(ri)'' fails.
+* Fail if ''(s1 + a2s2 + ... + ausu)⋅G ≠ R1 + a2⋅R2 + ... + au⋅Ru + e1⋅P1 + (a2e2)⋅P2 + ... + (aueu)⋅Pu''.
+* Return success iff no failure occurred before reaching this point.
+
+If all individual signatures are valid (i.e., ''Verify'' would return success for them), ''BatchVerify'' will always return success. If at least one signature is invalid, ''BatchVerify'' will return success with at most a negligible probability.
+
+=== Usage Considerations ===
+
+==== Messages of Arbitrary Size ====
+
+The signature scheme specified in this BIP accepts byte strings of arbitrary size as input messages.In theory, the message size is restricted due to the fact that SHA256 accepts byte strings only up to size of 2^61-1 bytes.
+It is understood that implementations may reject messages which are too large in their environment or application context,
+e.g., messages which exceed predefined buffers or would otherwise cause resource exhaustion.
+
+Earlier revisions of this BIP required messages to be exactly 32 bytes.
+This restriction puts a burden on callers
+who typically need to perform pre-hashing of the actual input message by feeding it through SHA256 (or another collision-resistant cryptographic hash function)
+to create a 32-byte digest which can be passed to signing or verification
+(as for example done in [[bip-0341.mediawiki|BIP341]].)
+
+Since pre-hashing may not always be desirable,
+e.g., when actual messages are shorter than 32 bytes,Another reason to omit pre-hashing is to protect against certain types of cryptanalytic advances against the hash function used for pre-hashing: If pre-hashing is used, an attacker that can find collisions in the pre-hashing function can necessarily forge signatures under chosen-message attacks. If pre-hashing is not used, an attacker that can find collisions in SHA256 (as used inside the signature scheme) may not be able to forge signatures. However, this seeming advantage is mostly irrelevant in the context of Bitcoin, which already relies on collision resistance of SHA256 in other places, e.g., for transaction hashes.
+the restriction to 32-byte messages has been lifted.
+We note that pre-hashing is recommended for performance reasons in applications that deal with large messages.
+If large messages are not pre-hashed,
+the algorithms of the signature scheme will perform more hashing internally.
+In particular, the signing algorithm needs two sequential hashing passes over the message,
+which means that the full message must necessarily be kept in memory during signing,
+and large messages entail a runtime penalty.Typically, messages of 56 bytes or longer enjoy a performance benefit from pre-hashing, assuming the speed of SHA256 inside the signing algorithm matches that of the pre-hashing done by the calling application.
+
+==== Domain Separation ====
+
+It is good cryptographic practice to use a key pair only for a single purpose.
+Nevertheless, there may be situations in which it may be desirable to use the same key pair in multiple contexts,
+i.e., to sign different types of messages within the same application
+or even messages in entirely different applications
+(e.g., a secret key may be used to sign Bitcoin transactions as well plain text messages).
+
+As a consequence, applications should ensure that a signed application message intended for one context is never deemed valid in a different context
+(e.g., a signed plain text message should never be misinterpreted as a signed Bitcoin transaction, because this could cause unintended loss of funds).
+This is called "domain separation" and it is typically realized by partitioning the message space.
+Even if key pairs are intended to be used only within a single context,
+domain separation is a good idea because it makes it easy to add more contexts later.
+
+As a best practice, we recommend applications to use exactly one of the following methods to pre-process application messages before passing it to the signature scheme:
+* Either, pre-hash the application message using ''hashname'', where ''name'' identifies the context uniquely (e.g., "foo-app/signed-bar"),
+* or prefix the actual message with a 33-byte string that identifies the context uniquely (e.g., the UTF-8 encoding of "foo-app/signed-bar", padded with null bytes to 33 bytes).
+
+As the two pre-processing methods yield different message sizes (32 bytes vs. at least 33 bytes), there is no risk of collision between them.
+
+== Applications ==
+
+There are several interesting applications beyond simple signatures.
+While recent academic papers claim that they are also possible with ECDSA, consensus support for Schnorr signature verification would significantly simplify the constructions.
+
+=== Multisignatures and Threshold Signatures ===
+
+By means of an interactive scheme such as [https://eprint.iacr.org/2020/1261.pdf MuSig2] ([[bip-0327.mediawiki|BIP327]]), participants can aggregate their public keys into a single public key which they can jointly sign for. This allows ''n''-of-''n'' multisignatures which, from a verifier's perspective, are no different from ordinary signatures, giving improved privacy and efficiency versus ''CHECKMULTISIG'' or other means.
+
+Moreover, Schnorr signatures are compatible with [https://en.wikipedia.org/wiki/Distributed_key_generation distributed key generation], which enables interactive threshold signatures schemes, e.g., the schemes by [http://cacr.uwaterloo.ca/techreports/2001/corr2001-13.ps Stinson and Strobl (2001)], by [https://link.springer.com/content/pdf/10.1007/s00145-006-0347-3.pdf Gennaro, Jarecki, Krawczyk, and Rabin (2007)], or the [https://eprint.iacr.org/2020/852.pdf FROST] scheme including its variants such as [https://eprint.iacr.org/2023/899.pdf FROST3]. These protocols make it possible to realize ''k''-of-''n'' threshold signatures, which ensure that any subset of size ''k'' of the set of ''n'' signers can sign but no subset of size less than ''k'' can produce a valid Schnorr signature.
+
+=== Adaptor Signatures ===
+
+[https://download.wpsoftware.net/bitcoin/wizardry/mw-slides/2018-05-18-l2/slides.pdf Adaptor signatures] can be produced by a signer by offsetting his public nonce ''R'' with a known point ''T = t⋅G'', but not offsetting the signature's ''s'' value.
+A correct signature (or partial signature, as individual signers' contributions to a multisignature are called) on the same message with same nonce will then be equal to the adaptor signature offset by ''t'', meaning that learning ''t'' is equivalent to learning a correct signature.
+This can be used to enable atomic swaps or even [https://eprint.iacr.org/2018/472 general payment channels] in which the atomicity of disjoint transactions is ensured using the signatures themselves, rather than Bitcoin script support. The resulting transactions will appear to verifiers to be no different from ordinary single-signer transactions, except perhaps for the inclusion of locktime refund logic.
+
+Adaptor signatures, beyond the efficiency and privacy benefits of encoding script semantics into constant-sized signatures, have additional benefits over traditional hash-based payment channels. Specifically, the secret values ''t'' may be reblinded between hops, allowing long chains of transactions to be made atomic while even the participants cannot identify which transactions are part of the chain. Also, because the secret values are chosen at signing time, rather than key generation time, existing outputs may be repurposed for different applications without recourse to the blockchain, even multiple times.
+
+=== Blind Signatures ===
+
+A blind signature protocol is an interactive protocol that enables a signer to sign a message at the behest of another party without learning any information about the signed message or the signature. Schnorr signatures admit a very [http://publikationen.ub.uni-frankfurt.de/files/4292/schnorr.blind_sigs_attack.2001.pdf simple blind signature scheme] which is however insecure because it's vulnerable to [https://www.iacr.org/archive/crypto2002/24420288/24420288.pdf Wagner's attack]. Known mitigations are to let the signer abort a signing session with a certain probability, which can be [https://eprint.iacr.org/2019/877 proven secure under non-standard cryptographic assumptions], or [https://eprint.iacr.org/2022/1676.pdf to use zero-knowledge proofs].
+
+Blind Schnorr signatures could for example be used in [https://github.com/ElementsProject/scriptless-scripts/blob/master/md/partially-blind-swap.md Partially Blind Atomic Swaps], a construction to enable transferring of coins, mediated by an untrusted escrow agent, without connecting the transactors in the public blockchain transaction graph.
+
+== Test Vectors and Reference Code ==
+
+For development and testing purposes, we provide a [[bip-0340/test-vectors.csv|collection of test vectors in CSV format]] and a naive, highly inefficient, and non-constant time [[bip-0340/reference.py|pure Python 3.7 reference implementation of the signing and verification algorithm]].
+The reference implementation is for demonstration purposes only and not to be used in production environments.
+
+== Changelog ==
+
+To help implementors understand updates to this BIP, we keep a list of substantial changes.
+
+* 2022-08: Fix function signature of lift_x in reference code
+* 2023-04: Allow messages of arbitrary size
+* 2024-05: Update "Applications" section with more recent references
+
+== Footnotes ==
+
+
+
+== Acknowledgements ==
+
+This document is the result of many discussions around Schnorr based signatures over the years, and had input from Johnson Lau, Greg Maxwell, Andrew Poelstra, Rusty Russell, and Anthony Towns. The authors further wish to thank all those who provided valuable feedback and reviews, including the participants of the [https://github.com/ajtowns/taproot-review structured reviews].
diff --git a/bip-0340/reference.py b/bip-0340/reference.py
new file mode 100644
index 0000000000..b327e0a228
--- /dev/null
+++ b/bip-0340/reference.py
@@ -0,0 +1,221 @@
+from typing import Tuple, Optional, Any
+import hashlib
+import binascii
+
+# Set DEBUG to True to get a detailed debug output including
+# intermediate values during key generation, signing, and
+# verification. This is implemented via calls to the
+# debug_print_vars() function.
+#
+# If you want to print values on an individual basis, use
+# the pretty() function, e.g., print(pretty(foo)).
+DEBUG = False
+
+p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
+n = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
+
+# Points are tuples of X and Y coordinates and the point at infinity is
+# represented by the None keyword.
+G = (0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8)
+
+Point = Tuple[int, int]
+
+# This implementation can be sped up by storing the midstate after hashing
+# tag_hash instead of rehashing it all the time.
+def tagged_hash(tag: str, msg: bytes) -> bytes:
+ tag_hash = hashlib.sha256(tag.encode()).digest()
+ return hashlib.sha256(tag_hash + tag_hash + msg).digest()
+
+def is_infinite(P: Optional[Point]) -> bool:
+ return P is None
+
+def x(P: Point) -> int:
+ assert not is_infinite(P)
+ return P[0]
+
+def y(P: Point) -> int:
+ assert not is_infinite(P)
+ return P[1]
+
+def point_add(P1: Optional[Point], P2: Optional[Point]) -> Optional[Point]:
+ if P1 is None:
+ return P2
+ if P2 is None:
+ return P1
+ if (x(P1) == x(P2)) and (y(P1) != y(P2)):
+ return None
+ if P1 == P2:
+ lam = (3 * x(P1) * x(P1) * pow(2 * y(P1), p - 2, p)) % p
+ else:
+ lam = ((y(P2) - y(P1)) * pow(x(P2) - x(P1), p - 2, p)) % p
+ x3 = (lam * lam - x(P1) - x(P2)) % p
+ return (x3, (lam * (x(P1) - x3) - y(P1)) % p)
+
+def point_mul(P: Optional[Point], n: int) -> Optional[Point]:
+ R = None
+ for i in range(256):
+ if (n >> i) & 1:
+ R = point_add(R, P)
+ P = point_add(P, P)
+ return R
+
+def bytes_from_int(x: int) -> bytes:
+ return x.to_bytes(32, byteorder="big")
+
+def bytes_from_point(P: Point) -> bytes:
+ return bytes_from_int(x(P))
+
+def xor_bytes(b0: bytes, b1: bytes) -> bytes:
+ return bytes(x ^ y for (x, y) in zip(b0, b1))
+
+def lift_x(x: int) -> Optional[Point]:
+ if x >= p:
+ return None
+ y_sq = (pow(x, 3, p) + 7) % p
+ y = pow(y_sq, (p + 1) // 4, p)
+ if pow(y, 2, p) != y_sq:
+ return None
+ return (x, y if y & 1 == 0 else p-y)
+
+def int_from_bytes(b: bytes) -> int:
+ return int.from_bytes(b, byteorder="big")
+
+def hash_sha256(b: bytes) -> bytes:
+ return hashlib.sha256(b).digest()
+
+def has_even_y(P: Point) -> bool:
+ assert not is_infinite(P)
+ return y(P) % 2 == 0
+
+def pubkey_gen(seckey: bytes) -> bytes:
+ d0 = int_from_bytes(seckey)
+ if not (1 <= d0 <= n - 1):
+ raise ValueError('The secret key must be an integer in the range 1..n-1.')
+ P = point_mul(G, d0)
+ assert P is not None
+ return bytes_from_point(P)
+
+def schnorr_sign(msg: bytes, seckey: bytes, aux_rand: bytes) -> bytes:
+ d0 = int_from_bytes(seckey)
+ if not (1 <= d0 <= n - 1):
+ raise ValueError('The secret key must be an integer in the range 1..n-1.')
+ if len(aux_rand) != 32:
+ raise ValueError('aux_rand must be 32 bytes instead of %i.' % len(aux_rand))
+ P = point_mul(G, d0)
+ assert P is not None
+ d = d0 if has_even_y(P) else n - d0
+ t = xor_bytes(bytes_from_int(d), tagged_hash("BIP0340/aux", aux_rand))
+ k0 = int_from_bytes(tagged_hash("BIP0340/nonce", t + bytes_from_point(P) + msg)) % n
+ if k0 == 0:
+ raise RuntimeError('Failure. This happens only with negligible probability.')
+ R = point_mul(G, k0)
+ assert R is not None
+ k = n - k0 if not has_even_y(R) else k0
+ e = int_from_bytes(tagged_hash("BIP0340/challenge", bytes_from_point(R) + bytes_from_point(P) + msg)) % n
+ sig = bytes_from_point(R) + bytes_from_int((k + e * d) % n)
+ debug_print_vars()
+ if not schnorr_verify(msg, bytes_from_point(P), sig):
+ raise RuntimeError('The created signature does not pass verification.')
+ return sig
+
+def schnorr_verify(msg: bytes, pubkey: bytes, sig: bytes) -> bool:
+ if len(pubkey) != 32:
+ raise ValueError('The public key must be a 32-byte array.')
+ if len(sig) != 64:
+ raise ValueError('The signature must be a 64-byte array.')
+ P = lift_x(int_from_bytes(pubkey))
+ r = int_from_bytes(sig[0:32])
+ s = int_from_bytes(sig[32:64])
+ if (P is None) or (r >= p) or (s >= n):
+ debug_print_vars()
+ return False
+ e = int_from_bytes(tagged_hash("BIP0340/challenge", sig[0:32] + pubkey + msg)) % n
+ R = point_add(point_mul(G, s), point_mul(P, n - e))
+ if (R is None) or (not has_even_y(R)) or (x(R) != r):
+ debug_print_vars()
+ return False
+ debug_print_vars()
+ return True
+
+#
+# The following code is only used to verify the test vectors.
+#
+import csv
+import os
+import sys
+
+def test_vectors() -> bool:
+ all_passed = True
+ with open(os.path.join(sys.path[0], 'test-vectors.csv'), newline='') as csvfile:
+ reader = csv.reader(csvfile)
+ reader.__next__()
+ for row in reader:
+ (index, seckey_hex, pubkey_hex, aux_rand_hex, msg_hex, sig_hex, result_str, comment) = row
+ pubkey = bytes.fromhex(pubkey_hex)
+ msg = bytes.fromhex(msg_hex)
+ sig = bytes.fromhex(sig_hex)
+ result = result_str == 'TRUE'
+ print('\nTest vector', ('#' + index).rjust(3, ' ') + ':')
+ if seckey_hex != '':
+ seckey = bytes.fromhex(seckey_hex)
+ pubkey_actual = pubkey_gen(seckey)
+ if pubkey != pubkey_actual:
+ print(' * Failed key generation.')
+ print(' Expected key:', pubkey.hex().upper())
+ print(' Actual key:', pubkey_actual.hex().upper())
+ aux_rand = bytes.fromhex(aux_rand_hex)
+ try:
+ sig_actual = schnorr_sign(msg, seckey, aux_rand)
+ if sig == sig_actual:
+ print(' * Passed signing test.')
+ else:
+ print(' * Failed signing test.')
+ print(' Expected signature:', sig.hex().upper())
+ print(' Actual signature:', sig_actual.hex().upper())
+ all_passed = False
+ except RuntimeError as e:
+ print(' * Signing test raised exception:', e)
+ all_passed = False
+ result_actual = schnorr_verify(msg, pubkey, sig)
+ if result == result_actual:
+ print(' * Passed verification test.')
+ else:
+ print(' * Failed verification test.')
+ print(' Expected verification result:', result)
+ print(' Actual verification result:', result_actual)
+ if comment:
+ print(' Comment:', comment)
+ all_passed = False
+ print()
+ if all_passed:
+ print('All test vectors passed.')
+ else:
+ print('Some test vectors failed.')
+ return all_passed
+
+#
+# The following code is only used for debugging
+#
+import inspect
+
+def pretty(v: Any) -> Any:
+ if isinstance(v, bytes):
+ return '0x' + v.hex()
+ if isinstance(v, int):
+ return pretty(bytes_from_int(v))
+ if isinstance(v, tuple):
+ return tuple(map(pretty, v))
+ return v
+
+def debug_print_vars() -> None:
+ if DEBUG:
+ current_frame = inspect.currentframe()
+ assert current_frame is not None
+ frame = current_frame.f_back
+ assert frame is not None
+ print(' Variables in function ', frame.f_code.co_name, ' at line ', frame.f_lineno, ':', sep='')
+ for var_name, var_val in frame.f_locals.items():
+ print(' ' + var_name.rjust(11, ' '), '==', pretty(var_val))
+
+if __name__ == '__main__':
+ test_vectors()
diff --git a/bip-0340/test-vectors.csv b/bip-0340/test-vectors.csv
new file mode 100644
index 0000000000..672339129a
--- /dev/null
+++ b/bip-0340/test-vectors.csv
@@ -0,0 +1,20 @@
+index,secret key,public key,aux_rand,message,signature,verification result,comment
+0,0000000000000000000000000000000000000000000000000000000000000003,F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9,0000000000000000000000000000000000000000000000000000000000000000,0000000000000000000000000000000000000000000000000000000000000000,E907831F80848D1069A5371B402410364BDF1C5F8307B0084C55F1CE2DCA821525F66A4A85EA8B71E482A74F382D2CE5EBEEE8FDB2172F477DF4900D310536C0,TRUE,
+1,B7E151628AED2A6ABF7158809CF4F3C762E7160F38B4DA56A784D9045190CFEF,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,0000000000000000000000000000000000000000000000000000000000000001,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,6896BD60EEAE296DB48A229FF71DFE071BDE413E6D43F917DC8DCF8C78DE33418906D11AC976ABCCB20B091292BFF4EA897EFCB639EA871CFA95F6DE339E4B0A,TRUE,
+2,C90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B14E5C9,DD308AFEC5777E13121FA72B9CC1B7CC0139715309B086C960E18FD969774EB8,C87AA53824B4D7AE2EB035A2B5BBBCCC080E76CDC6D1692C4B0B62D798E6D906,7E2D58D8B3BCDF1ABADEC7829054F90DDA9805AAB56C77333024B9D0A508B75C,5831AAEED7B44BB74E5EAB94BA9D4294C49BCF2A60728D8B4C200F50DD313C1BAB745879A5AD954A72C45A91C3A51D3C7ADEA98D82F8481E0E1E03674A6F3FB7,TRUE,
+3,0B432B2677937381AEF05BB02A66ECD012773062CF3FA2549E44F58ED2401710,25D1DFF95105F5253C4022F628A996AD3A0D95FBF21D468A1B33F8C160D8F517,FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF,FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF,7EB0509757E246F19449885651611CB965ECC1A187DD51B64FDA1EDC9637D5EC97582B9CB13DB3933705B32BA982AF5AF25FD78881EBB32771FC5922EFC66EA3,TRUE,test fails if msg is reduced modulo p or n
+4,,D69C3509BB99E412E68B0FE8544E72837DFA30746D8BE2AA65975F29D22DC7B9,,4DF3C3F68FCC83B27E9D42C90431A72499F17875C81A599B566C9889B9696703,00000000000000000000003B78CE563F89A0ED9414F5AA28AD0D96D6795F9C6376AFB1548AF603B3EB45C9F8207DEE1060CB71C04E80F593060B07D28308D7F4,TRUE,
+5,,EEFDEA4CDB677750A420FEE807EACF21EB9898AE79B9768766E4FAA04A2D4A34,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,6CFF5C3BA86C69EA4B7376F31A9BCB4F74C1976089B2D9963DA2E5543E17776969E89B4C5564D00349106B8497785DD7D1D713A8AE82B32FA79D5F7FC407D39B,FALSE,public key not on the curve
+6,,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,FFF97BD5755EEEA420453A14355235D382F6472F8568A18B2F057A14602975563CC27944640AC607CD107AE10923D9EF7A73C643E166BE5EBEAFA34B1AC553E2,FALSE,has_even_y(R) is false
+7,,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,1FA62E331EDBC21C394792D2AB1100A7B432B013DF3F6FF4F99FCB33E0E1515F28890B3EDB6E7189B630448B515CE4F8622A954CFE545735AAEA5134FCCDB2BD,FALSE,negated message
+8,,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,6CFF5C3BA86C69EA4B7376F31A9BCB4F74C1976089B2D9963DA2E5543E177769961764B3AA9B2FFCB6EF947B6887A226E8D7C93E00C5ED0C1834FF0D0C2E6DA6,FALSE,negated s value
+9,,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,0000000000000000000000000000000000000000000000000000000000000000123DDA8328AF9C23A94C1FEECFD123BA4FB73476F0D594DCB65C6425BD186051,FALSE,sG - eP is infinite. Test fails in single verification if has_even_y(inf) is defined as true and x(inf) as 0
+10,,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,00000000000000000000000000000000000000000000000000000000000000017615FBAF5AE28864013C099742DEADB4DBA87F11AC6754F93780D5A1837CF197,FALSE,sG - eP is infinite. Test fails in single verification if has_even_y(inf) is defined as true and x(inf) as 1
+11,,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,4A298DACAE57395A15D0795DDBFD1DCB564DA82B0F269BC70A74F8220429BA1D69E89B4C5564D00349106B8497785DD7D1D713A8AE82B32FA79D5F7FC407D39B,FALSE,sig[0:32] is not an X coordinate on the curve
+12,,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F69E89B4C5564D00349106B8497785DD7D1D713A8AE82B32FA79D5F7FC407D39B,FALSE,sig[0:32] is equal to field size
+13,,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,6CFF5C3BA86C69EA4B7376F31A9BCB4F74C1976089B2D9963DA2E5543E177769FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141,FALSE,sig[32:64] is equal to curve order
+14,,FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC30,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,6CFF5C3BA86C69EA4B7376F31A9BCB4F74C1976089B2D9963DA2E5543E17776969E89B4C5564D00349106B8497785DD7D1D713A8AE82B32FA79D5F7FC407D39B,FALSE,public key is not a valid X coordinate because it exceeds the field size
+15,0340034003400340034003400340034003400340034003400340034003400340,778CAA53B4393AC467774D09497A87224BF9FAB6F6E68B23086497324D6FD117,0000000000000000000000000000000000000000000000000000000000000000,,71535DB165ECD9FBBC046E5FFAEA61186BB6AD436732FCCC25291A55895464CF6069CE26BF03466228F19A3A62DB8A649F2D560FAC652827D1AF0574E427AB63,TRUE,message of size 0 (added 2022-12)
+16,0340034003400340034003400340034003400340034003400340034003400340,778CAA53B4393AC467774D09497A87224BF9FAB6F6E68B23086497324D6FD117,0000000000000000000000000000000000000000000000000000000000000000,11,08A20A0AFEF64124649232E0693C583AB1B9934AE63B4C3511F3AE1134C6A303EA3173BFEA6683BD101FA5AA5DBC1996FE7CACFC5A577D33EC14564CEC2BACBF,TRUE,message of size 1 (added 2022-12)
+17,0340034003400340034003400340034003400340034003400340034003400340,778CAA53B4393AC467774D09497A87224BF9FAB6F6E68B23086497324D6FD117,0000000000000000000000000000000000000000000000000000000000000000,0102030405060708090A0B0C0D0E0F1011,5130F39A4059B43BC7CAC09A19ECE52B5D8699D1A71E3C52DA9AFDB6B50AC370C4A482B77BF960F8681540E25B6771ECE1E5A37FD80E5A51897C5566A97EA5A5,TRUE,message of size 17 (added 2022-12)
+18,0340034003400340034003400340034003400340034003400340034003400340,778CAA53B4393AC467774D09497A87224BF9FAB6F6E68B23086497324D6FD117,0000000000000000000000000000000000000000000000000000000000000000,99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999,403B12B0D8555A344175EA7EC746566303321E5DBFA8BE6F091635163ECA79A8585ED3E3170807E7C03B720FC54C7B23897FCBA0E9D0B4A06894CFD249F22367,TRUE,message of size 100 (added 2022-12)
diff --git a/bip-0340/test-vectors.py b/bip-0340/test-vectors.py
new file mode 100644
index 0000000000..8442a713fb
--- /dev/null
+++ b/bip-0340/test-vectors.py
@@ -0,0 +1,301 @@
+import sys
+from reference import *
+
+def is_square(x):
+ return int(pow(x, (p - 1) // 2, p)) == 1
+
+def has_square_y(P):
+ """Determine if P has a square Y coordinate. Used in an earlier draft of BIP340."""
+ assert not is_infinite(P)
+ return is_square(P[1])
+
+def vector0():
+ seckey = bytes_from_int(3)
+ msg = bytes_from_int(0)
+ aux_rand = bytes_from_int(0)
+ sig = schnorr_sign(msg, seckey, aux_rand)
+ pubkey = pubkey_gen(seckey)
+
+ # We should have at least one test vector where the seckey needs to be
+ # negated and one where it doesn't. In this one the seckey doesn't need to
+ # be negated.
+ x = int_from_bytes(seckey)
+ P = point_mul(G, x)
+ assert(y(P) % 2 == 0)
+
+ # For historical reasons (pubkey tiebreaker was squareness and not evenness)
+ # we should have at least one test vector where the point reconstructed
+ # from the public key has a square and one where it has a non-square Y
+ # coordinate. In this one Y is non-square.
+ pubkey_point = lift_x(int_from_bytes(pubkey))
+ assert(not has_square_y(pubkey_point))
+
+ # For historical reasons (R tiebreaker was squareness and not evenness)
+ # we should have at least one test vector where the point reconstructed
+ # from the R.x coordinate has a square and one where it has a non-square Y
+ # coordinate. In this one Y is non-square.
+ R = lift_x(int_from_bytes(sig[0:32]))
+ assert(not has_square_y(R))
+
+ return (seckey, pubkey, aux_rand, msg, sig, "TRUE", None)
+
+def vector1():
+ seckey = bytes_from_int(0xB7E151628AED2A6ABF7158809CF4F3C762E7160F38B4DA56A784D9045190CFEF)
+ msg = bytes_from_int(0x243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89)
+ aux_rand = bytes_from_int(1)
+
+ sig = schnorr_sign(msg, seckey, aux_rand)
+
+ # The point reconstructed from the R.x coordinate has a square Y coordinate.
+ R = lift_x(int_from_bytes(sig[0:32]))
+ assert(has_square_y(R))
+
+ return (seckey, pubkey_gen(seckey), aux_rand, msg, sig, "TRUE", None)
+
+def vector2():
+ seckey = bytes_from_int(0xC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B14E5C9)
+ msg = bytes_from_int(0x7E2D58D8B3BCDF1ABADEC7829054F90DDA9805AAB56C77333024B9D0A508B75C)
+ aux_rand = bytes_from_int(0xC87AA53824B4D7AE2EB035A2B5BBBCCC080E76CDC6D1692C4B0B62D798E6D906)
+ sig = schnorr_sign(msg, seckey, aux_rand)
+
+ # The point reconstructed from the public key has a square Y coordinate.
+ pubkey = pubkey_gen(seckey)
+ pubkey_point = lift_x(int_from_bytes(pubkey))
+ assert(has_square_y(pubkey_point))
+
+ # This signature vector would not verify if the implementer checked the
+ # evenness of the X coordinate of R instead of the Y coordinate.
+ R = lift_x(int_from_bytes(sig[0:32]))
+ assert(R[0] % 2 == 1)
+
+ return (seckey, pubkey, aux_rand, msg, sig, "TRUE", None)
+
+def vector3():
+ seckey = bytes_from_int(0x0B432B2677937381AEF05BB02A66ECD012773062CF3FA2549E44F58ED2401710)
+
+ # Need to negate this seckey before signing
+ x = int_from_bytes(seckey)
+ P = point_mul(G, x)
+ assert(y(P) % 2 != 0)
+
+ msg = bytes_from_int(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
+ aux_rand = bytes_from_int(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
+
+ sig = schnorr_sign(msg, seckey, aux_rand)
+ return (seckey, pubkey_gen(seckey), aux_rand, msg, sig, "TRUE", "test fails if msg is reduced modulo p or n")
+
+# Signs with a given nonce. This can be INSECURE and is only INTENDED FOR
+# GENERATING TEST VECTORS. Results in an invalid signature if y(kG) is not
+# even.
+def insecure_schnorr_sign_fixed_nonce(msg, seckey0, k):
+ if len(msg) != 32:
+ raise ValueError('The message must be a 32-byte array.')
+ seckey0 = int_from_bytes(seckey0)
+ if not (1 <= seckey0 <= n - 1):
+ raise ValueError('The secret key must be an integer in the range 1..n-1.')
+ P = point_mul(G, seckey0)
+ seckey = seckey0 if has_even_y(P) else n - seckey0
+ R = point_mul(G, k)
+ e = int_from_bytes(tagged_hash("BIP0340/challenge", bytes_from_point(R) + bytes_from_point(P) + msg)) % n
+ return bytes_from_point(R) + bytes_from_int((k + e * seckey) % n)
+
+# Creates a signature with a small x(R) by using k = -1/2
+def vector4():
+ one_half = n - 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0
+ seckey = bytes_from_int(0x763758E5CBEEDEE4F7D3FC86F531C36578933228998226672F13C4F0EBE855EB)
+ msg = bytes_from_int(0x4DF3C3F68FCC83B27E9D42C90431A72499F17875C81A599B566C9889B9696703)
+ sig = insecure_schnorr_sign_fixed_nonce(msg, seckey, one_half)
+ return (None, pubkey_gen(seckey), None, msg, sig, "TRUE", None)
+
+default_seckey = bytes_from_int(0xB7E151628AED2A6ABF7158809CF4F3C762E7160F38B4DA56A784D9045190CFEF)
+default_msg = bytes_from_int(0x243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89)
+default_aux_rand = bytes_from_int(0xC87AA53824B4D7AE2EB035A2B5BBBCCC080E76CDC6D1692C4B0B62D798E6D906)
+
+# Public key is not on the curve
+def vector5():
+ # This creates a dummy signature that doesn't have anything to do with the
+ # public key.
+ seckey = default_seckey
+ msg = default_msg
+ sig = schnorr_sign(msg, seckey, default_aux_rand)
+
+ pubkey_int = 0xEEFDEA4CDB677750A420FEE807EACF21EB9898AE79B9768766E4FAA04A2D4A34
+ pubkey = bytes_from_int(pubkey_int)
+ assert(lift_x(pubkey_int) is None)
+
+ return (None, pubkey, None, msg, sig, "FALSE", "public key not on the curve")
+
+def vector6():
+ seckey = default_seckey
+ msg = default_msg
+ k = 6
+ sig = insecure_schnorr_sign_fixed_nonce(msg, seckey, k)
+
+ # Y coordinate of R is not even
+ R = point_mul(G, k)
+ assert(not has_even_y(R))
+
+ return (None, pubkey_gen(seckey), None, msg, sig, "FALSE", "has_even_y(R) is false")
+
+def vector7():
+ seckey = default_seckey
+ msg = int_from_bytes(default_msg)
+ neg_msg = bytes_from_int(n - msg)
+ sig = schnorr_sign(neg_msg, seckey, default_aux_rand)
+ return (None, pubkey_gen(seckey), None, bytes_from_int(msg), sig, "FALSE", "negated message")
+
+def vector8():
+ seckey = default_seckey
+ msg = default_msg
+ sig = schnorr_sign(msg, seckey, default_aux_rand)
+ sig = sig[0:32] + bytes_from_int(n - int_from_bytes(sig[32:64]))
+ return (None, pubkey_gen(seckey), None, msg, sig, "FALSE", "negated s value")
+
+def bytes_from_point_inf0(P):
+ if P == None:
+ return bytes_from_int(0)
+ return bytes_from_int(P[0])
+
+def vector9():
+ seckey = default_seckey
+ msg = default_msg
+
+ # Override bytes_from_point in schnorr_sign to allow creating a signature
+ # with k = 0.
+ k = 0
+ bytes_from_point_tmp = bytes_from_point.__code__
+ bytes_from_point.__code__ = bytes_from_point_inf0.__code__
+ sig = insecure_schnorr_sign_fixed_nonce(msg, seckey, k)
+ bytes_from_point.__code__ = bytes_from_point_tmp
+
+ return (None, pubkey_gen(seckey), None, msg, sig, "FALSE", "sG - eP is infinite. Test fails in single verification if has_even_y(inf) is defined as true and x(inf) as 0")
+
+def bytes_from_point_inf1(P):
+ if P == None:
+ return bytes_from_int(1)
+ return bytes_from_int(P[0])
+
+def vector10():
+ seckey = default_seckey
+ msg = default_msg
+
+ # Override bytes_from_point in schnorr_sign to allow creating a signature
+ # with k = 0.
+ k = 0
+ bytes_from_point_tmp = bytes_from_point.__code__
+ bytes_from_point.__code__ = bytes_from_point_inf1.__code__
+ sig = insecure_schnorr_sign_fixed_nonce(msg, seckey, k)
+ bytes_from_point.__code__ = bytes_from_point_tmp
+
+ return (None, pubkey_gen(seckey), None, msg, sig, "FALSE", "sG - eP is infinite. Test fails in single verification if has_even_y(inf) is defined as true and x(inf) as 1")
+
+# It's cryptographically impossible to create a test vector that fails if run
+# in an implementation which merely misses the check that sig[0:32] is an X
+# coordinate on the curve. This test vector just increases test coverage.
+def vector11():
+ seckey = default_seckey
+ msg = default_msg
+ sig = schnorr_sign(msg, seckey, default_aux_rand)
+
+ # Replace R's X coordinate with an X coordinate that's not on the curve
+ x_not_on_curve = 0x4A298DACAE57395A15D0795DDBFD1DCB564DA82B0F269BC70A74F8220429BA1D
+ assert(lift_x(x_not_on_curve) is None)
+ sig = bytes_from_int(x_not_on_curve) + sig[32:64]
+
+ return (None, pubkey_gen(seckey), None, msg, sig, "FALSE", "sig[0:32] is not an X coordinate on the curve")
+
+# It's cryptographically impossible to create a test vector that fails if run
+# in an implementation which merely misses the check that sig[0:32] is smaller
+# than the field size. This test vector just increases test coverage.
+def vector12():
+ seckey = default_seckey
+ msg = default_msg
+ sig = schnorr_sign(msg, seckey, default_aux_rand)
+
+ # Replace R's X coordinate with an X coordinate that's equal to field size
+ sig = bytes_from_int(p) + sig[32:64]
+
+ return (None, pubkey_gen(seckey), None, msg, sig, "FALSE", "sig[0:32] is equal to field size")
+
+# It's cryptographically impossible to create a test vector that fails if run
+# in an implementation which merely misses the check that sig[32:64] is smaller
+# than the curve order. This test vector just increases test coverage.
+def vector13():
+ seckey = default_seckey
+ msg = default_msg
+ sig = schnorr_sign(msg, seckey, default_aux_rand)
+
+ # Replace s with a number that's equal to the curve order
+ sig = sig[0:32] + bytes_from_int(n)
+
+ return (None, pubkey_gen(seckey), None, msg, sig, "FALSE", "sig[32:64] is equal to curve order")
+
+# Test out of range pubkey
+# It's cryptographically impossible to create a test vector that fails if run
+# in an implementation which accepts out of range pubkeys because we can't find
+# a secret key for such a public key and therefore can not create a signature.
+# This test vector just increases test coverage.
+def vector14():
+ # This creates a dummy signature that doesn't have anything to do with the
+ # public key.
+ seckey = default_seckey
+ msg = default_msg
+ sig = schnorr_sign(msg, seckey, default_aux_rand)
+ pubkey_int = p + 1
+ pubkey = bytes_from_int(pubkey_int)
+ assert(lift_x(pubkey_int) is None)
+ # If an implementation would reduce a given public key modulo p then the
+ # pubkey would be valid
+ assert(lift_x(pubkey_int % p) is not None)
+
+ return (None, pubkey, None, msg, sig, "FALSE", "public key is not a valid X coordinate because it exceeds the field size")
+
+def varlen_vector(msg_int):
+ seckey = bytes_from_int(int(16 * "0340", 16))
+ pubkey = pubkey_gen(seckey)
+ aux_rand = bytes_from_int(0)
+ msg = msg_int.to_bytes((msg_int.bit_length() + 7) // 8, "big")
+ sig = schnorr_sign(msg, seckey, aux_rand)
+ comment = "message of size %d (added 2022-12)"
+ return (seckey, pubkey, aux_rand, msg, sig, "TRUE", comment % len(msg))
+
+vector15 = lambda : varlen_vector(0)
+vector16 = lambda : varlen_vector(0x11)
+vector17 = lambda : varlen_vector(0x0102030405060708090A0B0C0D0E0F1011)
+vector18 = lambda : varlen_vector(int(100 * "99", 16))
+
+vectors = [
+ vector0(),
+ vector1(),
+ vector2(),
+ vector3(),
+ vector4(),
+ vector5(),
+ vector6(),
+ vector7(),
+ vector8(),
+ vector9(),
+ vector10(),
+ vector11(),
+ vector12(),
+ vector13(),
+ vector14(),
+ vector15(),
+ vector16(),
+ vector17(),
+ vector18(),
+ ]
+
+# Converts the byte strings of a test vector into hex strings
+def bytes_to_hex(seckey, pubkey, aux_rand, msg, sig, result, comment):
+ return (seckey.hex().upper() if seckey is not None else None, pubkey.hex().upper(), aux_rand.hex().upper() if aux_rand is not None else None, msg.hex().upper(), sig.hex().upper(), result, comment)
+
+vectors = list(map(lambda vector: bytes_to_hex(vector[0], vector[1], vector[2], vector[3], vector[4], vector[5], vector[6]), vectors))
+
+def print_csv(vectors):
+ writer = csv.writer(sys.stdout)
+ writer.writerow(("index", "secret key", "public key", "aux_rand", "message", "signature", "verification result", "comment"))
+ for (i,v) in enumerate(vectors):
+ writer.writerow((i,)+v)
+
+print_csv(vectors)
diff --git a/bip-0341.mediawiki b/bip-0341.mediawiki
new file mode 100644
index 0000000000..bd45f3d92c
--- /dev/null
+++ b/bip-0341.mediawiki
@@ -0,0 +1,362 @@
+
+
+==Introduction==
+
+===Abstract===
+
+This document proposes a new SegWit version 1 output type, with spending rules based on Taproot, Schnorr signatures, and Merkle branches.
+
+===Copyright===
+
+This document is licensed under the 3-clause BSD license.
+
+===Motivation===
+
+This proposal aims to improve privacy, efficiency, and flexibility of Bitcoin's scripting capabilities without adding new security assumptions'''What does not adding security assumptions mean?''' Unforgeability of signatures is a necessary requirement to prevent theft. At least when treating script execution as a digital signature scheme itself, unforgeability can be [https://github.com/apoelstra/taproot proven] in the Random Oracle Model assuming the Discrete Logarithm problem is hard. A [https://nbn-resolving.de/urn:nbn:de:hbz:294-60803 proof] for unforgeability of ECDSA in the current script system needs non-standard assumptions on top of that. Note that it is hard in general to model exactly what security for script means, as it depends on the policies and protocols used by wallet software.. Specifically, it seeks to minimize how much information about the spendability conditions of a transaction output is revealed on chain at creation or spending time and to add a number of upgrade mechanisms, while fixing a few minor but long-standing issues.
+
+==Design==
+
+A number of related ideas for improving Bitcoin's scripting capabilities have been previously proposed: Schnorr signatures ([[bip-0340.mediawiki|BIP340]]), Merkle branches ("MAST", [[bip-0114.mediawiki|BIP114]], [[bip-0117.mediawiki|BIP117]]), new sighash modes ([[bip-0118.mediawiki|BIP118]]), new opcodes like CHECKSIGFROMSTACK, [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-January/015614.html Taproot], [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-February/015700.html Graftroot], [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-July/016249.html G'root], and [https://bitcointalk.org/index.php?topic=1377298.0 cross-input aggregation].
+
+Combining all these ideas in a single proposal would be an extensive change, be hard to review, and likely miss new discoveries that otherwise could have been made along the way. Not all are equally mature as well. For example, cross-input aggregation [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-March/015838.html interacts] in complex ways with upgrade mechanisms, and solutions to that are still [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-October/016461.html in flux]. On the other hand, separating them all into independent upgrades would reduce the efficiency and privacy gains to be had, and wallet and service providers may not be inclined to go through many incremental updates. Therefore, we're faced with a tradeoff between functionality and scope creep. In this design we strike a balance by focusing on the structural script improvements offered by Taproot and Merkle branches, as well as changes necessary to make them usable and efficient. For things like sighashes and opcodes we include fixes for known problems, but exclude new features that can be added independently with no downsides.
+
+As a result we choose this combination of technologies:
+* '''Merkle branches''' 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.
+* '''Taproot''' on top of that lets us merge the traditionally separate pay-to-pubkey and pay-to-scripthash policies, making all outputs spendable by either a key or (optionally) a script, and indistinguishable from each other. As long as the key-based spending path is used for spending, it is not revealed whether a script path was permitted as well, resulting in space savings and an increase in scripting privacy at spending time.
+* Taproot's advantages become apparent under the assumption that most applications involve outputs that could be spent by all parties agreeing. That's where '''Schnorr''' signatures come in, as they permit [https://eprint.iacr.org/2018/068 key aggregation]: a public key can be constructed from multiple participant public keys, and which requires cooperation between all participants to sign for. Such multi-party public keys and signatures are indistinguishable from their single-party equivalents. This means that with taproot most applications can use the key-based spending path, which is both efficient and private. This can be generalized to arbitrary M-of-N policies, as Schnorr signatures support threshold signing, at the cost of more complex setup protocols.
+* As Schnorr signatures also permit '''batch validation''', allowing multiple signatures to be validated together more efficiently than validating each one independently, we make sure all parts of the design are compatible with this.
+* Where unused bits appear as a result of the above changes, they are reserved for mechanisms for '''future extensions'''. As a result, every script in the Merkle tree has an associated version such that new script versions can be introduced with a soft fork while remaining compatible with BIP 341. Additionally, future soft forks can make use of the currently unused annex in the witness (see [[bip-0341.mediawiki#rationale|Rationale]]).
+* While the core semantics of the '''signature hashing algorithm''' are not changed, a number of improvements are included in this proposal. The new signature hashing algorithm fixes the verification capabilities of offline signing devices by including amount and scriptPubKey in the signature message, avoids unnecessary hashing, uses '''tagged hashes''' and defines a default sighash byte.
+* The '''public key is directly included in the output''' in contrast to typical earlier constructions which store a hash of the public key or script in the output. This has the same cost for senders and is more space efficient overall if the key-based spending path is taken. '''Why is the public key directly included in the output?''' While typical earlier constructions store a hash of a script or a public key in the output, this is rather wasteful when a public key is always involved. To guarantee batch verifiability, the public key must be known to every verifier, and thus only revealing its hash as an output would imply adding an additional 32 bytes to the witness. Furthermore, to maintain [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2016-January/012198.html 128-bit collision security] for outputs, a 256-bit hash would be required anyway, which is comparable in size (and thus in cost for senders) to revealing the public key directly. While the usage of public key hashes is often said to protect against ECDLP breaks or quantum computers, this protection is very weak at best: transactions are not protected while being confirmed, and a very [https://twitter.com/pwuille/status/1108097835365339136 large portion] of the currency's supply is not under such protection regardless. Actual resistance to such systems can be introduced by relying on different cryptographic assumptions, but this proposal focuses on improvements that do not change the security model.
+
+Informally, the resulting design is as follows: a new witness version is added (version 1), whose programs consist of 32-byte encodings of points ''Q''. ''Q'' is computed as ''P + hash(P||m)G'' for a public key ''P'', and the root ''m'' of a Merkle tree whose leaves consist of a version number and a script. These outputs can be spent directly by providing a signature for ''Q'', or indirectly by revealing ''P'', the script and leaf version, inputs that satisfy the script, and a Merkle path that proves ''Q'' committed to that leaf. All hashes in this construction (the hash for computing ''Q'' from ''P'', the hashes inside the Merkle tree's inner nodes, and the signature hashes used) are tagged to guarantee domain separation.
+
+== Specification ==
+
+This section specifies the Taproot consensus rules. Validity is defined by exclusion: a block or transaction is valid if no condition exists that marks it failed.
+
+The notation below follows that of [[bip-0340.mediawiki#design|BIP340]]. This includes the ''hashtag(x)'' notation to refer to ''SHA256(SHA256(tag) || SHA256(tag) || x)''. To the best of the authors' knowledge, no existing use of SHA256 in Bitcoin feeds it a message that starts with two single SHA256 outputs, making collisions between ''hashtag'' with other hashes extremely unlikely.
+
+=== Script validation rules ===
+
+A Taproot output is a native SegWit output (see [[bip-0141.mediawiki|BIP141]]) with version number 1, and a 32-byte witness program.
+The following rules only apply when such an output is being spent. Any other outputs, including version 1 outputs with lengths other than 32 bytes, or P2SH-wrapped version 1 outputs'''Why is P2SH-wrapping not supported?''' Using P2SH-wrapped outputs only provides 80-bit collision security due to the use of a 160-bit hash. This is considered low, and becomes a security risk whenever the output includes data from more than a single party (public keys, hashes, ...)., remain unencumbered.
+
+* Let ''q'' be the 32-byte array containing the witness program (the second push in the scriptPubKey) which represents a public key according to [[bip-0340.mediawiki#design|BIP340]].
+* Fail if the witness stack has 0 elements.
+* If there are at least two witness elements, and the first byte of the last element is 0x50'''Why is the first byte of the annex 0x50?''' The 0x50 is chosen as it could not be confused with a valid P2WPKH or P2WSH spending. As the control block's initial byte's lowest bit is used to indicate the parity of the public key's Y coordinate, each leaf version needs an even byte value and the immediately following odd byte value that are both not yet used in P2WPKH or P2WSH spending. To indicate the annex, only an "unpaired" available byte is necessary like 0x50. This choice maximizes the available options for future script versions., this last element is called ''annex'' ''a'''''What is the purpose of the annex?''' The annex is a reserved space for future extensions, such as indicating the validation costs of computationally expensive new opcodes in a way that is recognizable without knowing the scriptPubKey of the output being spent. Until the meaning of this field is defined by another softfork, users SHOULD NOT include annex in transactions, or it may lead to PERMANENT FUND LOSS. and is removed from the witness stack. The annex (or the lack of thereof) is always covered by the signature and contributes to transaction weight, but is otherwise ignored during taproot validation.
+* If there is exactly one element left in the witness stack, key path spending is used:
+** The single witness stack element is interpreted as the signature and must be valid (see the next section) for the public key ''q'' (see the next subsection).
+* If there are at least two witness elements left, script path spending is used:
+** Call the second-to-last stack element ''s'', the script.
+** The last stack element is called the control block ''c'', and must have length ''33 + 32m'', for a value of ''m'' that is an integer between 0 and 128'''Why is the Merkle path length limited to 128?''' The optimally space-efficient Merkle tree can be constructed based on the probabilities of the scripts in the leaves, using the Huffman algorithm. This algorithm will construct branches with lengths approximately equal to ''log2(1/probability)'', but to have branches longer than 128 you would need to have scripts with an execution chance below 1 in ''2128''. As that is our security bound, scripts that truly have such a low chance can probably be removed entirely., inclusive. Fail if it does not have such a length.
+** Let ''p = c[1:33]'' and let ''P = lift_x(int(p))'' where ''lift_x'' and ''[:]'' are defined as in [[bip-0340.mediawiki#design|BIP340]]. Fail if this point is not on the curve.
+** Let ''v = c[0] & 0xfe'' and call it the ''leaf version'''''What constraints are there on the leaf version?''' First, the leaf version cannot be odd as ''c[0] & 0xfe'' will always be even, and cannot be ''0x50'' as that would result in ambiguity with the annex. In addition, in order to support some forms of static analysis that rely on being able to identify script spends without access to the output being spent, it is recommended to avoid using any leaf versions that would conflict with a valid first byte of either a valid P2WPKH pubkey or a valid P2WSH script (that is, both ''v'' and ''v | 1'' should be an undefined, invalid or disabled opcode or an opcode that is not valid as the first opcode). The values that comply to this rule are the 32 even values between ''0xc0'' and ''0xfe'' and also ''0x66'', ''0x7e'', ''0x80'', ''0x84'', ''0x96'', ''0x98'', ''0xba'', ''0xbc'', ''0xbe''. Note also that this constraint implies that leaf versions should be shared amongst different witness versions, as knowing the witness version requires access to the output being spent..
+** Let ''k0 = hashTapLeaf(v || compact_size(size of s) || s)''; also call it the ''tapleaf hash''.
+** For ''j'' in ''[0,1,...,m-1]'':
+*** Let ''ej = c[33+32j:65+32j]''.
+*** Let ''kj+1 depend on whether ''kj < ej'' (lexicographically)'''Why are child elements sorted before hashing in the Merkle tree?''' By doing so, it is not necessary to reveal the left/right directions along with the hashes in revealed Merkle branches. This is possible because we do not actually care about the position of specific scripts in the tree; only that they are actually committed to.:
+**** If ''kj < ej'': ''kj+1 = hashTapBranch(kj || ej)'''''Why not use a more efficient hash construction for inner Merkle nodes?''' The chosen construction does require two invocations of the SHA256 compression functions, one of which can be avoided in theory (see [[bip-0098.mediawiki|BIP98]]). However, it seems preferable to stick to constructions that can be implemented using standard cryptographic primitives, both for implementation simplicity and analyzability. If necessary, a significant part of the second compression function can be optimized out by [https://github.com/bitcoin/bitcoin/pull/13191 specialization] for 64-byte inputs..
+**** If ''kj ≥ ej'': ''kj+1 = hashTapBranch(ej || kj)''.
+** Let ''t = hashTapTweak(p || km)''.
+** If ''t ≥ 0xFFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141'' (order of secp256k1), fail.
+** Let ''Q = P + int(t)G''.
+** If ''q ≠ x(Q)'' or ''c[0] & 1 ≠ y(Q) mod 2'', fail'''Why is it necessary to reveal a bit in a script path spend and check that it matches the parity of the Y coordinate of ''Q''?''' The parity of the Y coordinate is necessary to lift the X coordinate ''q'' to a unique point. While this is not strictly necessary for verifying the taproot commitment as described above, it is necessary to allow batch verification. Alternatively, ''Q'' could be forced to have an even Y coordinate, but that would require retrying with different internal public keys (or different messages) until ''Q'' has that property. There is no downside to adding the parity bit because otherwise the control block bit would be unused..
+** Execute the script, according to the applicable script rules'''What are the applicable script rules in script path spends?''' [[bip-0342.mediawiki|BIP342]] specifies validity rules that apply for leaf version 0xc0, but future proposals can introduce rules for other leaf versions., using the witness stack elements excluding the script ''s'', the control block ''c'', and the annex ''a'' if present, as initial stack. This implies that for the future leaf versions (non-''0xC0'') the execution must succeed.'''Why we need to success on future leaf version validation''' This is required to enable future leaf versions as soft forks.
+
+''q'' is referred to as ''taproot output key'' and ''p'' as ''taproot internal key''.
+
+=== Signature validation rules ===
+
+We first define a reusable common signature message calculation function, followed by the actual signature validation as it's used in key path spending.
+
+==== Common signature message ====
+
+The function ''SigMsg(hash_type, ext_flag)'' computes the common portion of the message being signed as a byte array. It is implicitly also a function of the spending transaction and the outputs it spends, but these are not listed to keep notation simple.
+
+The parameter ''hash_type'' is an 8-bit unsigned value. The SIGHASH encodings from the legacy script system are reused, including SIGHASH_ALL, SIGHASH_NONE, SIGHASH_SINGLE, and SIGHASH_ANYONECANPAY. We define a new ''hashtype'' SIGHASH_DEFAULT (value ''0x00'') which results in signing over the whole transaction just as for SIGHASH_ALL. The following restrictions apply, which cause validation failure if violated:
+* Using any undefined ''hash_type'' (not ''0x00'', ''0x01'', ''0x02'', ''0x03'', ''0x81'', ''0x82'', or ''0x83'''''Why reject unknown ''hash_type'' values?''' By doing so, it is easier to reason about the worst case amount of signature hashing an implementation with adequate caching must perform.).
+* Using SIGHASH_SINGLE without a "corresponding output" (an output with the same index as the input being verified).
+
+The parameter ''ext_flag'' is an integer in range 0-127, and is used for indicating (in the message) that extensions are appended to the output of ''SigMsg()'''''What extensions use the ''ext_flag'' mechanism?''' [[bip-0342.mediawiki#common-signature-message-extension|BIP342]] reuses the same common signature message algorithm, but adds BIP342-specific data at the end, which is indicated using ''ext_flag = 1''..
+
+If the parameters take acceptable values, the message is the concatenation of the following data, in order (with byte size of each item listed in parentheses). Numerical values in 2, 4, or 8-byte are encoded in little-endian.
+
+* Control:
+** ''hash_type'' (1).
+* Transaction data:
+** ''nVersion'' (4): the ''nVersion'' of the transaction.
+** ''nLockTime'' (4): the ''nLockTime'' of the transaction.
+** If the ''hash_type & 0x80'' does not equal SIGHASH_ANYONECANPAY:
+*** ''sha_prevouts'' (32): the SHA256 of the serialization of all input outpoints.
+*** ''sha_amounts'' (32): the SHA256 of the serialization of all input amounts.
+*** ''sha_scriptpubkeys'' (32): the SHA256 of all spent outputs' ''scriptPubKeys'', serialized as script inside CTxOut.
+*** ''sha_sequences'' (32): the SHA256 of the serialization of all input ''nSequence''.
+** If ''hash_type & 3'' does not equal SIGHASH_NONE or SIGHASH_SINGLE:
+*** ''sha_outputs'' (32): the SHA256 of the serialization of all outputs in CTxOut format.
+* Data about this input:
+** ''spend_type'' (1): equal to ''(ext_flag * 2) + annex_present'', where ''annex_present'' is 0 if no annex is present, or 1 otherwise (the original witness stack has two or more witness elements, and the first byte of the last element is ''0x50'')
+** If ''hash_type & 0x80'' equals SIGHASH_ANYONECANPAY:
+*** ''outpoint'' (36): the COutPoint of this input (32-byte hash + 4-byte little-endian).
+*** ''amount'' (8): value of the previous output spent by this input.
+*** ''scriptPubKey'' (35): ''scriptPubKey'' of the previous output spent by this input, serialized as script inside CTxOut. Its size is always 35 bytes.
+*** ''nSequence'' (4): ''nSequence'' of this input.
+** If ''hash_type & 0x80'' does not equal SIGHASH_ANYONECANPAY:
+*** ''input_index'' (4): index of this input in the transaction input vector. Index of the first input is 0.
+** If an annex is present (the lowest bit of ''spend_type'' is set):
+*** ''sha_annex'' (32): the SHA256 of ''(compact_size(size of annex) || annex)'', where ''annex'' includes the mandatory ''0x50'' prefix.
+* Data about this output:
+** If ''hash_type & 3'' equals SIGHASH_SINGLE:
+*** ''sha_single_output'' (32): the SHA256 of the corresponding output in CTxOut format.
+
+The total length of ''SigMsg()'' is at most ''206'' bytes'''What is the output length of ''SigMsg()''?''' The total length of ''SigMsg()'' can be computed using the following formula: ''174 - is_anyonecanpay * 49 - is_none * 32 + has_annex * 32''.. Note that this does not include the size of sub-hashes such as ''sha_prevouts'', which may be cached across signatures of the same transaction.
+
+In summary, the semantics of the [[bip-0143.mediawiki|BIP143]] sighash types remain unchanged, except the following:
+# The way and order of serialization is changed.'''Why is the serialization in the signature message changed?''' Hashes that go into the signature message and the message itself are now computed with a single SHA256 invocation instead of double SHA256. There is no expected security improvement by doubling SHA256 because this only protects against length-extension attacks against SHA256 which are not a concern for signature messages because there is no secret data. Therefore doubling SHA256 is a waste of resources. The message computation now follows a logical order with transaction level data first, then input data and output data. This allows to efficiently cache the transaction part of the message across different inputs using the SHA256 midstate. Additionally, sub-hashes can be skipped when calculating the message (for example `sha_prevouts` if SIGHASH_ANYONECANPAY is set) instead of setting them to zero and then hashing them as in BIP143. Despite that, collisions are made impossible by committing to the length of the data (implicit in ''hash_type'' and ''spend_type'') before the variable length data.
+# The signature message commits to the ''scriptPubKey'' of the spent output and if the SIGHASH_ANYONECANPAY flag is not set, the message commits to the ''scriptPubKey''s of ''all'' outputs spent by the transaction. '''Why does the signature message commit to the ''scriptPubKey''?''' This prevents lying to offline signing devices about output being spent, even when the actually executed script (''scriptCode'' in BIP143) is correct. This means it's possible to compactly prove to a hardware wallet what (unused) execution paths existed. Moreover, committing to all spent ''scriptPubKey''s helps offline signing devices to determine the subset that belong to its own wallet. This is useful in [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2020-April/017801.html automated coinjoins]..
+# If the SIGHASH_ANYONECANPAY flag is not set, the message commits to the amounts of ''all'' transaction inputs.'''Why does the signature message commit to the amounts of all transaction inputs?''' This eliminates the possibility to lie to offline signing devices about the fee of a transaction.
+# The signature message commits to all input ''nSequence'' if SIGHASH_NONE or SIGHASH_SINGLE are set (unless SIGHASH_ANYONECANPAY is set as well).'''Why does the signature message commit to all input ''nSequence'' if SIGHASH_SINGLE or SIGHASH_NONE are set?''' Because setting them already makes the message commit to the prevouts part of all transaction inputs, it is not useful to treat the ''nSequence'' any different. Moreover, this change makes ''nSequence'' consistent with the view that SIGHASH_SINGLE and SIGHASH_NONE only modify the signature message with respect to transaction outputs and not inputs.
+# The signature message includes commitments to the taproot-specific data ''spend_type'' and ''annex'' (if present).
+
+==== Taproot key path spending signature validation ====
+
+To validate a signature ''sig'' with public key ''q'':
+* If the ''sig'' is 64 bytes long, return ''Verify(q, hashTapSighash(0x00 || SigMsg(0x00, 0)), sig)'''''Why is the input to ''hashTapSighash'' prefixed with 0x00?''' This prefix is called the sighash epoch, and allows reusing the ''hashTapSighash'' tagged hash in future signature algorithms that make invasive changes to how hashing is performed (as opposed to the ''ext_flag'' mechanism that is used for incremental extensions). An alternative is having them use a different tag, but supporting a growing number of tags may become undesirable., where ''Verify'' is defined in [[bip-0340.mediawiki#design|BIP340]].
+* If the ''sig'' is 65 bytes long, return ''sig[64] ≠ 0x00'''Why can the hash_type not be 0x00 in 65-byte signatures?''' Permitting that would enable malleating (by third parties, including miners) 64-byte signatures into 65-byte ones, resulting in a different `wtxid` and a different fee rate than the creator intended. and Verify(q, hashTapSighash(0x00 || SigMsg(sig[64], 0)), sig[0:64])''.
+* Otherwise, fail'''Why permit two signature lengths?''' By making the most common type of hash_type implicit, a byte can often be saved..
+
+== Constructing and spending Taproot outputs ==
+
+This section discusses how to construct and spend Taproot outputs. It only affects wallet software that chooses to implement receiving and spending,
+and is not consensus critical in any way.
+
+Conceptually, every Taproot output corresponds to a combination of a single public key condition (the internal key), and zero or more general conditions encoded in scripts organized in a tree.
+Satisfying any of these conditions is sufficient to spend the output.
+
+'''Initial steps''' The first step is determining what the internal key and the organization of the rest of the scripts should be. The specifics are likely application dependent, but here are some general guidelines:
+* When deciding between scripts with conditionals (OP_IF etc.) and splitting them up into multiple scripts (each corresponding to one execution path through the original script), it is generally preferable to pick the latter.
+* When a single condition requires signatures with multiple keys, key aggregation techniques like MuSig can be used to combine them into a single key. The details are out of scope for this document, but note that this may complicate the signing procedure.
+* If one or more of the spending conditions consist of just a single key (after aggregation), the most likely one should be made the internal key. If no such condition exists, it may be worthwhile adding one that consists of an aggregation of all keys participating in all scripts combined; effectively adding an "everyone agrees" branch. If that is inacceptable, pick as internal key a "Nothing Up My Sleeve" (NUMS) point, i.e., a point with unknown discrete logarithm. One example of such a point is ''H = lift_x(0x50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0)'' which is [https://github.com/ElementsProject/secp256k1-zkp/blob/11af7015de624b010424273be3d91f117f172c82/src/modules/rangeproof/main_impl.h#L16 constructed] by taking the hash of the standard uncompressed encoding of the [https://www.secg.org/sec2-v2.pdf secp256k1] base point ''G'' as X coordinate. In order to avoid leaking the information that key path spending is not possible it is recommended to pick a fresh integer ''r'' in the range ''0...n-1'' uniformly at random and use ''H + rG'' as internal key. It is possible to prove that this internal key does not have a known discrete logarithm with respect to ''G'' by revealing ''r'' to a verifier who can then reconstruct how the internal key was created.
+* If the spending conditions do not require a script path, the output key should commit to an unspendable script path instead of having no script path. This can be achieved by computing the output key point as ''Q = P + int(hashTapTweak(bytes(P)))G''. '''Why should the output key always have a taproot commitment, even if there is no script path?'''
+If the taproot output key is an aggregate of keys, there is the possibility for a malicious party to add a script path without being noticed by the other parties.
+This allows to bypass the multiparty policy and to steal the coin.
+MuSig key aggregation does not have this issue because it already causes the internal key to be randomized.
+
+The attack works as follows: Assume Alice and Mallory want to aggregate their keys into a taproot output key without a script path.
+In order to prevent key cancellation and related attacks they use [https://eprint.iacr.org/2018/483.pdf MSDL-pop] instead of MuSig.
+The MSDL-pop protocol requires all parties to provide a proof of possession of their corresponding secret key and the aggregated key is just the sum of the individual keys.
+After Mallory receives Alice's key ''A'', Mallory creates ''M = M0 + int(t)G'' where ''M0'' is Mallory's original key and ''t'' allows a script path spend with internal key ''P = A + M0'' and a script that only contains Mallory's key.
+Mallory sends a proof of possession of ''M'' to Alice and both parties compute output key ''Q = A + M = P + int(t)G''.
+Alice will not be able to notice the script path, but Mallory can unilaterally spend any coin with output key ''Q''.
+
+* The remaining scripts should be organized into the leaves of a binary tree. This can be a balanced tree if each of the conditions these scripts correspond to are equally likely. If probabilities for each condition are known, consider constructing the tree as a Huffman tree.
+
+'''Computing the output script''' Once the spending conditions are split into an internal key internal_pubkey and a binary tree whose leaves are (leaf_version, script) tuples, the output script can be computed using the Python3 algorithms below. These algorithms take advantage of helper functions from the [[bip-0340/reference.py|BIP340 reference code]] for integer conversion, point multiplication, and tagged hashes.
+
+First, we define taproot_tweak_pubkey for 32-byte [[bip-0340.mediawiki|BIP340]] public key arrays.
+The function returns a bit indicating the tweaked public key's Y coordinate as well as the public key byte array.
+The parity bit will be required for spending the output with a script path.
+In order to allow spending with the key path, we define taproot_tweak_seckey to compute the secret key for a tweaked public key.
+For any byte string h it holds that taproot_tweak_pubkey(pubkey_gen(seckey), h)[1] == pubkey_gen(taproot_tweak_seckey(seckey, h)).
+
+Note that because tweaks are applied to 32-byte public keys, `taproot_tweak_seckey` may need to negate the secret key before applying the tweak.
+
+
+def taproot_tweak_pubkey(pubkey, h):
+ t = int_from_bytes(tagged_hash("TapTweak", pubkey + h))
+ if t >= SECP256K1_ORDER:
+ raise ValueError
+ P = lift_x(int_from_bytes(pubkey))
+ if P is None:
+ raise ValueError
+ Q = point_add(P, point_mul(G, t))
+ return 0 if has_even_y(Q) else 1, bytes_from_int(x(Q))
+
+def taproot_tweak_seckey(seckey0, h):
+ seckey0 = int_from_bytes(seckey0)
+ P = point_mul(G, seckey0)
+ seckey = seckey0 if has_even_y(P) else SECP256K1_ORDER - seckey0
+ t = int_from_bytes(tagged_hash("TapTweak", bytes_from_int(x(P)) + h))
+ if t >= SECP256K1_ORDER:
+ raise ValueError
+ return bytes_from_int((seckey + t) % SECP256K1_ORDER)
+
+
+The following function, taproot_output_script, returns a byte array with the scriptPubKey (see [[bip-0141.mediawiki|BIP141]]).
+ser_script refers to a function that prefixes its input with a CompactSize-encoded length.
+
+
+def taproot_tree_helper(script_tree):
+ if isinstance(script_tree, tuple):
+ leaf_version, script = script_tree
+ h = tagged_hash("TapLeaf", bytes([leaf_version]) + ser_script(script))
+ return ([((leaf_version, script), bytes())], h)
+ left, left_h = taproot_tree_helper(script_tree[0])
+ right, right_h = taproot_tree_helper(script_tree[1])
+ ret = [(l, c + right_h) for l, c in left] + [(l, c + left_h) for l, c in right]
+ if right_h < left_h:
+ left_h, right_h = right_h, left_h
+ return (ret, tagged_hash("TapBranch", left_h + right_h))
+
+def taproot_output_script(internal_pubkey, script_tree):
+ """Given a internal public key and a tree of scripts, compute the output script.
+ script_tree is either:
+ - a (leaf_version, script) tuple (leaf_version is 0xc0 for [[bip-0342.mediawiki|BIP342]] scripts)
+ - a list of two elements, each with the same structure as script_tree itself
+ - None
+ """
+ if script_tree is None:
+ h = bytes()
+ else:
+ _, h = taproot_tree_helper(script_tree)
+ _, output_pubkey = taproot_tweak_pubkey(internal_pubkey, h)
+ return bytes([0x51, 0x20]) + output_pubkey
+
+
+[[File:bip-0341/tree.png|frame|This diagram shows the hashing structure to obtain the tweak from an internal key ''P'' and a Merkle tree consisting of 5 script leaves. ''A'', ''B'', ''C'' and ''E'' are ''TapLeaf'' hashes similar to ''D'' and ''AB'' is a ''TapBranch'' hash. Note that when ''CDE'' is computed ''E'' is hashed first because ''E'' is less than ''CD''.]]
+
+To spend this output using script ''D'', the control block would contain the following data in this order:
+
+
+
+The TapTweak would then be computed as described [[bip-0341.mediawiki#script-validation-rules|above]] like so:
+
+
+D = tagged_hash("TapLeaf", bytes([leaf_version]) + ser_script(script))
+CD = tagged_hash("TapBranch", C + D)
+CDE = tagged_hash("TapBranch", E + CD)
+ABCDE = tagged_hash("TapBranch", AB + CDE)
+TapTweak = tagged_hash("TapTweak", p + ABCDE)
+
+
+'''Spending using the key path''' A Taproot output can be spent with the secret key corresponding to the internal_pubkey. To do so, a witness stack consists of a single element: a [[bip-0340.mediawiki|BIP340]] signature on the signature hash as defined above, with the secret key tweaked by the same h as in the above snippet. See the code below:
+
+
+def taproot_sign_key(script_tree, internal_seckey, hash_type, bip340_aux_rand):
+ if script_tree is None:
+ h = bytes()
+ else:
+ _, h = taproot_tree_helper(script_tree)
+ output_seckey = taproot_tweak_seckey(internal_seckey, h)
+ sig = schnorr_sign(sighash(hash_type), output_seckey, bip340_aux_rand)
+ if hash_type != 0:
+ sig += bytes([hash_type])
+ return [sig]
+
+
+This function returns the witness stack necessary and a sighash function to compute the signature hash as defined above (for simplicity, the snippet above ignores passing information like the transaction, the input position, ... to the sighashing code).
+
+'''Spending using one of the scripts''' A Taproot output can be spent by satisfying any of the scripts used in its construction. To do so, a witness stack consisting of the script's inputs, plus the script itself and the control block are necessary. See the code below:
+
+
+def taproot_sign_script(internal_pubkey, script_tree, script_num, inputs):
+ info, h = taproot_tree_helper(script_tree)
+ (leaf_version, script), path = info[script_num]
+ output_pubkey_y_parity, _ = taproot_tweak_pubkey(internal_pubkey, h)
+ pubkey_data = bytes([output_pubkey_y_parity + leaf_version]) + internal_pubkey
+ return inputs + [script, pubkey_data + path]
+
+
+== Security ==
+
+Taproot improves the privacy of Bitcoin because instead of revealing all possible conditions for spending an output, only the satisfied spending condition has to be published.
+Ideally, outputs are spent using the key path which prevents observers from learning the spending conditions of a coin.
+A key path spend could be a "normal" payment from a single- or multi-signature wallet or the cooperative settlement of hidden multiparty contract.
+
+A script path spend leaks that there is a script path and that the key path was not applicable - for example because the involved parties failed to reach agreement.
+Moreover, the depth of a script in the Merkle root leaks information including the minimum depth of the tree, which suggests specific wallet software that created the output and helps clustering.
+Therefore, the privacy of script spends can be improved by deviating from the optimal tree determined by the probability distribution over the leaves.
+
+Just like other existing output types, taproot outputs should never reuse keys, for privacy reasons.
+This does not only apply to the particular leaf that was used to spend an output but to all leaves committed to in the output.
+If leaves were reused, it could happen that spending a different output would reuse the same Merkle branches in the Merkle proof.
+Using fresh keys implies that taproot output construction does not need to take special measures to randomizing leaf positions because they are already randomized due to the branch-sorting Merkle tree construction used in taproot.
+This does not avoid leaking information through the leaf depth and therefore only applies to balanced (sub-) trees.
+In addition, every leaf should have a set of keys distinct from every other leaf.
+The reason for this is to increase leaf entropy and prevent an observer from learning an undisclosed script using brute-force search.
+
+== Test vectors ==
+
+Test vectors for wallet operation (scriptPubKey computation, key path spending, control block construction) can be found [[bip-0341/wallet-test-vectors.json|here]].
+It consists of two sets of vectors.
+* The first "scriptPubKey" tests concern computing the scriptPubKey and (mainnet) BIP350 address given an internal public key, and a script tree. The script tree is encoded as null to represent no scripts, a JSON object to represent a leaf node, or a 2-element array to represent an inner node. The control blocks needed for script path spending are also provided for each of the script leaves.
+* The second "keyPathSpending" tests consists of a list of test cases, each of which provides an unsigned transaction and the UTXOs it spends. For each of its BIP341 inputs, the internal private key and the Merkle root it was derived from is given, as well as the expected witness to spend it. All signatures are created with an all-zero (0x0000...0000) BIP340 auxiliary randomness array.
+* In all cases, hexadecimal values represent byte arrays, not numbers. In particular, that means that provided hash values have the hex digits corresponding to the first bytes first. This differs from the convention used for txids and block hashes, where the hex strings represent numbers, resulting in a reversed order.
+
+Validation test vectors used in the [https://github.com/bitcoin/bitcoin/blob/3820090bd619ac85ab35eff376c03136fe4a9f04/src/test/script_tests.cpp#L1718 Bitcoin Core unit test framework] can be found [https://github.com/bitcoin-core/qa-assets/blob/main/unit_test_data/script_assets_test.json?raw=true here].
+
+== Rationale ==
+
+
+
+== Deployment ==
+
+This BIP is deployed concurrently with [[bip-0342.mediawiki|BIP342]].
+
+For Bitcoin signet, these BIPs are always active.
+
+For Bitcoin mainnet and testnet3, these BIPs are deployed by "version bits" with the name "taproot" and bit 2, using [[bip-0009.mediawiki|BIP9]] modified to use a lower threshold, with an additional ''min_activation_height'' parameter and replacing the state transition logic for the DEFINED, STARTED and LOCKED_IN states as follows:
+
+ case DEFINED:
+ if (GetMedianTimePast(block.parent) >= starttime) {
+ return STARTED;
+ }
+ return DEFINED;
+
+ case STARTED:
+ int count = 0;
+ walk = block;
+ for (i = 0; i < 2016; i++) {
+ walk = walk.parent;
+ if ((walk.nVersion & 0xE0000000) == 0x20000000 && ((walk.nVersion >> bit) & 1) == 1) {
+ count++;
+ }
+ }
+ if (count >= threshold) {
+ return LOCKED_IN;
+ } else if (GetMedianTimePast(block.parent) >= timeout) {
+ return FAILED;
+ }
+ return STARTED;
+
+ case LOCKED_IN:
+ if (block.nHeight < min_activation_height) {
+ return LOCKED_IN;
+ }
+ return ACTIVE;
+
+For Bitcoin mainnet, the starttime is epoch timestamp 1619222400 (midnight 24 April 2021 UTC), timeout is epoch timestamp 1628640000 (midnight 11 August 2021 UTC), the threshold is 1815 blocks (90%) instead of 1916 blocks (95%), and the min_activation_height is block 709632.
+The deployment did activate at height 709632 on Bitcoin mainnet.
+
+For Bitcoin testnet3, the starttime is epoch timestamp 1619222400 (midnight 24 April 2021 UTC), timeout is epoch timestamp 1628640000 (midnight 11 August 2021 UTC), the threshold is 1512 blocks (75%), and the min_activation_height is block 0.
+The deployment did activate at height 2011968 on Bitcoin testnet3.
+
+== Backwards compatibility ==
+As a soft fork, older software will continue to operate without modification.
+Non-upgraded nodes, however, will consider all SegWit version 1 witness programs as anyone-can-spend scripts.
+They are strongly encouraged to upgrade in order to fully validate the new programs.
+
+Non-upgraded wallets can receive and send bitcoin from non-upgraded and upgraded wallets using SegWit version 0 programs, traditional pay-to-pubkey-hash, etc.
+Depending on the implementation non-upgraded wallets may be able to send to Segwit version 1 programs if they support sending to [[bip-0350.mediawiki|BIP350]] Bech32m addresses.
+
+== Acknowledgements ==
+
+This document is the result of discussions around script and signature improvements with many people, and had direct contributions from Greg Maxwell and others. It further builds on top of earlier published proposals such as Taproot by Greg Maxwell, and Merkle branch constructions by Russell O'Connor, Johnson Lau, and Mark Friedenbach.
+
+The authors wish the thank Arik Sosman for suggesting to sort Merkle node children before hashes, removing the need to transfer the position in the tree, as well as all those who provided valuable feedback and reviews, including the participants of the [https://github.com/ajtowns/taproot-review structured reviews].
diff --git a/bip-0341/tree.png b/bip-0341/tree.png
new file mode 100644
index 0000000000..af56edaf3f
Binary files /dev/null and b/bip-0341/tree.png differ
diff --git a/bip-0341/wallet-test-vectors.json b/bip-0341/wallet-test-vectors.json
new file mode 100644
index 0000000000..11261b00ba
--- /dev/null
+++ b/bip-0341/wallet-test-vectors.json
@@ -0,0 +1,452 @@
+{
+ "version": 1,
+ "scriptPubKey": [
+ {
+ "given": {
+ "internalPubkey": "d6889cb081036e0faefa3a35157ad71086b123b2b144b649798b494c300a961d",
+ "scriptTree": null
+ },
+ "intermediary": {
+ "merkleRoot": null,
+ "tweak": "b86e7be8f39bab32a6f2c0443abbc210f0edac0e2c53d501b36b64437d9c6c70",
+ "tweakedPubkey": "53a1f6e454df1aa2776a2814a721372d6258050de330b3c6d10ee8f4e0dda343"
+ },
+ "expected": {
+ "scriptPubKey": "512053a1f6e454df1aa2776a2814a721372d6258050de330b3c6d10ee8f4e0dda343",
+ "bip350Address": "bc1p2wsldez5mud2yam29q22wgfh9439spgduvct83k3pm50fcxa5dps59h4z5"
+ }
+ },
+ {
+ "given": {
+ "internalPubkey": "187791b6f712a8ea41c8ecdd0ee77fab3e85263b37e1ec18a3651926b3a6cf27",
+ "scriptTree": {
+ "id": 0,
+ "script": "20d85a959b0290bf19bb89ed43c916be835475d013da4b362117393e25a48229b8ac",
+ "leafVersion": 192
+ }
+ },
+ "intermediary": {
+ "leafHashes": [
+ "5b75adecf53548f3ec6ad7d78383bf84cc57b55a3127c72b9a2481752dd88b21"
+ ],
+ "merkleRoot": "5b75adecf53548f3ec6ad7d78383bf84cc57b55a3127c72b9a2481752dd88b21",
+ "tweak": "cbd8679ba636c1110ea247542cfbd964131a6be84f873f7f3b62a777528ed001",
+ "tweakedPubkey": "147c9c57132f6e7ecddba9800bb0c4449251c92a1e60371ee77557b6620f3ea3"
+ },
+ "expected": {
+ "scriptPubKey": "5120147c9c57132f6e7ecddba9800bb0c4449251c92a1e60371ee77557b6620f3ea3",
+ "bip350Address": "bc1pz37fc4cn9ah8anwm4xqqhvxygjf9rjf2resrw8h8w4tmvcs0863sa2e586",
+ "scriptPathControlBlocks": [
+ "c1187791b6f712a8ea41c8ecdd0ee77fab3e85263b37e1ec18a3651926b3a6cf27"
+ ]
+ }
+ },
+ {
+ "given": {
+ "internalPubkey": "93478e9488f956df2396be2ce6c5cced75f900dfa18e7dabd2428aae78451820",
+ "scriptTree": {
+ "id": 0,
+ "script": "20b617298552a72ade070667e86ca63b8f5789a9fe8731ef91202a91c9f3459007ac",
+ "leafVersion": 192
+ }
+ },
+ "intermediary": {
+ "leafHashes": [
+ "c525714a7f49c28aedbbba78c005931a81c234b2f6c99a73e4d06082adc8bf2b"
+ ],
+ "merkleRoot": "c525714a7f49c28aedbbba78c005931a81c234b2f6c99a73e4d06082adc8bf2b",
+ "tweak": "6af9e28dbf9d6aaf027696e2598a5b3d056f5fd2355a7fd5a37a0e5008132d30",
+ "tweakedPubkey": "e4d810fd50586274face62b8a807eb9719cef49c04177cc6b76a9a4251d5450e"
+ },
+ "expected": {
+ "scriptPubKey": "5120e4d810fd50586274face62b8a807eb9719cef49c04177cc6b76a9a4251d5450e",
+ "bip350Address": "bc1punvppl2stp38f7kwv2u2spltjuvuaayuqsthe34hd2dyy5w4g58qqfuag5",
+ "scriptPathControlBlocks": [
+ "c093478e9488f956df2396be2ce6c5cced75f900dfa18e7dabd2428aae78451820"
+ ]
+ }
+ },
+ {
+ "given": {
+ "internalPubkey": "ee4fe085983462a184015d1f782d6a5f8b9c2b60130aff050ce221ecf3786592",
+ "scriptTree": [
+ {
+ "id": 0,
+ "script": "20387671353e273264c495656e27e39ba899ea8fee3bb69fb2a680e22093447d48ac",
+ "leafVersion": 192
+ },
+ {
+ "id": 1,
+ "script": "06424950333431",
+ "leafVersion": 250
+ }
+ ]
+ },
+ "intermediary": {
+ "leafHashes": [
+ "8ad69ec7cf41c2a4001fd1f738bf1e505ce2277acdcaa63fe4765192497f47a7",
+ "f224a923cd0021ab202ab139cc56802ddb92dcfc172b9212261a539df79a112a"
+ ],
+ "merkleRoot": "6c2dc106ab816b73f9d07e3cd1ef2c8c1256f519748e0813e4edd2405d277bef",
+ "tweak": "9e0517edc8259bb3359255400b23ca9507f2a91cd1e4250ba068b4eafceba4a9",
+ "tweakedPubkey": "712447206d7a5238acc7ff53fbe94a3b64539ad291c7cdbc490b7577e4b17df5"
+ },
+ "expected": {
+ "scriptPubKey": "5120712447206d7a5238acc7ff53fbe94a3b64539ad291c7cdbc490b7577e4b17df5",
+ "bip350Address": "bc1pwyjywgrd0ffr3tx8laflh6228dj98xkjj8rum0zfpd6h0e930h6saqxrrm",
+ "scriptPathControlBlocks": [
+ "c0ee4fe085983462a184015d1f782d6a5f8b9c2b60130aff050ce221ecf3786592f224a923cd0021ab202ab139cc56802ddb92dcfc172b9212261a539df79a112a",
+ "faee4fe085983462a184015d1f782d6a5f8b9c2b60130aff050ce221ecf37865928ad69ec7cf41c2a4001fd1f738bf1e505ce2277acdcaa63fe4765192497f47a7"
+ ]
+ }
+ },
+ {
+ "given": {
+ "internalPubkey": "f9f400803e683727b14f463836e1e78e1c64417638aa066919291a225f0e8dd8",
+ "scriptTree": [
+ {
+ "id": 0,
+ "script": "2044b178d64c32c4a05cc4f4d1407268f764c940d20ce97abfd44db5c3592b72fdac",
+ "leafVersion": 192
+ },
+ {
+ "id": 1,
+ "script": "07546170726f6f74",
+ "leafVersion": 192
+ }
+ ]
+ },
+ "intermediary": {
+ "leafHashes": [
+ "64512fecdb5afa04f98839b50e6f0cb7b1e539bf6f205f67934083cdcc3c8d89",
+ "2cb2b90daa543b544161530c925f285b06196940d6085ca9474d41dc3822c5cb"
+ ],
+ "merkleRoot": "ab179431c28d3b68fb798957faf5497d69c883c6fb1e1cd9f81483d87bac90cc",
+ "tweak": "639f0281b7ac49e742cd25b7f188657626da1ad169209078e2761cefd91fd65e",
+ "tweakedPubkey": "77e30a5522dd9f894c3f8b8bd4c4b2cf82ca7da8a3ea6a239655c39c050ab220"
+ },
+ "expected": {
+ "scriptPubKey": "512077e30a5522dd9f894c3f8b8bd4c4b2cf82ca7da8a3ea6a239655c39c050ab220",
+ "bip350Address": "bc1pwl3s54fzmk0cjnpl3w9af39je7pv5ldg504x5guk2hpecpg2kgsqaqstjq",
+ "scriptPathControlBlocks": [
+ "c1f9f400803e683727b14f463836e1e78e1c64417638aa066919291a225f0e8dd82cb2b90daa543b544161530c925f285b06196940d6085ca9474d41dc3822c5cb",
+ "c1f9f400803e683727b14f463836e1e78e1c64417638aa066919291a225f0e8dd864512fecdb5afa04f98839b50e6f0cb7b1e539bf6f205f67934083cdcc3c8d89"
+ ]
+ }
+ },
+ {
+ "given": {
+ "internalPubkey": "e0dfe2300b0dd746a3f8674dfd4525623639042569d829c7f0eed9602d263e6f",
+ "scriptTree": [
+ {
+ "id": 0,
+ "script": "2072ea6adcf1d371dea8fba1035a09f3d24ed5a059799bae114084130ee5898e69ac",
+ "leafVersion": 192
+ },
+ [
+ {
+ "id": 1,
+ "script": "202352d137f2f3ab38d1eaa976758873377fa5ebb817372c71e2c542313d4abda8ac",
+ "leafVersion": 192
+ },
+ {
+ "id": 2,
+ "script": "207337c0dd4253cb86f2c43a2351aadd82cccb12a172cd120452b9bb8324f2186aac",
+ "leafVersion": 192
+ }
+ ]
+ ]
+ },
+ "intermediary": {
+ "leafHashes": [
+ "2645a02e0aac1fe69d69755733a9b7621b694bb5b5cde2bbfc94066ed62b9817",
+ "ba982a91d4fc552163cb1c0da03676102d5b7a014304c01f0c77b2b8e888de1c",
+ "9e31407bffa15fefbf5090b149d53959ecdf3f62b1246780238c24501d5ceaf6"
+ ],
+ "merkleRoot": "ccbd66c6f7e8fdab47b3a486f59d28262be857f30d4773f2d5ea47f7761ce0e2",
+ "tweak": "b57bfa183d28eeb6ad688ddaabb265b4a41fbf68e5fed2c72c74de70d5a786f4",
+ "tweakedPubkey": "91b64d5324723a985170e4dc5a0f84c041804f2cd12660fa5dec09fc21783605"
+ },
+ "expected": {
+ "scriptPubKey": "512091b64d5324723a985170e4dc5a0f84c041804f2cd12660fa5dec09fc21783605",
+ "bip350Address": "bc1pjxmy65eywgafs5tsunw95ruycpqcqnev6ynxp7jaasylcgtcxczs6n332e",
+ "scriptPathControlBlocks": [
+ "c0e0dfe2300b0dd746a3f8674dfd4525623639042569d829c7f0eed9602d263e6fffe578e9ea769027e4f5a3de40732f75a88a6353a09d767ddeb66accef85e553",
+ "c0e0dfe2300b0dd746a3f8674dfd4525623639042569d829c7f0eed9602d263e6f9e31407bffa15fefbf5090b149d53959ecdf3f62b1246780238c24501d5ceaf62645a02e0aac1fe69d69755733a9b7621b694bb5b5cde2bbfc94066ed62b9817",
+ "c0e0dfe2300b0dd746a3f8674dfd4525623639042569d829c7f0eed9602d263e6fba982a91d4fc552163cb1c0da03676102d5b7a014304c01f0c77b2b8e888de1c2645a02e0aac1fe69d69755733a9b7621b694bb5b5cde2bbfc94066ed62b9817"
+ ]
+ }
+ },
+ {
+ "given": {
+ "internalPubkey": "55adf4e8967fbd2e29f20ac896e60c3b0f1d5b0efa9d34941b5958c7b0a0312d",
+ "scriptTree": [
+ {
+ "id": 0,
+ "script": "2071981521ad9fc9036687364118fb6ccd2035b96a423c59c5430e98310a11abe2ac",
+ "leafVersion": 192
+ },
+ [
+ {
+ "id": 1,
+ "script": "20d5094d2dbe9b76e2c245a2b89b6006888952e2faa6a149ae318d69e520617748ac",
+ "leafVersion": 192
+ },
+ {
+ "id": 2,
+ "script": "20c440b462ad48c7a77f94cd4532d8f2119dcebbd7c9764557e62726419b08ad4cac",
+ "leafVersion": 192
+ }
+ ]
+ ]
+ },
+ "intermediary": {
+ "leafHashes": [
+ "f154e8e8e17c31d3462d7132589ed29353c6fafdb884c5a6e04ea938834f0d9d",
+ "737ed1fe30bc42b8022d717b44f0d93516617af64a64753b7a06bf16b26cd711",
+ "d7485025fceb78b9ed667db36ed8b8dc7b1f0b307ac167fa516fe4352b9f4ef7"
+ ],
+ "merkleRoot": "2f6b2c5397b6d68ca18e09a3f05161668ffe93a988582d55c6f07bd5b3329def",
+ "tweak": "6579138e7976dc13b6a92f7bfd5a2fc7684f5ea42419d43368301470f3b74ed9",
+ "tweakedPubkey": "75169f4001aa68f15bbed28b218df1d0a62cbbcf1188c6665110c293c907b831"
+ },
+ "expected": {
+ "scriptPubKey": "512075169f4001aa68f15bbed28b218df1d0a62cbbcf1188c6665110c293c907b831",
+ "bip350Address": "bc1pw5tf7sqp4f50zka7629jrr036znzew70zxyvvej3zrpf8jg8hqcssyuewe",
+ "scriptPathControlBlocks": [
+ "c155adf4e8967fbd2e29f20ac896e60c3b0f1d5b0efa9d34941b5958c7b0a0312d3cd369a528b326bc9d2133cbd2ac21451acb31681a410434672c8e34fe757e91",
+ "c155adf4e8967fbd2e29f20ac896e60c3b0f1d5b0efa9d34941b5958c7b0a0312dd7485025fceb78b9ed667db36ed8b8dc7b1f0b307ac167fa516fe4352b9f4ef7f154e8e8e17c31d3462d7132589ed29353c6fafdb884c5a6e04ea938834f0d9d",
+ "c155adf4e8967fbd2e29f20ac896e60c3b0f1d5b0efa9d34941b5958c7b0a0312d737ed1fe30bc42b8022d717b44f0d93516617af64a64753b7a06bf16b26cd711f154e8e8e17c31d3462d7132589ed29353c6fafdb884c5a6e04ea938834f0d9d"
+ ]
+ }
+ }
+ ],
+ "keyPathSpending": [
+ {
+ "given": {
+ "rawUnsignedTx": "02000000097de20cbff686da83a54981d2b9bab3586f4ca7e48f57f5b55963115f3b334e9c010000000000000000d7b7cab57b1393ace2d064f4d4a2cb8af6def61273e127517d44759b6dafdd990000000000fffffffff8e1f583384333689228c5d28eac13366be082dc57441760d957275419a418420000000000fffffffff0689180aa63b30cb162a73c6d2a38b7eeda2a83ece74310fda0843ad604853b0100000000feffffffaa5202bdf6d8ccd2ee0f0202afbbb7461d9264a25e5bfd3c5a52ee1239e0ba6c0000000000feffffff956149bdc66faa968eb2be2d2faa29718acbfe3941215893a2a3446d32acd050000000000000000000e664b9773b88c09c32cb70a2a3e4da0ced63b7ba3b22f848531bbb1d5d5f4c94010000000000000000e9aa6b8e6c9de67619e6a3924ae25696bb7b694bb677a632a74ef7eadfd4eabf0000000000ffffffffa778eb6a263dc090464cd125c466b5a99667720b1c110468831d058aa1b82af10100000000ffffffff0200ca9a3b000000001976a91406afd46bcdfd22ef94ac122aa11f241244a37ecc88ac807840cb0000000020ac9a87f5594be208f8532db38cff670c450ed2fea8fcdefcc9a663f78bab962b0065cd1d",
+ "utxosSpent": [
+ {
+ "scriptPubKey": "512053a1f6e454df1aa2776a2814a721372d6258050de330b3c6d10ee8f4e0dda343",
+ "amountSats": 420000000
+ },
+ {
+ "scriptPubKey": "5120147c9c57132f6e7ecddba9800bb0c4449251c92a1e60371ee77557b6620f3ea3",
+ "amountSats": 462000000
+ },
+ {
+ "scriptPubKey": "76a914751e76e8199196d454941c45d1b3a323f1433bd688ac",
+ "amountSats": 294000000
+ },
+ {
+ "scriptPubKey": "5120e4d810fd50586274face62b8a807eb9719cef49c04177cc6b76a9a4251d5450e",
+ "amountSats": 504000000
+ },
+ {
+ "scriptPubKey": "512091b64d5324723a985170e4dc5a0f84c041804f2cd12660fa5dec09fc21783605",
+ "amountSats": 630000000
+ },
+ {
+ "scriptPubKey": "00147dd65592d0ab2fe0d0257d571abf032cd9db93dc",
+ "amountSats": 378000000
+ },
+ {
+ "scriptPubKey": "512075169f4001aa68f15bbed28b218df1d0a62cbbcf1188c6665110c293c907b831",
+ "amountSats": 672000000
+ },
+ {
+ "scriptPubKey": "5120712447206d7a5238acc7ff53fbe94a3b64539ad291c7cdbc490b7577e4b17df5",
+ "amountSats": 546000000
+ },
+ {
+ "scriptPubKey": "512077e30a5522dd9f894c3f8b8bd4c4b2cf82ca7da8a3ea6a239655c39c050ab220",
+ "amountSats": 588000000
+ }
+ ]
+ },
+ "intermediary": {
+ "hashAmounts": "58a6964a4f5f8f0b642ded0a8a553be7622a719da71d1f5befcefcdee8e0fde6",
+ "hashOutputs": "a2e6dab7c1f0dcd297c8d61647fd17d821541ea69c3cc37dcbad7f90d4eb4bc5",
+ "hashPrevouts": "e3b33bb4ef3a52ad1fffb555c0d82828eb22737036eaeb02a235d82b909c4c3f",
+ "hashScriptPubkeys": "23ad0f61ad2bca5ba6a7693f50fce988e17c3780bf2b1e720cfbb38fbdd52e21",
+ "hashSequences": "18959c7221ab5ce9e26c3cd67b22c24f8baa54bac281d8e6b05e400e6c3a957e"
+ },
+ "inputSpending": [
+ {
+ "given": {
+ "txinIndex": 0,
+ "internalPrivkey": "6b973d88838f27366ed61c9ad6367663045cb456e28335c109e30717ae0c6baa",
+ "merkleRoot": null,
+ "hashType": 3
+ },
+ "intermediary": {
+ "internalPubkey": "d6889cb081036e0faefa3a35157ad71086b123b2b144b649798b494c300a961d",
+ "tweak": "b86e7be8f39bab32a6f2c0443abbc210f0edac0e2c53d501b36b64437d9c6c70",
+ "tweakedPrivkey": "2405b971772ad26915c8dcdf10f238753a9b837e5f8e6a86fd7c0cce5b7296d9",
+ "sigMsg": "0003020000000065cd1de3b33bb4ef3a52ad1fffb555c0d82828eb22737036eaeb02a235d82b909c4c3f58a6964a4f5f8f0b642ded0a8a553be7622a719da71d1f5befcefcdee8e0fde623ad0f61ad2bca5ba6a7693f50fce988e17c3780bf2b1e720cfbb38fbdd52e2118959c7221ab5ce9e26c3cd67b22c24f8baa54bac281d8e6b05e400e6c3a957e0000000000d0418f0e9a36245b9a50ec87f8bf5be5bcae434337b87139c3a5b1f56e33cba0",
+ "precomputedUsed": [
+ "hashAmounts",
+ "hashPrevouts",
+ "hashScriptPubkeys",
+ "hashSequences"
+ ],
+ "sigHash": "2514a6272f85cfa0f45eb907fcb0d121b808ed37c6ea160a5a9046ed5526d555"
+ },
+ "expected": {
+ "witness": [
+ "ed7c1647cb97379e76892be0cacff57ec4a7102aa24296ca39af7541246d8ff14d38958d4cc1e2e478e4d4a764bbfd835b16d4e314b72937b29833060b87276c03"
+ ]
+ }
+ },
+ {
+ "given": {
+ "txinIndex": 1,
+ "internalPrivkey": "1e4da49f6aaf4e5cd175fe08a32bb5cb4863d963921255f33d3bc31e1343907f",
+ "merkleRoot": "5b75adecf53548f3ec6ad7d78383bf84cc57b55a3127c72b9a2481752dd88b21",
+ "hashType": 131
+ },
+ "intermediary": {
+ "internalPubkey": "187791b6f712a8ea41c8ecdd0ee77fab3e85263b37e1ec18a3651926b3a6cf27",
+ "tweak": "cbd8679ba636c1110ea247542cfbd964131a6be84f873f7f3b62a777528ed001",
+ "tweakedPrivkey": "ea260c3b10e60f6de018455cd0278f2f5b7e454be1999572789e6a9565d26080",
+ "sigMsg": "0083020000000065cd1d00d7b7cab57b1393ace2d064f4d4a2cb8af6def61273e127517d44759b6dafdd9900000000808f891b00000000225120147c9c57132f6e7ecddba9800bb0c4449251c92a1e60371ee77557b6620f3ea3ffffffffffcef8fb4ca7efc5433f591ecfc57391811ce1e186a3793024def5c884cba51d",
+ "precomputedUsed": [],
+ "sigHash": "325a644af47e8a5a2591cda0ab0723978537318f10e6a63d4eed783b96a71a4d"
+ },
+ "expected": {
+ "witness": [
+ "052aedffc554b41f52b521071793a6b88d6dbca9dba94cf34c83696de0c1ec35ca9c5ed4ab28059bd606a4f3a657eec0bb96661d42921b5f50a95ad33675b54f83"
+ ]
+ }
+ },
+ {
+ "given": {
+ "txinIndex": 3,
+ "internalPrivkey": "d3c7af07da2d54f7a7735d3d0fc4f0a73164db638b2f2f7c43f711f6d4aa7e64",
+ "merkleRoot": "c525714a7f49c28aedbbba78c005931a81c234b2f6c99a73e4d06082adc8bf2b",
+ "hashType": 1
+ },
+ "intermediary": {
+ "internalPubkey": "93478e9488f956df2396be2ce6c5cced75f900dfa18e7dabd2428aae78451820",
+ "tweak": "6af9e28dbf9d6aaf027696e2598a5b3d056f5fd2355a7fd5a37a0e5008132d30",
+ "tweakedPrivkey": "97323385e57015b75b0339a549c56a948eb961555973f0951f555ae6039ef00d",
+ "sigMsg": "0001020000000065cd1de3b33bb4ef3a52ad1fffb555c0d82828eb22737036eaeb02a235d82b909c4c3f58a6964a4f5f8f0b642ded0a8a553be7622a719da71d1f5befcefcdee8e0fde623ad0f61ad2bca5ba6a7693f50fce988e17c3780bf2b1e720cfbb38fbdd52e2118959c7221ab5ce9e26c3cd67b22c24f8baa54bac281d8e6b05e400e6c3a957ea2e6dab7c1f0dcd297c8d61647fd17d821541ea69c3cc37dcbad7f90d4eb4bc50003000000",
+ "precomputedUsed": [
+ "hashAmounts",
+ "hashOutputs",
+ "hashPrevouts",
+ "hashScriptPubkeys",
+ "hashSequences"
+ ],
+ "sigHash": "bf013ea93474aa67815b1b6cc441d23b64fa310911d991e713cd34c7f5d46669"
+ },
+ "expected": {
+ "witness": [
+ "ff45f742a876139946a149ab4d9185574b98dc919d2eb6754f8abaa59d18b025637a3aa043b91817739554f4ed2026cf8022dbd83e351ce1fabc272841d2510a01"
+ ]
+ }
+ },
+ {
+ "given": {
+ "txinIndex": 4,
+ "internalPrivkey": "f36bb07a11e469ce941d16b63b11b9b9120a84d9d87cff2c84a8d4affb438f4e",
+ "merkleRoot": "ccbd66c6f7e8fdab47b3a486f59d28262be857f30d4773f2d5ea47f7761ce0e2",
+ "hashType": 0
+ },
+ "intermediary": {
+ "internalPubkey": "e0dfe2300b0dd746a3f8674dfd4525623639042569d829c7f0eed9602d263e6f",
+ "tweak": "b57bfa183d28eeb6ad688ddaabb265b4a41fbf68e5fed2c72c74de70d5a786f4",
+ "tweakedPrivkey": "a8e7aa924f0d58854185a490e6c41f6efb7b675c0f3331b7f14b549400b4d501",
+ "sigMsg": "0000020000000065cd1de3b33bb4ef3a52ad1fffb555c0d82828eb22737036eaeb02a235d82b909c4c3f58a6964a4f5f8f0b642ded0a8a553be7622a719da71d1f5befcefcdee8e0fde623ad0f61ad2bca5ba6a7693f50fce988e17c3780bf2b1e720cfbb38fbdd52e2118959c7221ab5ce9e26c3cd67b22c24f8baa54bac281d8e6b05e400e6c3a957ea2e6dab7c1f0dcd297c8d61647fd17d821541ea69c3cc37dcbad7f90d4eb4bc50004000000",
+ "precomputedUsed": [
+ "hashAmounts",
+ "hashOutputs",
+ "hashPrevouts",
+ "hashScriptPubkeys",
+ "hashSequences"
+ ],
+ "sigHash": "4f900a0bae3f1446fd48490c2958b5a023228f01661cda3496a11da502a7f7ef"
+ },
+ "expected": {
+ "witness": [
+ "b4010dd48a617db09926f729e79c33ae0b4e94b79f04a1ae93ede6315eb3669de185a17d2b0ac9ee09fd4c64b678a0b61a0a86fa888a273c8511be83bfd6810f"
+ ]
+ }
+ },
+ {
+ "given": {
+ "txinIndex": 6,
+ "internalPrivkey": "415cfe9c15d9cea27d8104d5517c06e9de48e2f986b695e4f5ffebf230e725d8",
+ "merkleRoot": "2f6b2c5397b6d68ca18e09a3f05161668ffe93a988582d55c6f07bd5b3329def",
+ "hashType": 2
+ },
+ "intermediary": {
+ "internalPubkey": "55adf4e8967fbd2e29f20ac896e60c3b0f1d5b0efa9d34941b5958c7b0a0312d",
+ "tweak": "6579138e7976dc13b6a92f7bfd5a2fc7684f5ea42419d43368301470f3b74ed9",
+ "tweakedPrivkey": "241c14f2639d0d7139282aa6abde28dd8a067baa9d633e4e7230287ec2d02901",
+ "sigMsg": "0002020000000065cd1de3b33bb4ef3a52ad1fffb555c0d82828eb22737036eaeb02a235d82b909c4c3f58a6964a4f5f8f0b642ded0a8a553be7622a719da71d1f5befcefcdee8e0fde623ad0f61ad2bca5ba6a7693f50fce988e17c3780bf2b1e720cfbb38fbdd52e2118959c7221ab5ce9e26c3cd67b22c24f8baa54bac281d8e6b05e400e6c3a957e0006000000",
+ "precomputedUsed": [
+ "hashAmounts",
+ "hashPrevouts",
+ "hashScriptPubkeys",
+ "hashSequences"
+ ],
+ "sigHash": "15f25c298eb5cdc7eb1d638dd2d45c97c4c59dcaec6679cfc16ad84f30876b85"
+ },
+ "expected": {
+ "witness": [
+ "a3785919a2ce3c4ce26f298c3d51619bc474ae24014bcdd31328cd8cfbab2eff3395fa0a16fe5f486d12f22a9cedded5ae74feb4bbe5351346508c5405bcfee002"
+ ]
+ }
+ },
+ {
+ "given": {
+ "txinIndex": 7,
+ "internalPrivkey": "c7b0e81f0a9a0b0499e112279d718cca98e79a12e2f137c72ae5b213aad0d103",
+ "merkleRoot": "6c2dc106ab816b73f9d07e3cd1ef2c8c1256f519748e0813e4edd2405d277bef",
+ "hashType": 130
+ },
+ "intermediary": {
+ "internalPubkey": "ee4fe085983462a184015d1f782d6a5f8b9c2b60130aff050ce221ecf3786592",
+ "tweak": "9e0517edc8259bb3359255400b23ca9507f2a91cd1e4250ba068b4eafceba4a9",
+ "tweakedPrivkey": "65b6000cd2bfa6b7cf736767a8955760e62b6649058cbc970b7c0871d786346b",
+ "sigMsg": "0082020000000065cd1d00e9aa6b8e6c9de67619e6a3924ae25696bb7b694bb677a632a74ef7eadfd4eabf00000000804c8b2000000000225120712447206d7a5238acc7ff53fbe94a3b64539ad291c7cdbc490b7577e4b17df5ffffffff",
+ "precomputedUsed": [],
+ "sigHash": "cd292de50313804dabe4685e83f923d2969577191a3e1d2882220dca88cbeb10"
+ },
+ "expected": {
+ "witness": [
+ "ea0c6ba90763c2d3a296ad82ba45881abb4f426b3f87af162dd24d5109edc1cdd11915095ba47c3a9963dc1e6c432939872bc49212fe34c632cd3ab9fed429c482"
+ ]
+ }
+ },
+ {
+ "given": {
+ "txinIndex": 8,
+ "internalPrivkey": "77863416be0d0665e517e1c375fd6f75839544eca553675ef7fdf4949518ebaa",
+ "merkleRoot": "ab179431c28d3b68fb798957faf5497d69c883c6fb1e1cd9f81483d87bac90cc",
+ "hashType": 129
+ },
+ "intermediary": {
+ "internalPubkey": "f9f400803e683727b14f463836e1e78e1c64417638aa066919291a225f0e8dd8",
+ "tweak": "639f0281b7ac49e742cd25b7f188657626da1ad169209078e2761cefd91fd65e",
+ "tweakedPrivkey": "ec18ce6af99f43815db543f47b8af5ff5df3b2cb7315c955aa4a86e8143d2bf5",
+ "sigMsg": "0081020000000065cd1da2e6dab7c1f0dcd297c8d61647fd17d821541ea69c3cc37dcbad7f90d4eb4bc500a778eb6a263dc090464cd125c466b5a99667720b1c110468831d058aa1b82af101000000002b0c230000000022512077e30a5522dd9f894c3f8b8bd4c4b2cf82ca7da8a3ea6a239655c39c050ab220ffffffff",
+ "precomputedUsed": [
+ "hashOutputs"
+ ],
+ "sigHash": "cccb739eca6c13a8a89e6e5cd317ffe55669bbda23f2fd37b0f18755e008edd2"
+ },
+ "expected": {
+ "witness": [
+ "bbc9584a11074e83bc8c6759ec55401f0ae7b03ef290c3139814f545b58a9f8127258000874f44bc46db7646322107d4d86aec8e73b8719a61fff761d75b5dd981"
+ ]
+ }
+ }
+ ],
+ "auxiliary": {
+ "fullySignedTx": "020000000001097de20cbff686da83a54981d2b9bab3586f4ca7e48f57f5b55963115f3b334e9c010000000000000000d7b7cab57b1393ace2d064f4d4a2cb8af6def61273e127517d44759b6dafdd990000000000fffffffff8e1f583384333689228c5d28eac13366be082dc57441760d957275419a41842000000006b4830450221008f3b8f8f0537c420654d2283673a761b7ee2ea3c130753103e08ce79201cf32a022079e7ab904a1980ef1c5890b648c8783f4d10103dd62f740d13daa79e298d50c201210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798fffffffff0689180aa63b30cb162a73c6d2a38b7eeda2a83ece74310fda0843ad604853b0100000000feffffffaa5202bdf6d8ccd2ee0f0202afbbb7461d9264a25e5bfd3c5a52ee1239e0ba6c0000000000feffffff956149bdc66faa968eb2be2d2faa29718acbfe3941215893a2a3446d32acd050000000000000000000e664b9773b88c09c32cb70a2a3e4da0ced63b7ba3b22f848531bbb1d5d5f4c94010000000000000000e9aa6b8e6c9de67619e6a3924ae25696bb7b694bb677a632a74ef7eadfd4eabf0000000000ffffffffa778eb6a263dc090464cd125c466b5a99667720b1c110468831d058aa1b82af10100000000ffffffff0200ca9a3b000000001976a91406afd46bcdfd22ef94ac122aa11f241244a37ecc88ac807840cb0000000020ac9a87f5594be208f8532db38cff670c450ed2fea8fcdefcc9a663f78bab962b0141ed7c1647cb97379e76892be0cacff57ec4a7102aa24296ca39af7541246d8ff14d38958d4cc1e2e478e4d4a764bbfd835b16d4e314b72937b29833060b87276c030141052aedffc554b41f52b521071793a6b88d6dbca9dba94cf34c83696de0c1ec35ca9c5ed4ab28059bd606a4f3a657eec0bb96661d42921b5f50a95ad33675b54f83000141ff45f742a876139946a149ab4d9185574b98dc919d2eb6754f8abaa59d18b025637a3aa043b91817739554f4ed2026cf8022dbd83e351ce1fabc272841d2510a010140b4010dd48a617db09926f729e79c33ae0b4e94b79f04a1ae93ede6315eb3669de185a17d2b0ac9ee09fd4c64b678a0b61a0a86fa888a273c8511be83bfd6810f0247304402202b795e4de72646d76eab3f0ab27dfa30b810e856ff3a46c9a702df53bb0d8cc302203ccc4d822edab5f35caddb10af1be93583526ccfbade4b4ead350781e2f8adcd012102f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f90141a3785919a2ce3c4ce26f298c3d51619bc474ae24014bcdd31328cd8cfbab2eff3395fa0a16fe5f486d12f22a9cedded5ae74feb4bbe5351346508c5405bcfee0020141ea0c6ba90763c2d3a296ad82ba45881abb4f426b3f87af162dd24d5109edc1cdd11915095ba47c3a9963dc1e6c432939872bc49212fe34c632cd3ab9fed429c4820141bbc9584a11074e83bc8c6759ec55401f0ae7b03ef290c3139814f545b58a9f8127258000874f44bc46db7646322107d4d86aec8e73b8719a61fff761d75b5dd9810065cd1d"
+ }
+ }
+ ]
+}
diff --git a/bip-0342.mediawiki b/bip-0342.mediawiki
new file mode 100644
index 0000000000..64d07cc2a0
--- /dev/null
+++ b/bip-0342.mediawiki
@@ -0,0 +1,150 @@
+
+ BIP: 342
+ Layer: Consensus (soft fork)
+ Title: Validation of Taproot Scripts
+ Author: Pieter Wuille
+ Jonas Nick
+ Anthony Towns
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0342
+ Status: Final
+ Type: Standards Track
+ Created: 2020-01-19
+ License: BSD-3-Clause
+ Requires: 340, 341
+ Post-History: 2019-05-06: https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2019-May/016914.html [bitcoin-dev] Taproot proposal
+
+
+==Introduction==
+
+===Abstract===
+
+This document specifies the semantics of the initial scripting system under [[bip-0341.mediawiki|BIP341]].
+
+===Copyright===
+
+This document is licensed under the 3-clause BSD license.
+
+===Motivation===
+
+[[bip-0341.mediawiki|BIP341]] proposes improvements to just the script structure, but some of its goals are incompatible with the semantics of certain opcodes within the scripting language itself.
+While it is possible to deal with these in separate optional improvements, their impact is not guaranteed unless they are addressed simultaneously with [[bip-0341.mediawiki|BIP341]] itself.
+
+Specifically, the goal is making '''Schnorr signatures''', '''batch validation''', and '''signature hash''' improvements available to spends that use the script system as well.
+
+==Design==
+
+In order to achieve these goals, signature opcodes OP_CHECKSIG and OP_CHECKSIGVERIFY are modified to verify Schnorr signatures as specified in [[bip-0340.mediawiki|BIP340]] and to use a signature message algorithm based on the common message calculation in [[bip-0341.mediawiki|BIP341]].
+The tapscript signature message also simplifies OP_CODESEPARATOR handling and makes it more efficient.
+
+The inefficient OP_CHECKMULTISIG and OP_CHECKMULTISIGVERIFY opcodes are disabled.
+Instead, a new opcode OP_CHECKSIGADD is introduced to allow creating the same multisignature policies in a batch-verifiable way.
+Tapscript uses a new, simpler signature opcode limit fixing complicated interactions with transaction weight.
+Furthermore, a potential malleability vector is eliminated by requiring MINIMALIF.
+
+Tapscript can be upgraded through soft forks by defining unknown key types, for example to add new hash_types or signature algorithms.
+Additionally, the new tapscript OP_SUCCESS opcodes allow introducing new opcodes more cleanly than through OP_NOP.
+
+==Specification==
+
+The rules below only apply when validating a transaction input for which all of the conditions below are true:
+* The transaction input is a '''segregated witness spend''' (i.e., the scriptPubKey contains a witness program as defined in [[bip-0141.mediawiki|BIP141]]).
+* It is a '''taproot spend''' as defined in [[bip-0341.mediawiki#design|BIP341]] (i.e., the witness version is 1, the witness program is 32 bytes, and it is not P2SH wrapped).
+* It is a '''script path spend''' as defined in [[bip-0341.mediawiki#design|BIP341]] (i.e., after removing the optional annex from the witness stack, two or more stack elements remain).
+* The leaf version is ''0xc0'' (i.e. the first byte of the last witness element after removing the optional annex is ''0xc0'' or ''0xc1''), marking it as a '''tapscript spend'''.
+
+Validation of such inputs must be equivalent to performing the following steps in the specified order.
+# If the input is invalid due to BIP141 or BIP341, fail.
+# The script as defined in BIP341 (i.e., the penultimate witness stack element after removing the optional annex) is called the '''tapscript''' and is decoded into opcodes, one by one:
+## If any opcode numbered ''80, 98, 126-129, 131-134, 137-138, 141-142, 149-153, 187-254'' is encountered, validation succeeds (none of the rules below apply). This is true even if later bytes in the tapscript would fail to decode otherwise. These opcodes are renamed to OP_SUCCESS80, ..., OP_SUCCESS254, and collectively known as OP_SUCCESSx'''OP_SUCCESSx''' OP_SUCCESSx is a mechanism to upgrade the Script system. Using an OP_SUCCESSx before its meaning is defined by a softfork is insecure and leads to fund loss. The inclusion of OP_SUCCESSx in a script will pass it unconditionally. It precedes any script execution rules to avoid the difficulties in specifying various edge cases, for example: OP_SUCCESSx in a script with an input stack larger than 1000 elements, OP_SUCCESSx after too many signature opcodes, or even scripts with conditionals lacking OP_ENDIF. The mere existence of an OP_SUCCESSx anywhere in the script will guarantee a pass for all such cases. OP_SUCCESSx are similar to the OP_RETURN in very early bitcoin versions (v0.1 up to and including v0.3.5). The original OP_RETURN terminates script execution immediately, and return pass or fail based on the top stack element at the moment of termination. This was one of a major design flaws in the original bitcoin protocol as it permitted unconditional third party theft by placing an OP_RETURN in scriptSig. This is not a concern in the present proposal since it is not possible for a third party to inject an OP_SUCCESSx to the validation process, as the OP_SUCCESSx is part of the script (and thus committed to by the taproot output), implying the consent of the coin owner. OP_SUCCESSx can be used for a variety of upgrade possibilities:
+* An OP_SUCCESSx could be turned into a functional opcode through a softfork. Unlike OP_NOPx-derived opcodes which only have read-only access to the stack, OP_SUCCESSx may also write to the stack. Any rule changes to an OP_SUCCESSx-containing script may only turn a valid script into an invalid one, and this is always achievable with softforks.
+* Since OP_SUCCESSx precedes size check of initial stack and push opcodes, an OP_SUCCESSx-derived opcode requiring stack elements bigger than 520 bytes may uplift the limit in a softfork.
+* OP_SUCCESSx may also redefine the behavior of existing opcodes so they could work together with the new opcode. For example, if an OP_SUCCESSx-derived opcode works with 64-bit integers, it may also allow the existing arithmetic opcodes in the ''same script'' to do the same.
+* Given that OP_SUCCESSx even causes potentially unparseable scripts to pass, it can be used to introduce multi-byte opcodes, or even a completely new scripting language when prefixed with a specific OP_SUCCESSx opcode..
+## If any push opcode fails to decode because it would extend past the end of the tapscript, fail.
+# If the '''initial stack''' as defined in BIP341 (i.e., the witness stack after removing both the optional annex and the two last stack elements after that) violates any resource limits (stack size, and size of the elements in the stack; see "Resource Limits" below), fail. Note that this check can be bypassed using OP_SUCCESSx.
+# The tapscript is executed according to the rules in the following section, with the initial stack as input.
+## If execution fails for any reason, fail.
+## If the execution results in anything but exactly one element on the stack which evaluates to true with CastToBool(), fail.
+# If this step is reached without encountering a failure, validation succeeds.
+
+===Script execution===
+
+The execution rules for tapscript are based on those for P2WSH according to BIP141, including the OP_CHECKLOCKTIMEVERIFY and OP_CHECKSEQUENCEVERIFY opcodes defined in [[bip-0065.mediawiki|BIP65]] and [[bip-0112.mediawiki|BIP112]], but with the following modifications:
+* '''Disabled script opcodes''' The following script opcodes are disabled in tapscript: OP_CHECKMULTISIG and OP_CHECKMULTISIGVERIFY'''Why are OP_CHECKMULTISIG and OP_CHECKMULTISIGVERIFY disabled, and not turned into OP_SUCCESSx?''' This is a precaution to make sure people who accidentally keep using OP_CHECKMULTISIG in Tapscript notice a problem immediately. It also avoids the complication of script disassemblers needing to become context-dependent.. The disabled opcodes behave in the same way as OP_RETURN, by failing and terminating the script immediately when executed, and being ignored when found in unexecuted branch of the script.
+* '''Consensus-enforced MINIMALIF''' The MINIMALIF rules, which are only a standardness rule in P2WSH, are consensus enforced in tapscript. This means that the input argument to the OP_IF and OP_NOTIF opcodes must be either exactly 0 (the empty vector) or exactly 1 (the one-byte vector with value 1)'''Why make MINIMALIF consensus?''' This makes it considerably easier to write non-malleable scripts that take branch information from the stack..
+* '''OP_SUCCESSx opcodes''' As listed above, some opcodes are renamed to OP_SUCCESSx, and make the script unconditionally valid.
+* '''Signature opcodes'''. The OP_CHECKSIG and OP_CHECKSIGVERIFY are modified to operate on Schnorr public keys and signatures (see [[bip-0340.mediawiki|BIP340]]) instead of ECDSA, and a new opcode OP_CHECKSIGADD is added.
+** The opcode 186 (0xba) is named as OP_CHECKSIGADD. '''OP_CHECKSIGADD''' This opcode is added to compensate for the loss of OP_CHECKMULTISIG-like opcodes, which are incompatible with batch verification. OP_CHECKSIGADD is functionally equivalent to OP_ROT OP_SWAP OP_CHECKSIG OP_ADD, but only takes 1 byte. All CScriptNum-related behaviours of OP_ADD are also applicable to OP_CHECKSIGADD.'''Alternatives to CHECKMULTISIG''' There are multiple ways of implementing a threshold ''k''-of-''n'' policy using Taproot and Tapscript:
+* '''Using a single OP_CHECKSIGADD-based script''' A CHECKMULTISIG script m ... n CHECKMULTISIG with witness 0 ... can be rewritten as script CHECKSIG CHECKSIGADD ... CHECKSIGADD m NUMEQUAL with witness ... . Every witness element w_i is either a signature corresponding to pubkey_i or an empty vector. A similar CHECKMULTISIGVERIFY script can be translated to BIP342 by replacing NUMEQUAL with NUMEQUALVERIFY. This approach has very similar characteristics to the existing OP_CHECKMULTISIG-based scripts.
+* '''Using a ''k''-of-''k'' script for every combination''' A ''k''-of-''n'' policy can be implemented by splitting the script into several leaves of the Merkle tree, each implementing a ''k''-of-''k'' policy using CHECKSIGVERIFY ... CHECKSIGVERIFY CHECKSIG. This may be preferable for privacy reasons over the previous approach, as it only exposes the participating public keys, but it is only more cost effective for small values of ''k'' (1-of-''n'' for any ''n'', 2-of-''n'' for ''n ≥ 6'', 3-of-''n'' for ''n ≥ 9'', ...). Furthermore, the signatures here commit to the branch used, which means signers need to be aware of which other signers will be participating, or produce signatures for each of the tree leaves.
+* '''Using an aggregated public key for every combination''' Instead of building a tree where every leaf consists of ''k'' public keys, it is possible instead build a tree where every leaf contains a single ''aggregate'' of those ''k'' keys using [https://eprint.iacr.org/2018/068 MuSig]. This approach is far more efficient, but does require a 3-round interactive signing protocol to jointly produce the (single) signature.
+* '''Native Schnorr threshold signatures''' Multisig policies can also be realized with [http://cacr.uwaterloo.ca/techreports/2001/corr2001-13.ps threshold signatures] using verifiable secret sharing. This results in outputs and inputs that are indistinguishable from single-key payments, but at the cost of needing an interactive protocol (and associated backup procedures) before determining the address to send to.
+
+===Rules for signature opcodes===
+
+The following rules apply to OP_CHECKSIG, OP_CHECKSIGVERIFY, and OP_CHECKSIGADD.
+
+* For OP_CHECKSIGVERIFY and OP_CHECKSIG, the public key (top element) and a signature (second to top element) are popped from the stack.
+** If fewer than 2 elements are on the stack, the script MUST fail and terminate immediately.
+* For OP_CHECKSIGADD, the public key (top element), a CScriptNumn (second to top element), and a signature (third to top element) are popped from the stack.
+** If fewer than 3 elements are on the stack, the script MUST fail and terminate immediately.
+** If n is larger than 4 bytes, the script MUST fail and terminate immediately.
+* If the public key size is zero, the script MUST fail and terminate immediately.
+* If the public key size is 32 bytes, it is considered to be a public key as described in BIP340:
+** If the signature is not the empty vector, the signature is validated against the public key (see the next subsection). Validation failure in this case immediately terminates script execution with failure.
+* If the public key size is not zero and not 32 bytes, the public key is of an ''unknown public key type'''''Unknown public key types''' allow adding new signature validation rules through softforks. A softfork could add actual signature validation which either passes or makes the script fail and terminate immediately. This way, new SIGHASH modes can be added, as well as [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-December/016549.html NOINPUT-tagged public keys] and a public key constant which is replaced by the taproot internal key for signature validation. and no actual signature verification is applied. During script execution of signature opcodes they behave exactly as known public key types except that signature validation is considered to be successful.
+* If the script did not fail and terminate before this step, regardless of the public key type:
+** If the signature is the empty vector:
+*** For OP_CHECKSIGVERIFY, the script MUST fail and terminate immediately.
+*** For OP_CHECKSIG, an empty vector is pushed onto the stack, and execution continues with the next opcode.
+*** For OP_CHECKSIGADD, a CScriptNum with value n is pushed onto the stack, and execution continues with the next opcode.
+** If the signature is not the empty vector, the opcode is counted towards the sigops budget (see further).
+*** For OP_CHECKSIGVERIFY, execution continues without any further changes to the stack.
+*** For OP_CHECKSIG, a 1-byte value 0x01 is pushed onto the stack.
+*** For OP_CHECKSIGADD, a CScriptNum with value of n + 1 is pushed onto the stack.
+
+===Common Signature Message Extension===
+
+We define the tapscript message extension ''ext'' to [[bip-0341.mediawiki#common-signature-message|BIP341 Common Signature Message]], indicated by ''ext_flag = 1'':
+* ''tapleaf_hash'' (32): the tapleaf hash as defined in [[bip-0341.mediawiki#design|BIP341]]
+* ''key_version'' (1): a constant value ''0x00'' representing the current version of public keys in the tapscript signature opcode execution.
+* ''codesep_pos'' (4): the opcode position of the last executed OP_CODESEPARATOR before the currently executed signature opcode, with the value in little endian (or ''0xffffffff'' if none executed). The first opcode in a script has a position of 0. A multi-byte push opcode is counted as one opcode, regardless of the size of data being pushed. Opcodes in parsed but unexecuted branches count towards this value as well.
+
+===Signature validation===
+
+To validate a signature ''sig'' with public key ''p'':
+* Compute the tapscript message extension ''ext'' described above.
+* If the ''sig'' is 64 bytes long, return ''Verify(p, hashTapSighash(0x00 || SigMsg(0x00, 1) || ext), sig)'', where ''Verify'' is defined in [[bip-0340.mediawiki#design|BIP340]].
+* If the ''sig'' is 65 bytes long, return ''sig[64] ≠ 0x00 and Verify(p, hashTapSighash(0x00 || SigMsg(sig[64], 1) || ext), sig[0:64])''.
+* Otherwise, fail.
+
+In summary, the semantics of signature validation is identical to BIP340, except the following:
+# The signature message includes the tapscript-specific data ''key_version''.'''Why does the signature message commit to the ''key_version''?''' This is for future extensions that define unknown public key types, making sure signatures can't be moved from one key type to another.
+# The signature message commits to the executed script through the ''tapleaf_hash'' which includes the leaf version and script instead of ''scriptCode''. This implies that this commitment is unaffected by OP_CODESEPARATOR.
+# The signature message includes the opcode position of the last executed OP_CODESEPARATOR.'''Why does the signature message include the position of the last executed OP_CODESEPARATOR?''' This allows continuing to use OP_CODESEPARATOR to sign the executed path of the script. Because the codeseparator_position is the last input to the hash, the SHA256 midstate can be efficiently cached for multiple OP_CODESEPARATORs in a single script. In contrast, the BIP143 handling of OP_CODESEPARATOR is to commit to the executed script only from the last executed OP_CODESEPARATOR onwards which requires unnecessary rehashing of the script. It should be noted that the one known OP_CODESEPARATOR use case of saving a second public key push in a script by sharing the first one between two code branches can be most likely expressed even cheaper by moving each branch into a separate taproot leaf.
+
+===Resource limits===
+
+In addition to changing the semantics of a number of opcodes, there are also some changes to the resource limitations:
+* '''Script size limit''' The maximum script size of 10000 bytes does not apply. Their size is only implicitly bounded by the block weight limit.'''Why is a limit on script size no longer needed?''' Since there is no scriptCode directly included in the signature hash (only indirectly through a precomputable tapleaf hash), the CPU time spent on a signature check is no longer proportional to the size of the script being executed.
+* '''Non-push opcodes limit''' The maximum non-push opcodes limit of 201 per script does not apply.'''Why is a limit on the number of opcodes no longer needed?''' An opcode limit only helps to the extent that it can prevent data structures from growing unboundedly during execution (both because of memory usage, and because of time that may grow in proportion to the size of those structures). The size of stack and altstack is already independently limited. By using O(1) logic for OP_IF, OP_NOTIF, OP_ELSE, and OP_ENDIF as suggested [https://bitslog.com/2017/04/17/new-quadratic-delays-in-bitcoin-scripts/ here] and implemented [https://github.com/bitcoin/bitcoin/pull/16902 here], the only other instance can be avoided as well.
+* '''Sigops limit''' The sigops in tapscripts do not count towards the block-wide limit of 80000 (weighted). Instead, there is a per-script sigops ''budget''. The budget equals 50 + the total serialized size in bytes of the transaction input's witness (including the CompactSize prefix). Executing a signature opcode (OP_CHECKSIG, OP_CHECKSIGVERIFY, or OP_CHECKSIGADD) with a non-empty signature decrements the budget by 50. If that brings the budget below zero, the script fails immediately. Signature opcodes with unknown public key type and non-empty signature are also counted.'''The tapscript sigop limit''' The signature opcode limit protects against scripts which are slow to verify due to excessively many signature operations. In tapscript the number of signature opcodes does not count towards the BIP141 or legacy sigop limit. The old sigop limit makes transaction selection in block construction unnecessarily difficult because it is a second constraint in addition to weight. Instead, the number of tapscript signature opcodes is limited by witness weight. Additionally, the limit applies to the transaction input instead of the block and only actually executed signature opcodes are counted. Tapscript execution allows one signature opcode per 50 witness weight units plus one free signature opcode.'''Parameter choice of the sigop limit''' Regular witnesses are unaffected by the limit as their weight is composed of public key and (SIGHASH_ALL) signature pairs with ''33 + 65'' weight units each (which includes a 1 weight unit CompactSize tag). This is also the case if public keys are reused in the script because a signature's weight alone is 65 or 66 weight units. However, the limit increases the fees of abnormal scripts with duplicate signatures (and public keys) by requiring additional weight. The weight per sigop factor 50 corresponds to the ratio of BIP141 block limits: 4 mega weight units divided by 80,000 sigops. The "free" signature opcode permitted by the limit exists to account for the weight of the non-witness parts of the transaction input.'''Why are only signature opcodes counted toward the budget, and not for example hashing opcodes or other expensive operations?''' It turns out that the CPU cost per witness byte for verification of a script consisting of the maximum density of signature checking opcodes (taking the 50 WU/sigop limit into account) is already very close to that of scripts packed with other opcodes, including hashing opcodes (taking the 520 byte stack element limit into account) and OP_ROLL (taking the 1000 stack element limit into account). That said, the construction is very flexible, and allows adding new signature opcodes like CHECKSIGFROMSTACK to count towards the limit through a soft fork. Even if in the future new opcodes are introduced which change normal script cost there is no need to stuff the witness with meaningless data. Instead, the taproot annex can be used to add weight to the witness without increasing the actual witness size..
+* '''Stack + altstack element count limit''' The existing limit of 1000 elements in the stack and altstack together after every executed opcode remains. It is extended to also apply to the size of initial stack.
+* '''Stack element size limit''' The existing limit of maximum 520 bytes per stack element remains, both in the initial stack and in push opcodes.
+
+==Rationale==
+
+
+
+==Deployment==
+
+This proposal is deployed identically to Taproot ([[bip-0341.mediawiki|BIP341]]).
+
+==Examples==
+
+The Taproot ([[bip-0341.mediawiki|BIP341]]) test vectors also contain examples for Tapscript execution.
+
+==Acknowledgements==
+
+This document is the result of many discussions and contains contributions by a number of people. The authors wish to thank all those who provided valuable feedback and reviews, including the participants of the [https://github.com/ajtowns/taproot-review structured reviews].
diff --git a/bip-0343.mediawiki b/bip-0343.mediawiki
new file mode 100644
index 0000000000..cab5cb707f
--- /dev/null
+++ b/bip-0343.mediawiki
@@ -0,0 +1,62 @@
+
+
+==Abstract==
+
+This document specifies a BIP8 (LOT=true) deployment to activate taproot.
+
+==Motivation==
+
+The Taproot soft fork upgrade has been assessed to have overwhelming community consensus and hence should attempt to be activated. Lessons have been learned from the BIP148 and BIP91 deployments in 2017 with regards to giving many months of advance warning before the mandatory signaling is attempted. The mandatory signaling is only required if miners have failed to meet the signaling threshold during the BIP8 deployment. It is important that mandatory signaling is included as without it miners would effectively have the ability to indefinitely block the activation of a soft fork with overwhelming consensus.
+
+==Specification==
+
+This BIP will begin an activation signaling period using bit 2 at blockheight 681408 with a minimum activation height of 709632 and an activation threshold of 90%. The signaling period will timeout at blockheight 760032 with a latest activation height of 762048. Lockinontimeout (LOT) is set to true so mandatory signaling will be enforced in the last signaling period before the timeout height. Blocks without the signaling bit 2 set run the risk of being rejected during this period if taproot is not locked in prior. This BIP will cease to be active when taproot is locked in.
+
+==Reference implementation==
+
+*[[https://github.com/BitcoinActivation/bitcoin]]
+
+==Backward Compatibility==
+
+As a soft fork, older software will continue to operate without modification. Non-upgraded nodes, however, will consider all SegWit version 1 witness programs as anyone-can-spend scripts. They are strongly encouraged to upgrade in order to fully validate the new programs.
+
+==Compatibility with later alternative activations==
+
+The activation mechanism “Speedy Trial” as proposed by Russell O’Connor and outlined in this bitcoin-dev mailing list [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2021-March/018583.html post] by David Harding was released in Bitcoin Core. It is effectively a BIP8 activation mechanism with one exception: start height and timeout height were defined using median time past (MTP) rather than block heights. It uses signaling bit 2, was deployed between midnight April 24th 2021 and midnight August 11th 2021, has a minimum activation height of 709632 and intends to activate BIPs 340, 341, and 342. The BIP8(LOT=true) deployment is compatible with the “Speedy Trial” deployment in Bitcoin Core as there was not a discrepancy between MTP and block height for the defined start heights.
+
+The BIP8 (LOT=true) deployment has also been deliberately designed to be compatible with a future BIP8(LOT=false) or BIP8(LOT=true) deployment in Bitcoin Core assuming Bitcoin Core releases one of these activation mechanisms in the event of the Speedy Trial deployment failing to activate.
+
+==Rationale==
+
+The deployment of BIP148 demonstrated that multiple implementations with different activation mechanisms can incentivize the necessary actors to act so that the different deployments activate in sync. A BIP8 LOT=true deployment can run in parallel with other BIP8 activation mechanisms that have eventual mandatory signaling or no mandatory signaling. Eventual mandatory signaling ensures that miners cannot prevent the activation of a desired feature with community consensus indefinitely.
+
+==Acknowledgements==
+
+Thanks to Shaolin Fry and Luke Dashjr for their work on BIP148 and BIP8 which were important prerequisites for this proposal.
+
+==References==
+
+*[[bip-0008.mediawiki|BIP8 Version bits with lock-in by height]]
+*[[bip-0148.mediawiki|BIP148 Mandatory activation of segwit deployment]]
+*[[bip-0340.mediawiki|BIP340 Schnorr Signatures for secp256k1]]
+*[[bip-0341.mediawiki|BIP341 Taproot: SegWit version 1 spending rules]]
+*[[bip-0342.mediawiki|BIP342 Validation of Taproot Scripts]]
+*[https://taproot.works/taproot-faq/ Taproot benefits]
+
+==Copyright==
+
+This document is dual licensed as BSD 3-clause, and Creative Commons CC0 1.0 Universal.
+
diff --git a/bip-0345.mediawiki b/bip-0345.mediawiki
new file mode 100644
index 0000000000..2bbb5ee84e
--- /dev/null
+++ b/bip-0345.mediawiki
@@ -0,0 +1,687 @@
+
+
+
+== Introduction ==
+
+This BIP proposes two new tapscript opcodes that add consensus support for a specialized
+covenant: OP_VAULT and OP_VAULT_RECOVER. These opcodes, in conjunction with
+OP_CHECKTEMPLATEVERIFY
+([https://github.com/bitcoin/bips/blob/master/bip-0119.mediawiki BIP-0119]),
+allow users to enforce a delay period before designated coins may be spent to
+an arbitrary destination, with the exception of a prespecified "recovery" path.
+At any time prior to final withdrawal, the coins can be spent to the
+recovery path.
+
+=== Copyright ===
+
+This document is licensed under the 3-clause BSD license.
+
+
+=== Motivation ===
+
+The hazard of custodying Bitcoin is well-known. Users of Bitcoin must go to
+significant effort to secure their private keys, and hope that once provisioned
+their custody system does not yield to any number of evolving and
+persistent threats. Users have little means to intervene once a compromise is
+detected. This proposal introduces a mechanism that significantly
+mitigates the worst-case outcome of key compromise: coin loss.
+
+Introducing a way to intervene during unexpected spends allows users to
+incorporate highly secure key storage methods or unusual fallback strategies
+that are only exercised in the worst case, and which may otherwise be
+operationally prohibitive. The goal of this proposal is to make this strategy
+usable for custodians of any size with minimal complication.
+
+==== Example uses ====
+
+A common configuration for an individual custodying Bitcoin is "single
+signature and passphrase" using a hardware wallet. A user with such a
+configuration might be concerned about the risk associated with relying on a
+single manufacturer for key management, as well as physical access to the
+hardware.
+
+This individual can use OP_VAULT to make use of a highly secure
+key as the unlikely recovery path, while using their existing signing procedure
+as the withdrawal trigger key with a configured spend delay of e.g. 1 day.
+
+The recovery path key can be of a highly secure nature that might otherwise
+make it impractical for daily use. For example, the key could be generated in
+some analog fashion, or on an old computer that is then destroyed, with the
+private key replicated only in paper form. Or the key could be a 2-of-3
+multisig using devices from different manufacturers. Perhaps the key is
+geographically or socially distributed.
+
+Since it can be any Bitcoin script policy, the recovery key can include a
+number of spending conditions, e.g. a time-delayed fallback to an "easier"
+recovery method, in case the highly secure key winds up being ''too'' highly
+secure.
+
+The user can run software on their mobile device that monitors the blockchain
+for spends of the vault outpoints. If the vaulted coins move in an unexpected
+way, the user can immediately sweep them to the recovery path, but spending the
+coins on a daily basis works in the same way it did prior to vaulting (aside
+from the spend delay).
+
+Institutional custodians of Bitcoin may use vaults in similar fashion.
+
+===== Provable timelocks =====
+
+This proposal provides a mitigation to the
+[https://web.archive.org/web/20230210123933/https://xkcd.com/538/ "$5 wrench attack."] By
+setting the spend delay to, say, a week, and using as the recovery path a
+script that enforces a longer relative timelock, the owner of the vault can
+prove that he is unable to access its value immediately. To the author's
+knowledge, this is the only way to configure this defense without rolling
+timelocked coins for perpetuity or relying on a trusted third party.
+
+== Goals ==
+
+[[File:bip-0345/vaults-Basic.png|frame|center]]
+
+Vaults in Bitcoin have been discussed formally since 2016
+([http://fc16.ifca.ai/bitcoin/papers/MES16.pdf MES16]) and informally since [https://web.archive.org/web/20160220215151/https://bitcointalk.org/index.php?topic=511881.0 2014]. The value of
+having a configurable delay period with recovery capability in light of an
+unexpected spend has been widely recognized.
+
+The only way to implement vaults given the existing consensus rules, aside from
+[https://github.com/revault emulating vaults with large multisig
+configurations], is to use presigned transactions created with a one-time-use
+key. This approach was first demonstrated
+[https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2020-April/017755.html in 2020].
+
+Unfortunately, this approach has a number of practical shortcomings:
+* generating and securely deleting ephemeral keys, which are used to emulate the vault covenant, is required,
+* amounts and withdrawal patterns must be precommitted to,
+* there is a necessity to precommit to an address that the funds must pass through on their way to the final withdrawal target, which is likely only known at unvault time,
+* the particular fee management technique or wallet must be decided upon vault creation,
+* coin loss follows if a vault address is reused,
+* the transaction data that represents the "bearer asset" of the vault must be stored for perpetuity, otherwise value is lost, and
+* the vault creation ceremony must be performed each time a new balance is to be deposited.
+
+The deployment of a "precomputed" covenant mechanism like
+[https://github.com/bitcoin/bips/blob/master/bip-0119.mediawiki OP_CHECKTEMPLATEVERIFY] or
+[https://github.com/bitcoin/bips/blob/master/bip-0118.mediawiki SIGHASH_ANYPREVOUT]
+would both remove the necessity to use an ephemeral key, since the
+covenant is enforced on-chain, and lessen the burden of sensitive data storage,
+since the necessary transactions can be generated from a set of compact
+parameters. This approach was demonstrated [https://github.com/jamesob/simple-ctv-vault in
+2022].
+
+However, the limitations of precomputation still apply: amounts,
+destinations, and fee management are all fixed. Funds must flow through a fixed
+intermediary to their final destination. Batch operations, which may be vital
+for successful recovery during fee spikes or short spend delay, are not possible.
+
+[[File:bip-0345/withdrawal-comparison.drawio.png|frame|center]]
+
+Having a "general" covenant mechanism that can encode arbitrary transactional
+state machines would allow us to solve these issues, but at the cost of complex
+and large scripts that would probably be duplicated many times over in the
+blockchain. The particular design and deployment timeline of such a general
+framework is also uncertain. This approach was demonstrated
+[https://blog.blockstream.com/en-covenants-in-elements-alpha/ in 2016].
+
+This proposal intends to address the problems outlined above by
+providing a delay period/recovery path use with minimal transactional and
+operational overhead using a specialized covenant.
+
+The design goals of the proposal are:
+
+* '''efficient reuse of an existing vault configuration.''''''Why does this support address reuse?''' The proposal doesn't rely on or encourage address reuse, but certain uses are unsafe if address reuse cannot be handled - for example, if a custodian gives its users a vault address to deposit to, it cannot enforce that those users make a single deposit for each address. A single vault configuration, whether the same literal scriptPubKey or not, should be able to “receive” multiple deposits.
+
+* '''batched operations''' for recovery and withdrawal to allow managing multiple vault coins efficiently.
+
+* '''unbounded partial withdrawals''', which allows users to withdraw partial vault balances without having to perform the setup ceremony for a new vault.
+
+* '''dynamic unvault targets''', which allow the proposed withdrawal target for a vault to be specified at withdrawal time rather than when the vault is first created. This would remove the need for a prespecified, intermediate wallet that only exists to route unvaulted funds to their desired destination.
+
+* '''dynamic fee management''' that, like dynamic targets, defers the specification of fee rates and source to unvault time rather than vault creation time.
+
+These goals are accompanied by basic safety considerations (e.g. not being
+vulnerable to mempool pinning) and a desire for concision, both in terms of the number
+of outputs created as well as script sizes.
+
+This proposal is designed to be compatible with any future sighash modes (e.g. SIGHASH_GROUP) or fee management strategies (e.g. [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2020-September/018168.html transaction sponsors]) that may be introduced. Use of these opcodes will benefit from, but do not strictly rely on, [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2022-September/020937.html v3 transaction relay] and [https://github.com/instagibbs/bips/blob/ephemeral_anchor/bip-ephemeralanchors.mediawiki ephemeral anchors].
+
+== Design ==
+
+In typical usage, a vault is created by encumbering coins under a
+taptree [https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki (BIP-341)]
+containing at least two leaves: one with an OP_VAULT-containing script that
+facilitates the expected withdrawal process, and another leaf with
+OP_VAULT_RECOVER which ensures the coins can be recovered
+at any time prior to withdrawal finalization.
+
+The rules of OP_VAULT ensure the timelocked, interruptible
+withdrawal by allowing a spending transaction to replace the
+OP_VAULT tapleaf with a prespecified script template, allowing for
+some parameters to be set at spend (trigger) time. All other leaves in the
+taptree must be unchanged in the destination output, which preserves the recovery path as well as any
+other spending conditions originally included in the vault. This is similar to
+the TAPLEAF_UPDATE_VERIFY design that was proposed
+[https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2021-September/019419.html in 2021].
+
+These tapleaf replacement rules, described more precisely below, ensure a
+timelocked withdrawal, where the timelock is fixed by the original
+OP_VAULT parameters, to a fixed set of outputs (via
+OP_CHECKTEMPLATEVERIFY'''Why is OP_CHECKTEMPLATEVERIFY (BIP-119) relied upon for this proposal?''' During the withdrawal process, the proposed final destination for value being withdrawn must be committed to. OP_CTV is the simplest, safest way to commit the spend of some coins to a particular set of outputs. An earlier version of this proposal attempted to use a simpler, but similar method, of locking the spend of coins to a set of outputs, but this method introduced txid malleability. Note that if some other method of locking spends to a particular set of outputs should be deployed, that method can be used in the OP_VAULT with no changes.) which is chosen when the withdrawal
+process is triggered.
+
+While OP_CHECKTEMPLATEVERIFY is used in this proposal as the
+preferred method to bind the proposed withdrawal to a particular set of final
+outputs, OP_VAULT is composable with other (and future) opcodes to
+facilitate other kinds of withdrawal processes.
+
+[[File:bip-0345/opvault.drawio.png|frame|center]]
+
+
+=== Transaction types ===
+
+The vault has a number of stages, some of them optional:
+
+* '''vault transaction''': encumbers some coins into a Taproot structure that includes at least one OP_VAULT leaf and one OP_VAULT_RECOVER leaf.
+
+* '''trigger transaction''': spends one or more OP_VAULT-tapleaf inputs into an output which is encumbered by a timelocked withdrawal to a fixed set of outputs, chosen at trigger time. This publicly broadcasts the intent to withdraw to some specific set of outputs.
The trigger transaction may have an additional output which allocates some of the vault balance into a partial "revault," which simply encumbers the revaulted portion of the value into the same scriptPubKey as the OP_VAULT-containing input(s) being spent.
+
+* '''withdrawal transaction''': spends the timelocked, destination-locked trigger inputs into a compatible set of final withdrawal outputs (per, e.g., a CHECKTEMPLATEVERIFY hash), after the trigger inputs have matured per the spend delay. Timelocked CTV transactions are the motivating usage of OP_VAULT, but any script template can be specified during the creation of the vault.
+
+* '''recovery transaction''': spends one or more vault inputs via OP_VAULT_RECOVER tapleaf to the prespecified recovery path, which can be done at any point before the withdrawal transaction confirms. Each input can optionally require a witness satisfying a specified ''recovery authorization'' script, an optional script prefixing the OP_VAULT_RECOVER fragment. The use of recovery authorization has certain trade-offs discussed later.
+
+
+=== Fee management ===
+
+A primary consideration of this proposal is how fee management is handled.
+Providing dynamic fee management is critical to the operation of a vault, since
+
+* precalculated fees are prone to making transactions unconfirmable in high fee environments, and
+* a fee wallet that is prespecified might be compromised or lost before use.
+
+But dynamic fee management can introduce
+[https://bitcoinops.org/en/topics/transaction-pinning/ pinning vectors]. Care
+has been taken to avoid unnecessarily introducing these vectors when using the new
+destination-based spending policies that this proposal introduces.
+
+Originally, this proposal had a hard dependency on reformed transaction
+nVersion=3 policies, including ephemeral anchors, but it has since been revised
+to simply benefit from these changes in policy as well as other potential fee
+management mechanisms.
+
+
+== Specification ==
+
+The tapscript opcodes OP_SUCCESS187 (0xbb) and
+OP_SUCCESS188 (0xbc) are constrained with new rules
+to implement OP_VAULT and OP_VAULT_RECOVER,
+respectively.
+
+=== OP_VAULT evaluation ===
+
+When evaluating OP_VAULT (OP_SUCCESS187,
+0xbb), the expected format of the stack, shown top to bottom, is:
+
+
+
+
+[ leaf-update script data items ... ]
+
+
+
+
+
+where
+
+* is a minimally-encoded data push of a serialized script. In conjunction with the leaf-update data items, it dictates the tapleaf script in the output taptree that will replace the one currently executing.
+** Otherwise, script execution MUST fail and terminate immediately.
+
+* is an up to 4-byte minimally encoded CScriptNum indicating how many leaf-update script items should be popped off the stack. '''Why only prefix with data pushes?''' Prefixing the leaf-update-script-body with opcodes opens up the door to prefix OP_SUCCESSX opcodes, to name a single issue only, side-stepping the validation that was meant to be run by the committed script.
+** If this value does not decode to a valid CScriptNum, script execution MUST fail and terminate immediately.
+** If this value is less than 0, script execution MUST fail and terminate immediately.
+** If there are fewer than 3 items following the items on the stack, script execution MUST fail and terminate immediately. In other words, after popping , there must be at least 3 + items remaining on the stack.
+
+* The following stack items are popped off the stack and prefixed as minimally-encoded push-data arguments to the to construct the expected tapleaf replacement script.
+
+* is an up to 4-byte minimally encoded CScriptNum indicating the index of the output which, in conjunction with an optional revault output, carries forward the value of this input, and has an identical taptree aside from the currently executing leaf.
+** If this value does not decode to a valid CScriptNum, script execution MUST fail and terminate immediately.
+** If this value is less than 0 or is greater than or equal to the number of outputs, script execution MUST fail and terminate immediately.
+
+* is an up to 4-byte minimally encoded CScriptNum optionally indicating the index of an output which, in conjunction with the trigger output, carries forward the value of this input, and has an identical scriptPubKey to the current input.
+** If this value does not decode to a valid CScriptNum, script execution MUST fail and terminate immediately.
+** If this value is greater than or equal to the number of outputs, script execution MUST fail and terminate immediately.
+** If this value is negative and not equal to -1, script execution MUST fail and terminate immediately.'''Why is -1 the only allowable negative value for revault-vout-idx?''' A negative revault index indicates that no revault output exists; if this value were allowed to be any negative number, the witness could be malleated (and bloated) while a transaction is waiting for confirmation.
+
+* is an up to 7-byte minimally encoded CScriptNum indicating the number of satoshis being revaulted.
+** If this value does not decode to a valid CScriptNum, script execution MUST fail and terminate immediately.
+** If this value is not greater than or equal to 0, script execution MUST fail and terminate immediately.
+** If this value is non-zero but is negative, script execution MUST fail and terminate immediately.
+** If this value is zero but is not -1, script execution MUST fail and terminate immediately.
+
+After the stack is parsed, the following validation checks are performed:
+
+* Decrement the per-script sigops budget (see [https://github.com/bitcoin/bips/blob/master/bip-0342.mediawiki#user-content-Resource_limits BIP-0342]) by 60'''Why is the sigops cost for OP_VAULT set to 60?''' To determine the validity of a trigger output, OP_VAULT must perform an EC multiplication and hashing proportional to the length of the control block in order to generate the output's expected TapTweak. This has been measured to have a cost in the worst case (max length control block) of roughly twice a Schnorr verification. Because the hashing cost could be mitigated by caching midstate, the cost is 60 and not 100.; if the budget is brought below zero, script execution MUST fail and terminate immediately.
+* Let the output designated by be called ''triggerOut''.
+* If the scriptPubKey of ''triggerOut'' is not a version 1 witness program, script execution MUST fail and terminate immediately.
+* Let the script constructed by taking the and prefixing it with minimally-encoded data pushes of the leaf-update script data items be called the ''leaf-update-script''.
+* If the scriptPubKey of ''triggerOut'' does not match that of a taptree that is identical to that of the currently evaluated input, but with the leaf script substituted for ''leaf-update-script'', script execution MUST fail and terminate immediately.
+** Note: the parity bit of the resulting taproot output is allowed to vary, so both values for the new output must be checked.
+* Let the output designated by (if the index value is non-negative) be called ''revaultOut''.
+* If the scriptPubKey of ''revaultOut'' is not equal to the scriptPubKey of the input being spent, script execution MUST fail and terminate immediately.
+* Implementation recommendation: if the sum of the amounts of ''triggerOut'' and ''revaultOut'' (if any) are not greater than or equal to the value of this input, script execution SHOULD fail and terminate immediately. This ensures that (at a minimum) the vaulted value for this input is carried through.
+** Amount checks are ultimately done with deferred checks, but this check can help short-circuit obviously invalid spends.
+* Queue a deferred check'''What is a deferred check and why does this proposal require them for correct script evaluation?''' A deferred check is a validation check that is executed only after all input scripts have been validated, and is based on aggregate information collected during each input's EvalScript run.
Currently, the validity of each input is (usually) checked concurrently across all inputs in a transaction. Because this proposal allows batching the spend of multiple vault inputs into a single recovery or withdrawal output, we need a mechanism to ensure that all expected values per output can be summed and then checked. This necessitates the introduction of an "aggregating" set of checks which can only be executed after each input's script is evaluated. Note that similar functionality would be required for batch input validation or cross-input signature aggregation. that ensures the satoshis for this input's nValue minus are included within the output nValue found at .
+* Queue a deferred check that ensures satoshis, if non-zero, are included within the output's nValue found at .
+** These deferred checks could be characterized in terms of the pseudocode below (in ''Deferred checks'') as TriggerCheck(input_amount, , , ).
+
+If none of the conditions fail, a single true value (0x01) is left on the stack.
+
+=== OP_VAULT_RECOVER evaluation ===
+
+When evaluating OP_VAULT_RECOVER (OP_SUCCESS188,
+0xbb), the expected format of the stack, shown top to bottom, is:
+
+
+
+
+
+
+where
+
+* is a 32-byte data push.
+** If this is not 32 bytes in length, script execution MUST fail and terminate immediately.
+* is an up to 4-byte minimally encoded CScriptNum indicating the index of the recovery output.
+** If this value does not decode to a valid CScriptNum, script execution MUST fail and terminate immediately.
+** If this value is less than 0 or is greater than or equal to the number of outputs, script execution MUST fail and terminate immediately.
+
+After the stack is parsed, the following validation checks are performed:
+
+* Let the output at index be called ''recoveryOut''.
+* If the scriptPubKey of ''recoveryOut'' does not have a tagged hash equal to (tagged_hash("VaultRecoverySPK", recoveryOut.scriptPubKey) == recovery-sPK-hash, where tagged_hash() is from the [https://github.com/bitcoin/bips/blob/master/bip-0340/reference.py BIP-0340 reference code]), script execution MUST fail and terminate immediately.
+** Implementation recommendation: if ''recoveryOut'' does not have an nValue greater than or equal to this input's amount, the script SHOULD fail and terminate immediately.
+* Queue a deferred check that ensures the nValue of ''recoveryOut'' contains the entire nValue of this input.'''How do recovery transactions pay for fees?''' If the recovery is unauthorized, fees are attached either via CPFP with an ephemeral anchor or as inputs which are solely spent to fees (i.e. no change output). If the recovery is authorized, fees can be attached in any manner, e.g. unrelated inputs and outputs or CPFP via anchor.
+** This deferred check could be characterized in terms of the pseudocode below as RecoveryCheck(, input_amount).
+
+If none of the conditions fail, a single true value (0x01) is left on the stack.
+
+=== Deferred check evaluation ===
+
+Once all inputs for a transaction are validated per the rules above, any
+deferred checks queued MUST be evaluated.
+
+The Python pseudocode for this is as follows:
+
+
+class TriggerCheck:
+ """Queued by evaluation of OP_VAULT (withdrawal trigger)."""
+ input_amount: int
+ revault_amount: int
+ trigger_vout_idx: int
+ revault_vout_idx: int
+
+
+class RecoveryCheck:
+ """Queued by evaluation of OP_VAULT_RECOVER."""
+ input_amount: int
+ vout_idx: int
+
+
+def validate_deferred_checks(checks: [DeferredCheck], tx: Transaction) -> bool:
+ """
+ Ensure that all value from vault inputs being triggered or recovered is preserved
+ in suitable output nValues.
+ """
+ # Map to hold expected output values.
+ out_map: Dict[int, int] = defaultdict(lambda: 0)
+
+ for c in checks:
+ if isinstance(c, TriggerCheck):
+ out_map[c.trigger_vout_idx] += (c.input_amount - c.revault_amount)
+
+ if c.revault_amount > 0:
+ out_map[c.revault_vout_idx] += c.revault_amount
+
+ elif isinstance(c, RecoveryCheck):
+ out_map[c.vout_idx] += c.input_amount
+
+ for (vout_idx, amount_sats) in out_map.items():
+ # Trigger/recovery value can be greater than the constituent vault input
+ # amounts.
+ if tx.vout[vout_idx].nValue < amount_sats:
+ return False
+
+ return True
+
+
+If the above procedure, or an equivalent, returns false, script execution MUST fail and terminate
+immediately.
+
+This ensures that all compatible vault inputs can be batched into shared
+corresponding trigger or recovery outputs while preserving their entire input value.
+
+
+== Policy changes ==
+
+In order to prevent possible pinning attacks, recovery transactions must be replaceable.
+
+* When validating an OP_VAULT_RECOVER input being spent, the script MUST fail (by policy, not consensus) and terminate immediately if both'''Why are recovery transactions required to be replaceable?''' In the case of unauthorized recoveries, an attacker may attempt to pin recovery transactions by broadcasting a "rebundled" version with a low fee rate. Vault owners must be able to overcome this with replacement. In the case of authorized recovery, if an attacker steals the recovery authorization key, the attacker may try to pin the recovery transaction during theft. Requiring replaceability ensures that the owner can always raise the fee rate of the recovery transaction, even if they are RBF rule #3 griefed in the process.
+*# the input is not marked as opt-in replaceable by having an nSequence number less than 0xffffffff - 1, per [https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki BIP-0125], and
+*# the version of the recovery transaction has an nVersion other than 3.
+
+If the script containing OP_VAULT_RECOVER is 34 bytes or less34 bytes is the length of a recovery script that consists solely of OP_VAULT_RECOVER., let
+it be called "unauthorized," because there is no script guarding the recovery
+process. In order to prevent pinning attacks in the case of unauthorized
+recovery - since the spend of the input (and the structure of the
+transaction) is not authorized by a signed signature message - the output structure of
+unauthorized recovery transaction is limited.
+
+* If the recovery is unauthorized, the recovery transaction MUST (by policy) abide by the following constraints:
+** If the spending transaction has more than two outputs, the script MUST fail and terminate immediately.
+** If the spending transaction has two outputs, and the output which is not ''recoveryOut'' is not an [https://github.com/instagibbs/bips/blob/ephemeral_anchor/bip-ephemeralanchors.mediawiki ephemeral anchor], the script MUST fail and terminate immediately.'''Why can unauthorized recoveries only process a single recovery path?''' Because there is no signature required for unauthorized recoveries, if additional outputs were allowed, someone observing a recovery in the mempool would be able to rebundle and broadcast the recovery with a lower fee rate.
+
+== Implementation ==
+
+A sample implementation is available on bitcoin-inquisition [https://github.com/jamesob/bitcoin/tree/2023-01-opvault-inq here], with an associated [https://github.com/bitcoin-inquisition/bitcoin/pull/21 pull request].
+
+
+== Applications ==
+
+The specification above, perhaps surprisingly, does not specifically cover how a relative timelocked withdrawal process with a fixed target is implemented. The tapleaf update semantics specified in OP_VAULT as well as the output-based authorization enabled by OP_VAULT_RECOVER can be used to implement a vault, but they are incomplete without two other pieces:
+
+* a way to enforce relative timelocks, like OP_CHECKSEQUENCEVERIFY, and
+* a way to enforce that proposed withdrawals are ultimately being spent to a precise set of outputs, like OP_CHECKTEMPLATEVERIFY.
+
+These two pieces are combined with the tapleaf update capabilities of
+OP_VAULT to create a vault, described below.
+
+=== Creating a vault ===
+
+In order to vault coins, they can be spent into a witness v1 scriptPubKey
+that contains a taptree of the form
+
+
+tr(,
+ leaves = {
+ recover:
+ OP_VAULT_RECOVER,
+
+ trigger:
+ OP_CHECKSIGVERIFY (i)
+ 2 $leaf-update-script-body OP_VAULT, (ii)
+
+ ... [ possibly other leaves ]
+ }
+)
+
+where
+* $leaf-update-script-body is, for example, OP_CHECKSEQUENCEVERIFY OP_DROP OP_CHECKTEMPLATEVERIFY.
+** This is one example of a trigger script, but ''any'' script fragment can be used, allowing the creation of different types of vaults. For example, you could use OP_CHECKSEQUENCEVERIFY OP_DROP OP_CHECKSIG to do a time-delayed transfer of the coins to another key. This also future-proofs OP_VAULT for future scripting capabilities.
+* The script fragment in (i) is called the "trigger authorization," because it gates triggering the withdrawal. This can be done in whatever manner the wallet designer would like.
+* The script fragment in (ii) is the incomplete OP_VAULT invocation - it will be completed once the rest of the parameters (the CTV target hash, trigger vout index, and revault vout index) are provided by the trigger transaction witness.
+
+Typically, the internal key for the vault taproot output will be specified so
+that it is controlled by the same descriptor as the recovery path, which
+facilitates another (though probably unused) means of recovering the vault
+output to the recovery path. This has the potential advantage of recovering the
+coin without ever revealing it was a vault.
+
+Otherwise, the internal key can be chosen to be an unspendable NUMS point to
+force execution of the taptree contents.
+
+=== Triggering a withdrawal ===
+
+To make use of the vault, and spend it towards some output, we construct a spend
+of the above tr() output that simply replaces the "trigger" leaf with the
+full leaf-update script (in this case, a timelocked CTV script):
+
+
+Witness stack:
+
+-
+- (-1 if none)
+-
+-
+-
+- [ "trigger" leaf script contents ]
+- [ taproot control block prompting a script-path spend to "trigger" leaf ]
+
+Output scripts:
+
+[
+ tr(,
+ leaves = {
+ recover:
+ OP_VAULT_RECOVER, <-- unchanged
+
+ trigger:
+
+ OP_CHECKSEQUENCEVERIFY OP_DROP OP_CHECKTEMPLATEVERIFY <-- changed per the
+ leaf-update
+ rules of OP_VAULT
+ ... [ possibly other leaves ]
+ }
+ ),
+
+ [ optional revault output with the
+ same sPK as the original vault output ],
+]
+
+
+OP_VAULT has allowed the taptree to be transformed so that the trigger leaf
+becomes a timelocked CTV script, which is what actually facilitates the announced
+withdrawal. The withdrawal is interruptible by the recovery path because the
+"recover" leaf is preserved exactly from the original taptree.
+
+Note that the CTV hash is specified at spend time using the witness stack, and
+"locked in" via the OP_VAULT spend rules which assert its existence in the output.
+
+The vault funds can be recovered at any time prior to the spend of the
+timelocked CTV script by way of a script-path spend using the "recover" leaf.
+
+
+=== Recovery authorization ===
+
+When configuring a vault, the user must decide if they want to have the
+recovery process gated by a script fragment prefixing the
+OP_VAULT_RECOVER instruction in the "recover" leaf. Its use
+entails trade-offs.
+
+==== Unauthorized recovery ====
+
+Unauthorized recovery simplifies vault use in that recovery never requires additional information aside from the location of the vault outpoints and the recovery path - the "authorization" is simply the reveal of the recovery path, i.e. the preimage of .
+
+But because this reveal is the only authorization necessary to spend the vault coins to recovery, the user must expect to recover all such vaults at once, since an observer can replay this recovery (provided they know the outpoints).
+
+Additionally, unauthorized recovery across multiple distinct recovery paths
+cannot be done in the same transaction, and fee control is more constrained:
+because the output structure is limited for unauthorized recovery, fee
+management relies either on inputs which are completely spent to fees or the
+use of the optional ephemeral anchor and package relay.
+
+These limitations are to avoid pinning attacks.
+
+==== Authorized recovery ====
+
+With authorized recovery, the user must keep track of an additional piece of information: how to solve the recovery authorization script fragment when recovery is required.
+
+If this key is lost, the user will be unable to initiate the recovery process for their coins. If an attacker obtains the recovery key, they may grief the user during the recovery process by constructing a low fee rate recovery transaction and broadcasting it (though they will not be able to pin because of the replaceability requirement on recovery transactions).
+
+However, authorized recovery configurations have significant benefits. Batched recoveries are possible for vaults with otherwise incompatible recovery parameters. Fee management is much more flexible, since authorized recovery transactions are "free form" and unrelated inputs and outputs can be added, potentially to handle fees.
+
+==== Recommendation: use a simple, offline recovery authorization key seed ====
+
+The benefits of batching and fee management that authorized recovery provides are significant. If the recovery authorization key falls into the hands of an attacker, the outcome is not catastrophic, whereas if the user loses their recovery authorization key as well as their trigger key, the result is likely coin loss. Consequently, the author's recommendation is to use a simple seed for the recovery authorization key that can be written down offline and replicated.
+
+Note that the recovery authorization key '''is not''' the recovery path key, and
+this is '''much different''' than any recommendation on how to generate the
+recovery path key itself.
+
+=== Address reuse and recovery ===
+
+When creating a vault, four factors affect the resulting P2TR address:
+# The internal pubkey (likely belonging to the recovery wallet)
+# The recovery leaf
+# The trigger leaf
+# Any other leaves that exist in the taptree
+
+The end user has the option of varying certain contents along descriptors in
+order to avoid reusing vault addresses without affecting key management, e.g.
+the trigger authorization pubkeys.
+
+Note that when using unauthorized recovery, the reveal of the
+recovery scriptPubKey will allow any observer to initiate the recovery process
+for any vault with matching recovery params, provided they are able to locate
+the vault outpoints. As a result, it is recommended to expect that
+'''all outputs sharing an identical unauthorized should be recovered together'''.
+
+This situation can be avoided with a comparable key management model by varying
+the generation of each vault's recovery scriptPubKey along a single descriptor,
+but note that this will prevent recovering multiple separate vaults into a single
+recovery output.
+
+Varying the internal pubkey will prevent batching the trigger of multiple vault
+inputs into a single trigger output; consequently it is recommended that users
+instead vary some component of the trigger leaf script if address reuse is
+undesirable. Users could vary the trigger pubkey along a descriptor, keeping
+the recovery path and internal-pubkey the same, which both avoids reusing
+addresses and allows batched trigger and recovery operations.
+
+==== Recommendation: generate new recovery addresses for new trigger keys ====
+
+If using unauthorized recovery, it is recommended that you do not share recovery scriptPubKeys
+across separate trigger keys. If one trigger key is compromised, that will necessitate the (unauthorized)
+recovery of all vaults with that trigger key, which will reveal the recovery path preimage. This
+means that an observer might be able to initiate recovery for vaults controlled by an uncompromised
+trigger key.
+
+==== Fee management ====
+
+Fees can be managed in a variety of ways, but it's worth noting that both
+trigger and recovery transactions must preserve the total value of vault
+inputs, so vaulted values cannot be repurposed to pay for fees. This does not
+apply to the withdrawal transaction, which can allocate value arbitrarily.
+
+In the case of vaults that use recovery authorization, all transactions can
+"bring their own fees" in the form of unrelated inputs and outputs. These
+transactions are also free to specify ephemeral anchors, once the related relay
+policies are deployed. This means that vaults using recovery authorization have
+no dependence on the deploy of v3 relay policy.
+
+For vaults using unauthorized recovery, the recovery
+transaction relies on the use of either fully-spent fee inputs or an ephemeral
+anchor output. This means that vaults which do not use recovery authorization
+are essentially dependent on v3 transaction relay policy being deployed.
+
+=== Batching ===
+
+==== During trigger ====
+
+OP_VAULT outputs with the same taptree, aside from slightly
+different trigger leaves, can be batched together in the same withdrawal
+process. Two "trigger" leaves are compatible if they have the same
+OP_VAULT arguments.
+
+Note that this allows the trigger authorization -- the script prefixing the
+OP_VAULT invocation -- to differ while still allowing batching.
+
+Trigger transactions can act on multiple incompatible OP_VAULT
+input sets, provided each set has a suitable associated ''triggerOut''
+output.
+
+Since SIGHASH_DEFAULT can be used to sign the trigger
+authorization, unrelated inputs and outputs can be included, possibly to
+facilitate fee management or the batch withdrawal of incompatible vaults.
+
+==== During withdrawal ====
+
+During final withdrawal, multiple trigger outputs can be used towards the same
+withdrawal transaction provided that they share identical
+ parameters. This facilitates batched
+withdrawals.
+
+==== During recovery ====
+
+OP_VAULT_RECOVER outputs with the same
+can be recovered into the same output.
+
+Recovery-incompatible vaults which have authorized recovery can be recovered in
+the same transaction, so long as each set (grouped by
+) has an associated ''recoveryOut''. This allows
+unrelated recoveries to share common fee management.
+
+=== Watchtowers ===
+
+The value of vaults is contingent upon having monitoring in place that will
+alert the owner when unexpected spends are taking place. This can be done in a
+variety of ways, with varying degrees of automation and trust in the
+watchtower.
+
+In the maximum-trust case, the watchtower can be fully aware of all vaulted
+coins and has the means to initiate the recovery process if spends are not
+pre-reported to the watchtower.
+
+In the minimum-trust case, the user can supply a probabilistic filter of which
+coins they wish to monitor; the watchtower would then alert the user if any
+coins matching the filter move, and the user would be responsible for ignoring
+false positives and handling recovery initiation.
+
+=== Output descriptors ===
+
+Output descriptors for vault-related outputs will be covered in a subsequent BIP.
+
+== Deployment ==
+
+Activation mechanism is to be determined.
+
+This BIP should be deployed concurrently with BIP-0119 to enable full use of vaults.
+
+== Backwards compatibility ==
+
+OP_VAULT and OP_VAULT_RECOVER replace, respectively,
+the witness v1-only opcodes OP_SUCCESS187 and OP_SUCCESS188 with stricter
+verification semantics. Consequently, scripts using those opcodes which
+previously were valid will cease to be valid with this change.
+
+Stricter verification semantics for an OP_SUCCESSx opcode are a soft fork, so
+existing software will be fully functional without upgrade except for mining
+and block validation.
+
+Backwards compatibility considerations are very comparable to previous
+deployments for OP_CHECKSEQUENCEVERIFY and OP_CHECKLOCKTIMEVERIFY (see
+[https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki BIP-0065] and
+[https://github.com/bitcoin/bips/blob/master/bip-0112.mediawiki BIP-0112]).
+
+
+== Rationale ==
+
+
+
+== References ==
+
+* [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2016-February/012470.html [bitcoin-dev] Bitcoin Vaults (2016)]
+* [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-February/015793.html [bitcoin-dev] Simple lock/unlock mechanism (2018)]
+* [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2020-April/017755.html [bitcoin-dev] On-chain vaults prototype (2020)]
+* [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2021-September/019419.html [bitcoin-dev] TAPLEAF_UPDATE_VERIFY covenant opcode (2021)]
+* [https://arxiv.org/abs/2005.11776 Custody Protocols Using Bitcoin Vaults (2020)]
+* [https://jameso.be/vaults.pdf Vaults and Covenants (2023)]
+
+== Acknowledgements ==
+
+The author would like to thank
+
+* AJ Towns and Greg Sanders for discussion, numerous suggestions that improved the proposal, and advice.
+* Jeremy Rubin for inspiration, advice, and mentorship.
+* BL for discussion and insight.
+* John Moffett for early feedback and a test case demonstrating a recursive script evaluation attack.
+* Johan Halseth for providing conceptual review and pointing out a pinning attack.
+* Pieter Wuille for implementation advice.
diff --git a/bip-0345/opvault.drawio.png b/bip-0345/opvault.drawio.png
new file mode 100644
index 0000000000..702189d156
Binary files /dev/null and b/bip-0345/opvault.drawio.png differ
diff --git a/bip-0345/vaults-Basic.png b/bip-0345/vaults-Basic.png
new file mode 100644
index 0000000000..591b633dad
Binary files /dev/null and b/bip-0345/vaults-Basic.png differ
diff --git a/bip-0345/vaults.drawio b/bip-0345/vaults.drawio
new file mode 100644
index 0000000000..6f7fd4ebc2
--- /dev/null
+++ b/bip-0345/vaults.drawio
@@ -0,0 +1,1113 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/bip-0345/withdrawal-comparison.drawio.png b/bip-0345/withdrawal-comparison.drawio.png
new file mode 100644
index 0000000000..8a76d20722
Binary files /dev/null and b/bip-0345/withdrawal-comparison.drawio.png differ
diff --git a/bip-0347.mediawiki b/bip-0347.mediawiki
new file mode 100644
index 0000000000..0aed70db49
--- /dev/null
+++ b/bip-0347.mediawiki
@@ -0,0 +1,113 @@
+
+
+==Abstract==
+
+This BIP introduces OP_CAT as a tapscript opcode which allows the concatenation of two values on the stack. OP_CAT would be activated via a soft fork by redefining the opcode OP_SUCCESS126 (126 in decimal and 0x7e in hexadecimal). This is the same opcode value used by the original OP_CAT.
+
+== Copyright ==
+
+This document is licensed under the 3-clause BSD license.
+
+==Specification==
+
+When evaluated, the OP_CAT instruction:
+# Pops the top two values off the stack,
+# concatenates the popped values together in stack order,
+# and then pushes the concatenated value on the top of the stack.
+
+Given the stack ''[x1, x2]'', where ''x2'' is at the top of the stack, OP_CAT will push ''x1 || x2'' onto the stack. By ''||'' we denote concatenation. OP_CAT fails if there are fewer than two values on the stack or if a concatenated value would have a combined size greater than the maximum script element size of 520 bytes.
+
+This opcode would be activated via a soft fork by redefining the tapscript opcode OP_SUCCESS126 (126 in decimal and 0x7e in hexadecimal) to OP_CAT.
+
+==Motivation==
+
+Bitcoin Tapscript lacks a general purpose way of combining objects on the stack, restricting the expressiveness and power of Tapscript. This prevents, among many other things, the ability to construct and evaluate merkle trees and other hashed data structures in Tapscript. OP_CAT, by adding a general purpose way to concatenate stack values, would overcome this limitation and greatly increase the functionality of Tapscript.
+
+OP_CAT aims to expand the toolbox of the tapscript developer with a simple, modular, and useful opcode in the spirit of Unix R. Pike and B. Kernighan, "Program design in the UNIX environment", 1983, https://harmful.cat-v.org/cat-v/unix_prog_design.pdf. To demonstrate the usefulness of OP_CAT below we provide a non-exhaustive list of some usecases that OP_CAT would enable:
+
+* Bitstream, a protocol for the atomic swap (fair exchange) of bitcoins for decryption keys, that enables decentralized file hosting systems paid in Bitcoin. While such swaps are currently possible on Bitcoin without OP_CAT, they require the use of complex and computationally expensive Verifiable Computation cryptographic techniques. OP_CAT would remove this requirement on Verifiable Computation, making such protocols far more practical to build in Bitcoin. R. Linus, "BitStream: Decentralized File Hosting Incentivised via Bitcoin Payments", 2023, https://robinlinus.com/bitstream.pdf
+* Tree signatures provide a multisignature script whose size can be logarithmic in the number of public keys and can encode spend conditions beyond n-of-m. For instance a transaction less than 1KB in size could support tree signatures with up to 4,294,967,296 public keys. This also enables generalized logical spend conditions. P. Wuille, "Multisig on steroids using tree signatures", 2015, https://blog.blockstream.com/en-treesignatures/
+* Post-Quantum Lamport signatures in Bitcoin transactions. Lamport signatures merely require the ability to hash and concatenate values on the stack. J. Rubin, "[bitcoin-dev] OP_CAT Makes Bitcoin Quantum Secure [was CheckSigFromStack for Arithmetic Values]", 2021, https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2021-July/019233.html It has been proposed that if ECDSA is broken or a powerful computer was on the horizon, there might be an effort to protect ownership of bitcoins by allowing people to mark their taproot outputs as "script-path only" and then move their coins into such outputs with a leaf in the script tree requiring a Lamport signature. It is an open question if a tapscript commitment would preserve the quantum resistance of Lamport signatures. Beyond this question, the use of Lamport Signatures in taproot outputs is unlikely to be quantum resistant even if the script spend-path is made quantum resistant. This is because taproot outputs can also be spent with a key. An attacker with a sufficiently powerful quantum computer could bypass the taproot script spend-path by finding the discrete log of the taproot output and thus spending the output using the key spend-path. The use of "Nothing Up My Sleeve" (NUMS) points as described in [[bip-0341.mediawiki|BIP341]] to disable the key spend-path does not disable the key spend-path against a quantum attacker as NUMS relies on the hardness of finding discrete logs. We are not aware of any mechanism which could disable the key spend-path in a taproot output without a softfork change to taproot.
+* Non-equivocation contracts T. Ruffing, A. Kate, D. Schröder, "Liar, Liar, Coins on Fire: Penalizing Equivocation by Loss of Bitcoins", 2015, https://web.archive.org/web/20221023121048/https://publications.cispa.saarland/565/1/penalizing.pdf in tapscript provide a mechanism to punish equivocation/double spending in Bitcoin payment channels. OP_CAT enables this by enforcing rules on the spending transaction's nonce. The capability is a useful building block for payment channels and other Bitcoin protocols.
+* Vaults M. Moser, I. Eyal, and E. G. Sirer, Bitcoin Covenants, http://fc16.ifca.ai/bitcoin/papers/MES16.pdf which are a specialized covenant that allows a user to block a malicious party who has compromised the user's secret key from stealing the funds in that output. As shown in A. Poelstra, "CAT and Schnorr Tricks II", 2021, https://www.wpsoftware.net/andrew/blog/cat-and-schnorr-tricks-ii.html OP_CAT is sufficient to build vaults in Bitcoin.
+* Replicating CheckSigFromStack A. Poelstra, "CAT and Schnorr Tricks I", 2021, https://www.wpsoftware.net/andrew/blog/cat-and-schnorr-tricks-i.html which would allow the creation of simple covenants and other advanced contracts without having to presign spending transactions, possibly reducing complexity and the amount of data that needs to be stored. Originally shown to work with Schnorr signatures, this result has been extended to ECDSA signatures R. Linus, "Covenants with CAT and ECDSA", 2023, https://gist.github.com/RobinLinus/9a69f5552be94d13170ec79bf34d5e85#file-covenants_cat_ecdsa-md.
+
+OP_CAT was available in early versions of Bitcoin.
+In 2010, a single commit disabled OP_CAT, along with another 15 opcodes.
+Folklore states that OP_CAT was removed in this commit because it enabled the construction of a script whose evaluation could have memory usage exponential in the size of the script.
+For example, a script that pushed a 1-byte value on the stack and then repeated the opcodes OP_DUP, OP_CAT 40 times would result in a stack element whose size was greater than 1 terabyte assuming no maximum stack element size. As Bitcoin at that time had a maximum stack element size of 5000 bytes, the effect of this expansion was limited to 5000 bytes.
+This is no longer an issue because tapscript enforces a maximum stack element size of 520 bytes.
+
+
+==Rationale==
+
+Our decision to reenable OP_CAT by redefining a tapscript OP_SUCCESSx opcode to OP_CAT was motivated to leverage the tapscript softfork opcode upgrade path introduced in [[bip-0342.mediawiki|BIP342]].
+
+We specifically choose to use OP_SUCCESS126 rather than another OP_SUCCESSx as OP_SUCCESS126 uses the same opcode value (126 in decimal and 0x7e in hexadecimal) that was used for OP_CAT prior to it being disabled in Bitcoin. This removes a potential source of confusion that would exist if we had a opcode value different from the one used in the original OP_CAT opcode.
+
+While the OP_SUCCESSx opcode upgrade path could enable us to increase the stack element size while reenabling OP_CAT, we wanted to separate the decision to change the stack element size limit from the decision to reenable OP_CAT. This BIP takes no position in favor or against increasing the stack element size limit.
+
+==Backwards Compatibility==
+
+OP_CAT usage in a non-tapscript script will continue to trigger the SCRIPT_ERR_DISABLED_OPCODE. The only change would be to OP_CAT usage in tapscript. This change to tapscript would be activated as a soft fork that redefines an OP_SUCCESSx opcode (OP_SUCCESS126) to OP_CAT.
+
+==Reference implementation==
+
+
+
+
+The value of MAX_SCRIPT_ELEMENT_SIZE is 520.
+
+This implementation is inspired by the original implementation of [https://github.com/bitcoin/bitcoin/blob/01cd2fdaf3ac6071304ceb80fb7436ac02b1059e/script.cpp#L381-L393 OP_CAT as it existed in the Bitcoin codebase] prior to the commit "misc changes" 4bd188cS. Nakamoto, "misc changes", Aug 25 2010, https://github.com/bitcoin/bitcoin/commit/4bd188c4383d6e614e18f79dc337fbabe8464c82#diff-27496895958ca30c47bbb873299a2ad7a7ea1003a9faa96b317250e3b7aa1fefR94 which disabled it:
+
+
+
+An alternative implementation of OP_CAT can be found in Elements Roose S., Elements Project, "Re-enable several disabled opcodes", 2019, https://github.com/ElementsProject/elements/commit/13e1103abe3e328c5a4e2039b51a546f8be6c60a#diff-a0337ffd7259e8c7c9a7786d6dbd420c80abfa1afdb34ebae3261109d9ae3c19R740-R759.
+
+==References==
+
+
+
+==Acknowledgements==
+
+We wish to acknowledge Dan Gould for encouraging and helping review this effort. We also want to thank Madars Virza, Jeremy Rubin, Andrew Poelstra, Bob Summerwill,
+Tim Ruffing and Johan T. Halseth for their feedback, review and helpful comments.
diff --git a/bip-0348.md b/bip-0348.md
new file mode 100644
index 0000000000..d65a0d75de
--- /dev/null
+++ b/bip-0348.md
@@ -0,0 +1,142 @@
+
+
+## Abstract
+
+This BIP describes a new opcode for the purpose of checking cryptographic
+signatures in bitcoin scripts against data from the stack.
+
+## Summary
+
+When verifying taproot script spends having leaf version 0xc0 (as defined in
+[BIP 342]), we propose `OP_CHECKSIGFROMSTACK` to replace `OP_SUCCESS204`
+(0xcc).
+
+`OP_CHECKSIGFROMSTACK` has semantics similar to `OP_CHECKSIG`, as specified
+below. Briefly, it pops 3 elements from the stack: a 32-byte public key, a
+message, and a signature. If the signature is valid for that public key and
+message, 1 is pushed to the stack. If the signature is the empty vector, 0 is
+pushed to the stack, and otherwise script execution fails.
+
+Only 32-byte keys are constrained. Similar to [BIP 341] unknown key types, for
+other key lengths no signature verification is performed and it is considered
+successful.
+
+## Specification
+
+* If fewer than 3 elements are on the stack, the script MUST fail and terminate immediately.
+* The public key (top element), message (second to top element), and signature (third from top element) are read from the stack.
+* The top three elements are popped from the stack.
+* If the public key size is zero, the script MUST fail and terminate immediately.
+* If the public key size is 32 bytes, it is considered to be a public key as described in [BIP 340]:
+ * If the signature is not the empty vector, the signature is validated against the public key and message according to [BIP 340]. Validation failure in this case immediately terminates script execution with failure.
+* If the public key size is not zero and not 32 bytes; the public key is of an unknown public key type. Signature verification for unknown public key types succeeds as if signature verification for a known public key type had succeeded.
+* If the script did not fail and terminate before this step, regardless of the public key type:
+ * If the signature is the empty vector: An empty vector is pushed onto the stack, and execution continues with the next opcode.
+ * If the signature is not the empty vector:
+ * The opcode is counted towards the sigops budget as described in [BIP 342].
+ * A 1-byte value 0x01 is pushed onto the stack.
+
+## Design Considerations
+
+1. Message hashing: [BIP 340] is compatible with any size of message and does not require it to be a securely hashed input, so the message is not hashed prior to [BIP 340] verification.
+2. Lack of verify semantics: Adding a single opcode for this purpose keeps the implementation and design simple. An earlier draft had a verify variant as a NOP upgrade, and if this functionality is later brought to legacy scripts, that would be a good time to add a verify variant.
+3. Add/multisig: No concession is made to `OP_CHECKMULTISIG` or `OP_CHECKSIGADD` semantics with `OP_CHECKSIGFROMSTACK`. In Tapscript, add semantics can be implemented with 1 additional vByte per key (`OP_TOALTSTACK OP_CHECKSIGFROMSTACK OP_FROMALTSTACK OP_ADD`).
+4. Splitting R/S on the stack: Implementing split/separate signatures is left as an exercise for other bitcoin upgrades, such as [BIP 347] (`OP_CAT`).
+5. APO-style ([BIP 118]) Taproot internal key: Rather than introducing an additional key type in this change, we suggest implementing `OP_INTERNALKEY` ([BIP 349]) or separately introducing that key type for all Tapscript signature checking operations in a separate change.
+
+## Resource Limits
+
+These opcodes are treated identically to other signature checking opcodes and
+count against the sigops and budget.
+
+## Motivation
+
+### LN Symmetry
+
+When combined with [BIP 119] (`OP_CHECKTEMPLATEVERIFY`/CTV),
+`OP_CHECKSIGFROMSTACK` (CSFS) can be used to implement Lightning Symmetry
+channels. The construction `OP_CHECKTEMPLATEVERIFY
+OP_CHECKSIGFROMSTACK` with a spend stack containing the CTV hash and a
+signature for it is logically equivalent to ` OP_CHECKSIG` and
+a signature over `SIGHASH_ALL|SIGHASH_ANYPREVOUTANYSCRIPT`. The
+`OP_CHECKSIGFROMSTACK` construction is 8 vBytes larger.
+
+Summary of alternatives:
+* CTV+CSFS is the minimal functionality needed for Lightning Symmetry but requires the use of an `OP_RETURN` for data availability
+* APO is the original design for Lightning Symmetry and uses the taproot annex for data availability.
+* LNHANCE (CTV+CSFS+IKEY+PC) is the most efficient and direct way currently designed to implement Lightning Symmetry.
+
+### Delegation
+
+Using a script like:
+` SWAP IF 2 PICK SWAP CSFS VERIFY ENDIF CHECKSIG`
+either direct verification or delegation can be achieved by the following
+unlock stacks: ` 0` or ` 1`
+
+### Advanced delegation when combined with [OP_PAIRCOMMIT] or OP_CAT
+
+Using a script like:
+`CLTV OVER PAIRCOMMIT TOALT CHECKSIGVERIFY FROMALT CSFS`
+or:
+`CLTV SHA256 OVER CAT TOALT CHECKSIGVERIFY FROMALT CSFS`
+with the unlock stack:
+``
+
+Delegates to a public key after a lock time, enabling delegation to various
+keys after various associated times.
+
+## Reference Implementation
+
+A reference implementation is provided here:
+
+https://github.com/bitcoin/bitcoin/pull/29270
+
+## Backward Compatibility
+
+By constraining the behavior of an OP_SUCCESS opcode,
+deployment of the BIP can be done in a backwards compatible, soft-fork manner.
+If anyone were to rely on the OP_SUCCESS behavior of
+`OP_SUCCESS204`, `OP_CHECKSIGFROMSTACK` would invalidate
+their spend.
+
+## Deployment
+
+TBD
+
+## Credits
+
+Reference implementation was made with reference to the implementation in
+Elements and started by moonsettler.
+
+## Copyright
+
+This document is licensed under the 3-clause BSD license.
+
+[BIP 119]: https://github.com/bitcoin/bips/blob/master/bip-0119.mediawiki
+
+[BIP 118]: https://github.com/bitcoin/bips/blob/master/bip-0118.mediawiki
+
+[BIP 340]: https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
+
+[BIP 341]: https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki
+
+[BIP 342]: https://github.com/bitcoin/bips/blob/master/bip-0342.mediawiki
+
+[BIP 349]: https://github.com/bitcoin/bips/blob/master/bip-0349.md
+
+[BIP 347]: https://github.com/bitcoin/bips/blob/master/bip-0347.mediawiki
+
+[OP_PAIRCOMMIT]: https://github.com/bitcoin/bips/pull/1699
+
+[mailing list]: https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2021-July/019192.html
diff --git a/bip-0349.md b/bip-0349.md
new file mode 100644
index 0000000000..22e07307cd
--- /dev/null
+++ b/bip-0349.md
@@ -0,0 +1,95 @@
+
+
+## Abstract
+
+This BIP describes a new tapscript opcode (`OP_INTERNALKEY`) which
+pushes the _taproot internal key_ to the stack.
+
+## Specification
+
+When verifying taproot script path spends having leaf version `0xc0` (as
+defined in [BIP 342]), `OP_INTERNALKEY` replaces `OP_SUCCESS203` (0xcb).
+`OP_INTERNALKEY` pushes the 32-byte x-only representation of the _taproot
+internal key_ (referred to as _p_), as defined in [BIP 341], to the stack.
+
+## Motivation
+
+### Key spend with additional conditions
+
+When building taproot outputs, especially those secured by an aggregate key
+representing more than one signer, the parties may wish to collaborate on
+signing with the _taproot internal key_, but only with additional script
+restrictions. In this case, `OP_INTERNALKEY` saves 8 vBytes.
+
+### Mitigated control block overhead for scripts using hash locks
+
+In cases where key path spending is not desired, the internal key may be set to
+a NUMS point whose bytes would otherwise be required in a tapscript. This could
+be used with any hash locked transaction, for example, to save 8 vBytes.
+
+Note: The internal key must be the X coordinate of a point on the SECP256K1
+curve, so any such hash must be checked and modified until it is such an X
+coordinate. This will typically take approximately 2 attempts.
+
+### Re-Keying with Merkle Root Preservation
+
+Consider a program such `CTV CSFS CLTV`. Such fragments are useful for LN-Symmetry applications.
+
+Such a program would be embedded within a Taproot script path, such as `TR(X, {CTV CSFS CLTV})`.
+
+Were the internal key to be updated from `X` to `Y`, the resulting program would be: `TR(Y, {CTV CSFS CLTV})`.
+
+The key in the leaf and the key-path would be mismatched. Were `OP_INTERNALKEY` to be used,
+the leaf would automatically re-key.
+E.g., `TR(X, {CTV OP_INTERNALKEY CSFS CLTV})` is equivalent to `TR(X, {CTV CSFS CLTV})`
+and `TR(Y, {CTV OP_INTERNALKEY CSFS CLTV})` is equivalent to `TR(Y, {CTV CSFS CLTV})`.
+
+While this particular example is contrived, the general technique of using `OP_INTERNALKEY`
+as updatable across an entire script tree is a helpful covenant primitive when it is desirable to
+invalidate signatures from prior states. For example, the theoretical `OP_TAPLEAFUPDATEVERIFY` opcode
+modifies the internal key directly to remove or add a participant, and `OP_INTERNALKEY` would ensure
+that the tweaked key is used from all script paths where desired.
+
+## Reference Implementation
+
+A reference implementation is provided here:
+
+https://github.com/bitcoin/bitcoin/pull/29269
+
+## Backward Compatibility
+
+By constraining the behavior of an OP_SUCCESS opcode, deployment of the BIP
+can be done in a backwards compatible, soft-fork manner. If anyone were to
+rely on the OP_SUCCESS behavior of `OP_SUCCESS203`, `OP_INTERNALKEY` would
+invalidate their spend.
+
+## Deployment
+
+TBD
+
+## Credits
+
+The concept for INTERNALKEY first arose in a [discussion](https://gnusha.org/bitcoin-wizards/2022-01-05.log) between Russell O'Connor
+and Jeremy Rubin in Bitcoin Wizards IRC, inspired by BIP-0118's key punning technique
+for the internal key. It was later
+drafted into this BIP by Brandon Black.
+
+
+## Copyright
+
+This document is licensed under the 3-clause BSD license.
+
+[BIP 341]: https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki
+
+[BIP 342]: https://github.com/bitcoin/bips/blob/master/bip-0342.mediawiki
diff --git a/bip-0350.mediawiki b/bip-0350.mediawiki
new file mode 100644
index 0000000000..4c30b8f841
--- /dev/null
+++ b/bip-0350.mediawiki
@@ -0,0 +1,336 @@
+
+ BIP: 350
+ Layer: Applications
+ Title: Bech32m format for v1+ witness addresses
+ Author: Pieter Wuille
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0350
+ Status: Final
+ Type: Standards Track
+ Created: 2020-12-16
+ License: BSD-2-Clause
+ Replaces: 173
+ Post-History: 2021-01-05: https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2021-January/018338.html [bitcoin-dev] Bech32m BIP: new checksum, and usage for segwit address
+
+
+==Introduction==
+
+===Abstract===
+
+This document defines an improved variant of Bech32 called '''Bech32m''', and amends BIP173 to use Bech32m for native segregated witness outputs of version 1 and later. Bech32 remains in use for segregated witness outputs of version 0.
+
+===Copyright===
+
+This BIP is licensed under the 2-clause BSD license.
+
+===Motivation===
+
+[[bip-0173.mediawiki|BIP173]] defined a generic checksummed base 32 encoded format called Bech32. It is in use for segregated witness outputs of version 0 (P2WPKH and P2WSH, see [[bip-0141.mediawiki|BIP141]]), and other applications.
+
+Bech32 has an unexpected [https://github.com/sipa/bech32/issues/51 weakness]: whenever the final character is a 'p', inserting or deleting any number of 'q' characters immediately preceding it does not invalidate the checksum. This does not affect existing uses of witness version 0 BIP173 addresses due to their restriction to two specific lengths, but may affect future uses and/or other applications using the Bech32 encoding.
+
+This document addresses that by specifying Bech32m, a variant of Bech32 that mitigates this insertion weakness and related issues.
+
+==Specification==
+
+We first specify the new checksum algorithm, and then document how it should be used for future Bitcoin addresses.
+
+===Bech32m===
+
+Bech32m modifies the checksum of the Bech32 specification, replacing the constant ''1'' that is xored into the checksum at the end with ''0x2bc830a3''. The resulting checksum verification and creation algorithm (in Python, cf. the code in [https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#Bech32|BIP173 Bech32 section]):
+
+
+BECH32M_CONST = 0x2bc830a3
+
+def bech32m_polymod(values):
+ GEN = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]
+ chk = 1
+ for v in values:
+ b = (chk >> 25)
+ chk = (chk & 0x1ffffff) << 5 ^ v
+ for i in range(5):
+ chk ^= GEN[i] if ((b >> i) & 1) else 0
+ return chk
+
+def bech32m_hrp_expand(s):
+ return [ord(x) >> 5 for x in s] + [0] + [ord(x) & 31 for x in s]
+
+def bech32m_verify_checksum(hrp, data):
+ return bech32m_polymod(bech32m_hrp_expand(hrp) + data) == BECH32M_CONST
+
+def bech32m_create_checksum(hrp, data):
+ values = bech32m_hrp_expand(hrp) + data
+ polymod = bech32m_polymod(values + [0,0,0,0,0,0]) ^ BECH32M_CONST
+ return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)]
+
+
+All other aspects of Bech32 remain unchanged, including its human-readable parts (HRPs).
+
+A combined function to decode both Bech32 and Bech32m simultaneously could be written using:
+
+
+
+which returns either None for failure, or one of the BECH32 / BECH32M enumeration values to indicate successful decoding according to the respective standard.
+
+===Addresses for segregated witness outputs===
+
+Version 0 outputs (specifically, P2WPKH and P2WSH addresses) continue to use Bech32'''Why not permit both Bech32 and Bech32m for v0 addresses?''' Permitting both encodings reduces the error detection capabilities (it makes it equivalent to only have 29 bits of checksum). as specified in BIP173. Addresses for segregated witness outputs version 1 through 16 use Bech32m. Again, all other aspects of the encoding remain the same, including the 'bc' HRP.
+
+To generate an address for a segregated witness output:
+
+* If its witness version is 0, encode it using Bech32.
+* If its witness version is 1 or higher, encode it using Bech32m.
+
+To decode an address, client software should either decode with both a Bech32 and a Bech32m decoder'''Can a single string simultaneously be valid as Bech32 and Bech32m?''' No, a valid Bech32 and Bech32m string will always differ by at least 3 characters if they are the same length., or use a decoder that supports both simultaneously. In both cases, the address decoder has to verify that the encoding matches what is expected for the decoded witness version (Bech32 for version 0, Bech32m for others).
+
+The following code demonstrates the checks that need to be performed. Refer to the Python code linked in the reference implementation section below for full details of the called functions.
+
+
+def decode(hrp, addr):
+ hrpgot, data, spec = bech32_decode(addr)
+ if hrpgot != hrp:
+ return (None, None)
+ decoded = convertbits(data[1:], 5, 8, False)
+ # Witness programs are between 2 and 40 bytes in length.
+ if decoded is None or len(decoded) < 2 or len(decoded) > 40:
+ return (None, None)
+ # Witness versions are in range 0..16.
+ if data[0] > 16:
+ return (None, None)
+ # Witness v0 programs must be exactly length 20 or 32.
+ if data[0] == 0 and len(decoded) != 20 and len(decoded) != 32:
+ return (None, None)
+ # Witness v0 uses Bech32; v1 through v16 use Bech32m.
+ if data[0] == 0 and spec != Encoding.BECH32 or data[0] != 0 and spec != Encoding.BECH32M:
+ return (None, None)
+ # Success.
+ return (data[0], decoded)
+
+
+'''Error locating'''
+
+Bech32m, like Bech32, does support locating'''What about error correction?''' As explained in BIP173, introducing error correction reduces the ability to detect errors. While it is technically possible to correct a small number of errors due to Bech32(m)'s nature as a BCH code, implementations should refrain from using this for more than indicating where an error may be present. the positions of a few substitution errors. To combine this functionality with
+the segregated witness addresses proposed by this document, simply try locating errors for both Bech32 and Bech32m. If only one finds error locations, report that one. If both do (which should be very rare),
+there are a number of options:
+* Report the one that needs fewer corrections (if they differ).
+* Eliminate the response(s) that are inconsistent. Any symbol that isn't on an error location can be checked. For example, if the witness version symbol is not an error location, and it doesn't correspond to the specification used (0 for Bech32, 1+ for Bech32m), that response can be eliminated.
+
+See the fancy Javascript decoder below for example of the above.
+
+==Compatibility==
+
+This document introduces a new encoding for v1 segregated witness outputs and higher versions. There should not be any compatibility issues on the receiver side; no wallets are creating v1 segregated witness addresses yet, as the output type is not usable on mainnet.
+
+On the other hand, the Bech32m proposal breaks forward-compatibility for sending to v1 and higher version segregated witness addresses. This incompatibility is [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2020-October/018236.html intentional]. An alternative design was [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2019-November/017460.html considered] where Bech32 remained in use for certain subsets of future addresses, but ultimately [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2020-December/018293.html discarded]. By introducing a clean break, we protect not only new software but also existing senders from the mutation issue, as new addresses will be incompatible with the existing Bech32 address validation. [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2020-November/018268.html Experiments] by Taproot proponents had shown that hardly any wallets and services supported sending to higher segregated witness output versions, so little is lost by [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2020-December/018298.html breaking] forward-compatibility. Furthermore, those experiments identified cases in which segregated witness implementations would have caused wallets to burn funds when sending to version 1 addresses. In case it is still in use, the chosen approach will prevent such software from destroying funds when attempting to send to a Bech32m address.
+
+==Reference implementations==
+
+* Reference encoder and decoder:
+** [https://github.com/sipa/bech32/blob/master/ref/python Reference Python implementation]
+** [https://github.com/sipa/bech32/blob/master/ref/c Reference C implementation]
+** [https://github.com/sipa/bech32/blob/master/ref/c++ Reference C++ implementation]
+** [https://github.com/bitcoin/bitcoin/pull/20861 Bitcoin Core C++ implementation]
+** [https://github.com/sipa/bech32/blob/master/ref/javascript Reference Javascript implementation]
+
+* Fancy decoder that localizes errors:
+** [https://github.com/sipa/bech32/blob/master/ecc/javascript For JavaScript] ([http://bitcoin.sipa.be/bech32/demo/demo.html demo website])
+
+==Test vectors==
+
+'''Implementation advice''' Experiments testing BIP173 implementations found that many wallets and services did not support sending to higher version segregated witness outputs. In anticipation of the proposed [https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki Taproot] soft fork introducing v1 segregated witness outputs on the network, we emphatically recommend employing the complete set of test vectors provided below as well as ensuring that your implementation supports sending to v1 '''and higher versions'''. All higher versions of native segregated witness outputs should be recognized as valid recipients. As higher versions are not defined on the network, no wallet should ever create them and no recipient should ever provide them to a sender. Nor should a recipient ever want to falsely provide them as the recipient would simply see a payment intended to themselves burned instead. However, by defining higher versions as valid recipients now, future soft forks introducing higher versions of native segwit outputs will be forward-compatible to all wallets correctly implementing the Bech32m specification.
+
+===Test vectors for Bech32m===
+
+The following strings are valid Bech32m:
+* A1LQFN3A
+* a1lqfn3a
+* an83characterlonghumanreadablepartthatcontainsthetheexcludedcharactersbioandnumber11sg7hg6
+* abcdef1l7aum6echk45nj3s0wdvt2fg8x9yrzpqzd3ryx
+* 11llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllludsr8
+* split1checkupstagehandshakeupstreamerranterredcaperredlc445v
+* ?1v759aa
+
+No string can be simultaneously valid Bech32 and Bech32m, so the above examples also serve as invalid test vectors for Bech32.
+
+The following string are not valid Bech32m (with reason for invalidity):
+* 0x20 + 1xj0phk: HRP character out of range
+* 0x7F + 1g6xzxy: HRP character out of range
+* 0x80 + 1vctc34: HRP character out of range
+* an84characterslonghumanreadablepartthatcontainsthetheexcludedcharactersbioandnumber11d6pts4: overall max length exceeded
+* qyrz8wqd2c9m: No separator character
+* 1qyrz8wqd2c9m: Empty HRP
+* y1b0jsk6g: Invalid data character
+* lt1igcx5c0: Invalid data character
+* in1muywd: Too short checksum
+* mm1crxm3i: Invalid character in checksum
+* au1s5cgom: Invalid character in checksum
+* M1VUXWEZ: checksum calculated with uppercase form of HRP
+* 16plkw9: empty HRP
+* 1p2gdwpf: empty HRP
+
+===Test vectors for v0-v16 native segregated witness addresses===
+
+The following list gives valid segwit addresses and the scriptPubKey that they
+translate to in hex.
+* BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4: 0014751e76e8199196d454941c45d1b3a323f1433bd6
+* tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7: 00201863143c14c5166804bd19203356da136c985678cd4d27a1b8c6329604903262
+* bc1pw508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7kt5nd6y: 5128751e76e8199196d454941c45d1b3a323f1433bd6751e76e8199196d454941c45d1b3a323f1433bd6
+* BC1SW50QGDZ25J: 6002751e
+* bc1zw508d6qejxtdg4y5r3zarvaryvaxxpcs: 5210751e76e8199196d454941c45d1b3a323
+* tb1qqqqqp399et2xygdj5xreqhjjvcmzhxw4aywxecjdzew6hylgvsesrxh6hy: 0020000000c4a5cad46221b2a187905e5266362b99d5e91c6ce24d165dab93e86433
+* tb1pqqqqp399et2xygdj5xreqhjjvcmzhxw4aywxecjdzew6hylgvsesf3hn0c: 5120000000c4a5cad46221b2a187905e5266362b99d5e91c6ce24d165dab93e86433
+* bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqzk5jj0: 512079be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798
+
+The following list gives invalid segwit addresses and the reason for
+their invalidity.
+* tc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vq5zuyut: Invalid human-readable part
+* bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqh2y7hd: Invalid checksum (Bech32 instead of Bech32m)
+* tb1z0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqglt7rf: Invalid checksum (Bech32 instead of Bech32m)
+* BC1S0XLXVLHEMJA6C4DQV22UAPCTQUPFHLXM9H8Z3K2E72Q4K9HCZ7VQ54WELL: Invalid checksum (Bech32 instead of Bech32m)
+* bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kemeawh: Invalid checksum (Bech32m instead of Bech32)
+* tb1q0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vq24jc47: Invalid checksum (Bech32m instead of Bech32)
+* bc1p38j9r5y49hruaue7wxjce0updqjuyyx0kh56v8s25huc6995vvpql3jow4: Invalid character in checksum
+* BC130XLXVLHEMJA6C4DQV22UAPCTQUPFHLXM9H8Z3K2E72Q4K9HCZ7VQ7ZWS8R: Invalid witness version
+* bc1pw5dgrnzv: Invalid program length (1 byte)
+* bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7v8n0nx0muaewav253zgeav: Invalid program length (41 bytes)
+* BC1QR508D6QEJXTDG4Y5R3ZARVARYV98GJ9P: Invalid program length for witness version 0 (per BIP141)
+* tb1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vq47Zagq: Mixed case
+* bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7v07qwwzcrf: zero padding of more than 4 bits
+* tb1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vpggkg4j: Non-zero padding in 8-to-5 conversion
+* bc1gmk9yu: Empty data section
+
+
+==Appendix: checksum design & properties==
+
+Checksums are used to detect errors introduced into data during transfer. A hash function-based checksum such as Base58Check detects any type of error uniformly, but not all classes of errors are equally likely to occur in practice. Bech32 prioritizes detection of substitution errors, but improving detection of one error class inevitably worsens detection of other error classes. During the design of Bech32, it was assumed that other simple error patterns beside substitutions would have a similar detection rate as in a hash function-based design, and detection would only be worse for complex, impractical errors. The discovered insertion weakness shows that this is not the case.
+
+For Bech32m, we aim to retain Bech32's guarantees for substitution errors, but make sure that other common errors don't perform worse than a hash function-based checksum would. To make sure the new standard is easy to implement, we restrict the design space to only amending the final constant that is xored in, as it was [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2019-December/017521.html observed] that is sufficient to mitigate the 'q' insertion issue while retaining the intended substitution error detection. In what follows, we explain how the new constant ''0x2bc830a3'' was chosen.
+
+===Error patterns & detection probability===
+
+We define an error pattern as a sequence of first one or more deletions, then swaps of adjacent characters, followed by substitutions, insertions, and duplications, in that order, all in specific positions, applied to a string with valid checksum that is otherwise randomly chosen. For insertions and substitutions we assume a uniformly random new character. For example, "delete the 17th character, swap the 11th character with the 12th character, and insert a random character in the 24th position" is an error pattern. "Replace the 43rd through 48th character with 'aardvark'" is not a valid error pattern, because the new characters are not random and there is no reason why this particular string is more likely than any other to be substituted.
+
+A hash function-based checksum design with a 30-bit hash would have a probability of incorrectly accepting equal to ''2-30'', for every error pattern. Bech32 has a probability of 0 to incorrectly accept error patterns consisting of up to 4 substitutions—they are always detected. The 'q'-insertion issue shows that for Bech32 a simple error pattern ("insert a random character in the penultimate position") with probability ''2-10'' exists: it requires the final character to be 'p' (leaving only 1 in 32 strings), and requires the inserted character to be 'q' (permitting only 1 of 32 possible inserted characters).
+
+Note that the choice of ''what'' the error pattern is (which types of errors, and where) isn't part of our probabilities: we try to make sure that ''every'' pattern behaves well, not just randomly chosen ones, because presumably humans
+make some kinds of errors more than others, and we cannot easily model which ones.
+
+===Detection properties of Bech32m===
+
+The table below shows the error detection properties of Bech32m, and a comparison with Bech32. The code used for this analysis can be found [https://gist.github.com/sipa/14c248c288c3880a3b191f978a34508e#file-const_analysis-cpp here]. Every row specifies one error pattern via the constraints in the left four columns. The remaining columns report what percentage of those patterns have certain probabilities of not being detected. The columns are:
+
+* '''errors''' The maximum number of individual errors considered
+* '''of type''' What type of errors are considered (either "subst. only" for just substitutions, or "any" to also include deletions, swaps, insertions, and duplications)
+* '''window''' The maximum size of the window in which the errors have to occur'''What is an error pattern’s window size?''' The window size of an error pattern is the length of the smallest consecutive range of characters that contains all modified characters (on input or output; whichever is larger). For example, an error pattern that turns "abcdef" into "accdbef" has a window size of 4, as it is replacing "bcd" with "ccdb", a 4 character string. Window size is only meaningful when the pattern consists of two or more errors.
+* '''code/verifier''' Whether this line is about Bech32 or Bech32m encoded strings, and whether those are evaluated regarding their probability of being accepted by either a Bech32 or a Bech32m verifier.'''Why do we care about probability of accepting Bech32m strings in Bech32 verifiers?''' For applications where Bech32m replaces an existing use of Bech32 (such as segregated witness addresses), we want to make sure that a Bech32m string created by new software won’t be erroneously accepted by old software that assumes Bech32 - even when a small number of errors were introduced as well.'''Should we also take into account failures that occur due to taking a valid Bech32m string, and after errors it becoming acceptable to a Bech32 verifier?''' This situation may in theory occur for segregated witness addresses when errors occur that change the version number in a v1+ address to v0. Due to the specificity of this type of error, plus the additional constraints that apply for v0 addresses, this is both unlikely and hard to analyze.
+* '''error patterns with failure probability''' For each probability (''0'', ''2-30'', ''2-25'', ''2-20'', ''2-15'', and ''2-10'') this reports what percentage of error patterns restricted by the constraints in the previous columns have those probabilities of being incorrectly accepted.
+
+The properties are divided into two classes: those that hold over all strings when averaged over all possible HRPs (human readable parts), and those specific to the "bc1" HRP with the length restrictions imposed by segregated witness addresses'''What restrictions were taken into account for the "bc1"-specific analysis?''' The minimum length (due to witness programs being at least 2 bytes), the maximum length (due to witness programs being at most 40 bytes), and the fact that the witness programs are a multiple of 8 bits. The fact that the first data symbol cannot be over 16, or that the padding has to be 0, is not taken into account..
+
+{| class="wikitable"
+! rowspan="2" | errors
+! rowspan="2" | of type
+! rowspan="2" | window
+! rowspan="2" | code/verifier
+! colspan="6" | error patterns with failure probability
+|-
+! ''0'' !! ''2-30'' !! ''2-25'' !! ''2-20'' !! ''2-15'' !! ''2-10''
+|-
+! colspan="10" | Properties averaged over all HRPs
+|-
+| ≤ 4 || only subst. || any || rowspan="6" | Bech32m/Bech32m || 100.00%|| colspan="5" | none(a)
+|-
+| any || any || ≤ 4 || 56.16%|| 43.84%|| colspan="4" | none(b)
+|-
+| ≤ 2 || any || ≤ 68 || 7.71%|| 92.28%|| colspan="4" | none(b)
+|-
+| ≤ 2 || any || any || 7.79%|| 92.20%|| 0.004%|| colspan="3" | none(b)
+|-
+| ≤ 3 || any || ≤ 69 || 7.73%|| 92.23%|| 0.033%(d) || colspan="3" | none(b)
+|-
+| ≤ 3 || any || any || 7.77%|| 92.19%|| 0.034%|| 0.000065% || colspan="2" | none(b)
+|-
+| ≤ 4 || only subst. || any || rowspan="6" | Bech32/Bech32 || 100.00%|| colspan="5" | none
+|-
+| any || any || ≤ 4 || 54.00%|| 43.84%|| 1.08%|| 0.90%|| 0.17%|| 0.0091%
+|-
+| ≤ 2 || any || ≤ 68 || 4.59%|| 92.29%|| 1.09%|| 1.01%|| 0.99%|| 0.039%
+|-
+| ≤ 2 || any || any || 4.58%|| 92.21%|| 1.11%|| 1.04%|| 1.02%|| 0.038%
+|-
+| ≤ 3 || any || ≤ 69 || 6.69%|| 92.23%|| 0.56%|| 0.48%|| 0.041%|| 0.00055%
+|-
+| ≤ 3 || any || any || 6.66%|| 92.19%|| 0.59%|| 0.52%|| 0.041%|| 0.00053%
+|-
+| 0 || - || - || rowspan="3" | Bech32m/Bech32 || 100.00%|| colspan="5" | none(a)
+|-
+| 1 || any || - || 46.53%|| 53.46%|| colspan="4" | none(b)
+|-
+| ≤ 2 || any || any || 22.18%|| 77.77%|| 0.048%|| colspan="3" | none(b)
+|-
+! colspan="10" | Properties for segregated witness addresses with HRP "bc"
+|-
+| ≤ 4 || only subst. || any || rowspan="6" | Bech32m/Bech32m || 100.00%|| colspan="5" | none(a)
+|-
+| 1 || any || - || 24.34%|| 75.66%|| colspan="4" | none(c)
+|-
+| ≤ 2 || any || ≤ 28 || 16.85%|| 83.15%|| colspan="4" | none(c)
+|-
+| any || any || ≤ 4 || 74.74%|| 25.25%|| 0.0016%|| colspan="3" | none(c)
+|-
+| ≤ 2 || any || any || 15.72%|| 84.23%|| 0.039%|| 0.0053%|| colspan="2" | none(c)
+|-
+| ≤ 3 || any || any || 13.98%|| 85.94%|| 0.078%|| 0.00063%|| colspan="2" | none(c)
+|-
+| ≤ 4 || only subst. || any || rowspan="6" | Bech32/Bech32 || 100.00%|| colspan="5" | none
+|-
+| 1 || any || - || 14.63%|| 75.71%|| 2.43%|| 2.43%|| 2.43%|| 2.38%
+|-
+| ≤ 2 || any || ≤ 28 || 14.22%|| 83.15%|| 0.94%|| 0.84%|| 0.79%|| 0.054%
+|-
+| any || any || ≤ 4 || 73.23%|| 25.26%|| 0.76%|| 0.63%|| 0.12%|| 0.0064%
+|-
+| ≤ 2 || any || any || 12.79%|| 84.24%|| 1.06%|| 0.95%|| 0.92%|| 0.041%
+|-
+| ≤ 3 || any || any || 13.00%|| 85.94%|| 0.57%|| 0.45%|| 0.044%|| 0.00067%
+|-
+| ≤ 3 || only subst. || any || rowspan="3" | Bech32m/Bech32 || 100.00%|| colspan="5" | none(c)
+|-
+| 1 || any || - || 70.89%|| 29.11%|| colspan="4" | none(c)
+|-
+| ≤ 2 || any || any || 36.12%|| 63.79%|| 0.092%|| 0.00049%|| colspan="2" | none(c)
+|}
+
+The numbers in this table, as well as a comparison with the numbers for the ‘’1’’ constant and earlier proposed improved constants, can be found [https://gist.github.com/sipa/14c248c288c3880a3b191f978a34508e#file-results_final-txt here].
+
+
+===Selection process===
+
+The details of the selection process can be found [https://gist.github.com/sipa/14c248c288c3880a3b191f978a34508e here], but in short:
+* Start with the set of all ''230-1'' constants different from Bech32's ''1''. All of these satisfy the properties marked (a) in the table above.
+* Through exhaustive analysis, reject all constants that do not exhibit the properties'''How were the properties to select for chosen?''' All these properties are as strong as they can be without rejecting every constant: rejecting constants with lower probabilities, or more errors, or wider windows all result in nothing left. marked (b) in the table above (e.g. all constants that permit any error pattern of 2 errors or less in a window of 68 characters or less with a detection probability ''≥ 2-20''). This selection leaves us with 12054 candidates.
+* Reject all constants that do not exhibit the (c) properties in the table above'''Why optimize for segregated witness addresses (with HRP "bc1") specifically?''' Our analysis for generic HRP has limitations (see the detailed description [https://gist.github.com/sipa/14c248c288c3880a3b191f978a34508e#file-bech32m_mail-txt here], under "Technical details"). We optimize for generic usage first, but optimize for segregated witness addresses as a tiebreaker.. This leaves us with 79 candidates.
+* Finally, select the candidate that minimizes the number of error classes matching (d) in the table above as a final tiebreaker. The result is the single constant ''0x2bc830a3''.
+
+==Footnotes==
+
+
+
+==Acknowledgements==
+
+Thanks to Greg Maxwell for doing most of the computation for code selection and analysis, and comments.
+Thanks to Mark Erhardt for help with writing and editing this document.
+Thanks to Rusty Russell and others on the bitcoin-dev list for the discussion around intentionally breaking compatibility with existing senders, which is used in this specification.
diff --git a/bip-0351.mediawiki b/bip-0351.mediawiki
new file mode 100644
index 0000000000..a782b0c8f9
--- /dev/null
+++ b/bip-0351.mediawiki
@@ -0,0 +1,263 @@
+
+
+==Abstract==
+
+This BIP makes it possible for two parties to transact using addresses that only they can calculate. This is done using exclusively on-chain methods and in a manner that minimizes blockchain footprint. Receiving parties can share their payment codes publicly without a loss of privacy, as every sender will calculate a unique set of addresses for each payment code.
+
+==Motivation==
+
+A recipient that wishes to receive funds privately has several options. Each has tradeoffs in terms of chain analysis potential, recoverability, and wallet complexity.
+
+'''Sharing a static address''' works well enough for one-time payments between two parties as long as the address is shared through a private channel. It does not work well for recurring payments because address reuse leads to a loss of privacy. Using this method for donations exacerbates the problem since the address will serve as a focal point for data collection and analysis. Wallets must not reissue the same address to multiple recipients.
+
+'''Sharing a BIP32 extended public key''' works for recurring payments between two parties only. The same key cannot be shared to any other party without leaking the chain of payments. Furthermore, an extended public key does not say anything about address types and makes it possible for a sender to send to a script that a recipient cannot spend from. Alternate [https://github.com/satoshilabs/slips/blob/master/slip-0132.md version bytes] have been proposed to specify address types, but wallet adoption is limited.
+
+'''Sharing a BIP380 descriptor containing an extended public key''' solves the address type issue from sharing a raw BIP32 extended key. The drawback is that descriptor support is not widespread, especially in mobile wallets.
+
+'''Using a payment server''' works in the case of recipients that have the resources to set up and maintain a payment server that will generate a fresh address for each payment. These are usually businesses and the method is usually out of reach for the average user. The centralized server is vulnerable to takedown remotely and physically.
+
+'''Sharing a BIP47 payment code''' addresses most of the above shortcomings. However, it introduces the following problems:
+
+* The BIP uses a notification mechanism that relies on publicly known per-recipient notification addresses. If Alice wants to send funds to Bob, she has to use the same notification address that everyone else uses to notify Bob. If Alice is not careful with coin selection, i.e. ensuring that her notification UTXO is not linked to her, she will publicly expose herself as someone who is trying to send funds to Bob and their relationship becomes permanently visible on the blockchain.
+
+* The BIP does not say anything about address types. Receiving wallets therefore have to watch all address types that can be created from a single public key. Even then, a sender could send to a script that a recipient cannot spend from.
+
+==Method==
+
+When Alice wants to start paying Bob in private, she imports his payment code into a compatible wallet. Her wallet extracts Bob's public key from the payment code and sends a notification transaction. If Bob finds a notification transaction addressed to himself, he imports Alice's public key contained therein and stores it. Bob then performs ECDH using Alice's public key and his own private key in order to calculate a common set of addresses to watch. Alice calculates the same set of addresses on her end and uses them to send coins to Bob. If Alice engages in coin control, both the initial notification transaction and subsequent payment transactions cannot be attributed to either party. Even if Alice uses coins that are already associated with her, chain analysis will identify her as a sender but Bob's privacy will remain entirely preserved.
+
+==Specification==
+
+===Definitions===
+
+* Alice: sender
+* Bob: recipient
+* Payment code: static string that Bob generates and shares with others so that he can receive payments
+* ''P'': public key contained in Bob's payment code
+* ''p'': private key associated with Bob's public key ''P''
+* ''N'': extended public key used by Alice to derive child keys for each Bob she wants to transact with
+* ''n'': private key associated with Alice's public key ''N''
+* ''x'': Alice's secret recipient index, unique for each Bob
+* ''Nx'': child public key derived from ''N'' at index ''x'' (non-hardened)
+* ''nx'': private key associated with ''Nx''
+* ''c'': Alice's transaction count toward Bob
+* ''Pc'': Bob's public key at index ''c''
+* ''pc'': Bob's private key at index ''c''
+* ''Ac'': Bob's receive address at index ''c''
+* ''H'': SHA256 hash function
+* ''*'': EC multiplication
+* ''+'': EC addition
+* ''|'': string concatenation
+* ''[a..b]'': string slicing (inclusive of ''a'', exclusive of ''b'')
+
+===Public Key Derivation Path===
+
+The derivation path for this BIP follows BIP44. The following BIP32 path levels are defined:
+
+
+m / purpose' / coin_type' / account'
+
+
+purpose is set to 351.
+
+''(p, P)'' and ''(n, N)'' are keys associated with the above path, depending on which side is performing the calculation.
+
+''Nx'' keys are the direct non-hardened children of ''N''. For instance, the path of ''N0'' from ''N'' is ''m / 0''.
+
+===Payment Code Structure and Encoding===
+
+* bytes [0..2]: address type flags (2 bytes)
+* bytes [2..35]: compressed public key P (33 bytes)
+
+Payment codes are encoded in bech32m and the human readable part is "pay" for mainnet and "payt" for testnet (all types), resulting in payment codes that look like "pay1cqqq8d29g0a7m8ghmycqk5yv24mfh3xg8ptzqcn8xz6d2tjl8ccdnfkpjl7p84".
+
+===Address Types===
+
+Address type flags determine which address types a payment code accepts. This is represented by big-endian ordered 16 bits. For instance, a hypothetical payment code that handles all address types will have all defined bits set to 1 (0xffff).
+
+Currently defined flags:
+
+{| class="wikitable"
+! Address Type !! Flag !! Flag Value !! Ordinal Value
+|-
+| P2PKH || 1 << 0 || 0x0001 || 0
+|-
+| P2WPKH || 1 << 1 || 0x0002 || 1
+|-
+| P2TR || 1 << 2 || 0x0004 || 2
+|}
+
+The remaining flags are reserved for future address types.
+
+While payment codes use 2-byte bitflag arrays, notifications use ordinal values in the form of a single byte.
+
+All keys are compressed. Using uncompressed keys at any point is illegal.
+
+===Notifications===
+
+Notifications are performed by publishing transactions that contain a 40-byte OP_RETURN output. The value of the OP_RETURN is constructed using the following formula:
+
+''search_key | notification_code | Nx | address_type''
+
+* ''search_key'' equals "PP" and is a static ASCII-encoded string (2 bytes)
+* ''notification_code'' is ''H(nx * P)[0..4]'' (4 bytes)
+* ''Nx'' is the unique public key a sender is using for a particular recipient (33 bytes)
+* ''address_type'' is the '''ordinal''' value of a single address type that a sender wants to send to (1 byte). This must be selected from the recipient's accepted address types.
+
+When Alice wants to notify Bob that he will receive future payments from her, she performs the following procedure:
+
+# Assigns an unused, unique index ''x'' to Bob (''0'' if Bob is the first party she is notifying).
+# Calculates a 4-byte notification code: ''notification_code = H(nx * P)[0..4]''
+# Commits to one of Bob's accepted address types by choosing its ordinal value. Going forward Alice must not send to address types other than the one she committed to in the notification.
+# Constructs a notification payload by concatenating the above values according to the formula.
+# Selects any UTXO in her wallet, preferably not associated with her.
+# Sends a transaction including an OP_RETURN output whose value is set to the constructed payload.
+
+When Bob notices a 40-byte OP_RETURN starting with ''search key'', he performs the following procedure:
+
+# Breaks down the payload into its four constituent parts.
+# Discards the ''search_key'' (item #0).
+# Selects ''Nx'' (item #2) and performs ''H(Nx * p)'' (Bob does not know the value of ''x''). Bob takes the first four bytes of the calculated value.
+# If the four bytes match the notification value (item #1), Bob found a notification addressed to himself and stores ''Nx'' together with ''address_type''.
+# If this process fails for any reason, Bob assumes a spurious notification or one not addressed to himself and gives up.
+
+Since changing ''x'' yields a completely different sender identity, Alice can always re-notify Bob from a different index when she does not want to be associated with her previous identity. Alice can also re-notify Bob when she wants to start sending to a different address type. Bob must be able to update his watchlist in that case and he can stop watching addresses associated with the old address type.
+
+Out-of-band notifications between Alice and Bob are legal (in fact, they may not be prevented), but in that case Bob loses the ability to restore his wallet from OP_RETURN outputs embedded in the blockchain. In that case, Bob has the burden of keeping a valid backup of any out-of-band notifications.
+
+===Allowing Notification Collisions===
+
+Since ''notification_code'' is a 4-byte truncation of the full value, Bob has a 1 in ~4.3 billion chance of detecting a spurious notification. This is considered acceptable because the cost of doing so is adding a few more addresses to Bob's watchlist. The benefit of this approach is that is saves 28 bytes per notification.
+
+===Scanning Requirement===
+
+There is a scanning requirement on the recipient side in that the recipient must have access to full blocks in order to be able to search them for OP_RETURN outputs containing notifications. For more information on how light clients can get around this limitation and still use the standard, see Appendix B.
+
+Recipients that do not want to decode raw block data can quickly search for notifications in a block by looking for the following byte array: [106, 40, 80, 80]. The first two bytes represent ''OP_RETURN'' and ''OP_PUSHBYTES_40'', followed by the ASCII value of ''search_key''.
+
+===Transacting===
+
+Alice initializes counter ''c'' which is unique to Bob and increments with each transaction. ''c'' is a 64-bit integer and must be inputted into a hasher as a big-endian encoded array of 8 bytes.
+
+1. Alice calculates a secret point (constant between Alice and Bob):
+
+''S = nx * P''
+
+2. Alice calculates a shared secret:
+
+''s = H(S | c)''
+
+3. Alice calculates Bob's ephemeral public key and its associated address where the funds will be sent:
+
+''Pc = P + s*G''
+
+4. Alice constructs an address using the key ''Pc'', using one of the address types she committed to in the notification transaction.
+
+Bob constructs his watchlist by mirroring this process on his end, except that his method of calculating ''S'' is:
+
+''S = Nx * p''
+
+When Bob wants to spend from such addresses, he calculates his private keys in the following manner:
+
+''pc = p + s''
+
+==Backward Compatibility==
+
+Private Payments is a new standard which is not compatible with any previous standard based on static payment codes, such as BIP47.
+
+While the standard does not support versioning, it reserves unused bits in the address type bitflag array which can be allocated to new address types once they are deemed ubiquitous. Older payment codes (i.e. those generated when fewer address types were available) are readable by software supporting new address types. The reverse is also supported since older software will ignore newer address type flags that are not understood.
+
+==Appendix A: Test Vectors==
+
+===Alice's Wallet===
+
+'''BIP32 seed:''' 0xfe
+
+'''Master xprv:''' xprv9s21ZrQH143K2qVytoy3eZSSuc1gfzFrkV4bgoHzYTkgge4UoNP62eV8jkHYNqddaaefpnjwkz71P5m4EW6RuQBJeP9pdfa9WBnjP6XUivG
+
+'''n:''' xprv9zNFGn56Wm1s89ycTCg4hB615ehu6ZvNL4mxUEAL28pNhBAb6SZgLdsgmQd1ECgAiCjy6XxTTRyBdPAhH1oMfLhv2bSwfiCYhL9s9ahEehf
+
+'''N:''' xpub6DMbgHbzM8aALe45ZED54K2jdgYPW2eDhHhZGcZwaUMMZyVjdysvtSCAcfPYiqB5Zw41EyLWPxCXko6iEckwRdF5CD2ZKdTxUKigPXsnpaE
+
+'''x:''' 0
+
+'''nx:''' be9518016ec15762877de7d2ce7367a2087cf5682e72bbffa89535d73bb42f40
+
+'''Nx:''' 02e3217349724307eed5514b53b1f53f0802672a9913d9bbb76afecc86be23f464
+
+
+===Bob's Wallet===
+'''BIP32 seed:''' 0xff
+
+'''Master xprv:''' xprv9s21ZrQH143K47bRNtc26e8Gb3wkUiJ4fH3ewYgJeiGABp7vQtTKsLBzHM2fsfiK7Er6uMrWbdDwwrdcVn5TDC1T1npTFFkdEVoMgTwfVuR
+
+'''p:''' 0x26c610e7d0ed4395be3f0664073d66b0a3442b49e1ec13faf2dd9b7d3c335441
+
+'''P:''' 0x0302be8bff520f35fae3439f245c52afb9085a7bf62d099c1f5e9e1b15a7e2121a
+
+'''Accepted scripts:''' 0x03 (legacy + segwit) (0x01 | 0x02)
+
+'''Payment code:''' pay1qqpsxq4730l4yre4lt3588eyt3f2lwggtfalvtgfns04a8smzkn7yys6xv2gs8
+
+
+===Alice notifying Bob===
+'''S:''' 0x02c0892d6ba30b5b1eafebd47172e46d358721f294698f9f59b4d96b781da09a62
+
+'''Notification code:''' 0x49cb55bb
+
+'''Address type commitment:''' 1 (segwit)
+
+'''Notification output script:''' OP_RETURN OP_PUSHBYTES_40 505049cb55bb02e3217349724307eed5514b53b1f53f0802672a9913d9bbb76afecc86be23f46401
+
+
+===Alice sending to Bob===
+'''c:''' 0
+
+'''s:''' 0x5dbe5efee4a5b9df73708241858f2bf7ec65f141dbd229ea8e2f9f51804a18f2
+
+'''s*G:''' 0x039362033c1bc3f05e081d4d7f76d5ffebde349b0f6a4d2e8ffc5c065c17233247
+
+'''Pc:''' 0x03e669bd1705691a080840b07d76713d040934a37f2e8dde2fe02f5d3286a49219
+
+'''Ac:''' bc1qw7ld5h9tj2ruwxqvetznjfq9g5jyp0gjhrs30w
+
+
+===Bob spending===
+'''c:''' 0
+
+'''pc:''' 0x84846fe6b592fd7531af88a58ccc92a88faa1c8bbdbe3de5810d3acebc7d6d33
+
+==Appendix B: Potential OP_RETURN Services==
+
+Compact Block Filters, as formulated in BIP-0158, do not cover OP_RETURN data payloads. In support of light wallets, an external service could publish transaction proofs for all transactions that include the tagged notification payload. Light wallets would download all such transactions, filter for matches against their payment code, then verify the transaction proofs against the block headers obtained over the P2P network.
+
+==Appendix C: Potential Notification Transaction Services==
+
+No specific instruction is given as to the details of the notification transaction beyond simply including the single OP_RETURN payload. Since no restriction exists for other inputs or outputs of this transaction, there is an opportunity for an external service to include this payload in a transaction completely unrelated to Alice's wallet. Such a service could charge a fee out-of-band to help cover fees.
+
+Another opportunity exists for an existing business to attach notification payloads to transactions sent during the normal course of operations. Large withdrawal transactions from mining pools or exchanges could include a marginal notification payload without affecting overall fees.
+
+==Reference Implementation==
+
+Reference implementation is available at https://github.com/private-payments/rust-private-payments
+
+==Reference==
+* [[bip-0032.mediawiki|BIP32 - Hierarchical Deterministic Wallets]]
+* [[bip-0043.mediawiki|BIP43 - Purpose Field for Deterministic Wallets]]
+* [[bip-0044.mediawiki|BIP44 - Multi-Account Hierarchy for Deterministic Wallets]]
+* [[bip-0047.mediawiki|BIP47 - Reusable Payment Codes for Hierarchical Deterministic Wallets]]
+* [[bip-0157.mediawiki|BIP157 - Client Side Block Filtering]]
+* [[bip-0158.mediawiki|BIP158 - Compact Block Filters for Light Clients]]
+* [https://gist.github.com/RubenSomsen/21c477c90c942acf45f8e8f5c1ad4fae BIP47 Prague Discussion (acknowledgements: @rubensomsen, @afilini, @kixunil])
+
diff --git a/bip-0352.mediawiki b/bip-0352.mediawiki
new file mode 100644
index 0000000000..4462efcaf6
--- /dev/null
+++ b/bip-0352.mediawiki
@@ -0,0 +1,498 @@
+
+ BIP: 352
+ Layer: Applications
+ Title: Silent Payments
+ Author: josibake
+ Ruben Somsen
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0352
+ Status: Proposed
+ Type: Standards Track
+ Created: 2023-03-09
+ License: BSD-2-Clause
+ Post-History: 2022-03-13: https://gist.github.com/RubenSomsen/c43b79517e7cb701ebf77eec6dbb46b8 [gist] Original proposal
+ 2022-03-28: https://gnusha.org/pi/bitcoindev/CAPv7TjbXm953U2h+-12MfJ24YqOM5Kcq77_xFTjVK+R2nf-nYg@mail.gmail.com/ [bitcoin-dev] Silent Payments – Non-interactive private payments with no on-chain overhead
+ 2022-10-11: https://gnusha.org/pi/bitcoindev/P_21MLHGJicZ-hkbC4DGu86c5BtNKiH8spY4TOw5FJsfimdi_6VyHzU_y-s1mZsOcC2FA3EW_6w6W5qfV9dRK_7AvTAxDlwVfU-yhWZPEuo=@protonmail.com/ [bitcoin-dev] Silent Payment v4 (coinjoin support added)
+ 2023-08-04: https://gnusha.org/pi/bitcoindev/ZM03twumu88V2NFH@petertodd.org/ [bitcoin-dev] BIP-352 Silent Payments addresses should have an expiration time
+
+
+== Introduction ==
+
+=== Abstract ===
+
+This document specifies a protocol for static payment addresses in Bitcoin without on-chain linkability of payments or a need for on-chain notifications.
+
+=== Copyright ===
+
+This BIP is licensed under the BSD 2-clause license.
+
+=== Motivation ===
+
+Using a new address for each Bitcoin transaction is a crucial aspect of maintaining privacy. This often requires a secure interaction between sender and receiver, so that the receiver can hand out a fresh address, a batch of fresh addresses, or a method for the sender to generate addresses on-demand, such as an xpub.
+
+However, interaction is often infeasible and in many cases undesirable. To solve for this, various protocols have been proposed which use a static payment address and notifications sent via the blockchain'''Why not use out-of-band notifications''' Out-of-band notifications (e.g. using something other than the Bitcoin blockchain) have been proposed as a way of addressing the privacy and cost concerns of using the Bitcoin blockchain as a messaging layer. This, however, simply moves the privacy and cost concerns somewhere else and increases the risk of losing money due to a notification not being reliably delivered, or even censored, and makes this notification data critical for backup to recover funds.. These protocols eliminate the need for interaction, but at the expense of increased costs for one-time payments and a noticeable footprint in the blockchain, potentially revealing metadata about the sender and receiver. Notification schemes also allow the receiver to link all payments from the same sender, compromising sender privacy.
+
+This proposal aims to address the limitations of these current approaches by presenting a solution that eliminates the need for interaction, eliminates the need for notifications, and protects both sender and receiver privacy. These benefits come at the cost of requiring wallets to scan the blockchain in order to detect payments. This added requirement is generally feasible for full nodes but poses a challenge for light clients. While it is possible today to implement a privacy-preserving light client at the cost of increased bandwidth, light client support is considered an area of open research (see [[#appendix-a-light-client-support|Appendix A: Light Client Support]]).
+
+The design keeps collaborative transactions such as CoinJoins and inputs with MuSig and FROST keys in mind, but it is recommended that the keys of all inputs of a transaction belong to the same entity as there is no formal proof that the protocol is secure in a collaborative setting.
+
+== Goals ==
+
+We aim to present a protocol which satisfies the following properties:
+
+* No increase in the size or cost of transactions
+* Resulting transactions blend in with other bitcoin transactions and can't be distinguished
+* Transactions can't be linked to a silent payment address by an outside observer
+* No sender-receiver interaction required
+* No linking of multiple payments to the same sender
+* Each silent payment goes to a unique address, avoiding accidental address reuse
+* Supports payment labeling
+* Uses existing seed phrase or descriptor methods for backup and recovery
+* Separates scanning and spending responsibilities
+* Compatible with other spending protocols, such as CoinJoin
+* Light client/SPV wallet support
+* Protocol is upgradeable
+
+== Overview ==
+
+We first present an informal overview of the protocol. In what follows, uppercase letters represent public keys, lowercase letters represent private keys, ''||'' refers to byte concatenation, ''·'' refers to elliptic curve scalar multiplication, ''G'' represents the generator point for secp256k1, and ''n'' represents the curve order for secp256k1. Each section of the overview is incomplete on its own and is meant to build on the previous section in order to introduce and briefly explain each aspect of the protocol. For the full protocol specification, see [[#specification|Specification]].
+
+''' Simple case '''
+
+Bob publishes a public key ''B'' as a silent payment address. Alice discovers Bob's silent payment address, selects a UTXO with private key ''a'', public key ''A'' and creates a destination output ''P'' for Bob in the following manner:
+
+* Let ''P = B + hash(a·B)·G''
+* Encode ''P'' as a [https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki BIP341] taproot output
+
+Since ''a·B == b·A'' ([https://en.wikipedia.org/wiki/Elliptic-curve_Diffie%E2%80%93Hellman Elliptic-curve Diffie–Hellman]), Bob scans with his private key ''b'' by collecting the input public keys for each transaction with at least one unspent taproot output and performing the ECDH calculation until ''P'' is found (i.e. calculating ''P = B + hash(b·A)·G'' and seeing that ''P'' is present in the transaction outputs).
+
+''' Creating more than one output '''
+
+In order to allow Alice to create more than one output for Bob'''Why allow for more than one output?''' Allowing Alice to break her payment to Bob into multiple amounts opens up a number of privacy improving techniques for Alice, making the transaction look like a CoinJoin or better hiding the change amount by splitting both the payment and change outputs into multiple amounts. It also allows for Alice and Carol to both have their own unique output paying Bob in the event they are in a collaborative transaction and both paying Bob's silent payment address., we include an integer in the following manner:
+
+* Let ''k = 0''
+* Let ''P0 = B + hash(a·B || k)·G''
+* For additional outputs:
+** Increment ''k'' by one (''k++'')
+** Let ''Pi = B + hash(a·B || k)·G''
+
+Bob detects this output the same as before by searching for ''P0 = B + hash(b·A || 0)·G''. Once he detects the first output, he must:
+
+* Check for ''P1 = B + hash(b·A || 1)·G''
+* If ''P1'' is not found, stop
+* If ''P1'' is found, continue to check for ''P2'' and so on until an additional output is not found
+
+Since Bob will only perform these subsequent checks after a transaction with at least one output paying him is found, the increase to his overall scanning requirement is negligible. It should also be noted that the order in which these outputs appear in the transaction does not affect the outcome.
+
+''' Preventing address reuse '''
+
+If Alice were to use a different UTXO from the same public key ''A'' for a subsequent payment to Bob, she would end up deriving the same destinations ''Pi''. To prevent this, Alice should include an input hash in the following manner:
+
+* Let ''input_hash = hash(outpoint || A)'''''Why include A in the input hash calculation?''' By committing to A in input hash, this ensures that the sender cannot maliciously choose a private key ''a′'' in a subsequent transaction where ''a′ = input_hash·a / input_hash′'', which would force address reuse in the protocol.
+* Let ''P0 = B + hash(input_hash·a·B || 0)·G''
+
+Bob must calculate the same ''input_hash'' when scanning.
+
+''' Using all inputs '''
+
+In our simplified example we have been referring to Alice's transactions as having only one input ''A'', but in reality a Bitcoin transaction can have many inputs. Instead of requiring Alice to pick a particular input and requiring Bob to check each input separately, we can instead require Alice to perform the tweak with the sum of the input public keys'''What about inputs without public keys?''' Inputs without public keys can still be spent in the transaction but are simply ignored in the silent payments protocol.. This significantly reduces Bob's scanning requirement, makes light client support more feasible'''How does using all inputs help light clients?''' If Alice uses a random input for the tweak, Bob necessarily has to have access to and check all transaction inputs, which requires performing an ECC multiplication per input. If instead Alice performs the tweak with the sum of the input public keys, Bob only needs the summed 33 byte public key per transaction and only does one ECC multiplication per transaction. Bob can then use BIP158 block filters to determine if any of the outputs exist in a block and thus avoids downloading transactions which don't belong to him. It is still an open question as to how Bob can source the 33 bytes per transaction in a trustless manner, see [[#appendix-a-light-client-support|Appendix A: Light Client Support]] for more details., and protects Alice's privacy in collaborative transaction protocols such as CoinJoin'''Why does using all inputs matter for CoinJoin?''' If Alice uses a random input to create the output for Bob, this necessarily reveals to Bob which input Alice has control of. If Alice is paying Bob as part of a CoinJoin, this would reveal which input belongs to her, degrading the anonymity set of the CoinJoin and giving Bob more information about Alice. If instead all inputs are used, Bob has no way of knowing which input(s) belong to Alice. This comes at the cost of increased complexity as the CoinJoin participants now need to coordinate to create the silent payment output and would need to use [https://gist.github.com/RubenSomsen/be7a4760dd4596d06963d67baf140406 Blind Diffie–Hellman] to prevent the other participants from learning who Alice is paying. Note it is currently not recommended to use this protocol for CoinJoins due to a lack of a formal security proof..
+
+Alice performs the tweak with the sum of her input private keys in the following manner:
+
+* Let ''a = a1 + a2 + ... + an''
+* Let ''input_hash = hash(outpointL || (a·G))'', where ''outpointL'' is the smallest outpoint lexicographically'''Why use the lexicographically smallest outpoint for the hash?''' Recall that the purpose of including the input hash is so that the sender and receiver can both come up with a deterministic nonce that ensures that a unique address is generated each time, even when reusing the same scriptPubKey as an input. Choosing the smallest outpoint lexicographically satisfies this requirement, while also ensuring that the generated output is not dependent on the final ordering of inputs in the transaction. Using a single outpoint also works well with memory constrained devices (such as hardware signing devices) as it does not require the device to have the entire transaction in memory in order to generate the silent payment output.
+* Let ''P0 = B + hash(input_hash·a·B || 0)·G''
+
+''' Spend and Scan Key '''
+
+Since Bob needs his private key ''b'' to check for incoming payments, this requires ''b'' to be exposed to an online device. To minimize the risks involved, Bob can instead publish an address of the form ''(Bscan, Bspend)''. This allows Bob to keep ''bspend'' in offline cold storage and perform the scanning with the public key ''Bspend'' and private key ''bscan''. Alice performs the tweak using both of Bob's public keys in the following manner:
+
+* Let ''P0 = Bspend + hash(input_hash·a·Bscan || 0)·G''
+
+Bob detects this payment by calculating ''P0 = Bspend + hash(input_hash·bscan·A || 0)·G'' with his online device and can spend from his cold storage signing device using ''(bspend + hash(input_hash·bscan·A || 0)) mod n'' as the private key.
+
+''' Labels '''
+
+For a single silent payment address of the form ''(Bscan, Bspend)'', Bob may wish to differentiate incoming payments. Naively, Bob could publish multiple silent payment addresses, but this would require him to scan for each one, which becomes prohibitively expensive. Instead, Bob can label his spend public key ''Bspend'' with an integer ''m'' in the following way:
+
+* Let ''Bm = Bspend + hash(bscan || m)·G'' where m is an incrementable integer starting from 1
+* Publish ''(Bscan, B1)'', ''(Bscan, B2)'' etc.
+
+Alice performs the tweak as before using one of the published ''(Bscan, Bm)'' pairs. Bob detects the labeled payment in the following manner:
+
+* Let ''P0 = Bspend + hash(input_hash·bscan·A || 0)·G''
+* Subtract ''P0'' from each of the transaction outputs and check if the remainder matches any of the labels (''hash(bscan || 1)·G'', ''hash(bscan || 2)·G'' etc.) that the wallet has previously used
+
+It is important to note that an outside observer can easily deduce that each published ''(Bscan, Bm)'' pair is owned by the same entity as each published address will have ''Bscan'' in common. As such, labels are not meant as a way for Bob to manage separate identities, but rather a way for Bob to determine the source of an incoming payment.
+
+''' Labels for change '''
+
+Bob can also use labels for managing his own change outputs. We reserve ''m = 0'' for this use case. This gives Bob an alternative to using BIP32 for managing change, while still allowing him to know which of his unspent outputs were change when recovering his wallet from the master key. It is important that the wallet never hands out the label with ''m = 0'' in order to ensure nobody else can create payments that are wrongly labeled as change.
+
+While the use of labels is optional, every receiving silent payments wallet should at least scan for the change label when recovering from backup in order to ensure maximum cross-compatibility.
+
+== Specification ==
+
+We use the following functions and conventions:
+
+* ''outpoint'' (36 bytes): the COutPoint of an input (32-byte txid, least significant byte first || 4-byte vout, least significant byte first)'''Why are outpoints little-endian?''' Despite using big endian throughout the rest of the BIP, outpoints are sorted and hashed matching their transaction serialization, which is little-endian. This allows a wallet to parse a serialized transaction for use in silent payments without needing to re-order the bytes when computing the input hash. Note: despite outpoints being stored and serialized as little-endian, the transaction hash (txid) is always displayed as big-endian.
+* ser32(i): serializes a 32-bit unsigned integer ''i'' as a 4-byte sequence, most significant byte first.
+* ser256(p): serializes the integer p as a 32-byte sequence, most significant byte first.
+* serP(P): serializes the coordinate pair P = (x,y) as a byte sequence using SEC1's compressed form: (0x02 or 0x03) || ser256(x), where the header byte depends on the parity of the omitted Y coordinate.
+
+For everything not defined above, we use the notation from [https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification BIP340]. This includes the ''hashtag(x)'' notation to refer to ''SHA256(SHA256(tag) || SHA256(tag) || x)''.
+
+=== Versions ===
+
+This document defines version 0 (''sp1q''). Version is communicated through the address in the same way as bech32 addresses (see [https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32 BIP173]. Future upgrades to silent payments will require a new version. As much as possible, future upgrades should support receiving from older wallets (e.g. a silent payments v0 wallet can send to both v0 and v1 addresses). Any changes that break compatibility with older silent payment versions should be a new BIP.
+
+Future silent payments versions will use the following scheme:
+
+{| class="wikitable"
+|-
+!
+!0
+!1
+!2
+!3
+!4
+!5
+!6
+!7
+!Compatibility
+|-
+!+0
+|q||p||z||r||y||9||x||8||rowspan="4" | backwards compatible
+|-
+!+8
+|g||f||2||t||v||d||w||0
+|-
+!+16
+|s||3||j||n||5||4||k||h
+|-
+!+24
+|c||e||6||m||u||a||7|| -
+|}
+
+''v31'' (l) is reserved for a backwards incompatible change, if needed. For silent payments v0:
+
+* If the receiver's silent payment address version is:
+** ''v0'': check that the data part is exactly 66-bytes. Otherwise, fail
+** ''v1'' through ''v30'': read the first 66-bytes of the data part and discard the remaining bytes
+** ''v31'': fail
+* Receiver addresses are always [https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki BIP341] taproot outputs'''Why only taproot outputs?''' Providing too much optionality for the protocol makes it difficult to implement and can be at odds with the goal of providing the best privacy. Limiting to taproot outputs helps simplify the implementation significantly while also putting users in the best eventual anonymity set.
+* The sender should sign with one of the sighash flags ''DEFAULT'', ''ALL'', ''SINGLE'', ''NONE'' (''ANYONECANPAY'' is unsafe). It is strongly recommended implementations use ''SIGHASH_ALL'' (''SIGHASH_DEFAULT'' for taproot inputs) when possible'''Why is it unsafe to use ''SIGHASH_ANYONECANPAY''?''' Since the output address for the receiver is derived from the sum of the [[#inputs-for-shared-secret-derivation|Inputs For Shared Secret Derivation]] public keys, the inputs must not change once the sender has signed the transaction. If the inputs are allowed to change after the fact, the receiver will not be able to calculate the shared secret needed to find and spend the output. It is currently an open question on how a future version of silent payments could be made to work with new sighash flags such as ''SIGHASH_GROUP'' and ''SIGHASH_ANYPREVOUT''.
+* Inputs used to derive the shared secret are from the ''[[#inputs-for-shared-secret-derivation|Inputs For Shared Secret Derivation]]'' list
+
+=== Scanning silent payment eligible transactions ===
+
+For silent payments v0 a transaction MUST be scanned if and only if all of the following are true:
+
+* The transaction contains at least one BIP341 taproot output (note: spent transactions optionally can be skipped by only considering transactions with at least one unspent taproot output)
+* The transaction has at least one input from the ''[[#inputs-for-shared-secret-derivation|Inputs For Shared Secret Derivation]]'' list
+* The transaction does not spend an output with SegWit version > 1'''Why skip transactions that spend SegWit version > 1?''' Skipping transactions that spend unknown output scripts allows us to have a clean upgrade path for silent payments by avoiding the need to scan the same transaction multiple times with different rule sets. If a new SegWit version is added in the future and silent payments v1 is released with support, we would want to avoid having to first scan the transaction with the silent payment v0 rules and then again with the silent payment v1 rules. Note: this restriction only applies to the inputs of a transaction.
+
+=== Address encoding ===
+
+A silent payment address is constructed in the following manner:
+
+* Let ''Bscan, bscan = Receiver's scan public key and corresponding private key''
+* Let ''Bspend, bspend = Receiver's spend public key and corresponding private key''
+* Let ''Bm = Bspend + hashBIP0352/Label(ser256(bscan) || ser32(m))·G'', where ''hashBIP0352/Label(ser256(bscan) || ser32(m))·G'' is an optional integer tweak for labeling
+** If no label is applied then ''Bm = Bspend''
+* The final address is a [https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki Bech32m] encoding of:
+** The human-readable part "sp" for mainnet, "tsp" for testnets (e.g. signet, testnet)
+** The data-part values:
+*** The character "q", to represent a silent payment address of version 0
+*** The 66-byte concatenation of the receiver's public keys, ''serP(Bscan) || serP(Bm)''
+
+Note: [https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki BIP173] imposes a 90 character limit for Bech32 segwit addresses and limits versions to 0 through 16, whereas a silent payment address requires ''at least'' 117 characters ''' Why do silent payment addresses need at least 117 characters?''' A silent payment address is a bech32m encoding comprised of the following parts:
+
+
+* HRP [2-3 characters]
+* separator [1 character]
+* version [1-2 characters]
+* payload, 66 bytes concatenated pubkeys [ceil(66*8/5) = 106 characters]
+* checksum [6 characters]
+
+
+For a silent payments v0 address, this results in a 117-character address when using a 3-character HRP. Future versions of silent payment addresses may add to the payload, which is why a 1023-character limit is suggested. and allows versions up to 31. Additionally, since higher versions may add to the data field, it is recommended implementations use a limit of 1023 characters (see [https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#checksum-design BIP173: Checksum design] for more details).
+
+=== Inputs For Shared Secret Derivation ===
+
+While any UTXO with known output scripts can be used to fund the transaction, the sender and receiver MUST use inputs from the following list when deriving the shared secret:
+
+* ''P2TR''
+* ''P2WPKH''
+* ''P2SH-P2WPKH''
+* ''P2PKH''
+
+Inputs with conditional branches or multiple public keys (e.g. ''CHECKMULTISIG'') are excluded from shared secret derivation as this introduces malleability and would allow a sender to re-sign with a different set of public keys after the silent payment output has been derived. This is not a concern when the sender controls all of the inputs, but is an issue for CoinJoins and other collaborative protocols, where a malicious participant can participate in deriving the silent payment address with one set of keys and then re-broadcast the transaction with signatures for a different set of public keys. P2TR can have hidden conditional branches (script path), but we work around this by using only the output public key.
+
+For all of the output types listed, only X-only and compressed public keys are permitted''' Why only compressed public keys ''' Uncompressed and hybrid public keys are less common than compressed keys and generally considered to be a bad idea due to their blockspace inefficiency. Additionally, [https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki#restrictions-on-public-key-type BIP143] recommends restricting P2WPKH inputs to compressed keys as a default policy..
+
+''' P2TR '''
+
+'' Keypath spend ''
+
+ witness:
+ scriptSig: (empty)
+ scriptPubKey: 1 <32-byte-x-only-key>
+ (0x5120{32-byte-x-only-key})
+
+The sender uses the private key corresponding to the taproot output key (i.e. the tweaked private key). This can be a single private key or an aggregate key (e.g. taproot outputs using MuSig or FROST)'''Are key aggregation techniques like FROST and MuSig supported?''' While we do not recommend it due to lack of a security proof (except if all participants are trusted or are the same entity), any taproot output able to do a key path theoretically is supported. Any offline key aggregation technique can be used, such as FROST or MuSig. This would require participants to perform the ECDH step collaboratively e.g. ''ECDH = a1·Bscan + a2·Bscan + ... + at·Bscan'' and ''P = Bspend + hash(input_hash·ECDH || 0)·G''. Additionally, it may be necessary for the participants to provide a DLEQ proof to ensure they are not acting maliciously.. The receiver obtains the public key from the ''scriptPubKey'' (i.e. the taproot output key).
+
+'' Script path spend ''
+
+ witness:
+ scriptSig: (empty)
+ scriptPubKey: 1 <32-byte-x-only-key>
+ (0x5120{32-byte-x-only-key})
+
+Same as a keypath spend, the sender MUST use the private key corresponding to the taproot output key. If this key is not available, the output cannot be included as an input to the transaction. Same as a keypath spend, the receiver obtains the public key from the ''scriptPubKey'' (i.e. the taproot output key)''' Why not skip all taproot script path spends? ''' This causes malleability issues for CoinJoins. If the silent payments protocol skipped taproot script path spends, this would allow an attacker to join a CoinJoin round, participate in deriving the silent payment address using the tweaked private key for a key path spend, and then broadcast their own version of the transaction using the script path spend. If the receiver were to only consider key path spends, they would skip the attacker's script path spend input when deriving the shared secret and not be able to find the funds. Additionally, there may be scenarios where the sender can perform ECDH with the key path private key but spends the output using the script path..
+
+The one exception is script path spends that use NUMS point ''H'' as their internal key (where ''H'' is constructed by taking the hash of the standard uncompressed encoding of the secp256k1 base point ''G'' as X coordinate, see [https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#constructing-and-spending-taproot-outputs BIP341: Constructing and spending Taproot outputs] for more details), in which case the input will be skipped for the purposes of shared secret derivation'''Why skip outputs with H as the internal taproot key?''' If use cases get popularized where the taproot key path cannot be used, these outputs can still be included without getting in the way of making a silent payment, provided they specifically use H as their internal taproot key.. The receiver determines whether or not to skip the input by checking in the control block if the taproot internal key is equal to ''H''.
+
+''' P2WPKH '''
+
+ witness: <33-byte-compressed-key>
+ scriptSig: (empty)
+ scriptPubKey: 0 <20-byte-key-hash>
+ (0x0014{20-byte-key-hash})
+
+The sender performs the tweak using the private key for the output and the receiver obtains the public key as the last witness item.
+
+''' P2SH-P2WPKH '''
+
+ witness: <33-byte-compressed-key>
+ scriptSig: <0 <20-byte-key-hash>>
+ (0x160014{20-byte-key-hash})
+ scriptPubKey: HASH160 <20-byte-script-hash> EQUAL
+ (0xA914{20-byte-script-hash}87)
+
+The sender performs the tweak using the private key for the nested ''P2WPKH'' output and the receiver obtains the public key as the last witness item.
+
+''' P2PKH '''
+
+ scriptSig: <33-byte-compressed-key>
+ scriptPubKey: OP_DUP HASH160 <20-byte-key-hash> OP_EQUALVERIFY OP_CHECKSIG
+ (0x76A914{20-byte-key-hash}88AC)
+
+The receiver obtains the public key from the ''scriptSig''. The receiver MUST parse the ''scriptSig'' for the public key, even if the ''scriptSig'' does not match the template specified (e.g. OP_DROP ). This is to address the [https://en.bitcoin.it/wiki/Transaction_malleability third-party malleability of ''P2PKH'' ''scriptSigs''].
+
+=== Sender ===
+
+==== Selecting inputs ====
+
+The sending wallet performs coin selection as usual with the following restrictions:
+
+* At least one input MUST be from the ''[[#inputs-for-shared-secret-derivation|Inputs For Shared Secret Derivation]]'' list
+* Exclude inputs with SegWit version > 1 (see ''[[#scanning-silent-payment-eligible-transactions|Scanning silent payment eligible transactions]]'')
+* For each taproot output spent the sending wallet MUST have access to the private key corresponding to the taproot output key, unless ''H'' is used as the internal public key
+
+==== Creating outputs ====
+
+After the inputs have been selected, the sender can create one or more outputs for one or more silent payment addresses in the following manner:
+
+* Collect the private keys for each input from the ''[[#inputs-for-shared-secret-derivation|Inputs For Shared Secret Derivation]]'' list
+* For each private key ''ai'' corresponding to a [https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki BIP341] taproot output, check that the private key produces a point with an even Y coordinate and negate the private key if not'''Why do taproot private keys need to be checked?''' Recall from [https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki BIP340] that each X-only public key has two corresponding private keys, ''d'' and ''n - d''. To maintain parity between sender and receiver, it is necessary to use the private key corresponding to the even Y coordinate when performing the ECDH step since the receiver will assume the even Y coordinate when summing the taproot X-only public keys.
+* Let ''a = a1 + a2 + ... + an'', where each ''ai'' has been negated if necessary
+** If ''a = 0'', fail
+* Let ''input_hash = hashBIP0352/Inputs(outpointL || A)'', where ''outpointL'' is the smallest ''outpoint'' lexicographically used in the transaction and ''A = a·G''
+* Group receiver silent payment addresses by ''Bscan'' (e.g. each group consists of one ''Bscan'' and one or more ''Bm'')
+* For each group:
+** Let ''ecdh_shared_secret = input_hash·a·Bscan''
+** Let ''k = 0''
+** For each ''Bm'' in the group:
+*** Let ''tk = hashBIP0352/SharedSecret(serP(ecdh_shared_secret) || ser32(k))''
+**** If ''tk'' is not valid tweak, i.e., if ''tk = 0'' or ''tk'' is larger or equal to the secp256k1 group order, fail
+*** Let ''Pmn = Bm + tk·G''
+*** Encode ''Pmn'' as a [https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki BIP341] taproot output
+*** Optionally, repeat with k++ to create additional outputs for the current ''Bm''
+*** If no additional outputs are required, continue to the next ''Bm'' with ''k++''''' Why not re-use ''tk'' when paying different labels to the same receiver?''' If paying the same entity but to two separate labeled addresses in the same transaction without incrementing ''k'', an outside observer could subtract the two output values and observe that this value is the same as the difference between two published silent payment addresses and learn who the recipient is.
+** Optionally, if the sending wallet implements receiving silent payments, it can create change outputs by sending to its own silent payment address using label ''m = 0'', following the steps above
+
+=== Receiver ===
+
+==== Key Derivation ====
+
+Two keys are needed to create a silent payments address: the spend key and the scan key. To ensure compatibility, wallets MAY use BIP32 derivation with the following derivation paths for the spend and scan key. When using BIP32 derivation, wallet software MUST use hardened derivation'''Why use BIP32 hardened derivation?''' Using BIP32 derivation allows users to add silent payments to an existing master seed. It also ensures that a user's silent payment funds are recoverable in any BIP32/BIP43 compatible wallet. Using hardened derivation ensures that it is safe to export the scan private key without exposing the master key or spend private key. for both the spend and scan key.
+
+A scan and spend key pair using BIP32 derivation are defined (taking inspiration from [https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki BIP44]) in the following manner:
+
+ scan_private_key: m / purpose' / coin_type' / account' / 1' / 0
+ spend_private_key: m / purpose' / coin_type' / account' / 0' / 0
+
+purpose is a constant set to ''352'' following the BIP43 recommendation. Refer to [https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki BIP43] and [https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki BIP44] for more details.
+
+==== Scanning ====
+
+If each of the checks in ''[[#scanning-silent-payment-eligible-transactions|Scanning silent payment eligible transactions]]'' passes, the receiving wallet must:
+
+* Let ''A = A1 + A2 + ... + An'', where each ''Ai'' is the public key of an input from the ''[[#inputs-for-shared-secret-derivation|Inputs For Shared Secret Derivation]]'' list
+** If ''A'' is the point at infinity, skip the transaction
+* Let ''input_hash = hashBIP0352/Inputs(outpointL || A)'', where ''outpointL'' is the smallest ''outpoint'' lexicographically used in the transaction
+* Let ''ecdh_shared_secret = input_hash·bscan·A''
+* Check for outputs:
+** Let ''outputs_to_check'' be the taproot output keys from all taproot outputs in the transaction (spent and unspent).
+** Starting with ''k = 0'':
+*** Let ''tk = hashBIP0352/SharedSecret(serP(ecdh_shared_secret) || ser32(k))''
+**** If ''tk'' is not valid tweak, i.e., if ''tk = 0'' or ''tk'' is larger or equal to the secp256k1 group order, fail
+*** Compute ''Pk = Bspend + tk·G''
+*** For each ''output'' in ''outputs_to_check'':
+**** If ''Pk'' equals ''output'':
+***** Add ''Pk'' to the wallet
+***** Remove ''output'' from ''outputs_to_check'' and rescan ''outputs_to_check'' with ''k++''
+**** Else, check for labels (always check for the change label, i.e. ''hashBIP0352/Label(ser256(bscan) || ser32(m))'' where ''m = 0'')''' Why precompute labels?''' Precomputing the labels is not strictly necessary: a wallet could track the max number of labels it has used (call it ''M'') and scan for labels by adding ''hash(bscan || m)·G'' to ''P0'' for each label ''m'' up to ''M'' and comparing to the transaction outputs. This is more performant than precomputing the labels and checking via subtraction in cases where the number of eligible outputs exceeds the number of labels in use. In practice this will mainly apply to users that choose never to use labels, or users that use a single label for generating silent payment change outputs. If using a large number of labels, the wallet would need to add all possible labels to each output. This ends up being ''n·M'' additions, where ''n'' is the number of outputs in the transaction and ''M'' is the number of labels in the wallet. By precomputing the labels, the wallet only needs to compute ''hash(bscan || m)·G'' once when creating the labeled address and can determine if a label was used via a lookup, rather than adding each label to each output.:
+***** Compute ''label = output - Pk''
+***** Check if ''label'' exists in the list of labels used by the wallet
+***** If a match is found:
+****** Add ''Pk + label'' to the wallet
+****** Remove ''output'' from ''outputs_to_check'' and rescan ''outputs_to_check'' with ''k++''
+***** If a label is not found, negate ''output'' and check a second time''' Why negate the output?''' Unfortunately taproot outputs are X-only, meaning we don't know what the correct Y coordinate is. This causes this specific calculation to fail 50% of the time, so we need to repeat it with the other Y coordinate by negating the output.
+*** If no matches are found, stop
+
+==== Spending ====
+
+Recall that a silent payment output is of the form ''Bspend + tk·G + hashBIP0352/Label(ser256(bscan) || ser32(m))·G'', where ''hashBIP0352/Label(ser256(bscan) || ser32(m))·G'' is an optional label. To spend a silent payment output:
+
+* Let ''d = (bspend + tk + hashBIP0352/Label(ser256(bscan) || ser32(m))) mod n'', where ''hashBIP0352/Label(ser256(bscan) || ser32(m))'' is the optional label
+* Spend the [https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki BIP341] output with the private key ''d''
+
+==== Backup and Recovery ====
+
+Since each silent payment output address is derived independently, regular backups are recommended. When recovering from a backup, the wallet will need to scan since the last backup to detect new payments.
+
+If using a seed/seed phrase only style backup, the user can recover the wallet's unspent outputs from the UTXO set (i.e. only scanning transactions with at least one unspent taproot output) and can recover the full wallet history by scanning the blockchain starting from the wallet birthday. If a wallet uses labels, this information SHOULD be included in the backup. If the user does not know whether labels were used, it is strongly recommended they always precompute and check a large number of labels (e.g. 100k labels) to use when re-scanning. This ensures that the wallet can recover all funds from only a seed/seed phrase backup. The change label should simply always be scanned for, even when no other labels were used. This ensures the use of a change label is not critical for backups and maximizes cross-compatibility.
+
+== Backward Compatibility ==
+
+Silent payments introduces a new address format and protocol for sending and as such is not compatible with older wallet software or wallets which have not implemented the silent payments protocol.
+
+== Test Vectors ==
+
+A [[bip-0352/send_and_receive_test_vectors.json|collection of test vectors in JSON format]] are provided, along with a [[bip-0352/reference.py|python reference implementation]]. Each test vector consists of a sending test case and corresponding receiving test case. This is to allow sending and receiving to be implemented separately. To ensure determinism while testing, sort the array of ''Bm'' by amount (see the [[bip-0352/reference.py|reference implementation]]). Test cases use the following schema:
+
+''' test_case '''
+
+ {
+ "comment": "Comment describing the behavior being tested",
+ "sending": [],
+ "receiving": [],
+ }
+
+''' sender '''
+
+ {
+ "given": {
+ "vin": [],
+ "recipients": []
+ },
+ "expected": {
+ "outputs": [],
+ "n_outputs": ,
+ },
+ }
+
+''' recipient '''
+
+ {
+ "given": {
+ "vin": [],
+ "key_material": {
+ "scan_priv_key": ,
+ "spend_priv_key": ,
+ }
+ "labels": [],
+ },
+ "expected": {
+ "addresses": [],
+ "outputs": [
+ {
+ "priv_key_tweak": ,
+ "pub_key": ,
+ "signature":
+ },
+ ...
+ ],
+ "n_outputs":
+ }
+ }
+
+Wallets should include inputs not in the ''[[#inputs-for-shared-secret-derivation|Inputs For Shared Secret Derivation]]'' list when testing to ensure that only inputs from the list are being used for shared secret derivation. Additionally, receiving wallets should include non-silent payment outputs for themselves in testing to ensure silent payments scanning does not interfere with regular outputs detection.
+
+=== Functional tests ===
+
+Below is a list of functional tests which should be included in sending and receiving implementations.
+
+==== Sending ====
+
+* Ensure taproot outputs are excluded during coin selection if the sender does not have access to the key path private key (unless using ''H'' as the taproot internal key)
+* Ensure the silent payment address is re-derived if inputs are added or removed during RBF
+
+==== Receiving ====
+
+* Ensure the public key can be extracted from non-standard ''P2PKH'' scriptSigs
+* Ensure taproot script path spends are included, using the taproot output key (unless ''H'' is used as the taproot internal key)
+* Ensure the scanner can extract the public key from each of the input types supported (e.g. ''P2WPKH'', ''P2SH-P2WPKH'', etc.)
+
+== Appendix A: Light Client Support ==
+
+This section proposes a few ideas for how light clients could support scanning for incoming silent payments (sending is fairly straightforward) in ways that preserve bandwidth and privacy. While this is out of scope for the current BIP, it is included to motivate further research into this topic. In this context, a light client refers to any bitcoin wallet client which does not process blocks and does not have a direct connection to a node which does process blocks (e.g. a full node). Based on this definition, clients that directly connect to a personal electrum server or a bitcoin node are not light clients.
+
+This distinction makes the problem for light clients more clear: light clients need a way to source the necessary data for performing the tweaks and a way of determining if any of the generated outputs exist in a block.
+
+=== Tweak Data ===
+
+Recall that a silent payment eligible transaction follows [[#scanning-silent-payment-eligible-transactions|certain conditions]] and should have at least one unspent taproot output. Full nodes (or any index server backed by a full node, such as electrum server) can build an index which collects all of the eligible public keys for a silent payments eligible transaction, sums them up, multiplies the sum by the ''input_hash'', and serves them to clients. This would be 33 bytes per silent payment eligible transaction.
+
+For a typical bitcoin block of ~3500 txs, lets assume every transaction is a silent payments eligible transaction. This means a client would need to request ''33 bytes * 3500'' of data per block (roughly 100 kB per block). If a client were to request data for every block, this would amount to ~450 MB per month, assuming 100% taproot usage and all non-dust outputs remain unspent for > 1 month. As of today, these numbers are closer to 7–12 kB per block (30–50 MB per month)''' Data for Appendix A ''' These numbers are based on data from January 2023 until July 2024. See [https://github.com/josibake/bitcoin-data-analysis/blob/main/notebooks/silent-payments-light-client-data.ipynb Silent payments light client data] for the full analysis..
+
+=== Transaction cut-through ===
+
+It is unlikely a light client would need to scan every block and as such can take advantage of transaction cut-through, depending on how often they choose to scan for new blocks. Empirically, ~75% of transactions with at least one non-dust unspent taproot output will have spent all non-dust taproot UTXOs in 150 blocks or less. This means a client that only scans once per day could ''significantly'' cut down on the number of blocks and the number of transactions per block that they need to request by only asking for data on transactions that were created since their last scan and that still have at least one non-dust unspent taproot output as of the current block height. Based on taproot adoption as of July 2024, a light client scanning once every 3 days would use roughly 30 MB per month.
+
+[[File:bip-0352/scan_data_downloader_per_month.png]]
+
+=== BIP158 ===
+
+Once a light client has the tweak data for a block, they can determine whether or not an output to them exists in the block using BIP158 block filters. Per BIP158, they would then request the entire block and add the transaction to their wallet, though it maybe be possible to only request the prevout txids and vouts for all transactions with at least one taproot output, along with the scriptPubKeys and amounts. This would allow the client to download the necessary data for constructing a spending transaction, without downloading the entire block. How this affects the security assumptions of BIP158 is an open question.
+
+=== Out-of-band notifications ===
+
+Assuming a secure messaging protocol exists, the sender can send an encrypted (using the scan public key of the silent payment address) notification to the receiver with the following information:
+* The spend public key (communicates the label)
+* The shared secret portion of the private key (i.e ''hash(ecdh_shared_secret || k)'')
+* The outpoint and amount (so it's immediately spendable)
+
+It is important to note that these notifications are not required. At any point, the receiver can fall back to scanning for silent payment transactions if they don't trust the notifications they are receiving, are being spammed with fake notifications, or if they are concerned that they are not receiving notifications.
+
+A malicious notification could potentially cause the following issues:
+
+* You did not actually receive money to the stated key
+** This can be probabilistically resolved by matching the key against the BIP158 block filters and assuming it's not a false positive, or fully resolved by downloading the block
+* You received money but the outpoint or amount is incorrect, so attempts to spend it will fail or cause you to overpay fees
+** There doesn't seem to be much motivation for malicious senders to ever do this, but light clients need to take into account that this can occur and should ideally check for it by downloading the block
+* The private key is correct but it wasn't actually derived using the silent payment protocol, causing recovery from back-up to fail (unsafe - no implementation should ever allow this)
+** This can be detected by downloading the tweak data of the corresponding block and should be resolved by immediately spending the output
+
+Wallet designers can choose which tradeoffs they find appropriate. For example, a wallet could check the block filter to at least probabilistically confirm the likely existence of the UTXO, thus efficiently cutting down on spam. The payment could then be marked as unconfirmed until a scan is performed and the existence of the UTXO in accordance to the silent payment specification is verified.
+
+== Change Log ==
+
+To help implementers understand updates to this document, we attach a version number that resembles ''semantic versioning'' (MAJOR.MINOR.PATCH).
+The MAJOR version is incremented if changes to the BIP are introduced that are incompatible with prior versions.
+The MINOR version is incremented whenever the inputs or the output of an algorithm changes in a backward-compatible way or new backward-compatible functionality is added.
+The PATCH version is incremented for other changes that are noteworthy (bug fixes, test vectors, important clarifications, etc.).
+
+* '''1.0.1''' (2024-06-22):
+** Add steps to fail if private key sum is zero (for sender) or public key sum is point at infinity (for receiver), add corresponding test vectors.
+* '''1.0.0''' (2024-05-08):
+** Initial version, merged as BIP-352.
+
+== Acknowledgements ==
+
+This document is the result of many discussions and contains contributions by a number of people. The authors wish to thank all those who provided valuable feedback and reviews, including the participants of the [https://gist.github.com/RubenSomsen/21c477c90c942acf45f8e8f5c1ad4fae BIP47 Prague discussion], the [https://github.com/josibake/silent-payments-workshop Advancing Bitcoin silent payments Workshop], and [https://btctranscripts.com/bitcoin-core-dev-tech/2023-04/2023-04-26-silent-payments/ coredev]. The authors would like to also thank [https://github.com/w0xlt w0xlt] for writing the initial implementation of silent payments.
+
+== Rationale and References ==
+
+
diff --git a/bip-0352/bech32m.py b/bip-0352/bech32m.py
new file mode 100644
index 0000000000..795e153863
--- /dev/null
+++ b/bip-0352/bech32m.py
@@ -0,0 +1,135 @@
+# Copyright (c) 2017, 2020 Pieter Wuille
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+
+"""Reference implementation for Bech32/Bech32m and segwit addresses."""
+
+
+from enum import Enum
+
+class Encoding(Enum):
+ """Enumeration type to list the various supported encodings."""
+ BECH32 = 1
+ BECH32M = 2
+
+CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
+BECH32M_CONST = 0x2bc830a3
+
+def bech32_polymod(values):
+ """Internal function that computes the Bech32 checksum."""
+ generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]
+ chk = 1
+ for value in values:
+ top = chk >> 25
+ chk = (chk & 0x1ffffff) << 5 ^ value
+ for i in range(5):
+ chk ^= generator[i] if ((top >> i) & 1) else 0
+ return chk
+
+
+def bech32_hrp_expand(hrp):
+ """Expand the HRP into values for checksum computation."""
+ return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp]
+
+
+def bech32_verify_checksum(hrp, data):
+ """Verify a checksum given HRP and converted data characters."""
+ const = bech32_polymod(bech32_hrp_expand(hrp) + data)
+ if const == 1:
+ return Encoding.BECH32
+ if const == BECH32M_CONST:
+ return Encoding.BECH32M
+ return None
+
+def bech32_create_checksum(hrp, data, spec):
+ """Compute the checksum values given HRP and data."""
+ values = bech32_hrp_expand(hrp) + data
+ const = BECH32M_CONST if spec == Encoding.BECH32M else 1
+ polymod = bech32_polymod(values + [0, 0, 0, 0, 0, 0]) ^ const
+ return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)]
+
+
+def bech32_encode(hrp, data, spec):
+ """Compute a Bech32 string given HRP and data values."""
+ combined = data + bech32_create_checksum(hrp, data, spec)
+ return hrp + '1' + ''.join([CHARSET[d] for d in combined])
+
+def bech32_decode(bech):
+ """Validate a Bech32/Bech32m string, and determine HRP and data."""
+ if ((any(ord(x) < 33 or ord(x) > 126 for x in bech)) or
+ (bech.lower() != bech and bech.upper() != bech)):
+ return (None, None, None)
+ bech = bech.lower()
+ pos = bech.rfind('1')
+
+ # remove the requirement that bech32m be less than 90 chars
+ if pos < 1 or pos + 7 > len(bech):
+ return (None, None, None)
+ if not all(x in CHARSET for x in bech[pos+1:]):
+ return (None, None, None)
+ hrp = bech[:pos]
+ data = [CHARSET.find(x) for x in bech[pos+1:]]
+ spec = bech32_verify_checksum(hrp, data)
+ if spec is None:
+ return (None, None, None)
+ return (hrp, data[:-6], spec)
+
+def convertbits(data, frombits, tobits, pad=True):
+ """General power-of-2 base conversion."""
+ acc = 0
+ bits = 0
+ ret = []
+ maxv = (1 << tobits) - 1
+ max_acc = (1 << (frombits + tobits - 1)) - 1
+ for value in data:
+ if value < 0 or (value >> frombits):
+ return None
+ acc = ((acc << frombits) | value) & max_acc
+ bits += frombits
+ while bits >= tobits:
+ bits -= tobits
+ ret.append((acc >> bits) & maxv)
+ if pad:
+ if bits:
+ ret.append((acc << (tobits - bits)) & maxv)
+ elif bits >= frombits or ((acc << (tobits - bits)) & maxv):
+ return None
+ return ret
+
+
+def decode(hrp, addr):
+ """Decode a segwit address."""
+ hrpgot, data, spec = bech32_decode(addr)
+ if hrpgot != hrp:
+ return (None, None)
+ decoded = convertbits(data[1:], 5, 8, False)
+ if decoded is None or len(decoded) < 2:
+ return (None, None)
+ if data[0] > 16:
+ return (None, None)
+ return (data[0], decoded)
+
+
+def encode(hrp, witver, witprog):
+ """Encode a segwit address."""
+ spec = Encoding.BECH32 if witver == 0 else Encoding.BECH32M
+ ret = bech32_encode(hrp, [witver] + convertbits(witprog, 8, 5), spec)
+ if decode(hrp, ret) == (None, None):
+ return None
+ return ret
diff --git a/bip-0352/bitcoin_utils.py b/bip-0352/bitcoin_utils.py
new file mode 100644
index 0000000000..ee55f2d3b3
--- /dev/null
+++ b/bip-0352/bitcoin_utils.py
@@ -0,0 +1,159 @@
+import hashlib
+import struct
+from io import BytesIO
+from ripemd160 import ripemd160
+from secp256k1 import ECKey
+from typing import Union
+
+
+def from_hex(hex_string):
+ """Deserialize from a hex string representation (e.g. from RPC)"""
+ return BytesIO(bytes.fromhex(hex_string))
+
+
+def ser_uint32(u: int) -> bytes:
+ return u.to_bytes(4, "big")
+
+
+def ser_uint256(u):
+ return u.to_bytes(32, 'little')
+
+
+def deser_uint256(f):
+ return int.from_bytes(f.read(32), 'little')
+
+
+def deser_txid(txid: str):
+ # recall that txids are serialized little-endian, but displayed big-endian
+ # this means when converting from a human readable hex txid, we need to first
+ # reverse it before deserializing it
+ dixt = "".join(map(str.__add__, txid[-2::-2], txid[-1::-2]))
+ return bytes.fromhex(dixt)
+
+
+def deser_compact_size(f: BytesIO):
+ view = f.getbuffer()
+ nbytes = view.nbytes;
+ view.release()
+ if (nbytes == 0):
+ return 0 # end of stream
+
+ nit = struct.unpack(" bytes:
+ return ripemd160(hashlib.sha256(s).digest())
+
+
+def is_p2tr(spk: bytes) -> bool:
+ if len(spk) != 34:
+ return False
+ # OP_1 OP_PUSHBYTES_32 <32 bytes>
+ return (spk[0] == 0x51) & (spk[1] == 0x20)
+
+
+def is_p2wpkh(spk: bytes) -> bool:
+ if len(spk) != 22:
+ return False
+ # OP_0 OP_PUSHBYTES_20 <20 bytes>
+ return (spk[0] == 0x00) & (spk[1] == 0x14)
+
+
+def is_p2sh(spk: bytes) -> bool:
+ if len(spk) != 23:
+ return False
+ # OP_HASH160 OP_PUSHBYTES_20 <20 bytes> OP_EQUAL
+ return (spk[0] == 0xA9) & (spk[1] == 0x14) & (spk[-1] == 0x87)
+
+
+def is_p2pkh(spk: bytes) -> bool:
+ if len(spk) != 25:
+ return False
+ # OP_DUP OP_HASH160 OP_PUSHBYTES_20 <20 bytes> OP_EQUALVERIFY OP_CHECKSIG
+ return (spk[0] == 0x76) & (spk[1] == 0xA9) & (spk[2] == 0x14) & (spk[-2] == 0x88) & (spk[-1] == 0xAC)
diff --git a/bip-0352/reference.py b/bip-0352/reference.py
new file mode 100755
index 0000000000..b4eaf94560
--- /dev/null
+++ b/bip-0352/reference.py
@@ -0,0 +1,342 @@
+#!/usr/bin/env python3
+# For running the test vectors, run this script:
+# ./reference.py send_and_receive_test_vectors.json
+
+import hashlib
+import json
+from typing import List, Tuple, Dict, cast
+from sys import argv, exit
+from functools import reduce
+from itertools import permutations
+
+# local files
+from bech32m import convertbits, bech32_encode, decode, Encoding
+from secp256k1 import ECKey, ECPubKey, TaggedHash, NUMS_H
+from bitcoin_utils import (
+ deser_txid,
+ from_hex,
+ hash160,
+ is_p2pkh,
+ is_p2sh,
+ is_p2wpkh,
+ is_p2tr,
+ ser_uint32,
+ COutPoint,
+ CTxInWitness,
+ VinInfo,
+ )
+
+
+def get_pubkey_from_input(vin: VinInfo) -> ECPubKey:
+ if is_p2pkh(vin.prevout):
+ # skip the first 3 op_codes and grab the 20 byte hash
+ # from the scriptPubKey
+ spk_hash = vin.prevout[3:3 + 20]
+ for i in range(len(vin.scriptSig), 0, -1):
+ if i - 33 >= 0:
+ # starting from the back, we move over the scriptSig with a 33 byte
+ # window (to match a compressed pubkey). we hash this and check if it matches
+ # the 20 byte has from the scriptPubKey. for standard scriptSigs, this will match
+ # right away because the pubkey is the last item in the scriptSig.
+ # if its a non-standard (malleated) scriptSig, we will still find the pubkey if its
+ # a compressed pubkey.
+ #
+ # note: this is an incredibly inefficient implementation, for demonstration purposes only.
+ pubkey_bytes = vin.scriptSig[i - 33:i]
+ pubkey_hash = hash160(pubkey_bytes)
+ if pubkey_hash == spk_hash:
+ pubkey = ECPubKey().set(pubkey_bytes)
+ if (pubkey.valid) & (pubkey.compressed):
+ return pubkey
+ if is_p2sh(vin.prevout):
+ redeem_script = vin.scriptSig[1:]
+ if is_p2wpkh(redeem_script):
+ pubkey = ECPubKey().set(vin.txinwitness.scriptWitness.stack[-1])
+ if (pubkey.valid) & (pubkey.compressed):
+ return pubkey
+ if is_p2wpkh(vin.prevout):
+ txin = vin.txinwitness
+ pubkey = ECPubKey().set(txin.scriptWitness.stack[-1])
+ if (pubkey.valid) & (pubkey.compressed):
+ return pubkey
+ if is_p2tr(vin.prevout):
+ witnessStack = vin.txinwitness.scriptWitness.stack
+ if (len(witnessStack) >= 1):
+ if (len(witnessStack) > 1 and witnessStack[-1][0] == 0x50):
+ # Last item is annex
+ witnessStack.pop()
+
+ if (len(witnessStack) > 1):
+ # Script-path spend
+ control_block = witnessStack[-1]
+ # control block is <32 byte internal key> and 0 or more <32 byte hash>
+ internal_key = control_block[1:33]
+ if (internal_key == NUMS_H.to_bytes(32, 'big')):
+ # Skip if NUMS_H
+ return ECPubKey()
+
+ pubkey = ECPubKey().set(vin.prevout[2:])
+ if (pubkey.valid) & (pubkey.compressed):
+ return pubkey
+
+
+ return ECPubKey()
+
+
+def get_input_hash(outpoints: List[COutPoint], sum_input_pubkeys: ECPubKey) -> bytes:
+ lowest_outpoint = sorted(outpoints, key=lambda outpoint: outpoint.serialize())[0]
+ return TaggedHash("BIP0352/Inputs", lowest_outpoint.serialize() + cast(bytes, sum_input_pubkeys.get_bytes(False)))
+
+
+
+def encode_silent_payment_address(B_scan: ECPubKey, B_m: ECPubKey, hrp: str = "tsp", version: int = 0) -> str:
+ data = convertbits(cast(bytes, B_scan.get_bytes(False)) + cast(bytes, B_m.get_bytes(False)), 8, 5)
+ return bech32_encode(hrp, [version] + cast(List[int], data), Encoding.BECH32M)
+
+
+def generate_label(b_scan: ECKey, m: int) -> bytes:
+ return TaggedHash("BIP0352/Label", b_scan.get_bytes() + ser_uint32(m))
+
+
+def create_labeled_silent_payment_address(b_scan: ECKey, B_spend: ECPubKey, m: int, hrp: str = "tsp", version: int = 0) -> str:
+ G = ECKey().set(1).get_pubkey()
+ B_scan = b_scan.get_pubkey()
+ B_m = B_spend + generate_label(b_scan, m) * G
+ labeled_address = encode_silent_payment_address(B_scan, B_m, hrp, version)
+
+ return labeled_address
+
+
+def decode_silent_payment_address(address: str, hrp: str = "tsp") -> Tuple[ECPubKey, ECPubKey]:
+ _, data = decode(hrp, address)
+ if data is None:
+ return ECPubKey(), ECPubKey()
+ B_scan = ECPubKey().set(data[:33])
+ B_spend = ECPubKey().set(data[33:])
+
+ return B_scan, B_spend
+
+
+def create_outputs(input_priv_keys: List[Tuple[ECKey, bool]], outpoints: List[COutPoint], recipients: List[str], hrp="tsp") -> List[str]:
+ G = ECKey().set(1).get_pubkey()
+ negated_keys = []
+ for key, is_xonly in input_priv_keys:
+ k = ECKey().set(key.get_bytes())
+ if is_xonly and k.get_pubkey().get_y() % 2 != 0:
+ k.negate()
+ negated_keys.append(k)
+
+ a_sum = sum(negated_keys)
+ if not a_sum.valid:
+ # Input privkeys sum is zero -> fail
+ return []
+ input_hash = get_input_hash(outpoints, a_sum * G)
+ silent_payment_groups: Dict[ECPubKey, List[ECPubKey]] = {}
+ for recipient in recipients:
+ B_scan, B_m = decode_silent_payment_address(recipient, hrp=hrp)
+ if B_scan in silent_payment_groups:
+ silent_payment_groups[B_scan].append(B_m)
+ else:
+ silent_payment_groups[B_scan] = [B_m]
+
+ outputs = []
+ for B_scan, B_m_values in silent_payment_groups.items():
+ ecdh_shared_secret = input_hash * a_sum * B_scan
+ k = 0
+ for B_m in B_m_values:
+ t_k = TaggedHash("BIP0352/SharedSecret", ecdh_shared_secret.get_bytes(False) + ser_uint32(k))
+ P_km = B_m + t_k * G
+ outputs.append(P_km.get_bytes().hex())
+ k += 1
+
+ return list(set(outputs))
+
+
+def scanning(b_scan: ECKey, B_spend: ECPubKey, A_sum: ECPubKey, input_hash: bytes, outputs_to_check: List[ECPubKey], labels: Dict[str, str] = {}) -> List[Dict[str, str]]:
+ G = ECKey().set(1).get_pubkey()
+ ecdh_shared_secret = input_hash * b_scan * A_sum
+ k = 0
+ wallet = []
+ while True:
+ t_k = TaggedHash("BIP0352/SharedSecret", ecdh_shared_secret.get_bytes(False) + ser_uint32(k))
+ P_k = B_spend + t_k * G
+ for output in outputs_to_check:
+ if P_k == output:
+ wallet.append({"pub_key": P_k.get_bytes().hex(), "priv_key_tweak": t_k.hex()})
+ outputs_to_check.remove(output)
+ k += 1
+ break
+ elif labels:
+ m_G_sub = output - P_k
+ if m_G_sub.get_bytes(False).hex() in labels:
+ P_km = P_k + m_G_sub
+ wallet.append({
+ "pub_key": P_km.get_bytes().hex(),
+ "priv_key_tweak": (ECKey().set(t_k).add(
+ bytes.fromhex(labels[m_G_sub.get_bytes(False).hex()])
+ )).get_bytes().hex(),
+ })
+ outputs_to_check.remove(output)
+ k += 1
+ break
+ else:
+ output.negate()
+ m_G_sub = output - P_k
+ if m_G_sub.get_bytes(False).hex() in labels:
+ P_km = P_k + m_G_sub
+ wallet.append({
+ "pub_key": P_km.get_bytes().hex(),
+ "priv_key_tweak": (ECKey().set(t_k).add(
+ bytes.fromhex(labels[m_G_sub.get_bytes(False).hex()])
+ )).get_bytes().hex(),
+ })
+ outputs_to_check.remove(output)
+ k += 1
+ break
+ else:
+ break
+ return wallet
+
+
+if __name__ == "__main__":
+ if len(argv) != 2 or argv[1] in ('-h', '--help'):
+ print("Usage: ./reference.py send_and_receive_test_vectors.json")
+ exit(0)
+
+ with open(argv[1], "r") as f:
+ test_data = json.loads(f.read())
+
+ # G , needed for generating the labels "database"
+ G = ECKey().set(1).get_pubkey()
+ for case in test_data:
+ print(case["comment"])
+ # Test sending
+ for sending_test in case["sending"]:
+ given = sending_test["given"]
+ expected = sending_test["expected"]
+
+ vins = [
+ VinInfo(
+ outpoint=COutPoint(hash=deser_txid(input["txid"]), n=input["vout"]),
+ scriptSig=bytes.fromhex(input["scriptSig"]),
+ txinwitness=CTxInWitness().deserialize(from_hex(input["txinwitness"])),
+ prevout=bytes.fromhex(input["prevout"]["scriptPubKey"]["hex"]),
+ private_key=ECKey().set(bytes.fromhex(input["private_key"])),
+ )
+ for input in given["vin"]
+ ]
+ # Convert the tuples to lists so they can be easily compared to the json list of lists from the given test vectors
+ input_priv_keys = []
+ input_pub_keys = []
+ for vin in vins:
+ pubkey = get_pubkey_from_input(vin)
+ if not pubkey.valid:
+ continue
+ input_priv_keys.append((
+ vin.private_key,
+ is_p2tr(vin.prevout),
+ ))
+ input_pub_keys.append(pubkey)
+
+ sending_outputs = []
+ if (len(input_pub_keys) > 0):
+ outpoints = [vin.outpoint for vin in vins]
+ sending_outputs = create_outputs(input_priv_keys, outpoints, given["recipients"], hrp="sp")
+
+ # Note: order doesn't matter for creating/finding the outputs. However, different orderings of the recipient addresses
+ # will produce different generated outputs if sending to multiple silent payment addresses belonging to the
+ # same sender but with different labels. Because of this, expected["outputs"] contains all possible valid output sets,
+ # based on all possible permutations of recipient address orderings. Must match exactly one of the possible output sets.
+ assert(any(set(sending_outputs) == set(lst) for lst in expected["outputs"])), "Sending test failed"
+ else:
+ assert(sending_outputs == expected["outputs"][0] == []), "Sending test failed"
+
+ # Test receiving
+ msg = hashlib.sha256(b"message").digest()
+ aux = hashlib.sha256(b"random auxiliary data").digest()
+ for receiving_test in case["receiving"]:
+ given = receiving_test["given"]
+ expected = receiving_test["expected"]
+ outputs_to_check = [
+ ECPubKey().set(bytes.fromhex(p)) for p in given["outputs"]
+ ]
+ vins = [
+ VinInfo(
+ outpoint=COutPoint(hash=deser_txid(input["txid"]), n=input["vout"]),
+ scriptSig=bytes.fromhex(input["scriptSig"]),
+ txinwitness=CTxInWitness().deserialize(from_hex(input["txinwitness"])),
+ prevout=bytes.fromhex(input["prevout"]["scriptPubKey"]["hex"]),
+ )
+ for input in given["vin"]
+ ]
+ # Check that the given inputs for the receiving test match what was generated during the sending test
+ receiving_addresses = []
+ b_scan = ECKey().set(bytes.fromhex(given["key_material"]["scan_priv_key"]))
+ b_spend = ECKey().set(
+ bytes.fromhex(given["key_material"]["spend_priv_key"])
+ )
+ B_scan = b_scan.get_pubkey()
+ B_spend = b_spend.get_pubkey()
+ receiving_addresses.append(
+ encode_silent_payment_address(B_scan, B_spend, hrp="sp")
+ )
+ if given["labels"]:
+ for label in given["labels"]:
+ receiving_addresses.append(
+ create_labeled_silent_payment_address(
+ b_scan, B_spend, m=label, hrp="sp"
+ )
+ )
+
+ # Check that the silent payment addresses match for the given BIP32 seed and labels dictionary
+ assert (receiving_addresses == expected["addresses"]), "Receiving addresses don't match"
+ input_pub_keys = []
+ for vin in vins:
+ pubkey = get_pubkey_from_input(vin)
+ if not pubkey.valid:
+ continue
+ input_pub_keys.append(pubkey)
+
+ add_to_wallet = []
+ if (len(input_pub_keys) > 0):
+ A_sum = reduce(lambda x, y: x + y, input_pub_keys)
+ if A_sum.get_bytes() is None:
+ # Input pubkeys sum is point at infinity -> skip tx
+ assert expected["outputs"] == []
+ continue
+ input_hash = get_input_hash([vin.outpoint for vin in vins], A_sum)
+ pre_computed_labels = {
+ (generate_label(b_scan, label) * G).get_bytes(False).hex(): generate_label(b_scan, label).hex()
+ for label in given["labels"]
+ }
+ add_to_wallet = scanning(
+ b_scan=b_scan,
+ B_spend=B_spend,
+ A_sum=A_sum,
+ input_hash=input_hash,
+ outputs_to_check=outputs_to_check,
+ labels=pre_computed_labels,
+ )
+
+ # Check that the private key is correct for the found output public key
+ for output in add_to_wallet:
+ pub_key = ECPubKey().set(bytes.fromhex(output["pub_key"]))
+ full_private_key = b_spend.add(bytes.fromhex(output["priv_key_tweak"]))
+ if full_private_key.get_pubkey().get_y() % 2 != 0:
+ full_private_key.negate()
+
+ sig = full_private_key.sign_schnorr(msg, aux)
+ assert pub_key.verify_schnorr(sig, msg), f"Invalid signature for {pub_key}"
+ output["signature"] = sig.hex()
+
+ # Note: order doesn't matter for creating/finding the outputs. However, different orderings of the recipient addresses
+ # will produce different generated outputs if sending to multiple silent payment addresses belonging to the
+ # same sender but with different labels. Because of this, expected["outputs"] contains all possible valid output sets,
+ # based on all possible permutations of recipient address orderings. Must match exactly one of the possible found output
+ # sets in expected["outputs"]
+ generated_set = {frozenset(d.items()) for d in add_to_wallet}
+ expected_set = {frozenset(d.items()) for d in expected["outputs"]}
+ assert generated_set == expected_set, "Receive test failed"
+
+
+ print("All tests passed")
diff --git a/bip-0352/ripemd160.py b/bip-0352/ripemd160.py
new file mode 100644
index 0000000000..12801364b4
--- /dev/null
+++ b/bip-0352/ripemd160.py
@@ -0,0 +1,130 @@
+# Copyright (c) 2021 Pieter Wuille
+# Distributed under the MIT software license, see the accompanying
+# file COPYING or http://www.opensource.org/licenses/mit-license.php.
+"""Test-only pure Python RIPEMD160 implementation."""
+
+import unittest
+
+# Message schedule indexes for the left path.
+ML = [
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+ 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
+ 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
+ 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
+ 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
+]
+
+# Message schedule indexes for the right path.
+MR = [
+ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
+ 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
+ 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
+ 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
+ 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
+]
+
+# Rotation counts for the left path.
+RL = [
+ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
+ 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
+ 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
+ 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
+ 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
+]
+
+# Rotation counts for the right path.
+RR = [
+ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
+ 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
+ 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
+ 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
+ 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
+]
+
+# K constants for the left path.
+KL = [0, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]
+
+# K constants for the right path.
+KR = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0]
+
+
+def fi(x, y, z, i):
+ """The f1, f2, f3, f4, and f5 functions from the specification."""
+ if i == 0:
+ return x ^ y ^ z
+ elif i == 1:
+ return (x & y) | (~x & z)
+ elif i == 2:
+ return (x | ~y) ^ z
+ elif i == 3:
+ return (x & z) | (y & ~z)
+ elif i == 4:
+ return x ^ (y | ~z)
+ else:
+ assert False
+
+
+def rol(x, i):
+ """Rotate the bottom 32 bits of x left by i bits."""
+ return ((x << i) | ((x & 0xffffffff) >> (32 - i))) & 0xffffffff
+
+
+def compress(h0, h1, h2, h3, h4, block):
+ """Compress state (h0, h1, h2, h3, h4) with block."""
+ # Left path variables.
+ al, bl, cl, dl, el = h0, h1, h2, h3, h4
+ # Right path variables.
+ ar, br, cr, dr, er = h0, h1, h2, h3, h4
+ # Message variables.
+ x = [int.from_bytes(block[4*i:4*(i+1)], 'little') for i in range(16)]
+
+ # Iterate over the 80 rounds of the compression.
+ for j in range(80):
+ rnd = j >> 4
+ # Perform left side of the transformation.
+ al = rol(al + fi(bl, cl, dl, rnd) + x[ML[j]] + KL[rnd], RL[j]) + el
+ al, bl, cl, dl, el = el, al, bl, rol(cl, 10), dl
+ # Perform right side of the transformation.
+ ar = rol(ar + fi(br, cr, dr, 4 - rnd) + x[MR[j]] + KR[rnd], RR[j]) + er
+ ar, br, cr, dr, er = er, ar, br, rol(cr, 10), dr
+
+ # Compose old state, left transform, and right transform into new state.
+ return h1 + cl + dr, h2 + dl + er, h3 + el + ar, h4 + al + br, h0 + bl + cr
+
+
+def ripemd160(data):
+ """Compute the RIPEMD-160 hash of data."""
+ # Initialize state.
+ state = (0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0)
+ # Process full 64-byte blocks in the input.
+ for b in range(len(data) >> 6):
+ state = compress(*state, data[64*b:64*(b+1)])
+ # Construct final blocks (with padding and size).
+ pad = b"\x80" + b"\x00" * ((119 - len(data)) & 63)
+ fin = data[len(data) & ~63:] + pad + (8 * len(data)).to_bytes(8, 'little')
+ # Process final blocks.
+ for b in range(len(fin) >> 6):
+ state = compress(*state, fin[64*b:64*(b+1)])
+ # Produce output.
+ return b"".join((h & 0xffffffff).to_bytes(4, 'little') for h in state)
+
+
+class TestFrameworkKey(unittest.TestCase):
+ def test_ripemd160(self):
+ """RIPEMD-160 test vectors."""
+ # See https://homes.esat.kuleuven.be/~bosselae/ripemd160.html
+ for msg, hexout in [
+ (b"", "9c1185a5c5e9fc54612808977ee8f548b2258d31"),
+ (b"a", "0bdc9d2d256b3ee9daae347be6f4dc835a467ffe"),
+ (b"abc", "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc"),
+ (b"message digest", "5d0689ef49d2fae572b881b123a85ffa21595f36"),
+ (b"abcdefghijklmnopqrstuvwxyz",
+ "f71c27109c692c1b56bbdceb5b9d2865b3708dbc"),
+ (b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
+ "12a053384a9c0c88e405a06c27dcf49ada62eb2b"),
+ (b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
+ "b0e20b6e3116640286ed3a87a5713079b21f5189"),
+ (b"1234567890" * 8, "9b752e45573d4b39f4dbd3323cab82bf63326bfb"),
+ (b"a" * 1000000, "52783243c1697bdbe16d37f97f68f08325dc1528")
+ ]:
+ self.assertEqual(ripemd160(msg).hex(), hexout)
diff --git a/bip-0352/scan_data_downloader_per_month.png b/bip-0352/scan_data_downloader_per_month.png
new file mode 100644
index 0000000000..a672a91add
Binary files /dev/null and b/bip-0352/scan_data_downloader_per_month.png differ
diff --git a/bip-0352/secp256k1.py b/bip-0352/secp256k1.py
new file mode 100644
index 0000000000..0ccbc4e6a4
--- /dev/null
+++ b/bip-0352/secp256k1.py
@@ -0,0 +1,696 @@
+# Copyright (c) 2019 Pieter Wuille
+# Distributed under the MIT software license, see the accompanying
+# file COPYING or http://www.opensource.org/licenses/mit-license.php.
+"""Test-only secp256k1 elliptic curve implementation
+
+WARNING: This code is slow, uses bad randomness, does not properly protect
+keys, and is trivially vulnerable to side channel attacks. Do not use for
+anything but tests."""
+import random
+import hashlib
+import hmac
+
+def TaggedHash(tag, data):
+ ss = hashlib.sha256(tag.encode('utf-8')).digest()
+ ss += ss
+ ss += data
+ return hashlib.sha256(ss).digest()
+
+def modinv(a, n):
+ """Compute the modular inverse of a modulo n
+
+ See https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Modular_integers.
+ """
+ t1, t2 = 0, 1
+ r1, r2 = n, a
+ while r2 != 0:
+ q = r1 // r2
+ t1, t2 = t2, t1 - q * t2
+ r1, r2 = r2, r1 - q * r2
+ if r1 > 1:
+ return None
+ if t1 < 0:
+ t1 += n
+ return t1
+
+def jacobi_symbol(n, k):
+ """Compute the Jacobi symbol of n modulo k
+
+ See http://en.wikipedia.org/wiki/Jacobi_symbol
+
+ For our application k is always prime, so this is the same as the Legendre symbol."""
+ assert k > 0 and k & 1, "jacobi symbol is only defined for positive odd k"
+ n %= k
+ t = 0
+ while n != 0:
+ while n & 1 == 0:
+ n >>= 1
+ r = k & 7
+ t ^= (r == 3 or r == 5)
+ n, k = k, n
+ t ^= (n & k & 3 == 3)
+ n = n % k
+ if k == 1:
+ return -1 if t else 1
+ return 0
+
+def modsqrt(a, p):
+ """Compute the square root of a modulo p when p % 4 = 3.
+
+ The Tonelli-Shanks algorithm can be used. See https://en.wikipedia.org/wiki/Tonelli-Shanks_algorithm
+
+ Limiting this function to only work for p % 4 = 3 means we don't need to
+ iterate through the loop. The highest n such that p - 1 = 2^n Q with Q odd
+ is n = 1. Therefore Q = (p-1)/2 and sqrt = a^((Q+1)/2) = a^((p+1)/4)
+
+ secp256k1's is defined over field of size 2**256 - 2**32 - 977, which is 3 mod 4.
+ """
+ if p % 4 != 3:
+ raise NotImplementedError("modsqrt only implemented for p % 4 = 3")
+ sqrt = pow(a, (p + 1)//4, p)
+ if pow(sqrt, 2, p) == a % p:
+ return sqrt
+ return None
+
+def int_or_bytes(s):
+ "Convert 32-bytes to int while accepting also int and returning it as is."
+ if isinstance(s, bytes):
+ assert(len(s) == 32)
+ s = int.from_bytes(s, 'big')
+ elif not isinstance(s, int):
+ raise TypeError
+ return s
+
+class EllipticCurve:
+ def __init__(self, p, a, b):
+ """Initialize elliptic curve y^2 = x^3 + a*x + b over GF(p)."""
+ self.p = p
+ self.a = a % p
+ self.b = b % p
+
+ def affine(self, p1):
+ """Convert a Jacobian point tuple p1 to affine form, or None if at infinity.
+
+ An affine point is represented as the Jacobian (x, y, 1)"""
+ x1, y1, z1 = p1
+ if z1 == 0:
+ return None
+ inv = modinv(z1, self.p)
+ inv_2 = (inv**2) % self.p
+ inv_3 = (inv_2 * inv) % self.p
+ return ((inv_2 * x1) % self.p, (inv_3 * y1) % self.p, 1)
+
+ def has_even_y(self, p1):
+ """Whether the point p1 has an even Y coordinate when expressed in affine coordinates."""
+ return not (p1[2] == 0 or self.affine(p1)[1] & 1)
+
+ def negate(self, p1):
+ """Negate a Jacobian point tuple p1."""
+ x1, y1, z1 = p1
+ return (x1, (self.p - y1) % self.p, z1)
+
+ def on_curve(self, p1):
+ """Determine whether a Jacobian tuple p is on the curve (and not infinity)"""
+ x1, y1, z1 = p1
+ z2 = pow(z1, 2, self.p)
+ z4 = pow(z2, 2, self.p)
+ return z1 != 0 and (pow(x1, 3, self.p) + self.a * x1 * z4 + self.b * z2 * z4 - pow(y1, 2, self.p)) % self.p == 0
+
+ def is_x_coord(self, x):
+ """Test whether x is a valid X coordinate on the curve."""
+ x_3 = pow(x, 3, self.p)
+ return jacobi_symbol(x_3 + self.a * x + self.b, self.p) != -1
+
+ def lift_x(self, x):
+ """Given an X coordinate on the curve, return a corresponding affine point."""
+ x_3 = pow(x, 3, self.p)
+ v = x_3 + self.a * x + self.b
+ y = modsqrt(v, self.p)
+ if y is None:
+ return None
+ return (x, y, 1)
+
+ def double(self, p1):
+ """Double a Jacobian tuple p1
+
+ See https://en.wikibooks.org/wiki/Cryptography/Prime_Curve/Jacobian_Coordinates - Point Doubling"""
+ x1, y1, z1 = p1
+ if z1 == 0:
+ return (0, 1, 0)
+ y1_2 = (y1**2) % self.p
+ y1_4 = (y1_2**2) % self.p
+ x1_2 = (x1**2) % self.p
+ s = (4*x1*y1_2) % self.p
+ m = 3*x1_2
+ if self.a:
+ m += self.a * pow(z1, 4, self.p)
+ m = m % self.p
+ x2 = (m**2 - 2*s) % self.p
+ y2 = (m*(s - x2) - 8*y1_4) % self.p
+ z2 = (2*y1*z1) % self.p
+ return (x2, y2, z2)
+
+ def add_mixed(self, p1, p2):
+ """Add a Jacobian tuple p1 and an affine tuple p2
+
+ See https://en.wikibooks.org/wiki/Cryptography/Prime_Curve/Jacobian_Coordinates - Point Addition (with affine point)"""
+ x1, y1, z1 = p1
+ x2, y2, z2 = p2
+ assert(z2 == 1)
+ # Adding to the point at infinity is a no-op
+ if z1 == 0:
+ return p2
+ z1_2 = (z1**2) % self.p
+ z1_3 = (z1_2 * z1) % self.p
+ u2 = (x2 * z1_2) % self.p
+ s2 = (y2 * z1_3) % self.p
+ if x1 == u2:
+ if (y1 != s2):
+ # p1 and p2 are inverses. Return the point at infinity.
+ return (0, 1, 0)
+ # p1 == p2. The formulas below fail when the two points are equal.
+ return self.double(p1)
+ h = u2 - x1
+ r = s2 - y1
+ h_2 = (h**2) % self.p
+ h_3 = (h_2 * h) % self.p
+ u1_h_2 = (x1 * h_2) % self.p
+ x3 = (r**2 - h_3 - 2*u1_h_2) % self.p
+ y3 = (r*(u1_h_2 - x3) - y1*h_3) % self.p
+ z3 = (h*z1) % self.p
+ return (x3, y3, z3)
+
+ def add(self, p1, p2):
+ """Add two Jacobian tuples p1 and p2
+
+ See https://en.wikibooks.org/wiki/Cryptography/Prime_Curve/Jacobian_Coordinates - Point Addition"""
+ x1, y1, z1 = p1
+ x2, y2, z2 = p2
+ # Adding the point at infinity is a no-op
+ if z1 == 0:
+ return p2
+ if z2 == 0:
+ return p1
+ # Adding an Affine to a Jacobian is more efficient since we save field multiplications and squarings when z = 1
+ if z1 == 1:
+ return self.add_mixed(p2, p1)
+ if z2 == 1:
+ return self.add_mixed(p1, p2)
+ z1_2 = (z1**2) % self.p
+ z1_3 = (z1_2 * z1) % self.p
+ z2_2 = (z2**2) % self.p
+ z2_3 = (z2_2 * z2) % self.p
+ u1 = (x1 * z2_2) % self.p
+ u2 = (x2 * z1_2) % self.p
+ s1 = (y1 * z2_3) % self.p
+ s2 = (y2 * z1_3) % self.p
+ if u1 == u2:
+ if (s1 != s2):
+ # p1 and p2 are inverses. Return the point at infinity.
+ return (0, 1, 0)
+ # p1 == p2. The formulas below fail when the two points are equal.
+ return self.double(p1)
+ h = u2 - u1
+ r = s2 - s1
+ h_2 = (h**2) % self.p
+ h_3 = (h_2 * h) % self.p
+ u1_h_2 = (u1 * h_2) % self.p
+ x3 = (r**2 - h_3 - 2*u1_h_2) % self.p
+ y3 = (r*(u1_h_2 - x3) - s1*h_3) % self.p
+ z3 = (h*z1*z2) % self.p
+ return (x3, y3, z3)
+
+ def mul(self, ps):
+ """Compute a (multi) point multiplication
+
+ ps is a list of (Jacobian tuple, scalar) pairs.
+ """
+ r = (0, 1, 0)
+ for i in range(255, -1, -1):
+ r = self.double(r)
+ for (p, n) in ps:
+ if ((n >> i) & 1):
+ r = self.add(r, p)
+ return r
+
+SECP256K1_FIELD_SIZE = 2**256 - 2**32 - 977
+SECP256K1 = EllipticCurve(SECP256K1_FIELD_SIZE, 0, 7)
+SECP256K1_G = (0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8, 1)
+SECP256K1_ORDER = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
+SECP256K1_ORDER_HALF = SECP256K1_ORDER // 2
+NUMS_H = 0x50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0
+
+class ECPubKey():
+ """A secp256k1 public key"""
+
+ def __init__(self):
+ """Construct an uninitialized public key"""
+ self.valid = False
+
+ def __repr__(self):
+ return self.get_bytes().hex()
+
+ def __eq__(self, other):
+ assert isinstance(other, ECPubKey)
+ return self.get_bytes() == other.get_bytes()
+
+ def __hash__(self):
+ return hash(self.get_bytes())
+
+ def set(self, data):
+ """Construct a public key from a serialization in compressed or uncompressed DER format or BIP340 format"""
+ if (len(data) == 65 and data[0] == 0x04):
+ p = (int.from_bytes(data[1:33], 'big'), int.from_bytes(data[33:65], 'big'), 1)
+ self.valid = SECP256K1.on_curve(p)
+ if self.valid:
+ self.p = p
+ self.compressed = False
+ elif (len(data) == 33 and (data[0] == 0x02 or data[0] == 0x03)):
+ x = int.from_bytes(data[1:33], 'big')
+ if SECP256K1.is_x_coord(x):
+ p = SECP256K1.lift_x(x)
+ # if the oddness of the y co-ord isn't correct, find the other
+ # valid y
+ if (p[1] & 1) != (data[0] & 1):
+ p = SECP256K1.negate(p)
+ self.p = p
+ self.valid = True
+ self.compressed = True
+ else:
+ self.valid = False
+ elif (len(data) == 32):
+ x = int.from_bytes(data[0:32], 'big')
+ if SECP256K1.is_x_coord(x):
+ p = SECP256K1.lift_x(x)
+ # if the oddness of the y co-ord isn't correct, find the other
+ # valid y
+ if p[1]%2 != 0:
+ p = SECP256K1.negate(p)
+ self.p = p
+ self.valid = True
+ self.compressed = True
+ else:
+ self.valid = False
+ else:
+ self.valid = False
+ return self
+
+ @property
+ def is_compressed(self):
+ return self.compressed
+
+ @property
+ def is_valid(self):
+ return self.valid
+
+ def get_y(self):
+ return SECP256K1.affine(self.p)[1]
+
+ def get_x(self):
+ return SECP256K1.affine(self.p)[0]
+
+ def get_bytes(self, bip340=True):
+ assert(self.valid)
+ p = SECP256K1.affine(self.p)
+ if p is None:
+ return None
+ if bip340:
+ return bytes(p[0].to_bytes(32, 'big'))
+ elif self.compressed:
+ return bytes([0x02 + (p[1] & 1)]) + p[0].to_bytes(32, 'big')
+ else:
+ return bytes([0x04]) + p[0].to_bytes(32, 'big') + p[1].to_bytes(32, 'big')
+
+ def verify_ecdsa(self, sig, msg, low_s=True):
+ """Verify a strictly DER-encoded ECDSA signature against this pubkey.
+
+ See https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm for the
+ ECDSA verifier algorithm"""
+ assert(self.valid)
+
+ # Extract r and s from the DER formatted signature. Return false for
+ # any DER encoding errors.
+ if (sig[1] + 2 != len(sig)):
+ return False
+ if (len(sig) < 4):
+ return False
+ if (sig[0] != 0x30):
+ return False
+ if (sig[2] != 0x02):
+ return False
+ rlen = sig[3]
+ if (len(sig) < 6 + rlen):
+ return False
+ if rlen < 1 or rlen > 33:
+ return False
+ if sig[4] >= 0x80:
+ return False
+ if (rlen > 1 and (sig[4] == 0) and not (sig[5] & 0x80)):
+ return False
+ r = int.from_bytes(sig[4:4+rlen], 'big')
+ if (sig[4+rlen] != 0x02):
+ return False
+ slen = sig[5+rlen]
+ if slen < 1 or slen > 33:
+ return False
+ if (len(sig) != 6 + rlen + slen):
+ return False
+ if sig[6+rlen] >= 0x80:
+ return False
+ if (slen > 1 and (sig[6+rlen] == 0) and not (sig[7+rlen] & 0x80)):
+ return False
+ s = int.from_bytes(sig[6+rlen:6+rlen+slen], 'big')
+
+ # Verify that r and s are within the group order
+ if r < 1 or s < 1 or r >= SECP256K1_ORDER or s >= SECP256K1_ORDER:
+ return False
+ if low_s and s >= SECP256K1_ORDER_HALF:
+ return False
+ z = int.from_bytes(msg, 'big')
+
+ # Run verifier algorithm on r, s
+ w = modinv(s, SECP256K1_ORDER)
+ u1 = z*w % SECP256K1_ORDER
+ u2 = r*w % SECP256K1_ORDER
+ R = SECP256K1.affine(SECP256K1.mul([(SECP256K1_G, u1), (self.p, u2)]))
+ if R is None or R[0] != r:
+ return False
+ return True
+
+ def verify_schnorr(self, sig, msg):
+ assert(len(msg) == 32)
+ assert(len(sig) == 64)
+ assert(self.valid)
+ r = int.from_bytes(sig[0:32], 'big')
+ if r >= SECP256K1_FIELD_SIZE:
+ return False
+ s = int.from_bytes(sig[32:64], 'big')
+ if s >= SECP256K1_ORDER:
+ return False
+ e = int.from_bytes(TaggedHash("BIP0340/challenge", sig[0:32] + self.get_bytes() + msg), 'big') % SECP256K1_ORDER
+ R = SECP256K1.mul([(SECP256K1_G, s), (self.p, SECP256K1_ORDER - e)])
+ if not SECP256K1.has_even_y(R):
+ return False
+ if ((r * R[2] * R[2]) % SECP256K1_FIELD_SIZE) != R[0]:
+ return False
+ return True
+
+ def __add__(self, other):
+ """Adds two ECPubKey points."""
+ assert isinstance(other, ECPubKey)
+ assert self.valid
+ assert other.valid
+ ret = ECPubKey()
+ ret.p = SECP256K1.add(other.p, self.p)
+ ret.valid = True
+ ret.compressed = self.compressed
+ return ret
+
+ def __radd__(self, other):
+ """Allows this ECPubKey to be added to 0 for sum()"""
+ if other == 0:
+ return self
+ else:
+ return self + other
+
+ def __mul__(self, other):
+ """Multiplies ECPubKey point with a scalar(int/32bytes/ECKey)."""
+ if isinstance(other, ECKey):
+ assert self.valid
+ assert other.secret is not None
+ multiplier = other.secret
+ else:
+ # int_or_bytes checks that other is `int` or `bytes`
+ multiplier = int_or_bytes(other)
+
+ assert multiplier < SECP256K1_ORDER
+ multiplier = multiplier % SECP256K1_ORDER
+ ret = ECPubKey()
+ ret.p = SECP256K1.mul([(self.p, multiplier)])
+ ret.valid = True
+ ret.compressed = self.compressed
+ return ret
+
+ def __rmul__(self, other):
+ """Multiplies a scalar(int/32bytes/ECKey) with an ECPubKey point"""
+ return self * other
+
+ def __sub__(self, other):
+ """Subtract one point from another"""
+ assert isinstance(other, ECPubKey)
+ assert self.valid
+ assert other.valid
+ ret = ECPubKey()
+ ret.p = SECP256K1.add(self.p, SECP256K1.negate(other.p))
+ ret.valid = True
+ ret.compressed = self.compressed
+ return ret
+
+ def tweak_add(self, tweak):
+ assert(self.valid)
+ t = int_or_bytes(tweak)
+ if t >= SECP256K1_ORDER:
+ return None
+ tweaked = SECP256K1.affine(SECP256K1.mul([(self.p, 1), (SECP256K1_G, t)]))
+ if tweaked is None:
+ return None
+ ret = ECPubKey()
+ ret.p = tweaked
+ ret.valid = True
+ ret.compressed = self.compressed
+ return ret
+
+ def mul(self, data):
+ """Multiplies ECPubKey point with scalar data."""
+ assert self.valid
+ other = ECKey()
+ other.set(data, True)
+ return self * other
+
+ def negate(self):
+ self.p = SECP256K1.affine(SECP256K1.negate(self.p))
+
+def rfc6979_nonce(key):
+ """Compute signing nonce using RFC6979."""
+ v = bytes([1] * 32)
+ k = bytes([0] * 32)
+ k = hmac.new(k, v + b"\x00" + key, 'sha256').digest()
+ v = hmac.new(k, v, 'sha256').digest()
+ k = hmac.new(k, v + b"\x01" + key, 'sha256').digest()
+ v = hmac.new(k, v, 'sha256').digest()
+ return hmac.new(k, v, 'sha256').digest()
+
+class ECKey():
+ """A secp256k1 private key"""
+
+ def __init__(self):
+ self.valid = False
+
+ def __repr__(self):
+ return str(self.secret)
+
+ def __eq__(self, other):
+ assert isinstance(other, ECKey)
+ return self.secret == other.secret
+
+ def __hash__(self):
+ return hash(self.secret)
+
+ def set(self, secret, compressed=True):
+ """Construct a private key object from either 32-bytes or an int secret and a compressed flag."""
+ secret = int_or_bytes(secret)
+
+ self.valid = (secret > 0 and secret < SECP256K1_ORDER)
+ if self.valid:
+ self.secret = secret
+ self.compressed = compressed
+ return self
+
+ def generate(self, compressed=True):
+ """Generate a random private key (compressed or uncompressed)."""
+ self.set(random.randrange(1, SECP256K1_ORDER).to_bytes(32, 'big'), compressed)
+ return self
+
+ def get_bytes(self):
+ """Retrieve the 32-byte representation of this key."""
+ assert(self.valid)
+ return self.secret.to_bytes(32, 'big')
+
+ def as_int(self):
+ return self.secret
+
+ def from_int(self, secret, compressed=True):
+ self.valid = (secret > 0 and secret < SECP256K1_ORDER)
+ if self.valid:
+ self.secret = secret
+ self.compressed = compressed
+
+ def __add__(self, other):
+ """Add key secrets. Returns compressed key."""
+ assert isinstance(other, ECKey)
+ assert other.secret > 0 and other.secret < SECP256K1_ORDER
+ assert self.valid is True
+ ret_data = ((self.secret + other.secret) % SECP256K1_ORDER).to_bytes(32, 'big')
+ ret = ECKey()
+ ret.set(ret_data, True)
+ return ret
+
+ def __radd__(self, other):
+ """Allows this ECKey to be added to 0 for sum()"""
+ if other == 0:
+ return self
+ else:
+ return self + other
+
+ def __sub__(self, other):
+ """Subtract key secrets. Returns compressed key."""
+ assert isinstance(other, ECKey)
+ assert other.secret > 0 and other.secret < SECP256K1_ORDER
+ assert self.valid is True
+ ret_data = ((self.secret - other.secret) % SECP256K1_ORDER).to_bytes(32, 'big')
+ ret = ECKey()
+ ret.set(ret_data, True)
+ return ret
+
+ def __mul__(self, other):
+ """Multiply a private key by another private key or multiply a public key by a private key. Returns compressed key."""
+ if isinstance(other, ECKey):
+ assert other.secret > 0 and other.secret < SECP256K1_ORDER
+ assert self.valid is True
+ ret_data = ((self.secret * other.secret) % SECP256K1_ORDER).to_bytes(32, 'big')
+ ret = ECKey()
+ ret.set(ret_data, True)
+ return ret
+ elif isinstance(other, ECPubKey):
+ return other * self
+ else:
+ # ECKey().set() checks that other is an `int` or `bytes`
+ assert self.valid
+ second = ECKey().set(other, self.compressed)
+ return self * second
+
+ def __rmul__(self, other):
+ return self * other
+
+ def add(self, data):
+ """Add key to scalar data. Returns compressed key."""
+ other = ECKey()
+ other.set(data, True)
+ return self + other
+
+ def mul(self, data):
+ """Multiply key secret with scalar data. Returns compressed key."""
+ other = ECKey()
+ other.set(data, True)
+ return self * other
+
+ def negate(self):
+ """Negate a private key."""
+ assert self.valid
+ self.secret = SECP256K1_ORDER - self.secret
+
+ @property
+ def is_valid(self):
+ return self.valid
+
+ @property
+ def is_compressed(self):
+ return self.compressed
+
+ def get_pubkey(self):
+ """Compute an ECPubKey object for this secret key."""
+ assert(self.valid)
+ ret = ECPubKey()
+ p = SECP256K1.mul([(SECP256K1_G, self.secret)])
+ ret.p = p
+ ret.valid = True
+ ret.compressed = self.compressed
+ return ret
+
+ def sign_ecdsa(self, msg, low_s=True, rfc6979=False):
+ """Construct a DER-encoded ECDSA signature with this key.
+
+ See https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm for the
+ ECDSA signer algorithm."""
+ assert(self.valid)
+ z = int.from_bytes(msg, 'big')
+ # Note: no RFC6979 by default, but a simple random nonce (some tests rely on distinct transactions for the same operation)
+ if rfc6979:
+ k = int.from_bytes(rfc6979_nonce(self.secret.to_bytes(32, 'big') + msg), 'big')
+ else:
+ k = random.randrange(1, SECP256K1_ORDER)
+ R = SECP256K1.affine(SECP256K1.mul([(SECP256K1_G, k)]))
+ r = R[0] % SECP256K1_ORDER
+ s = (modinv(k, SECP256K1_ORDER) * (z + self.secret * r)) % SECP256K1_ORDER
+ if low_s and s > SECP256K1_ORDER_HALF:
+ s = SECP256K1_ORDER - s
+ # Represent in DER format. The byte representations of r and s have
+ # length rounded up (255 bits becomes 32 bytes and 256 bits becomes 33
+ # bytes).
+ rb = r.to_bytes((r.bit_length() + 8) // 8, 'big')
+ sb = s.to_bytes((s.bit_length() + 8) // 8, 'big')
+ return b'\x30' + bytes([4 + len(rb) + len(sb), 2, len(rb)]) + rb + bytes([2, len(sb)]) + sb
+
+ def sign_schnorr(self, msg, aux=None):
+ """Create a Schnorr signature (see BIP340)."""
+ if aux is None:
+ aux = bytes(32)
+
+ assert self.valid
+ assert len(msg) == 32
+ assert len(aux) == 32
+
+ t = (self.secret ^ int.from_bytes(TaggedHash("BIP0340/aux", aux), 'big')).to_bytes(32, 'big')
+ kp = int.from_bytes(TaggedHash("BIP0340/nonce", t + self.get_pubkey().get_bytes() + msg), 'big') % SECP256K1_ORDER
+ assert kp != 0
+ R = SECP256K1.affine(SECP256K1.mul([(SECP256K1_G, kp)]))
+ k = kp if SECP256K1.has_even_y(R) else SECP256K1_ORDER - kp
+ e = int.from_bytes(TaggedHash("BIP0340/challenge", R[0].to_bytes(32, 'big') + self.get_pubkey().get_bytes() + msg), 'big') % SECP256K1_ORDER
+ return R[0].to_bytes(32, 'big') + ((k + e * self.secret) % SECP256K1_ORDER).to_bytes(32, 'big')
+
+ def tweak_add(self, tweak):
+ """Return a tweaked version of this private key."""
+ assert(self.valid)
+ t = int_or_bytes(tweak)
+ if t >= SECP256K1_ORDER:
+ return None
+ tweaked = (self.secret + t) % SECP256K1_ORDER
+ if tweaked == 0:
+ return None
+ ret = ECKey()
+ ret.set(tweaked.to_bytes(32, 'big'), self.compressed)
+ return ret
+
+def generate_key_pair(secret=None, compressed=True):
+ """Convenience function to generate a private-public key pair."""
+ d = ECKey()
+ if secret:
+ d.set(secret, compressed)
+ else:
+ d.generate(compressed)
+
+ P = d.get_pubkey()
+ return d, P
+
+def generate_bip340_key_pair():
+ """Convenience function to generate a BIP0340 private-public key pair."""
+ d = ECKey()
+ d.generate()
+ P = d.get_pubkey()
+ if P.get_y()%2 != 0:
+ d.negate()
+ P.negate()
+ return d, P
+
+def generate_schnorr_nonce():
+ """Generate a random valid BIP340 nonce.
+
+ See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki.
+ This implementation ensures the y-coordinate of the nonce point is even."""
+ kp = random.randrange(1, SECP256K1_ORDER)
+ assert kp != 0
+ R = SECP256K1.affine(SECP256K1.mul([(SECP256K1_G, kp)]))
+ k = kp if R[1] % 2 == 0 else SECP256K1_ORDER - kp
+ k_key = ECKey()
+ k_key.set(k.to_bytes(32, 'big'), True)
+ return k_key
diff --git a/bip-0352/send_and_receive_test_vectors.json b/bip-0352/send_and_receive_test_vectors.json
new file mode 100644
index 0000000000..264f7becb5
--- /dev/null
+++ b/bip-0352/send_and_receive_test_vectors.json
@@ -0,0 +1,2760 @@
+[
+ {
+ "comment": "Simple send: two inputs",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "48304602210086783ded73e961037e77d49d9deee4edc2b23136e9728d56e4491c80015c3a63022100fda4c0f21ea18de29edbce57f7134d613e044ee150a89e2e64700de2d4e83d4e2103bd85685d03d111699b15d046319febe77f8de5286e9e512703cdee1bf3be3792",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a914d9317c66f54ff0a152ec50b1d19c25be50c8e15988ac"
+ }
+ },
+ "private_key": "93f5ed907ad5b2bdbbdcb5d9116ebc0a4e1f92f910d5260237fa45a9408aad16"
+ }
+ ],
+ "recipients": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ [
+ "3e9fce73d4e77a4809908e3c3a2e54ee147b9312dc5044a193d1fc85de46e3c1"
+ ]
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ }
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "48304602210086783ded73e961037e77d49d9deee4edc2b23136e9728d56e4491c80015c3a63022100fda4c0f21ea18de29edbce57f7134d613e044ee150a89e2e64700de2d4e83d4e2103bd85685d03d111699b15d046319febe77f8de5286e9e512703cdee1bf3be3792",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a914d9317c66f54ff0a152ec50b1d19c25be50c8e15988ac"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "3e9fce73d4e77a4809908e3c3a2e54ee147b9312dc5044a193d1fc85de46e3c1"
+ ],
+ "key_material": {
+ "spend_priv_key": "9d6ad855ce3417ef84e836892e5a56392bfba05fa5d97ccea30e266f540e08b3",
+ "scan_priv_key": "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"
+ },
+ "labels": []
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ],
+ "outputs": [
+ {
+ "priv_key_tweak": "f438b40179a3c4262de12986c0e6cce0634007cdc79c1dcd3e20b9ebc2e7eef6",
+ "pub_key": "3e9fce73d4e77a4809908e3c3a2e54ee147b9312dc5044a193d1fc85de46e3c1",
+ "signature": "74f85b856337fbe837643b86f462118159f93ac4acc2671522f27e8f67b079959195ccc7a5dbee396d2909f5d680d6e30cda7359aa2755822509b70d6b0687a1"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "comment": "Simple send: two inputs, order reversed",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ },
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "48304602210086783ded73e961037e77d49d9deee4edc2b23136e9728d56e4491c80015c3a63022100fda4c0f21ea18de29edbce57f7134d613e044ee150a89e2e64700de2d4e83d4e2103bd85685d03d111699b15d046319febe77f8de5286e9e512703cdee1bf3be3792",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a914d9317c66f54ff0a152ec50b1d19c25be50c8e15988ac"
+ }
+ },
+ "private_key": "93f5ed907ad5b2bdbbdcb5d9116ebc0a4e1f92f910d5260237fa45a9408aad16"
+ }
+ ],
+ "recipients": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ [
+ "3e9fce73d4e77a4809908e3c3a2e54ee147b9312dc5044a193d1fc85de46e3c1"
+ ]
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ }
+ },
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "48304602210086783ded73e961037e77d49d9deee4edc2b23136e9728d56e4491c80015c3a63022100fda4c0f21ea18de29edbce57f7134d613e044ee150a89e2e64700de2d4e83d4e2103bd85685d03d111699b15d046319febe77f8de5286e9e512703cdee1bf3be3792",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a914d9317c66f54ff0a152ec50b1d19c25be50c8e15988ac"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "3e9fce73d4e77a4809908e3c3a2e54ee147b9312dc5044a193d1fc85de46e3c1"
+ ],
+ "key_material": {
+ "spend_priv_key": "9d6ad855ce3417ef84e836892e5a56392bfba05fa5d97ccea30e266f540e08b3",
+ "scan_priv_key": "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"
+ },
+ "labels": []
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ],
+ "outputs": [
+ {
+ "priv_key_tweak": "f438b40179a3c4262de12986c0e6cce0634007cdc79c1dcd3e20b9ebc2e7eef6",
+ "pub_key": "3e9fce73d4e77a4809908e3c3a2e54ee147b9312dc5044a193d1fc85de46e3c1",
+ "signature": "74f85b856337fbe837643b86f462118159f93ac4acc2671522f27e8f67b079959195ccc7a5dbee396d2909f5d680d6e30cda7359aa2755822509b70d6b0687a1"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "comment": "Simple send: two inputs from the same transaction",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 3,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ },
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 7,
+ "scriptSig": "48304602210086783ded73e961037e77d49d9deee4edc2b23136e9728d56e4491c80015c3a63022100fda4c0f21ea18de29edbce57f7134d613e044ee150a89e2e64700de2d4e83d4e2103bd85685d03d111699b15d046319febe77f8de5286e9e512703cdee1bf3be3792",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a914d9317c66f54ff0a152ec50b1d19c25be50c8e15988ac"
+ }
+ },
+ "private_key": "93f5ed907ad5b2bdbbdcb5d9116ebc0a4e1f92f910d5260237fa45a9408aad16"
+ }
+ ],
+ "recipients": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ [
+ "79e71baa2ba3fc66396de3a04f168c7bf24d6870ec88ca877754790c1db357b6"
+ ]
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 3,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ }
+ },
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 7,
+ "scriptSig": "48304602210086783ded73e961037e77d49d9deee4edc2b23136e9728d56e4491c80015c3a63022100fda4c0f21ea18de29edbce57f7134d613e044ee150a89e2e64700de2d4e83d4e2103bd85685d03d111699b15d046319febe77f8de5286e9e512703cdee1bf3be3792",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a914d9317c66f54ff0a152ec50b1d19c25be50c8e15988ac"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "79e71baa2ba3fc66396de3a04f168c7bf24d6870ec88ca877754790c1db357b6"
+ ],
+ "key_material": {
+ "spend_priv_key": "9d6ad855ce3417ef84e836892e5a56392bfba05fa5d97ccea30e266f540e08b3",
+ "scan_priv_key": "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"
+ },
+ "labels": []
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ],
+ "outputs": [
+ {
+ "priv_key_tweak": "4851455bfbe1ab4f80156570aa45063201aa5c9e1b1dcd29f0f8c33d10bf77ae",
+ "pub_key": "79e71baa2ba3fc66396de3a04f168c7bf24d6870ec88ca877754790c1db357b6",
+ "signature": "10332eea808b6a13f70059a8a73195808db782012907f5ba32b6eae66a2f66b4f65147e2b968a1678c5f73d57d5d195dbaf667b606ff80c8490eac1f3b710657"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "comment": "Simple send: two inputs from the same transaction, order reversed",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 7,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 3,
+ "scriptSig": "48304602210086783ded73e961037e77d49d9deee4edc2b23136e9728d56e4491c80015c3a63022100fda4c0f21ea18de29edbce57f7134d613e044ee150a89e2e64700de2d4e83d4e2103bd85685d03d111699b15d046319febe77f8de5286e9e512703cdee1bf3be3792",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a914d9317c66f54ff0a152ec50b1d19c25be50c8e15988ac"
+ }
+ },
+ "private_key": "93f5ed907ad5b2bdbbdcb5d9116ebc0a4e1f92f910d5260237fa45a9408aad16"
+ }
+ ],
+ "recipients": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ [
+ "f4c2da807f89cb1501f1a77322a895acfb93c28e08ed2724d2beb8e44539ba38"
+ ]
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 7,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ }
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 3,
+ "scriptSig": "48304602210086783ded73e961037e77d49d9deee4edc2b23136e9728d56e4491c80015c3a63022100fda4c0f21ea18de29edbce57f7134d613e044ee150a89e2e64700de2d4e83d4e2103bd85685d03d111699b15d046319febe77f8de5286e9e512703cdee1bf3be3792",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a914d9317c66f54ff0a152ec50b1d19c25be50c8e15988ac"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "f4c2da807f89cb1501f1a77322a895acfb93c28e08ed2724d2beb8e44539ba38"
+ ],
+ "key_material": {
+ "spend_priv_key": "9d6ad855ce3417ef84e836892e5a56392bfba05fa5d97ccea30e266f540e08b3",
+ "scan_priv_key": "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"
+ },
+ "labels": []
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ],
+ "outputs": [
+ {
+ "priv_key_tweak": "ab0c9b87181bf527879f48db9f14a02233619b986f8e8f2d5d408ce68a709f51",
+ "pub_key": "f4c2da807f89cb1501f1a77322a895acfb93c28e08ed2724d2beb8e44539ba38",
+ "signature": "398a9790865791a9db41a8015afad3a47d60fec5086c50557806a49a1bc038808632b8fe679a7bb65fc6b455be994502eed849f1da3729cd948fc7be73d67295"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "comment": "Outpoint ordering byte-lexicographically vs. vout-integer",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 1,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ },
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 256,
+ "scriptSig": "48304602210086783ded73e961037e77d49d9deee4edc2b23136e9728d56e4491c80015c3a63022100fda4c0f21ea18de29edbce57f7134d613e044ee150a89e2e64700de2d4e83d4e2103bd85685d03d111699b15d046319febe77f8de5286e9e512703cdee1bf3be3792",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a914d9317c66f54ff0a152ec50b1d19c25be50c8e15988ac"
+ }
+ },
+ "private_key": "93f5ed907ad5b2bdbbdcb5d9116ebc0a4e1f92f910d5260237fa45a9408aad16"
+ }
+ ],
+ "recipients": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ [
+ "a85ef8701394b517a4b35217c4bd37ac01ebeed4b008f8d0879f9e09ba95319c"
+ ]
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 1,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ }
+ },
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 256,
+ "scriptSig": "48304602210086783ded73e961037e77d49d9deee4edc2b23136e9728d56e4491c80015c3a63022100fda4c0f21ea18de29edbce57f7134d613e044ee150a89e2e64700de2d4e83d4e2103bd85685d03d111699b15d046319febe77f8de5286e9e512703cdee1bf3be3792",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a914d9317c66f54ff0a152ec50b1d19c25be50c8e15988ac"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "a85ef8701394b517a4b35217c4bd37ac01ebeed4b008f8d0879f9e09ba95319c"
+ ],
+ "key_material": {
+ "spend_priv_key": "9d6ad855ce3417ef84e836892e5a56392bfba05fa5d97ccea30e266f540e08b3",
+ "scan_priv_key": "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"
+ },
+ "labels": []
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ],
+ "outputs": [
+ {
+ "priv_key_tweak": "c8ac0292997b5bca98b3ebd99a57e253071137550f270452cd3df8a3e2266d36",
+ "pub_key": "a85ef8701394b517a4b35217c4bd37ac01ebeed4b008f8d0879f9e09ba95319c",
+ "signature": "c036ee38bfe46aba03234339ae7219b31b824b52ef9d5ce05810a0d6f62330dedc2b55652578aa5bdabf930fae941acd839d5a66f8fce7caa9710ccb446bddd1"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "comment": "Single recipient: multiple UTXOs from the same public key",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ }
+ ],
+ "recipients": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ [
+ "548ae55c8eec1e736e8d3e520f011f1f42a56d166116ad210b3937599f87f566"
+ ]
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ }
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "548ae55c8eec1e736e8d3e520f011f1f42a56d166116ad210b3937599f87f566"
+ ],
+ "key_material": {
+ "spend_priv_key": "9d6ad855ce3417ef84e836892e5a56392bfba05fa5d97ccea30e266f540e08b3",
+ "scan_priv_key": "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"
+ },
+ "labels": []
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ],
+ "outputs": [
+ {
+ "priv_key_tweak": "f032695e2636619efa523fffaa9ef93c8802299181fd0461913c1b8daf9784cd",
+ "pub_key": "548ae55c8eec1e736e8d3e520f011f1f42a56d166116ad210b3937599f87f566",
+ "signature": "f238386c5d5e5444f8d2c75aabbcb28c346f208c76f60823f5de3b67b79e0ec72ea5de2d7caec314e0971d3454f122dda342b3eede01b3857e83654e36b25f76"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "comment": "Single recipient: taproot only inputs with even y-values",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "",
+ "txinwitness": "0140c459b671370d12cfb5acee76da7e3ba7cc29b0b4653e3af8388591082660137d087fdc8e89a612cd5d15be0febe61fc7cdcf3161a26e599a4514aa5c3e86f47b",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "51205a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "",
+ "txinwitness": "0140bd1e708f92dbeaf24a6b8dd22e59c6274355424d62baea976b449e220fd75b13578e262ab11b7aa58e037f0c6b0519b66803b7d9decaa1906dedebfb531c56c1",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "5120782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338"
+ }
+ },
+ "private_key": "fc8716a97a48ba9a05a98ae47b5cd201a25a7fd5d8b73c203c5f7b6b6b3b6ad7"
+ }
+ ],
+ "recipients": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ [
+ "de88bea8e7ffc9ce1af30d1132f910323c505185aec8eae361670421e749a1fb"
+ ]
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "",
+ "txinwitness": "0140c459b671370d12cfb5acee76da7e3ba7cc29b0b4653e3af8388591082660137d087fdc8e89a612cd5d15be0febe61fc7cdcf3161a26e599a4514aa5c3e86f47b",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "51205a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5"
+ }
+ }
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "",
+ "txinwitness": "0140bd1e708f92dbeaf24a6b8dd22e59c6274355424d62baea976b449e220fd75b13578e262ab11b7aa58e037f0c6b0519b66803b7d9decaa1906dedebfb531c56c1",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "5120782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "de88bea8e7ffc9ce1af30d1132f910323c505185aec8eae361670421e749a1fb"
+ ],
+ "key_material": {
+ "spend_priv_key": "9d6ad855ce3417ef84e836892e5a56392bfba05fa5d97ccea30e266f540e08b3",
+ "scan_priv_key": "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"
+ },
+ "labels": []
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ],
+ "outputs": [
+ {
+ "priv_key_tweak": "3fb9ce5ce1746ced103c8ed254e81f6690764637ddbc876ec1f9b3ddab776b03",
+ "pub_key": "de88bea8e7ffc9ce1af30d1132f910323c505185aec8eae361670421e749a1fb",
+ "signature": "c5acd25a8f021a4192f93bc34403fd8b76484613466336fb259c72d04c169824f2690ca34e96cee86b69f376c8377003268fda56feeb1b873e5783d7e19bcca5"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "comment": "Single recipient: taproot only with mixed even/odd y-values",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "",
+ "txinwitness": "0140c459b671370d12cfb5acee76da7e3ba7cc29b0b4653e3af8388591082660137d087fdc8e89a612cd5d15be0febe61fc7cdcf3161a26e599a4514aa5c3e86f47b",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "51205a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "",
+ "txinwitness": "01400a4d0dca6293f40499394d7eefe14a1de11e0e3454f51de2e802592abf5ee549042a1b1a8fb2e149ee9dd3f086c1b69b2f182565ab6ecf599b1ec9ebadfda6c5",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "51208c8d23d4764feffcd5e72e380802540fa0f88e3d62ad5e0b47955f74d7b283c4"
+ }
+ },
+ "private_key": "1d37787c2b7116ee983e9f9c13269df29091b391c04db94239e0d2bc2182c3bf"
+ }
+ ],
+ "recipients": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ [
+ "77cab7dd12b10259ee82c6ea4b509774e33e7078e7138f568092241bf26b99f1"
+ ]
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "",
+ "txinwitness": "0140c459b671370d12cfb5acee76da7e3ba7cc29b0b4653e3af8388591082660137d087fdc8e89a612cd5d15be0febe61fc7cdcf3161a26e599a4514aa5c3e86f47b",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "51205a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5"
+ }
+ }
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "",
+ "txinwitness": "01400a4d0dca6293f40499394d7eefe14a1de11e0e3454f51de2e802592abf5ee549042a1b1a8fb2e149ee9dd3f086c1b69b2f182565ab6ecf599b1ec9ebadfda6c5",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "51208c8d23d4764feffcd5e72e380802540fa0f88e3d62ad5e0b47955f74d7b283c4"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "77cab7dd12b10259ee82c6ea4b509774e33e7078e7138f568092241bf26b99f1"
+ ],
+ "key_material": {
+ "spend_priv_key": "9d6ad855ce3417ef84e836892e5a56392bfba05fa5d97ccea30e266f540e08b3",
+ "scan_priv_key": "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"
+ },
+ "labels": []
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ],
+ "outputs": [
+ {
+ "priv_key_tweak": "f5382508609771068ed079b24e1f72e4a17ee6d1c979066bf1d4e2a5676f09d4",
+ "pub_key": "77cab7dd12b10259ee82c6ea4b509774e33e7078e7138f568092241bf26b99f1",
+ "signature": "ff65833b8fd1ed3ef9d0443b4f702b45a3f2dd457ba247687e8207745c3be9d2bdad0ab3f07118f8b2efc6a04b95f7b3e218daf8a64137ec91bd2fc67fc137a5"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "comment": "Single recipient: taproot input with even y-value and non-taproot input",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "",
+ "txinwitness": "0140c459b671370d12cfb5acee76da7e3ba7cc29b0b4653e3af8388591082660137d087fdc8e89a612cd5d15be0febe61fc7cdcf3161a26e599a4514aa5c3e86f47b",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "51205a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "463044021f24e010c6e475814740ba24c8cf9362c4db1276b7f46a7b1e63473159a80ec30221008198e8ece7b7f88e6c6cc6bb8c86f9f00b7458222a8c91addf6e1577bcf7697e2103e0ec4f64b3fa2e463ccfcf4e856e37d5e1e20275bc89ec1def9eb098eff1f85d",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9148cbc7dfe44f1579bff3340bbef1eddeaeb1fc97788ac"
+ }
+ },
+ "private_key": "8d4751f6e8a3586880fb66c19ae277969bd5aa06f61c4ee2f1e2486efdf666d3"
+ }
+ ],
+ "recipients": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ [
+ "30523cca96b2a9ae3c98beb5e60f7d190ec5bc79b2d11a0b2d4d09a608c448f0"
+ ]
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "",
+ "txinwitness": "0140c459b671370d12cfb5acee76da7e3ba7cc29b0b4653e3af8388591082660137d087fdc8e89a612cd5d15be0febe61fc7cdcf3161a26e599a4514aa5c3e86f47b",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "51205a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5"
+ }
+ }
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "463044021f24e010c6e475814740ba24c8cf9362c4db1276b7f46a7b1e63473159a80ec30221008198e8ece7b7f88e6c6cc6bb8c86f9f00b7458222a8c91addf6e1577bcf7697e2103e0ec4f64b3fa2e463ccfcf4e856e37d5e1e20275bc89ec1def9eb098eff1f85d",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9148cbc7dfe44f1579bff3340bbef1eddeaeb1fc97788ac"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "30523cca96b2a9ae3c98beb5e60f7d190ec5bc79b2d11a0b2d4d09a608c448f0"
+ ],
+ "key_material": {
+ "spend_priv_key": "9d6ad855ce3417ef84e836892e5a56392bfba05fa5d97ccea30e266f540e08b3",
+ "scan_priv_key": "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"
+ },
+ "labels": []
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ],
+ "outputs": [
+ {
+ "priv_key_tweak": "b40017865c79b1fcbed68896791be93186d08f47e416b289b8c063777e14e8df",
+ "pub_key": "30523cca96b2a9ae3c98beb5e60f7d190ec5bc79b2d11a0b2d4d09a608c448f0",
+ "signature": "d1edeea28cf1033bcb3d89376cabaaaa2886cbd8fda112b5c61cc90a4e7f1878bdd62180b07d1dfc8ffee1863c525a0c7b5bcd413183282cfda756cb65787266"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "comment": "Single recipient: taproot input with odd y-value and non-taproot input",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "",
+ "txinwitness": "01400a4d0dca6293f40499394d7eefe14a1de11e0e3454f51de2e802592abf5ee549042a1b1a8fb2e149ee9dd3f086c1b69b2f182565ab6ecf599b1ec9ebadfda6c5",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "51208c8d23d4764feffcd5e72e380802540fa0f88e3d62ad5e0b47955f74d7b283c4"
+ }
+ },
+ "private_key": "1d37787c2b7116ee983e9f9c13269df29091b391c04db94239e0d2bc2182c3bf"
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "463044021f24e010c6e475814740ba24c8cf9362c4db1276b7f46a7b1e63473159a80ec30221008198e8ece7b7f88e6c6cc6bb8c86f9f00b7458222a8c91addf6e1577bcf7697e2103e0ec4f64b3fa2e463ccfcf4e856e37d5e1e20275bc89ec1def9eb098eff1f85d",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9148cbc7dfe44f1579bff3340bbef1eddeaeb1fc97788ac"
+ }
+ },
+ "private_key": "8d4751f6e8a3586880fb66c19ae277969bd5aa06f61c4ee2f1e2486efdf666d3"
+ }
+ ],
+ "recipients": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ [
+ "359358f59ee9e9eec3f00bdf4882570fd5c182e451aa2650b788544aff012a3a"
+ ]
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "",
+ "txinwitness": "01400a4d0dca6293f40499394d7eefe14a1de11e0e3454f51de2e802592abf5ee549042a1b1a8fb2e149ee9dd3f086c1b69b2f182565ab6ecf599b1ec9ebadfda6c5",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "51208c8d23d4764feffcd5e72e380802540fa0f88e3d62ad5e0b47955f74d7b283c4"
+ }
+ }
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "463044021f24e010c6e475814740ba24c8cf9362c4db1276b7f46a7b1e63473159a80ec30221008198e8ece7b7f88e6c6cc6bb8c86f9f00b7458222a8c91addf6e1577bcf7697e2103e0ec4f64b3fa2e463ccfcf4e856e37d5e1e20275bc89ec1def9eb098eff1f85d",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9148cbc7dfe44f1579bff3340bbef1eddeaeb1fc97788ac"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "359358f59ee9e9eec3f00bdf4882570fd5c182e451aa2650b788544aff012a3a"
+ ],
+ "key_material": {
+ "spend_priv_key": "9d6ad855ce3417ef84e836892e5a56392bfba05fa5d97ccea30e266f540e08b3",
+ "scan_priv_key": "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"
+ },
+ "labels": []
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ],
+ "outputs": [
+ {
+ "priv_key_tweak": "a2f9dd05d1d398347c885d9c61a64d18a264de6d49cea4326bafc2791d627fa7",
+ "pub_key": "359358f59ee9e9eec3f00bdf4882570fd5c182e451aa2650b788544aff012a3a",
+ "signature": "96038ad233d8befe342573a6e54828d863471fb2afbad575cc65271a2a649480ea14912b6abbd3fbf92efc1928c036f6e3eef927105af4ec1dd57cb909f360b8"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "comment": "Multiple outputs: multiple outputs, same recipient",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b972103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9147cdd63cc408564188e8e472640e921c7c90e651d88ac"
+ }
+ },
+ "private_key": "0378e95685b74565fa56751b84a32dfd18545d10d691641b8372e32164fad66a"
+ }
+ ],
+ "recipients": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv",
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ [
+ "e976a58fbd38aeb4e6093d4df02e9c1de0c4513ae0c588cef68cda5b2f8834ca",
+ "f207162b1a7abc51c42017bef055e9ec1efc3d3567cb720357e2b84325db33ac"
+ ]
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ }
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b972103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9147cdd63cc408564188e8e472640e921c7c90e651d88ac"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "e976a58fbd38aeb4e6093d4df02e9c1de0c4513ae0c588cef68cda5b2f8834ca",
+ "f207162b1a7abc51c42017bef055e9ec1efc3d3567cb720357e2b84325db33ac"
+ ],
+ "key_material": {
+ "spend_priv_key": "9d6ad855ce3417ef84e836892e5a56392bfba05fa5d97ccea30e266f540e08b3",
+ "scan_priv_key": "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"
+ },
+ "labels": []
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ],
+ "outputs": [
+ {
+ "priv_key_tweak": "d97e442d110c0bdd31161a7bb6e7862e038d02a09b1484dfbb463f2e0f7c9230",
+ "pub_key": "e976a58fbd38aeb4e6093d4df02e9c1de0c4513ae0c588cef68cda5b2f8834ca",
+ "signature": "29bd25d0f808d7fcd2aa6d5ed206053899198397506c301b218a9e47a3d7070af03e903ff718978d50d1b6b9af8cc0e313d84eda5d5b1e8e85e5516d630bbeb9"
+ },
+ {
+ "priv_key_tweak": "33ce085c3c11eaad13694aae3c20301a6c83382ec89a7cde96c6799e2f88805a",
+ "pub_key": "f207162b1a7abc51c42017bef055e9ec1efc3d3567cb720357e2b84325db33ac",
+ "signature": "335667ca6cae7a26438f5cfdd73b3d48fa832fa9768521d7d5445f22c203ab0d74ed85088f27d29959ba627a4509996676f47df8ff284d292567b1beef0e3912"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "comment": "Multiple outputs: multiple outputs, multiple recipients",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b972103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9147cdd63cc408564188e8e472640e921c7c90e651d88ac"
+ }
+ },
+ "private_key": "0378e95685b74565fa56751b84a32dfd18545d10d691641b8372e32164fad66a"
+ }
+ ],
+ "recipients": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv",
+ "sp1qqgrz6j0lcqnc04vxccydl0kpsj4frfje0ktmgcl2t346hkw30226xqupawdf48k8882j0strrvcmgg2kdawz53a54dd376ngdhak364hzcmynqtn",
+ "sp1qqgrz6j0lcqnc04vxccydl0kpsj4frfje0ktmgcl2t346hkw30226xqupawdf48k8882j0strrvcmgg2kdawz53a54dd376ngdhak364hzcmynqtn"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ [
+ "2e847bb01d1b491da512ddd760b8509617ee38057003d6115d00ba562451323a",
+ "841792c33c9dc6193e76744134125d40add8f2f4a96475f28ba150be032d64e8",
+ "f207162b1a7abc51c42017bef055e9ec1efc3d3567cb720357e2b84325db33ac"
+ ]
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ }
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b972103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9147cdd63cc408564188e8e472640e921c7c90e651d88ac"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "2e847bb01d1b491da512ddd760b8509617ee38057003d6115d00ba562451323a",
+ "841792c33c9dc6193e76744134125d40add8f2f4a96475f28ba150be032d64e8",
+ "f207162b1a7abc51c42017bef055e9ec1efc3d3567cb720357e2b84325db33ac"
+ ],
+ "key_material": {
+ "spend_priv_key": "9902c3c56e84002a7cd410113a9ab21d142be7f53cf5200720bb01314c5eb920",
+ "scan_priv_key": "060b751d7892149006ed7b98606955a29fe284a1e900070c0971f5fb93dbf422"
+ },
+ "labels": []
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgrz6j0lcqnc04vxccydl0kpsj4frfje0ktmgcl2t346hkw30226xqupawdf48k8882j0strrvcmgg2kdawz53a54dd376ngdhak364hzcmynqtn"
+ ],
+ "outputs": [
+ {
+ "priv_key_tweak": "72cd082cccb633bf85240a83494b32dc943a4d05647a6686d23ad4ca59c0ebe4",
+ "pub_key": "2e847bb01d1b491da512ddd760b8509617ee38057003d6115d00ba562451323a",
+ "signature": "38745f3d9f5eef0b1cfb17ca314efa8c521efab28a23aa20ec5e3abb561d42804d539906dce60c4ee7977966184e6f2cab1faa0e5377ceb7148ec5218b4e7878"
+ },
+ {
+ "priv_key_tweak": "2f17ea873a0047fc01ba8010fef0969e76d0e4283f600d48f735098b1fee6eb9",
+ "pub_key": "841792c33c9dc6193e76744134125d40add8f2f4a96475f28ba150be032d64e8",
+ "signature": "c26f4e3cf371b90b840f48ea0e761b5ec31883ed55719f9ef06a90e282d85f565790ab780a3f491bc2668cc64e944dca849d1022a878cdadb8d168b8da4a6da3"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "comment": "Receiving with labels: label with even parity",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b972103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9147cdd63cc408564188e8e472640e921c7c90e651d88ac"
+ }
+ },
+ "private_key": "0378e95685b74565fa56751b84a32dfd18545d10d691641b8372e32164fad66a"
+ }
+ ],
+ "recipients": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjex54dmqmmv6rw353tsuqhs99ydvadxzrsy9nuvk74epvee55drs734pqq"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ [
+ "d014d4860f67d607d60b1af70e0ee236b99658b61bb769832acbbe87c374439a"
+ ]
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ }
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b972103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9147cdd63cc408564188e8e472640e921c7c90e651d88ac"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "d014d4860f67d607d60b1af70e0ee236b99658b61bb769832acbbe87c374439a"
+ ],
+ "key_material": {
+ "spend_priv_key": "9d6ad855ce3417ef84e836892e5a56392bfba05fa5d97ccea30e266f540e08b3",
+ "scan_priv_key": "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"
+ },
+ "labels": [
+ 2,
+ 3,
+ 1001337
+ ]
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv",
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjex54dmqmmv6rw353tsuqhs99ydvadxzrsy9nuvk74epvee55drs734pqq",
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqsg59z2rppn4qlkx0yz9sdltmjv3j8zgcqadjn4ug98m3t6plujsq9qvu5n",
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgq7c2zfthc6x3a5yecwc52nxa0kfd20xuz08zyrjpfw4l2j257yq6qgnkdh5"
+ ],
+ "outputs": [
+ {
+ "priv_key_tweak": "51d4e9d0d482b5700109b4b2e16ff508269b03d800192a043d61dca4a0a72a52",
+ "pub_key": "d014d4860f67d607d60b1af70e0ee236b99658b61bb769832acbbe87c374439a",
+ "signature": "c30fa63bad6f0a317f39a773a5cbf0b0f8193c71dfebba05ee6ae4ed28e3775e6e04c3ea70a83703bb888122855dc894cab61692e7fd10c9b3494d479a60785e"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "comment": "Receiving with labels: label with odd parity",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b972103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9147cdd63cc408564188e8e472640e921c7c90e651d88ac"
+ }
+ },
+ "private_key": "0378e95685b74565fa56751b84a32dfd18545d10d691641b8372e32164fad66a"
+ }
+ ],
+ "recipients": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqsg59z2rppn4qlkx0yz9sdltmjv3j8zgcqadjn4ug98m3t6plujsq9qvu5n"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ [
+ "67626aebb3c4307cf0f6c39ca23247598fabf675ab783292eb2f81ae75ad1f8c"
+ ]
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ }
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b972103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9147cdd63cc408564188e8e472640e921c7c90e651d88ac"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "67626aebb3c4307cf0f6c39ca23247598fabf675ab783292eb2f81ae75ad1f8c"
+ ],
+ "key_material": {
+ "spend_priv_key": "9d6ad855ce3417ef84e836892e5a56392bfba05fa5d97ccea30e266f540e08b3",
+ "scan_priv_key": "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"
+ },
+ "labels": [
+ 2,
+ 3,
+ 1001337
+ ]
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv",
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjex54dmqmmv6rw353tsuqhs99ydvadxzrsy9nuvk74epvee55drs734pqq",
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqsg59z2rppn4qlkx0yz9sdltmjv3j8zgcqadjn4ug98m3t6plujsq9qvu5n",
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgq7c2zfthc6x3a5yecwc52nxa0kfd20xuz08zyrjpfw4l2j257yq6qgnkdh5"
+ ],
+ "outputs": [
+ {
+ "priv_key_tweak": "6024ae214876356b8d917716e7707d267ae16a0fdb07de2a786b74a7bbcddead",
+ "pub_key": "67626aebb3c4307cf0f6c39ca23247598fabf675ab783292eb2f81ae75ad1f8c",
+ "signature": "a86d554d0d6b7aa0907155f7e0b47f0182752472fffaeddd68da90e99b9402f166fd9b33039c302c7115098d971c1399e67c19e9e4de180b10ea0b9d6f0db832"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "comment": "Receiving with labels: large label integer",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b972103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9147cdd63cc408564188e8e472640e921c7c90e651d88ac"
+ }
+ },
+ "private_key": "0378e95685b74565fa56751b84a32dfd18545d10d691641b8372e32164fad66a"
+ }
+ ],
+ "recipients": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgq7c2zfthc6x3a5yecwc52nxa0kfd20xuz08zyrjpfw4l2j257yq6qgnkdh5"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ [
+ "7efa60ce78ac343df8a013a2027c6c5ef29f9502edcbd769d2c21717fecc5951"
+ ]
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ }
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b972103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9147cdd63cc408564188e8e472640e921c7c90e651d88ac"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "7efa60ce78ac343df8a013a2027c6c5ef29f9502edcbd769d2c21717fecc5951"
+ ],
+ "key_material": {
+ "spend_priv_key": "9d6ad855ce3417ef84e836892e5a56392bfba05fa5d97ccea30e266f540e08b3",
+ "scan_priv_key": "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"
+ },
+ "labels": [
+ 2,
+ 3,
+ 1001337
+ ]
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv",
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjex54dmqmmv6rw353tsuqhs99ydvadxzrsy9nuvk74epvee55drs734pqq",
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqsg59z2rppn4qlkx0yz9sdltmjv3j8zgcqadjn4ug98m3t6plujsq9qvu5n",
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgq7c2zfthc6x3a5yecwc52nxa0kfd20xuz08zyrjpfw4l2j257yq6qgnkdh5"
+ ],
+ "outputs": [
+ {
+ "priv_key_tweak": "e336b92330c33030285ce42e4115ad92d5197913c88e06b9072b4a9b47c664a2",
+ "pub_key": "7efa60ce78ac343df8a013a2027c6c5ef29f9502edcbd769d2c21717fecc5951",
+ "signature": "c9e80dd3bdd25ca2d352ce77510f1aed37ba3509dc8cc0677f2d7c2dd04090707950ce9dd6c83d2a428063063aff5c04f1744e334f661f2fc01b4ef80b50f739"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "comment": "Multiple outputs with labels: un-labeled and labeled address; same recipient",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b972103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9147cdd63cc408564188e8e472640e921c7c90e651d88ac"
+ }
+ },
+ "private_key": "0378e95685b74565fa56751b84a32dfd18545d10d691641b8372e32164fad66a"
+ }
+ ],
+ "recipients": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqaxww2fnhrx05cghth75n0qcj59e3e2anscr0q9wyknjxtxycg07y3pevyj",
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ [
+ "39f42624d5c32a77fda80ff0acee269afec601d3791803e80252ae04e4ffcf4c",
+ "f207162b1a7abc51c42017bef055e9ec1efc3d3567cb720357e2b84325db33ac"
+ ],
+ [
+ "83dc944e61603137294829aed56c74c9b087d80f2c021b98a7fae5799000696c",
+ "e976a58fbd38aeb4e6093d4df02e9c1de0c4513ae0c588cef68cda5b2f8834ca"
+ ]
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ }
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b972103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9147cdd63cc408564188e8e472640e921c7c90e651d88ac"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "39f42624d5c32a77fda80ff0acee269afec601d3791803e80252ae04e4ffcf4c",
+ "f207162b1a7abc51c42017bef055e9ec1efc3d3567cb720357e2b84325db33ac"
+ ],
+ "key_material": {
+ "spend_priv_key": "9d6ad855ce3417ef84e836892e5a56392bfba05fa5d97ccea30e266f540e08b3",
+ "scan_priv_key": "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"
+ },
+ "labels": [
+ 1
+ ]
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv",
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqaxww2fnhrx05cghth75n0qcj59e3e2anscr0q9wyknjxtxycg07y3pevyj"
+ ],
+ "outputs": [
+ {
+ "priv_key_tweak": "43100f89f1a6bf10081c92b473ffc57ceac7dbed600b6aba9bb3976f17dbb914",
+ "pub_key": "39f42624d5c32a77fda80ff0acee269afec601d3791803e80252ae04e4ffcf4c",
+ "signature": "15c92509b67a6c211ebb4a51b7528d0666e6720de2343b2e92cfb97942ca14693c1f1fdc8451acfdb2644039f8f5c76114807fdc3d3a002d8a46afab6756bd75"
+ },
+ {
+ "priv_key_tweak": "33ce085c3c11eaad13694aae3c20301a6c83382ec89a7cde96c6799e2f88805a",
+ "pub_key": "f207162b1a7abc51c42017bef055e9ec1efc3d3567cb720357e2b84325db33ac",
+ "signature": "335667ca6cae7a26438f5cfdd73b3d48fa832fa9768521d7d5445f22c203ab0d74ed85088f27d29959ba627a4509996676f47df8ff284d292567b1beef0e3912"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "comment": "Multiple outputs with labels: multiple outputs for labeled address; same recipient",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b972103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9147cdd63cc408564188e8e472640e921c7c90e651d88ac"
+ }
+ },
+ "private_key": "0378e95685b74565fa56751b84a32dfd18545d10d691641b8372e32164fad66a"
+ }
+ ],
+ "recipients": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqaxww2fnhrx05cghth75n0qcj59e3e2anscr0q9wyknjxtxycg07y3pevyj",
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqaxww2fnhrx05cghth75n0qcj59e3e2anscr0q9wyknjxtxycg07y3pevyj"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ [
+ "39f42624d5c32a77fda80ff0acee269afec601d3791803e80252ae04e4ffcf4c",
+ "83dc944e61603137294829aed56c74c9b087d80f2c021b98a7fae5799000696c"
+ ]
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ }
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b972103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9147cdd63cc408564188e8e472640e921c7c90e651d88ac"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "39f42624d5c32a77fda80ff0acee269afec601d3791803e80252ae04e4ffcf4c",
+ "83dc944e61603137294829aed56c74c9b087d80f2c021b98a7fae5799000696c"
+ ],
+ "key_material": {
+ "spend_priv_key": "9d6ad855ce3417ef84e836892e5a56392bfba05fa5d97ccea30e266f540e08b3",
+ "scan_priv_key": "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"
+ },
+ "labels": [
+ 1
+ ]
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv",
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqaxww2fnhrx05cghth75n0qcj59e3e2anscr0q9wyknjxtxycg07y3pevyj"
+ ],
+ "outputs": [
+ {
+ "priv_key_tweak": "43100f89f1a6bf10081c92b473ffc57ceac7dbed600b6aba9bb3976f17dbb914",
+ "pub_key": "39f42624d5c32a77fda80ff0acee269afec601d3791803e80252ae04e4ffcf4c",
+ "signature": "15c92509b67a6c211ebb4a51b7528d0666e6720de2343b2e92cfb97942ca14693c1f1fdc8451acfdb2644039f8f5c76114807fdc3d3a002d8a46afab6756bd75"
+ },
+ {
+ "priv_key_tweak": "9d5fd3b91cac9ddfea6fc2e6f9386f680e6cee623cda02f53706306c081de87f",
+ "pub_key": "83dc944e61603137294829aed56c74c9b087d80f2c021b98a7fae5799000696c",
+ "signature": "db0dfacc98b6a6fcc67cc4631f080b1ca38c60d8c397f2f19843f8f95ec91594b24e47c5bd39480a861c1209f7e3145c440371f9191fb96e324690101eac8e8e"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "comment": "Multiple outputs with labels: un-labeled, labeled, and multiple outputs for labeled address; same recipients",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b972103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9147cdd63cc408564188e8e472640e921c7c90e651d88ac"
+ }
+ },
+ "private_key": "0378e95685b74565fa56751b84a32dfd18545d10d691641b8372e32164fad66a"
+ }
+ ],
+ "recipients": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv",
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqaxww2fnhrx05cghth75n0qcj59e3e2anscr0q9wyknjxtxycg07y3pevyj",
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjyh2ju7hd5gj57jg5r9lev3pckk4n2shtzaq34467erzzdfajfggty6aa5",
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjyh2ju7hd5gj57jg5r9lev3pckk4n2shtzaq34467erzzdfajfggty6aa5"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ [
+ "006a02c308ccdbf3ac49f0638f6de128f875db5a213095cf112b3b77722472ae",
+ "39f42624d5c32a77fda80ff0acee269afec601d3791803e80252ae04e4ffcf4c",
+ "ae1a780c04237bd577283c3ddb2e499767c3214160d5a6b0767e6b8c278bd701",
+ "ca64abe1e0f737823fb9a94f597eed418fb2df77b1317e26b881a14bb594faaa"
+ ],
+ [
+ "006a02c308ccdbf3ac49f0638f6de128f875db5a213095cf112b3b77722472ae",
+ "3edf1ff6657c6e69568811bd726a7a7f480493aa42161acfe8dd4f44521f99ed",
+ "7ee1543ed5d123ffa66fbebc128c020173eb490d5fa2ba306e0c9573a77db8f3",
+ "ca64abe1e0f737823fb9a94f597eed418fb2df77b1317e26b881a14bb594faaa"
+ ],
+ [
+ "006a02c308ccdbf3ac49f0638f6de128f875db5a213095cf112b3b77722472ae",
+ "7ee1543ed5d123ffa66fbebc128c020173eb490d5fa2ba306e0c9573a77db8f3",
+ "83dc944e61603137294829aed56c74c9b087d80f2c021b98a7fae5799000696c",
+ "ae1a780c04237bd577283c3ddb2e499767c3214160d5a6b0767e6b8c278bd701"
+ ],
+ [
+ "39f42624d5c32a77fda80ff0acee269afec601d3791803e80252ae04e4ffcf4c",
+ "3c54444944d176437644378c23efb999ab6ab1cacdfe1dc1537b607e3df330e2",
+ "ca64abe1e0f737823fb9a94f597eed418fb2df77b1317e26b881a14bb594faaa",
+ "f4569fc5f69c10f0082cfbb8e072e6266ec55f69fba8cffca4cbb4c144b7e59b"
+ ],
+ [
+ "39f42624d5c32a77fda80ff0acee269afec601d3791803e80252ae04e4ffcf4c",
+ "ae1a780c04237bd577283c3ddb2e499767c3214160d5a6b0767e6b8c278bd701",
+ "f207162b1a7abc51c42017bef055e9ec1efc3d3567cb720357e2b84325db33ac",
+ "f4569fc5f69c10f0082cfbb8e072e6266ec55f69fba8cffca4cbb4c144b7e59b"
+ ],
+ [
+ "3c54444944d176437644378c23efb999ab6ab1cacdfe1dc1537b607e3df330e2",
+ "602e10e6944107c9b48bd885b493676578c935723287e0ab2f8b7f136862568e",
+ "7ee1543ed5d123ffa66fbebc128c020173eb490d5fa2ba306e0c9573a77db8f3",
+ "ca64abe1e0f737823fb9a94f597eed418fb2df77b1317e26b881a14bb594faaa"
+ ],
+ [
+ "3c54444944d176437644378c23efb999ab6ab1cacdfe1dc1537b607e3df330e2",
+ "7ee1543ed5d123ffa66fbebc128c020173eb490d5fa2ba306e0c9573a77db8f3",
+ "83dc944e61603137294829aed56c74c9b087d80f2c021b98a7fae5799000696c",
+ "f4569fc5f69c10f0082cfbb8e072e6266ec55f69fba8cffca4cbb4c144b7e59b"
+ ],
+ [
+ "3edf1ff6657c6e69568811bd726a7a7f480493aa42161acfe8dd4f44521f99ed",
+ "7ee1543ed5d123ffa66fbebc128c020173eb490d5fa2ba306e0c9573a77db8f3",
+ "f207162b1a7abc51c42017bef055e9ec1efc3d3567cb720357e2b84325db33ac",
+ "f4569fc5f69c10f0082cfbb8e072e6266ec55f69fba8cffca4cbb4c144b7e59b"
+ ],
+ [
+ "3edf1ff6657c6e69568811bd726a7a7f480493aa42161acfe8dd4f44521f99ed",
+ "ca64abe1e0f737823fb9a94f597eed418fb2df77b1317e26b881a14bb594faaa",
+ "e976a58fbd38aeb4e6093d4df02e9c1de0c4513ae0c588cef68cda5b2f8834ca",
+ "f4569fc5f69c10f0082cfbb8e072e6266ec55f69fba8cffca4cbb4c144b7e59b"
+ ],
+ [
+ "602e10e6944107c9b48bd885b493676578c935723287e0ab2f8b7f136862568e",
+ "7ee1543ed5d123ffa66fbebc128c020173eb490d5fa2ba306e0c9573a77db8f3",
+ "ae1a780c04237bd577283c3ddb2e499767c3214160d5a6b0767e6b8c278bd701",
+ "f207162b1a7abc51c42017bef055e9ec1efc3d3567cb720357e2b84325db33ac"
+ ],
+ [
+ "602e10e6944107c9b48bd885b493676578c935723287e0ab2f8b7f136862568e",
+ "ae1a780c04237bd577283c3ddb2e499767c3214160d5a6b0767e6b8c278bd701",
+ "ca64abe1e0f737823fb9a94f597eed418fb2df77b1317e26b881a14bb594faaa",
+ "e976a58fbd38aeb4e6093d4df02e9c1de0c4513ae0c588cef68cda5b2f8834ca"
+ ],
+ [
+ "83dc944e61603137294829aed56c74c9b087d80f2c021b98a7fae5799000696c",
+ "ae1a780c04237bd577283c3ddb2e499767c3214160d5a6b0767e6b8c278bd701",
+ "e976a58fbd38aeb4e6093d4df02e9c1de0c4513ae0c588cef68cda5b2f8834ca",
+ "f4569fc5f69c10f0082cfbb8e072e6266ec55f69fba8cffca4cbb4c144b7e59b"
+ ]
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ }
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b972103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9147cdd63cc408564188e8e472640e921c7c90e651d88ac"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "006a02c308ccdbf3ac49f0638f6de128f875db5a213095cf112b3b77722472ae",
+ "39f42624d5c32a77fda80ff0acee269afec601d3791803e80252ae04e4ffcf4c",
+ "ae1a780c04237bd577283c3ddb2e499767c3214160d5a6b0767e6b8c278bd701",
+ "ca64abe1e0f737823fb9a94f597eed418fb2df77b1317e26b881a14bb594faaa"
+ ],
+ "key_material": {
+ "spend_priv_key": "9d6ad855ce3417ef84e836892e5a56392bfba05fa5d97ccea30e266f540e08b3",
+ "scan_priv_key": "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"
+ },
+ "labels": [
+ 1,
+ 1337
+ ]
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv",
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqaxww2fnhrx05cghth75n0qcj59e3e2anscr0q9wyknjxtxycg07y3pevyj",
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjyh2ju7hd5gj57jg5r9lev3pckk4n2shtzaq34467erzzdfajfggty6aa5"
+ ],
+ "outputs": [
+ {
+ "priv_key_tweak": "4e3352fbe0505c25e718d96007c259ef08db34f8c844e4ff742d9855ff03805a",
+ "pub_key": "006a02c308ccdbf3ac49f0638f6de128f875db5a213095cf112b3b77722472ae",
+ "signature": "6eeae1ea9eb826e3d0e812f65937100e0836ea188c04f36fabc4981eda29de8d3d3529390a0a8b3d830f7bca4f5eae5994b9788ddaf05ad259ffe26d86144b4b"
+ },
+ {
+ "priv_key_tweak": "43100f89f1a6bf10081c92b473ffc57ceac7dbed600b6aba9bb3976f17dbb914",
+ "pub_key": "39f42624d5c32a77fda80ff0acee269afec601d3791803e80252ae04e4ffcf4c",
+ "signature": "15c92509b67a6c211ebb4a51b7528d0666e6720de2343b2e92cfb97942ca14693c1f1fdc8451acfdb2644039f8f5c76114807fdc3d3a002d8a46afab6756bd75"
+ },
+ {
+ "priv_key_tweak": "bf709f98d4418f8a67e738154ae48818dad44689cd37fbc070891a396dd1c633",
+ "pub_key": "ae1a780c04237bd577283c3ddb2e499767c3214160d5a6b0767e6b8c278bd701",
+ "signature": "42a19fd8a63dde1824966a95d65a28203e631e49bf96ca5dae1b390e7a0ace2cc8709c9b0c5715047032f57f536a3c80273cbecf4c05be0b5456c183fa122c06"
+ },
+ {
+ "priv_key_tweak": "736f05e4e3072c3b8656bedef2e9bf54cbcaa2b6fe5320d3e86f5b96874dda71",
+ "pub_key": "ca64abe1e0f737823fb9a94f597eed418fb2df77b1317e26b881a14bb594faaa",
+ "signature": "2e61bb3d79418ecf55f68847cf121bfc12d397b39d1da8643246b2f0a9b96c3daa4bfe9651beb5c9ce20e1f29282c4566400a4b45ee6657ec3b18fdc554da0b4"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "comment": "Single recipient: use silent payments for sender change",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b972103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9147cdd63cc408564188e8e472640e921c7c90e651d88ac"
+ }
+ },
+ "private_key": "0378e95685b74565fa56751b84a32dfd18545d10d691641b8372e32164fad66a"
+ }
+ ],
+ "recipients": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv",
+ "sp1qqw6vczcfpdh5nf5y2ky99kmqae0tr30hgdfg88parz50cp80wd2wqqlv6saelkk5snl4wfutyxrchpzzwm8rjp3z6q7apna59z9huq4x754e5atr"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ [
+ "be368e28979d950245d742891ae6064020ba548c1e2e65a639a8bb0675d95cff",
+ "f207162b1a7abc51c42017bef055e9ec1efc3d3567cb720357e2b84325db33ac"
+ ]
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ }
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b972103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9147cdd63cc408564188e8e472640e921c7c90e651d88ac"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "be368e28979d950245d742891ae6064020ba548c1e2e65a639a8bb0675d95cff",
+ "f207162b1a7abc51c42017bef055e9ec1efc3d3567cb720357e2b84325db33ac"
+ ],
+ "key_material": {
+ "spend_priv_key": "b8f87388cbb41934c50daca018901b00070a5ff6cc25a7e9e716a9d5b9e4d664",
+ "scan_priv_key": "11b7a82e06ca2648d5fded2366478078ec4fc9dc1d8ff487518226f229d768fd"
+ },
+ "labels": [
+ 0
+ ]
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqw6vczcfpdh5nf5y2ky99kmqae0tr30hgdfg88parz50cp80wd2wqqauj52ymtc4xdkmx3tgyhrsemg2g3303xk2gtzfy8h8ejet8fz8jcw23zua",
+ "sp1qqw6vczcfpdh5nf5y2ky99kmqae0tr30hgdfg88parz50cp80wd2wqqlv6saelkk5snl4wfutyxrchpzzwm8rjp3z6q7apna59z9huq4x754e5atr"
+ ],
+ "outputs": [
+ {
+ "priv_key_tweak": "80cd767ed20bd0bb7d8ea5e803f8c381293a62e8a073cf46fb0081da46e64e1f",
+ "pub_key": "be368e28979d950245d742891ae6064020ba548c1e2e65a639a8bb0675d95cff",
+ "signature": "7fbd5074cf1377273155eefafc7c330cb61b31da252f22206ac27530d2b2567040d9af7808342ed4a09598c26d8307446e4ed77079e6a2e61fea736e44da5f5a"
+ }
+ ]
+ }
+ },
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ }
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b972103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9147cdd63cc408564188e8e472640e921c7c90e651d88ac"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "be368e28979d950245d742891ae6064020ba548c1e2e65a639a8bb0675d95cff",
+ "f207162b1a7abc51c42017bef055e9ec1efc3d3567cb720357e2b84325db33ac"
+ ],
+ "key_material": {
+ "spend_priv_key": "9d6ad855ce3417ef84e836892e5a56392bfba05fa5d97ccea30e266f540e08b3",
+ "scan_priv_key": "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"
+ },
+ "labels": []
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ],
+ "outputs": [
+ {
+ "priv_key_tweak": "33ce085c3c11eaad13694aae3c20301a6c83382ec89a7cde96c6799e2f88805a",
+ "pub_key": "f207162b1a7abc51c42017bef055e9ec1efc3d3567cb720357e2b84325db33ac",
+ "signature": "335667ca6cae7a26438f5cfdd73b3d48fa832fa9768521d7d5445f22c203ab0d74ed85088f27d29959ba627a4509996676f47df8ff284d292567b1beef0e3912"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "comment": "Single recipient: taproot input with NUMS point",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "",
+ "txinwitness": "0440c459b671370d12cfb5acee76da7e3ba7cc29b0b4653e3af8388591082660137d087fdc8e89a612cd5d15be0febe61fc7cdcf3161a26e599a4514aa5c3e86f47b22205a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5ac21c150929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac00150",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "5120da6f0595ecb302bbe73e2f221f05ab10f336b06817d36fd28fc6691725ddaa85"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "",
+ "txinwitness": "0140bd1e708f92dbeaf24a6b8dd22e59c6274355424d62baea976b449e220fd75b13578e262ab11b7aa58e037f0c6b0519b66803b7d9decaa1906dedebfb531c56c1",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "5120782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338"
+ }
+ },
+ "private_key": "fc8716a97a48ba9a05a98ae47b5cd201a25a7fd5d8b73c203c5f7b6b6b3b6ad7"
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 1,
+ "scriptSig": "",
+ "txinwitness": "0340268d31a9276f6380107d5321cafa6d9e8e5ea39204318fdc8206b31507c891c3bbcea3c99e2208d73bd127a8e8c5f1e45a54f1bd217205414ddb566ab7eda0092220e0ec4f64b3fa2e463ccfcf4e856e37d5e1e20275bc89ec1def9eb098eff1f85dac21c150929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "51200a3c9365ceb131f89b0a4feb6896ebd67bb15a98c31eaa3da143bb955a0f3fcb"
+ }
+ },
+ "private_key": "8d4751f6e8a3586880fb66c19ae277969bd5aa06f61c4ee2f1e2486efdf666d3"
+ }
+ ],
+ "recipients": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ [
+ "79e79897c52935bfd97fc6e076a6431a0c7543ca8c31e0fc3cf719bb572c842d"
+ ]
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "",
+ "txinwitness": "0440c459b671370d12cfb5acee76da7e3ba7cc29b0b4653e3af8388591082660137d087fdc8e89a612cd5d15be0febe61fc7cdcf3161a26e599a4514aa5c3e86f47b22205a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5ac21c150929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac00150",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "5120da6f0595ecb302bbe73e2f221f05ab10f336b06817d36fd28fc6691725ddaa85"
+ }
+ }
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "",
+ "txinwitness": "0140bd1e708f92dbeaf24a6b8dd22e59c6274355424d62baea976b449e220fd75b13578e262ab11b7aa58e037f0c6b0519b66803b7d9decaa1906dedebfb531c56c1",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "5120782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338"
+ }
+ }
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 1,
+ "scriptSig": "",
+ "txinwitness": "0340268d31a9276f6380107d5321cafa6d9e8e5ea39204318fdc8206b31507c891c3bbcea3c99e2208d73bd127a8e8c5f1e45a54f1bd217205414ddb566ab7eda0092220e0ec4f64b3fa2e463ccfcf4e856e37d5e1e20275bc89ec1def9eb098eff1f85dac21c150929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "51200a3c9365ceb131f89b0a4feb6896ebd67bb15a98c31eaa3da143bb955a0f3fcb"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "79e79897c52935bfd97fc6e076a6431a0c7543ca8c31e0fc3cf719bb572c842d"
+ ],
+ "key_material": {
+ "spend_priv_key": "9d6ad855ce3417ef84e836892e5a56392bfba05fa5d97ccea30e266f540e08b3",
+ "scan_priv_key": "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"
+ },
+ "labels": []
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ],
+ "outputs": [
+ {
+ "priv_key_tweak": "3ddec3232609d348d6b8b53123b4f40f6d4f5398ca586f087b0416ec3b851496",
+ "pub_key": "79e79897c52935bfd97fc6e076a6431a0c7543ca8c31e0fc3cf719bb572c842d",
+ "signature": "d7d06e3afb68363031e4eb18035c46ceae41bdbebe7888a4754bc9848c596436869aeaecff0527649a1f458b71c9ceecec10b535c09d01d720229aa228547706"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "comment": "Pubkey extraction from malleated p2pkh",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ },
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 1,
+ "scriptSig": "0075473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b972103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9147cdd63cc408564188e8e472640e921c7c90e651d88ac"
+ }
+ },
+ "private_key": "0378e95685b74565fa56751b84a32dfd18545d10d691641b8372e32164fad66a"
+ },
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 2,
+ "scriptSig": "5163473045022100e7d26e77290b37128f5215ade25b9b908ce87cc9a4d498908b5bb8fd6daa1b8d022002568c3a8226f4f0436510283052bfb780b76f3fe4aa60c4c5eb118e43b187372102e0ec4f64b3fa2e463ccfcf4e856e37d5e1e20275bc89ec1def9eb098eff1f85d67483046022100c0d3c851d3bd562ae93d56bcefd735ea57c027af46145a4d5e9cac113bfeb0c2022100ee5b2239af199fa9b7aa1d98da83a29d0a2cf1e4f29e2f37134ce386d51c544c2102ad0f26ddc7b3fcc340155963b3051b85289c1869612ecb290184ac952e2864ec68",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a914c82c5ec473cbc6c86e5ef410e36f9495adcf979988ac"
+ }
+ },
+ "private_key": "72b8ae09175ca7977f04993e651d88681ed932dfb92c5158cdf0161dd23fda6e"
+ }
+ ],
+ "recipients": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ [
+ "4612cdbf845c66c7511d70aab4d9aed11e49e48cdb8d799d787101cdd0d53e4f"
+ ]
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ }
+ },
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 1,
+ "scriptSig": "0075473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b972103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9147cdd63cc408564188e8e472640e921c7c90e651d88ac"
+ }
+ }
+ },
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 2,
+ "scriptSig": "5163473045022100e7d26e77290b37128f5215ade25b9b908ce87cc9a4d498908b5bb8fd6daa1b8d022002568c3a8226f4f0436510283052bfb780b76f3fe4aa60c4c5eb118e43b187372102e0ec4f64b3fa2e463ccfcf4e856e37d5e1e20275bc89ec1def9eb098eff1f85d67483046022100c0d3c851d3bd562ae93d56bcefd735ea57c027af46145a4d5e9cac113bfeb0c2022100ee5b2239af199fa9b7aa1d98da83a29d0a2cf1e4f29e2f37134ce386d51c544c2102ad0f26ddc7b3fcc340155963b3051b85289c1869612ecb290184ac952e2864ec68",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a914c82c5ec473cbc6c86e5ef410e36f9495adcf979988ac"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "4612cdbf845c66c7511d70aab4d9aed11e49e48cdb8d799d787101cdd0d53e4f"
+ ],
+ "key_material": {
+ "spend_priv_key": "9d6ad855ce3417ef84e836892e5a56392bfba05fa5d97ccea30e266f540e08b3",
+ "scan_priv_key": "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"
+ },
+ "labels": []
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ],
+ "outputs": [
+ {
+ "priv_key_tweak": "10bde9781def20d7701e7603ef1b1e5e71c67bae7154818814e3c81ef5b1a3d3",
+ "pub_key": "4612cdbf845c66c7511d70aab4d9aed11e49e48cdb8d799d787101cdd0d53e4f",
+ "signature": "6137969f810e9e8ef6c9755010e808f5dd1aed705882e44d7f0ae64eb0c509ec8b62a0671bee0d5914ac27d2c463443e28e999d82dc3d3a4919f093872d947bb"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "comment": "P2PKH and P2WPKH Uncompressed Keys are skipped",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ },
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b974104782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c3799373233387c5343bf58e23269e903335b958a12182f9849297321e8d710e49a8727129cab",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9144b92ac4ac6fe6212393894addda332f2e47a315688ac"
+ }
+ },
+ "private_key": "0378e95685b74565fa56751b84a32dfd18545d10d691641b8372e32164fad66a"
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 1,
+ "scriptSig": "",
+ "txinwitness": "02473045022100e7d26e77290b37128f5215ade25b9b908ce87cc9a4d498908b5bb8fd6daa1b8d022002568c3a8226f4f0436510283052bfb780b76f3fe4aa60c4c5eb118e43b187374104e0ec4f64b3fa2e463ccfcf4e856e37d5e1e20275bc89ec1def9eb098eff1f85d6fe8190e189be57d0d5bcd17dbcbcd04c9b4a1c5f605b10d5c90abfcc0d12884",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "00140423f731a07491364e8dce98b7c00bda63336950"
+ }
+ },
+ "private_key": "72b8ae09175ca7977f04993e651d88681ed932dfb92c5158cdf0161dd23fda6e"
+ }
+ ],
+ "recipients": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ [
+ "67fee277da9e8542b5d2e6f32d660a9bbd3f0e107c2d53638ab1d869088882d6"
+ ]
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a91419c2f3ae0ca3b642bd3e49598b8da89f50c1416188ac"
+ }
+ }
+ },
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b974104782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c3799373233387c5343bf58e23269e903335b958a12182f9849297321e8d710e49a8727129cab",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9144b92ac4ac6fe6212393894addda332f2e47a315688ac"
+ }
+ }
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 1,
+ "scriptSig": "",
+ "txinwitness": "02473045022100e7d26e77290b37128f5215ade25b9b908ce87cc9a4d498908b5bb8fd6daa1b8d022002568c3a8226f4f0436510283052bfb780b76f3fe4aa60c4c5eb118e43b187374104e0ec4f64b3fa2e463ccfcf4e856e37d5e1e20275bc89ec1def9eb098eff1f85d6fe8190e189be57d0d5bcd17dbcbcd04c9b4a1c5f605b10d5c90abfcc0d12884",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "00140423f731a07491364e8dce98b7c00bda63336950"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "67fee277da9e8542b5d2e6f32d660a9bbd3f0e107c2d53638ab1d869088882d6"
+ ],
+ "key_material": {
+ "spend_priv_key": "9d6ad855ce3417ef84e836892e5a56392bfba05fa5d97ccea30e266f540e08b3",
+ "scan_priv_key": "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"
+ },
+ "labels": []
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ],
+ "outputs": [
+ {
+ "priv_key_tweak": "688fa3aeb97d2a46ae87b03591921c2eaf4b505eb0ddca2733c94701e01060cf",
+ "pub_key": "67fee277da9e8542b5d2e6f32d660a9bbd3f0e107c2d53638ab1d869088882d6",
+ "signature": "72e7ad573ac23255d4651d5b0326a200496588acb7a4894b22092236d5eda6a0a9a4d8429b022c2219081fefce5b33795cae488d10f5ea9438849ed8353624f2"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "comment": "Skip invalid P2SH inputs",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "16001419c2f3ae0ca3b642bd3e49598b8da89f50c14161",
+ "txinwitness": "02483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "a9148629db5007d5fcfbdbb466637af09daf9125969387"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ },
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 1,
+ "scriptSig": "1600144b92ac4ac6fe6212393894addda332f2e47a3156",
+ "txinwitness": "02473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b974104782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c3799373233387c5343bf58e23269e903335b958a12182f9849297321e8d710e49a8727129cab",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "a9146c9bf136fbb7305fd99d771a95127fcf87dedd0d87"
+ }
+ },
+ "private_key": "0378e95685b74565fa56751b84a32dfd18545d10d691641b8372e32164fad66a"
+ },
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 2,
+ "scriptSig": "00493046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d601483045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b97014c695221025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be52103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c3799373233382102e0ec4f64b3fa2e463ccfcf4e856e37d5e1e20275bc89ec1def9eb098eff1f85d53ae",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "a9141044ddc6cea09e4ac40fbec2ba34ad62de6db25b87"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ }
+ ],
+ "recipients": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ [
+ "67fee277da9e8542b5d2e6f32d660a9bbd3f0e107c2d53638ab1d869088882d6"
+ ]
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "16001419c2f3ae0ca3b642bd3e49598b8da89f50c14161",
+ "txinwitness": "02483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d621025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "a9148629db5007d5fcfbdbb466637af09daf9125969387"
+ }
+ }
+ },
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 1,
+ "scriptSig": "1600144b92ac4ac6fe6212393894addda332f2e47a3156",
+ "txinwitness": "02473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b974104782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c3799373233387c5343bf58e23269e903335b958a12182f9849297321e8d710e49a8727129cab",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "a9146c9bf136fbb7305fd99d771a95127fcf87dedd0d87"
+ }
+ }
+ },
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 2,
+ "scriptSig": "00493046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d601483045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b97014c695221025a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be52103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c3799373233382102e0ec4f64b3fa2e463ccfcf4e856e37d5e1e20275bc89ec1def9eb098eff1f85d53ae",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "a9141044ddc6cea09e4ac40fbec2ba34ad62de6db25b87"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "67fee277da9e8542b5d2e6f32d660a9bbd3f0e107c2d53638ab1d869088882d6"
+ ],
+ "key_material": {
+ "spend_priv_key": "9d6ad855ce3417ef84e836892e5a56392bfba05fa5d97ccea30e266f540e08b3",
+ "scan_priv_key": "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"
+ },
+ "labels": []
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ],
+ "outputs": [
+ {
+ "priv_key_tweak": "688fa3aeb97d2a46ae87b03591921c2eaf4b505eb0ddca2733c94701e01060cf",
+ "pub_key": "67fee277da9e8542b5d2e6f32d660a9bbd3f0e107c2d53638ab1d869088882d6",
+ "signature": "72e7ad573ac23255d4651d5b0326a200496588acb7a4894b22092236d5eda6a0a9a4d8429b022c2219081fefce5b33795cae488d10f5ea9438849ed8353624f2"
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "comment": "Recipient ignores unrelated outputs",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "",
+ "txinwitness": "0140c459b671370d12cfb5acee76da7e3ba7cc29b0b4653e3af8388591082660137d087fdc8e89a612cd5d15be0febe61fc7cdcf3161a26e599a4514aa5c3e86f47b",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "51205a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b972103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9147cdd63cc408564188e8e472640e921c7c90e651d88ac"
+ }
+ },
+ "private_key": "0378e95685b74565fa56751b84a32dfd18545d10d691641b8372e32164fad66a"
+ }
+ ],
+ "recipients": [
+ "sp1qqgrz6j0lcqnc04vxccydl0kpsj4frfje0ktmgcl2t346hkw30226xqupawdf48k8882j0strrvcmgg2kdawz53a54dd376ngdhak364hzcmynqtn"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ [
+ "841792c33c9dc6193e76744134125d40add8f2f4a96475f28ba150be032d64e8"
+ ]
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "",
+ "txinwitness": "0140c459b671370d12cfb5acee76da7e3ba7cc29b0b4653e3af8388591082660137d087fdc8e89a612cd5d15be0febe61fc7cdcf3161a26e599a4514aa5c3e86f47b",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "51205a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5"
+ }
+ }
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b972103782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9147cdd63cc408564188e8e472640e921c7c90e651d88ac"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "841792c33c9dc6193e76744134125d40add8f2f4a96475f28ba150be032d64e8",
+ "782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338"
+ ],
+ "key_material": {
+ "spend_priv_key": "9d6ad855ce3417ef84e836892e5a56392bfba05fa5d97ccea30e266f540e08b3",
+ "scan_priv_key": "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"
+ },
+ "labels": []
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ],
+ "outputs": []
+ }
+ }
+ ]
+ },
+ {
+ "comment": "No valid inputs, sender generates no outputs",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d641045a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5c61836c9b1688ba431f7ea3039742251f62f0dca3da1bee58a47fa9b456c2d52",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a914460e8b41545d2dbe7e0671f0f573e2232814260a88ac"
+ }
+ },
+ "private_key": "eadc78165ff1f8ea94ad7cfdc54990738a4c53f6e0507b42154201b8e5dff3b1"
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b974104782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c3799373233387c5343bf58e23269e903335b958a12182f9849297321e8d710e49a8727129cab",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9144b92ac4ac6fe6212393894addda332f2e47a315688ac"
+ }
+ },
+ "private_key": "0378e95685b74565fa56751b84a32dfd18545d10d691641b8372e32164fad66a"
+ }
+ ],
+ "recipients": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ []
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16",
+ "vout": 0,
+ "scriptSig": "483046022100ad79e6801dd9a8727f342f31c71c4912866f59dc6e7981878e92c5844a0ce929022100fb0d2393e813968648b9753b7e9871d90ab3d815ebf91820d704b19f4ed224d641045a1e61f898173040e20616d43e9f496fba90338a39faa1ed98fcbaeee4dd9be5c61836c9b1688ba431f7ea3039742251f62f0dca3da1bee58a47fa9b456c2d52",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a914460e8b41545d2dbe7e0671f0f573e2232814260a88ac"
+ }
+ }
+ },
+ {
+ "txid": "a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d",
+ "vout": 0,
+ "scriptSig": "473045022100a8c61b2d470e393279d1ba54f254b7c237de299580b7fa01ffcc940442ecec4502201afba952f4e4661c40acde7acc0341589031ba103a307b886eb867b23b850b974104782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c3799373233387c5343bf58e23269e903335b958a12182f9849297321e8d710e49a8727129cab",
+ "txinwitness": "",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "76a9144b92ac4ac6fe6212393894addda332f2e47a315688ac"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "782eeb913431ca6e9b8c2fd80a5f72ed2024ef72a3c6fb10263c379937323338",
+ "e0ec4f64b3fa2e463ccfcf4e856e37d5e1e20275bc89ec1def9eb098eff1f85d"
+ ],
+ "key_material": {
+ "spend_priv_key": "9d6ad855ce3417ef84e836892e5a56392bfba05fa5d97ccea30e266f540e08b3",
+ "scan_priv_key": "0f694e068028a717f8af6b9411f9a133dd3565258714cc226594b34db90c1f2c"
+ },
+ "labels": []
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv"
+ ],
+ "outputs": []
+ }
+ }
+ ]
+ },
+ {
+ "comment": "Input keys sum up to zero / point at infinity: sending fails, receiver skips tx",
+ "sending": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "3a286147b25e16ae80aff406f2673c6e565418c40f45c071245cdebc8a94174e",
+ "vout": 0,
+ "scriptSig": "",
+ "txinwitness": "024730440220085003179ce1a3a88ce0069aa6ea045e140761ab88c22a26ae2a8cfe983a6e4602204a8a39940f0735c8a4424270ac8da65240c261ab3fda9272f6d6efbf9cfea366012102557ef3e55b0a52489b4454c1169e06bdea43687a69c1f190eb50781644ab6975",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "00149d9e24f9fab4e35bf1a6df4b46cb533296ac0792"
+ }
+ },
+ "private_key": "a6df6a0bb448992a301df4258e06a89fe7cf7146f59ac3bd5ff26083acb22ceb"
+ },
+ {
+ "txid": "3a286147b25e16ae80aff406f2673c6e565418c40f45c071245cdebc8a94174e",
+ "vout": 1,
+ "scriptSig": "",
+ "txinwitness": "0247304402204586a68e1d97dd3c6928e3622799859f8c3b20c3c670cf654cc905c9be29fdb7022043fbcde1689f3f4045e8816caf6163624bd19e62e4565bc99f95c533e599782c012103557ef3e55b0a52489b4454c1169e06bdea43687a69c1f190eb50781644ab6975",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "00149860538b5575962776ed0814ae222c7d60c72d7b"
+ }
+ },
+ "private_key": "592095f44bb766d5cfe20bda71f9575ed2df6b9fb9addc7e5fdffe0923841456"
+ }
+ ],
+ "recipients": [
+ "sp1qqtrqglu5g8kh6mfsg4qxa9wq0nv9cauwfwxw70984wkqnw2uwz0w2qnehen8a7wuhwk9tgrzjh8gwzc8q2dlekedec5djk0js9d3d7qhnq6lqj3s"
+ ]
+ },
+ "expected": {
+ "outputs": [
+ []
+ ]
+ }
+ }
+ ],
+ "receiving": [
+ {
+ "given": {
+ "vin": [
+ {
+ "txid": "3a286147b25e16ae80aff406f2673c6e565418c40f45c071245cdebc8a94174e",
+ "vout": 0,
+ "scriptSig": "",
+ "txinwitness": "024730440220085003179ce1a3a88ce0069aa6ea045e140761ab88c22a26ae2a8cfe983a6e4602204a8a39940f0735c8a4424270ac8da65240c261ab3fda9272f6d6efbf9cfea366012102557ef3e55b0a52489b4454c1169e06bdea43687a69c1f190eb50781644ab6975",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "00149d9e24f9fab4e35bf1a6df4b46cb533296ac0792"
+ }
+ }
+ },
+ {
+ "txid": "3a286147b25e16ae80aff406f2673c6e565418c40f45c071245cdebc8a94174e",
+ "vout": 1,
+ "scriptSig": "",
+ "txinwitness": "0247304402204586a68e1d97dd3c6928e3622799859f8c3b20c3c670cf654cc905c9be29fdb7022043fbcde1689f3f4045e8816caf6163624bd19e62e4565bc99f95c533e599782c012103557ef3e55b0a52489b4454c1169e06bdea43687a69c1f190eb50781644ab6975",
+ "prevout": {
+ "scriptPubKey": {
+ "hex": "00149860538b5575962776ed0814ae222c7d60c72d7b"
+ }
+ }
+ }
+ ],
+ "outputs": [
+ "0000000000000000000000000000000000000000000000000000000000000000"
+ ],
+ "key_material": {
+ "spend_priv_key": "0000000000000000000000000000000000000000000000000000000000000001",
+ "scan_priv_key": "0000000000000000000000000000000000000000000000000000000000000002"
+ },
+ "labels": []
+ },
+ "expected": {
+ "addresses": [
+ "sp1qqtrqglu5g8kh6mfsg4qxa9wq0nv9cauwfwxw70984wkqnw2uwz0w2qnehen8a7wuhwk9tgrzjh8gwzc8q2dlekedec5djk0js9d3d7qhnq6lqj3s"
+ ],
+ "outputs": []
+ }
+ }
+ ]
+ }
+]
diff --git a/bip-0353.mediawiki b/bip-0353.mediawiki
new file mode 100644
index 0000000000..ef4b6c0abc
--- /dev/null
+++ b/bip-0353.mediawiki
@@ -0,0 +1,176 @@
+
+
+
+==Copyright==
+
+This BIP is licensed under the CC0-1.0 license.
+
+==Abstract==
+This BIP proposes a standard format for encoding [[bip-0021.mediawiki|BIP 21]] URI schemes in DNS TXT records.
+
+==Motivation==
+Various Bitcoin and other cryptocurrency applications have developed human-readable names for payment instructions over time, with marketplace adoption signaling strong demand for it from users.
+
+The DNS provides a standard, global, hierarchical namespace mapping human-readable labels to records of various forms. Using DNSSEC, the DNS provides cryptographic guarantees using a straightforward PKI which follows the hierarchical nature of the DNS, allowing for stateless and even offline validation of DNS records from a single trusted root.
+
+Further, because DNS queries are generally proxied through ISP-provided or other resolvers, DNS queries usually do not directly expose the queryer's IP address. Further, because of the prevalence of open resolvers, the simplicity of the protocol, and broad availability of DNS recursive resolver implementations, finding a proxy for DNS records is trivial.
+
+Thus, using TXT records to store Bitcoin payment instructions allows for human-readable Bitcoin payment destinations which can be trivially verified on hardware wallets and which can be resolved relatively privately.
+
+==Specification==
+
+=== General rules for handling ===
+Bitcoin wallets MUST NOT prefer to use DNS-based resolving when methods with explicit public keys or addresses are available. In other words, if a standard Bitcoin address or direct BIP 21 URI is available or would suffice, Bitcoin wallets MUST prefer to use that instead.
+
+=== Records ===
+Payment instructions are indexed by both a user and a domain. Instructions for a given `user` and `domain` are stored at `user`.user._bitcoin-payment.`domain` in a single TXT record.
+
+All payment instructions MUST be DNSSEC-signed.
+
+Payment instructions MAY resolve through CNAME or DNAME records as long as all such records and the ultimate records pointed to by them are DNSSEC signed.
+
+User and domain names which are not expressible using standard printable ASCII MUST be encoded using the punycode IDN encoding defined in [[https://datatracker.ietf.org/doc/html/rfc3492|RFC 3492]] and [[https://datatracker.ietf.org/doc/html/rfc5891|RFC 5891]].
+
+Note that because resolvers are not required to support resolving non-ASCII identifiers, wallets SHOULD avoid using non-ASCII identifiers.
+
+For payment instructions that have a built-in expiry time (e.g. Lightning BOLT 12 offers), care must be taken to ensure that the DNS records expire prior to the expiry of the payment instructions. Otherwise, senders may have payment instructions cached locally which have expired, preventing payment.
+
+=== Resolution ===
+
+Clients resolving Bitcoin payment instructions MUST ignore any TXT records at the same label which do not begin with (ignoring case) "bitcoin:". Resolvers encountering multiple "bitcoin:"-matching TXT records at the same label MUST treat the records as invalid and refuse to use any payment instructions therein.
+
+Clients resolving Bitcoin payment instructions MUST concatenate all strings in the TXT record before processing the complete URI.TXT records are defined as "one or more character-strings" in [[https://www.rfc-editor.org/rfc/rfc1035#section-3.3.14|RFC 1035]], and a "character-string" is a single byte (with a max value of 255) followed by that many characters.
+
+Clients resolving Bitcoin payment instructions MUST fully validate DNSSEC signatures leading to the DNS root (including any relevant CNAME or DNAME records) and MUST NOT accept DNSSEC signatures which use SHA-1 or RSA with keys shorter than 1024 bits. Resolvers MAY accept SHA-1 DS records.
+
+Clients resolving Bitcoin payment instructions MUST NOT trust a remote resolver to validate DNSSEC records on their behalf.
+
+Clients resolving Bitcoin payment instructions MUST support resolving through CNAME or DNAME records.
+
+Resolvers MAY support resolving non-ASCII user and domain identifiers. Resolvers which do support non-ASCII user and domain identifiers MUST take precautions to prevent homograph attacks and SHOULD consider denying paste functionality when entering non-ASCII identifiers. Wallets which do not take any such precautions MUST instead display non-ASCII user and domain identifiers using their raw punycode. As such, wallets SHOULD NOT create identifiers which are not entirely printable ASCII.
+
+While clients MAY cache the payment instructions they receive from the DNS, clients MUST NOT cache the payment instructions received from the DNS for longer than the TTL provided by their DNS resolver, and further MUST NOT cache the payment instructions for longer than the lowest initial TTL (which is signed as a part of DNSSEC signatures) received in the full DNSSEC chain leading from the DNS root to the resolved TXT record.
+
+=== Address Reuse ===
+
+Payment instructions with on-chain addresses which will be re-used SHOULD be rotated as regularly as possible to reduce address reuse. Such payment instructions SHOULD also use a relatively short DNS TTL to ensure regular rotation takes effect quickly. In cases where this is not practical, payment instructions SHOULD NOT contain on-chain addresses (i.e. the URI path SHOULD be empty).
+
+Payment instructions which do contain on-chain addresses which will be re-used SHOULD be rotated after any transaction to such an address is confirmed on-chain.
+
+=== Display ===
+
+When displaying a verified human-readable name, wallets SHOULD prefix it with ₿, i.e. ₿`user`@`domain`. They SHOULD parse recipient information in both `user`@`domain` and ₿`user`@`domain` forms and resolve such an entry into recipient information using the above record. For the avoidance of doubt, the ₿ is *not* included in the DNS label which is resolved.
+
+Wallets providing the ability for users to "copy" their address information SHOULD copy the underlying URI directly, rather than the human-readable name. This avoids an additional DNS lookup by the application in which it is pasted. Wallets that nevertheless provide users the ability to copy their human-readable name, MUST include the ₿ prefix (i.e. copy it in the form ₿`user`@`domain`).
+
+Wallets accepting payment information from external devices (e.g. hardware wallets) SHOULD accept RFC 9102-formatted proofs (as a series of unsorted `AuthenticationChain` records) and, if verification succeeds, SHOULD display the recipient in the form ₿`user`@`domain`.
+
+=== PSBT types ===
+
+Wallets accepting payment information from external devices (e.g. hardware wallets) MAY examine the following per-output PSBT fields to fetch RFC 9102-formatted proofs. Wallets creating PSBTs with recipient information derived from human-readable names SHOULD include the following fields.
+
+When validating the contained proof, clients MUST enforce the inception on all contained RRSigs is no later than the current time and that the expiry of all RRSigs is no earlier than an hour in the past. Clients MAY allow for an expiry up to an hour in the past to allow for delays between PSBT construction and signing only if such a delay is likely to occur in their intended usecase.
+
+{|
+! Name
+!
+!
+!
+! Description
+! Versions Requiring Inclusion
+! Versions Requiring Exclusion
+! Versions Allowing Inclusion
+|-
+| BIP 353 DNSSEC proof
+| PSBT_OUT_DNSSEC_PROOF = 0x35
+| None
+| <1-byte-length-prefixed BIP 353 human-readable name without the ₿ prefix>
+| A BIP 353 human-readable name (without the ₿ prefix), prefixed by a 1-byte length.
+Followed by an [[https://www.rfc-editor.org/rfc/rfc9102.html#name-dnssec-authentication-chain|RFC 9102 DNSSEC AuthenticationChain]] (i.e. a series of DNS Resource Records in no particular order) providing a DNSSEC proof to a BIP 353 DNS TXT record.
+|
+|
+| 0, 2
+|}
+
+== Rationale ==
+
+=== Display ===
+
+There are several ways in which human-readable payment instructions could be displayed in wallets. In order to ensure compatibility with existing human-readable names schemes, @ is used as the separator between the `user` and `domain` parts. However, simply using the @ separator can lead to confusion between email addresses on a given domain and payment instructions on a domain. In order to somewhat reduce the incidence of such confusion, a ₿ prefix is used.
+
+=== Rotation ===
+
+On-chain addresses which are re-used (i.e. not including schemes like [[bip-0352.mediawiki|Silent Payments]]) need to be rotated to avoid contributing substantially to address reuse. However, rotating them on a timer or any time a transaction enters the mempool could lead to substantial overhead from excess address generation. Instead, rotating addresses any time a transaction is confirmed on-chain ensures address rotation happens often while bounding the maximum number of addresses needed to one per block, which grows very slowly and will not generate an address set too large to handle while scanning the chain going forward.
+
+=== Alternatives ===
+There are many existing schemes to resolve human-readable names to cryptocurrency payment instructions. Sadly, these current schemes suffer from a myriad of drawbacks, including (a) lacking succinct proofs of namespace to public key mappings, (b) revealing sender IP addresses to recipients or other intermediaries as a side-effect of payment, (c) relying on the bloated TLS Certificate Authority infrastructure, or (d) lacking open access, not allowing anyone to create a namespace mapping.
+
+==== DNS Rather than blockchain-based solutions ====
+There are many blockchain-based alternatives to the DNS which feature better censorship-resistance and, in many cases, security. However, here we chose to use the standard ICANN-managed DNS namespace as many blockchain-based schemes suffer from (a), above (though in some cases this could be addressed with cryptographic SNARK schemes). Further, because they do not have simple client-side querying ability, many of these schemes use trusted intermediaries which resolve names on behalf of clients. This reintroduces drawbacks (b) and often (c) as well.
+
+Finally, it is worth noting that none of the blockchain-based alternatives to the DNS have had material adoption outside of their specific silos, and committing Bitcoin wallets to rely on a separate system which doesn't see broad adoption may not be sustainable.
+
+==== DNS Rather than HTTP-based solutions ====
+HTTP(s)-based payment instruction resolution protocols suffer from drawbacks (a), (b), and (c), above, and generally shouldn't be considered a serious alternative for payment instruction resolution.
+
+==== Private DNS Querying ====
+While public recursive DNS resolvers are very common (e.g. 1.1.1.1, 8.8.8.8, and 9.9.9.9), using such resolvers directly (even after validating DNSSEC signatures) introduces drawback (b), at least in regard to a centralized intermediary. Resolving payment instructions recursively locally using a resolver on the same local network or in the paying application would instead introduce drawback (b) directly to the recipient, which may well be worse.
+
+For payers not using VPN or other proxying technologies, they generally trust their ISP to not snoop on their DNS requests anyway, so using ISP-provided recursive DNS resolvers is likely the best option.
+
+However, for the best privacy, payers are encouraged to perform DNS resolution over Tor or another VPN technology.
+
+Lightning payers should consider utilizing DNS resolution over native onion messages, using the protocol described in [[https://github.com/lightning/blips/blob/master/blip-0032.md|BLIP 32]]
+
+=== DNS Enumeration ===
+
+In most cases where payments are accepted from any third-party, user enumeration is practical by simply attempting to send small value payments to a list of possible user names. However, storing all valid users in the DNS directly may make such enumeration marginally more practical. Thus, those wishing to avoid such enumeration should carefully ensure all DNS names return valid payment instructions. Note when doing so that wildcard records are identified as such by the DNSSEC RRSIG labels counter and are differentiable from non-wildcard records.
+
+== Backwards Compatibility ==
+
+This work is intended to extend and subsume the existing "Lightning Address" scheme, which maps similar names (without the ₿ prefix) using HTTPS servers to Lightning BOLT 11 payment instructions. Wallets implementing this scheme MAY fall back to existing "Lightning Address" logic if DNS resolution fails but SHOULD NOT do so after this scheme is sufficiently broadly deployed to avoid leaking sender IP address information.
+
+== Examples ==
+
+matt@mattcorallo.com resolves to
+
+
+
+* Note that `lno` indicates a value containing a lightning BOLT12 offer.
+* Note that the complete URI is broken into two strings with maximum 255 characters each
+
+== Reference Implementations ==
+* A DNSSEC proof generation and validation implementation can be found at https://git.bitcoin.ninja/index.cgi?p=dnssec-prover;a=summary
+* A lightning-specific name to payment instruction resolver can be found at https://git.bitcoin.ninja/index.cgi?p=lightning-resolver;a=summary
+* Reference implementations for parsing the URI contents can be found in [[bip-0021.mediawiki|BIP 21]].
+
+
+== Footnotes ==
+
+
+
+== Acknowledgements ==
+
+Thanks to Rusty Russell for the concrete address rotation suggestion.
+
+Thanks to the Bitcoin Design Community, and especially Christoph Ono for lots of discussion, analysis, and UX mockups in how human-readable payment instructions should be displayed.
+
+Thanks to Andrew Kaizer for the suggestion to explicitly restrict cache lifetime to the relevant DNS TTLs.
diff --git a/bip-0370.mediawiki b/bip-0370.mediawiki
new file mode 100644
index 0000000000..05d4e50773
--- /dev/null
+++ b/bip-0370.mediawiki
@@ -0,0 +1,500 @@
+
+ BIP: 370
+ Layer: Applications
+ Title: PSBT Version 2
+ Author: Ava Chow
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0370
+ Status: Final
+ Type: Standards Track
+ Created: 2021-01-14
+ License: BSD-2-Clause
+
+
+==Introduction==
+
+===Abstract===
+
+This document proposes a second version of the Partially Signed Bitcoin Transaction format
+described in BIP 174 which allows for inputs and outputs to be added to the PSBT after creation.
+
+===Copyright===
+
+This BIP is licensed under the 2-clause BSD license.
+
+===Motivation===
+
+Partially Signed Bitcoin Transaction Version 0 as described in BIP 174 is unable to have new
+inputs and outputs be added to the transaction. The fixed global unsigned transaction
+cannot be changed which prevents any additional inputs or outputs to be added.
+PSBT Version 2 is intended to rectify this problem.
+
+An additional beneficial side effect is that all information for a given input or output will be
+provided by its or . With Version 0, to retrieve
+all of the information for an input or output, data would need to be found in two locations:
+the / and the global unsigned transaction. PSBT
+Version 2 now moves all related information to one place.
+
+==Specification==
+
+PSBT Version 2 (PSBTv2) only specifies new fields and field inclusion/exclusion requirements.
+
+PSBT_GLOBAL_UNSIGNED_TX must be excluded in PSBTv2.
+PSBT_GLOBAL_VERSION must be included in PSBTv2 and set to version number 2'''What happened to version number 1?'''
+Version number 1 is skipped because PSBT Version 0 has been colloquially referred to as version 1. Originally this BIP was to be
+version 1, but because it has been colloquially referred to as version 2 during its design phase, it was decided to change the
+version number to 2 so that there would not be any confusion.
+
+The new global types for PSBT Version 2 are as follows:
+
+{|
+! Name
+!
+!
+! Description
+!
+! Description
+! Versions Requiring Inclusion
+! Versions Requiring Exclusion
+! Versions Allowing Inclusion
+|-
+| Transaction Version
+| PSBT_GLOBAL_TX_VERSION = 0x02
+| None
+| No key data
+| <32-bit little endian int version>
+| The 32-bit little endian signed integer representing the version number of the transaction being created. Note that this is not the same as the PSBT version number specified by the PSBT_GLOBAL_VERSION field.
+| 2
+| 0
+| 2
+|-
+| Fallback Locktime
+| PSBT_GLOBAL_FALLBACK_LOCKTIME = 0x03
+| None
+| No key data
+| <32-bit little endian uint locktime>
+| The 32-bit little endian unsigned integer representing the transaction locktime to use if no inputs specify a required locktime.
+|
+| 0
+| 2
+|-
+| Input Count
+| PSBT_GLOBAL_INPUT_COUNT = 0x04
+| None
+| No key data
+|
+| Compact size unsigned integer representing the number of inputs in this PSBT.
+| 2
+| 0
+| 2
+|-
+| Output Count
+| PSBT_GLOBAL_OUTPUT_COUNT = 0x05
+| None
+| No key data
+|
+| Compact size unsigned integer representing the number of outputs in this PSBT.
+| 2
+| 0
+| 2
+|-
+| Transaction Modifiable Flags
+| PSBT_GLOBAL_TX_MODIFIABLE = 0x06
+| None
+| No key data
+| <8-bit uint flags>
+| An 8 bit unsigned integer as a bitfield for various transaction modification flags. Bit 0 is the Inputs Modifiable Flag, set to 1 to indicate whether inputs can be added or removed. Bit 1 is the Outputs Modifiable Flag, set to 1 to indicate whether outputs can be added or removed. Bit 2 is the Has SIGHASH_SINGLE flag, set to 1 to indicate whether the transaction has a SIGHASH_SINGLE signature who's input and output pairing must be preserved. Bit 2 essentially indicates that the Constructor must iterate the inputs to determine whether and how to add or remove an input.
+|
+| 0
+| 2
+|}
+
+The new per-input types for PSBT Version 2 are defined as follows:
+
+{|
+! Name
+!
+!
+! Description
+!
+! Description
+! Versions Requiring Inclusion
+! Versions Requiring Exclusion
+! Versions Allowing Inclusion
+|-
+| Previous TXID
+| PSBT_IN_PREVIOUS_TXID = 0x0e
+| None
+| No key data
+| <32 byte txid>
+| 32 byte txid of the previous transaction whose output at PSBT_IN_OUTPUT_INDEX is being spent.
+| 2
+| 0
+| 2
+|-
+| Spent Output Index
+| PSBT_IN_OUTPUT_INDEX = 0x0f
+| None
+| No key data
+| <32-bit little endian uint index>
+| 32 bit little endian integer representing the index of the output being spent in the transaction with the txid of PSBT_IN_PREVIOUS_TXID.
+| 2
+| 0
+| 2
+|-
+| Sequence Number
+| PSBT_IN_SEQUENCE = 0x10
+| None
+| No key data
+| <32-bit little endian uint sequence>
+| The 32 bit unsigned little endian integer for the sequence number of this input. If omitted, the sequence number is assumed to be the final sequence number (0xffffffff).
+|
+| 0
+| 2
+|-
+| Required Time-based Locktime
+| PSBT_IN_REQUIRED_TIME_LOCKTIME = 0x11
+| None
+| No key data
+| <32-bit little endian uint locktime>
+| 32 bit unsigned little endian integer greater than or equal to 500000000 representing the minimum Unix timestamp that this input requires to be set as the transaction's lock time.
+|
+| 0
+| 2
+|-
+| Required Height-based Locktime
+| PSBT_IN_REQUIRED_HEIGHT_LOCKTIME = 0x12
+| None
+| No key data
+| <32-bit uint locktime>
+| 32 bit unsigned little endian integer greater than 0 and less than 500000000 representing the minimum block height that this input requires to be set as the transaction's lock time.
+|
+| 0
+| 2
+|}
+
+The new per-output types for PSBT Version 2 are defined as follows:
+
+{|
+! Name
+!
+!
+! Description
+!
+! Description
+! Versions Requiring Inclusion
+! Versions Requiring Exclusion
+! Versions Allowing Inclusion
+|-
+| Output Amount
+| PSBT_OUT_AMOUNT = 0x03
+| None
+| No key data
+| <64-bit little endian int amount>
+| 64 bit signed little endian integer representing the output's amount in satoshis.
+| 2
+| 0
+| 2
+|-
+| Output Script
+| PSBT_OUT_SCRIPT = 0x04
+| None
+| No key data
+|
+| The script for this output, also known as the scriptPubKey. Must be omitted in PSBTv0. Must be provided in PSBTv2.
+| 2
+| 0
+| 2
+|}
+
+===Determining Lock Time===
+
+The nLockTime field of a transaction is determined by inspecting the PSBT_GLOBAL_FALLBACK_LOCKTIME and each input's PSBT_IN_REQUIRED_TIME_LOCKTIME and PSBT_IN_REQUIRED_HEIGHT_LOCKTIME fields.
+If none of the inputs have a PSBT_IN_REQUIRED_TIME_LOCKTIME and PSBT_IN_REQUIRED_HEIGHT_LOCKTIME, then PSBT_GLOBAL_FALLBACK_LOCKTIME must be used.
+If PSBT_GLOBAL_FALLBACK_LOCKTIME is not provided, then it is assumed to be 0.
+
+If one or more inputs have a PSBT_IN_REQUIRED_TIME_LOCKTIME or PSBT_IN_REQUIRED_HEIGHT_LOCKTIME, then the field chosen is the one which is supported by all of the inputs.
+This can be determined by looking at all of the inputs which specify a locktime in either of those fields, and choosing the field which is present in all of those inputs.
+Inputs not specifying a lock time field can take both types of lock times, as can those that specify both.
+The lock time chosen is then the maximum value of the chosen type of lock time.
+
+If a PSBT has both types of locktimes possible because one or more inputs specify both PSBT_IN_REQUIRED_TIME_LOCKTIME and PSBT_IN_REQUIRED_HEIGHT_LOCKTIME, then locktime determined by looking at the PSBT_IN_REQUIRED_HEIGHT_LOCKTIME fields of the inputs must be chosen.'''Why choose the height based locktime?'''
+In the event of a tie for the locktime type, signers need to be able to know which locktime to use as their signatures will commit to the locktime in the transaction, so choosing the wrong one will result in an invalid transaction.
+Height based locktime is preferred over time based as Bitcoin's unit of time is the block height, so a height makes more sense in the context of Bitcoin.
+
+===Unique Identification===
+
+PSBTv2s can be uniquely identified by constructing an unsigned transaction given the information provided in the PSBT, and computing the transaction ID of that transaction.
+Since PSBT_IN_SEQUENCE can be changed by Updaters and Combiners, the sequence number in this unsigned transaction must be set to 0 (not final, nor the sequence in PSBT_IN_SEQUENCE).
+The lock time in this unsigned transaction must be computed as described previously.
+
+==Roles==
+
+PSBTv2 introduces new roles and modifies some existing roles.
+
+===Creator===
+
+In PSBTv2, the Creator initializes the PSBT with 0 inputs and 0 outputs.
+The PSBT version number is set to 2.
+The Creator should also set PSBT_GLOBAL_FALLBACK_LOCKTIME.
+If the Creator is not also a Constructor and will be giving the PSBT to others to add inputs and outputs, the PSBT_GLOBAL_TX_MODIFIABLE field must be present and the Inputs Modifiable and Outputs Modifiable flags set appropriately; moreover, the transaction version number must be set to at least 2. '''Why does the transaction version number need to be at least 2?''' The transaction version number is part of the validation rules for some features such as OP_CHECKSEQUENCEVERIFY. Since it is backwards compatible, and there are other ways to disable those features (e.g. through sequence numbers), it is easier to require transactions be able to support these features than to try to negotiate the transaction version number.
+If the Creator is a Constructor and no inputs and outputs will be added by other entities, PSBT_GLOBAL_TX_MODIFIABLE may be omitted.
+
+===Constructor===
+
+This Constructor is only present for PSBTv2.
+Once a Creator initializes the PSBT, a constructor will add inputs and outputs.
+Before any input or output may be added, the constructor must check the PSBT_GLOBAL_TX_MODIFIABLE field.
+Inputs may only be added if the Inputs Modifiable flag is True.
+Outputs may only be added if the Outputs Modifiable flag is True.
+
+When an input or output is added, the corresponding PSBT_GLOBAL_INPUT_COUNT or PSBT_GLOBAL_OUTPUT_COUNT must be incremented to reflect the number of inputs and outputs in the PSBT.
+When an input is added, it must have PSBT_IN_PREVIOUS_TXID and PSBT_IN_OUTPUT_INDEX set.
+When an output is added, it must have PSBT_OUT_VALUE and PSBT_OUT_OUTPUT_SCRIPT set.
+If the input has a required timelock, Constructors must set the requisite timelock field.
+If the input has a required time based timelock, then PSBT_IN_REQUIRED_TIME_TIMELOCK must be set.
+If the input has a required height based timelock, then PSBT_IN_REQUIRED_HEIGHT_TIMELOCK must be set.
+If an input has both types of timelocks, then both may be set.
+In some cases, an input that can allow both types, but a particular branch supporting only one type of timelock will be taken, then the type of timelock that will be used can be the only one set.
+
+If an input being added specifies a required time lock, then the Constructor must iterate through all of the existing inputs and ensure that the time lock types are compatible.
+Additionally, if during this iteration, it finds that any inputs have signatures, it must ensure that the newly added input does not change the transaction's locktime.
+If the newly added input has an incompatible time lock, then it must not be added.
+If it changes the transaction's locktime when there are existing signatures, it must not be added.
+
+If the Has SIGHASH_SINGLE flag is True, then the Constructor must iterate through the inputs and find the inputs which have signatures that use SIGHASH_SINGLE.
+The same number of inputs and outputs must be added before those inputs and their corresponding outputs.
+
+A Constructor may choose to declare that no further inputs and outputs can be added to the transaction by setting the appropriate bits in PSBT_GLOBAL_TX_MODIFIABLE to 0 or by removing the field entirely.
+
+A single entity is likely to be both a Creator and Constructor.
+
+===Updater===
+
+For PSBTv2, an Updater can set the sequence number.
+
+===Signer===
+
+For PSBTv2s, a signer must update the PSBT_GLOBAL_TX_MODIFIABLE field after signing inputs so that it accurately reflects the state of the PSBT.
+If the Signer added a signature that does not use SIGHASH_ANYONECANPAY, the Input Modifiable flag must be set to False.
+If the Signer added a signature that does not use SIGHASH_NONE, the Outputs Modifiable flag must be set to False.
+If the Signer added a signature that uses SIGHASH_SINGLE, the Has SIGHASH_SINGLE flag must be set to True.
+
+===Transaction Extractor===
+
+For PSBTv2s, the transaction is constructed using the PSBTv2 fields.
+The lock time for this transaction is determined as described in the Determining Lock Time section.
+The Extractor should produce a fully valid, network serialized transaction if all inputs are complete.
+
+==Backwards Compatibility==
+
+PSBTv2 shares the same generic format as PSBTv0 as defined in BIP 174. Parsers for PSBTv0 should
+be able to deserialize PSBTv2 with only changes to support the new fields.
+
+However PSBTv2 is incompatible with PSBTv0, and vice versa due to the use of the PSBT_GLOBAL_VERSION.
+This incompatibility is intentional so that PSBT_GLOBAL_UNSIGNED_TX could be removed in PSBTv2.
+However it is possible to convert a PSBTv2 to a PSBTv0 by creating an unsigned
+transaction from the PSBTv2 fields.
+
+==Test Vectors==
+
+The following are invalid PSBTs:
+
+* Case: PSBTv0 but with PSBT_GLOBAL_VERSION set to 2.
+** Bytes in Hex:
+
+* Case: 1 input, 2 output updated PSBTv2, with both Inputs Modifiable Flag (bit 0) and Outputs Modifiable Flag (bit 1) of PSBT_GLOBAL_TX_MODIFIABLE set
+** Bytes in Hex:
+
+* Case: 1 input, 2 output updated PSBTv2, with both Inputs Modifiable Flag (bit 0) and Has SIGHASH_SINGLE Flag (bit 2) of PSBT_GLOBAL_TX_MODIFIABLE set
+** Bytes in Hex:
+
+* Case: 1 input, 2 output updated PSBTv2, with both Outputs Modifiable Flag (bit 1) and Has SIGHASH_SINGLE FLag (bit 2) of PSBT_GLOBAL_TX_MODIFIABLE set
+** Bytes in Hex:
+
+The following tests are the timelock determination algorithm.
+
+The timelock for the following PSBTs should be computed to be 0:
+
+* Case: No locktimes specified
+** Bytes in Hex:
+
+The timelock for the following PSBTs should be computed to be 10000:
+
+* Case: Input 1 has PSBT_IN_REQUIRED_HEIGHT_LOCKTIME of 10000, Input 2 has no locktime fields
+** Bytes in Hex:
+
+* Case: Input 1 has PSBT_IN_REQUIRED_HEIGHT_LOCKTIME of 10000, Input 2 has PSBT_IN_REQUIRED_HEIGHT_LOCKTIME of 9000 and PSBT_IN_REQUIRED_TIME_LOCKTIME of 1657048460
+** Bytes in Hex:
+
+* Case: Input 1 has PSBT_IN_REQUIRED_HEIGHT_LOCKTIME of 10000 and PSBT_IN_REQUIRED_TIME_LOCKTIME of 1657048459, Input 2 has PSBT_IN_REQUIRED_HEIGHT_LOCKTIME of 9000 and PSBT_IN_REQUIRED_TIME_LOCKTIME of 1657048460
+** Bytes in Hex:
+
+The timelock for the following PSBTs should be computed to be 1657048460:
+
+* Case: Input 1 has PSBT_IN_REQUIRED_TIME_LOCKTIME of 1657048459, Input 2 has PSBT_IN_REQUIRED_HEIGHT_LOCKTIME of 9000 and PSBT_IN_REQUIRED_TIME_LOCKTIME of 1657048460
+** Bytes in Hex:
+
+* Case: Input 1 has PSBT_IN_REQUIRED_HEIGHT_LOCKTIME of 10000 and PSBT_IN_REQUIRED_TIME_LOCKTIME of 1657048459, Input 2 has PSBT_IN_REQUIRED_TIME_LOCKTIME of 1657048460
+** Bytes in Hex:
+
+The timelock for the following PSBTs cannot be computed:
+
+* Case: Input 1 has PSBT_IN_REQUIRED_HEIGHT_LOCKTIME of 10000, Input 2 has PSBT_IN_REQUIRED_TIME_LOCKTIME of 1657048460
+** Bytes in Hex:
+
+==Rationale==
+
+
+
+==Reference implementation==
+
+The reference implementation of the PSBT format is available in [https://github.com/bitcoin/bitcoin/pull/21283 Bitcoin Core PR 21283].
diff --git a/bip-0371.mediawiki b/bip-0371.mediawiki
new file mode 100644
index 0000000000..92275698a4
--- /dev/null
+++ b/bip-0371.mediawiki
@@ -0,0 +1,250 @@
+
+ BIP: 371
+ Layer: Applications
+ Title: Taproot Fields for PSBT
+ Author: Ava Chow
+ Comments-Summary: No comments yet.
+ Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0371
+ Status: Final
+ Type: Standards Track
+ Created: 2021-06-21
+ License: BSD-2-Clause
+
+
+==Introduction==
+
+===Abstract===
+
+This document proposes additional fields for BIP 174 PSBTv0 and BIP 370 PSBTv2 that allow for
+BIP 340/341/342 Taproot data to be included in a PSBT of any version. These will be fields for
+signatures and scripts that are relevant to the creation of Taproot inputs.
+
+===Copyright===
+
+This BIP is licensed under the 2-clause BSD license.
+
+===Motivation===
+
+BIPs 340, 341, and 342 specify Taproot which provides a wholly new way to create and spend Bitcoin outputs.
+The existing PSBT fields are unable to support Taproot due to the new signature algorithm and the method
+by which scripts are embedded inside of a Taproot output. Therefore new fields must be defined to allow
+PSBTs to carry the information necessary for signing Taproot inputs.
+
+==Specification==
+
+The new per-input types are defined as follows:
+
+{|
+! Name
+!
+!
+! Description
+!
+! Description
+! Versions Requiring Inclusion
+! Versions Requiring Exclusion
+! Versions Allowing Inclusion
+|-
+| Taproot Key Spend Signature
+| PSBT_IN_TAP_KEY_SIG = 0x13
+| None
+| No key data '''Why is there no key data for PSBT_IN_TAP_KEY_SIG'''The signature in a key path spend corresponds directly with the pubkey provided in the output script. Thus it is not necessary to provide any metadata that attaches the key path spend signature to a particular pubkey.
+| <64 or 65 byte signature>
+| The 64 or 65 byte Schnorr signature for key path spending a Taproot output. Finalizers should remove this field after PSBT_IN_FINAL_SCRIPTWITNESS is constructed.
+|
+|
+| 0, 2
+|-
+| Taproot Script Spend Signature
+| PSBT_IN_TAP_SCRIPT_SIG = 0x14
+|
+| A 32 byte X-only public key involved in a leaf script concatenated with the 32 byte hash of the leaf it is part of.
+| <64 or 65 byte signature>
+| The 64 or 65 byte Schnorr signature for this pubkey and leaf combination. Finalizers should remove this field after PSBT_IN_FINAL_SCRIPTWITNESS is constructed.
+|
+|
+| 0, 2
+|-
+| Taproot Leaf Script
+| PSBT_IN_TAP_LEAF_SCRIPT = 0x15
+|
+| The control block for this leaf as specified in BIP 341. The control block contains the merkle tree path to this leaf.
+| <8-bit uint leaf version>
+| The script for this leaf as would be provided in the witness stack followed by the single byte leaf version. Note that the leaves included in this field should be those that the signers of this input are expected to be able to sign for. Finalizers should remove this field after PSBT_IN_FINAL_SCRIPTWITNESS is constructed.
+|
+|
+| 0, 2
+|-
+| Taproot Key BIP 32 Derivation Path
+| PSBT_IN_TAP_BIP32_DERIVATION = 0x16
+| <32 byte xonlypubkey>
+| A 32 byte X-only public key involved in this input. It may be the output key, the internal key, or a key present in a leaf script.
+| <32 byte leaf hash>* <4 byte fingerprint> <32-bit little endian uint path element>*
+| A compact size unsigned integer representing the number of leaf hashes, followed by a list of leaf hashes, followed by the 4 byte master key fingerprint concatenated with the derivation path of the public key. The derivation path is represented as 32-bit little endian unsigned integer indexes concatenated with each other. Public keys are those needed to spend this output. The leaf hashes are of the leaves which involve this public key. The internal key does not have leaf hashes, so can be indicated with a hashes len of 0. Finalizers should remove this field after PSBT_IN_FINAL_SCRIPTWITNESS is constructed.
+|
+|
+| 0, 2
+|-
+| Taproot Internal Key
+| PSBT_IN_TAP_INTERNAL_KEY = 0x17
+| None
+| No key data
+| <32 byte xonlypubkey>
+| The X-only pubkey used as the internal key in this output.'''Why is the internal key provided?'''The internal key is not necessarily the same key as in the Taproot output script. BIP 341 recommends tweaking the key with the hash of itself. It may be necessary for signers to know what the internal key actually is so that they are able to determine whether an input can be signed by it. Finalizers should remove this field after PSBT_IN_FINAL_SCRIPTWITNESS is constructed.
+|
+|
+| 0, 2
+|-
+| Taproot Merkle Root
+| PSBT_IN_TAP_MERKLE_ROOT = 0x18
+| None
+| No key data
+| <32-byte hash>
+| The 32 byte Merkle root hash. Finalizers should remove this field after PSBT_IN_FINAL_SCRIPTWITNESS is constructed.
+|
+|
+| 0, 2
+|}
+
+The new per-output types are defined as follows:
+
+{|
+! Name
+!
+!
+! Description
+!
+! Description
+! Versions Requiring Inclusion
+! Versions Requiring Exclusion
+! Versions Allowing Inclusion
+|-
+| Taproot Internal Key
+| PSBT_OUT_TAP_INTERNAL_KEY = 0x05
+| None
+| No key data
+| <32 byte xonlypubkey>
+| The X-only pubkey used as the internal key in this output.
+|
+|
+| 0, 2
+|-
+| Taproot Tree
+| PSBT_OUT_TAP_TREE = 0x06
+| None
+| No key data
+| {<8-bit uint depth> <8-bit uint leaf version> }*
+| One or more tuples representing the depth, leaf version, and script for a leaf in the Taproot tree, allowing the entire tree to be reconstructed. The tuples must be in depth first search order so that the tree is correctly reconstructed. Each tuple is an 8-bit unsigned integer representing the depth in the Taproot tree for this script, an 8-bit unsigned integer representing the leaf version, the length of the script as a compact size unsigned integer, and the script itself.
+|
+|
+| 0, 2
+|-
+| Taproot Key BIP 32 Derivation Path
+| PSBT_OUT_TAP_BIP32_DERIVATION = 0x07
+| <32 byte xonlypubkey>
+| A 32 byte X-only public key involved in this output. It may be the output key, the internal key, or a key present in a leaf script.
+| <32 byte leaf hash>* <4 byte fingerprint> <32-bit little endian uint path element>*
+| A compact size unsigned integer representing the number of leaf hashes, followed by a list of leaf hashes, followed by the 4 byte master key fingerprint concatenated with the derivation path of the public key. The derivation path is represented as 32-bit little endian unsigned integer indexes concatenated with each other. Public keys are those needed to spend this output. The leaf hashes are of the leaves which involve this public key. The internal key does not have leaf hashes, so can be indicated with a hashes len of 0. Finalizers should remove this field after PSBT_IN_FINAL_SCRIPTWITNESS is constructed.
+|
+|
+| 0, 2
+|}
+
+===UTXO Types===
+
+BIP 174 recommends using PSBT_IN_NON_WITNESS_UTXO for all inputs because of potential attacks involving
+an updater lying about the amounts in an output. Because a Taproot signature will commit to all of the amounts
+and output scripts spent by the inputs of the transaction, such attacks are prevented as any such lying would
+result in an invalid signature. Thus Taproot inputs can use just PSBT_IN_WITNESS_UTXO.
+
+==Compatibility==
+
+These are simply new fields added to the existing PSBT format. Because PSBT is designed to be extensible, old
+software will ignore the new fields.
+
+==Test Vectors==
+
+The following are invalid PSBTs:
+
+* Case: PSBT With PSBT_IN_TAP_INTERNAL_KEY key that is too long (incorrectly serialized as compressed DER)
+** Bytes in Hex:
+
+* Case: PSBT with one P2TR script path only input with dummy internal key, scripts, derivation paths for keys in the scripts, and merkle root
+** Bytes in Hex:
+
+* Case: PSBT with one P2TR script path only input with dummy internal key, scripts, script key derivation paths, merkle root, and script path signatures
+** Bytes in Hex:
+
+==Introduction==
+
+===Abstract===
+
+This document proposes additional fields for BIP 174 PSBTv0 and BIP 370 PSBTv2
+that allow for pay-to-contract key tweaking data to be included in a PSBT
+of any version. These will represent an extra-transaction information required
+for the signer to produce valid signatures spending previous outputs.
+
+===Copyright===
+
+This BIP is licensed under the 2-clause BSD license.
+
+===Background===
+
+Key tweaking is a procedure for creating a cryptographic commitment to some
+message using elliptic curve properties. The procedure uses the discrete log
+problem (DLP) to commit to an extra-transaction message. This is done by adding
+to a public key (for which the output owner knows the corresponding private key)
+a hash of the message multiplied on the generator point G of the elliptic curve.
+This produces a tweaked public key, containing the commitment. Later, in order
+to spend an output containing P2C commitment, the same commitment should be
+added to the corresponding private key.
+
+This type of commitment was originally proposed as a part of the pay to contract
+concept by Ilja Gerhardt and Timo Hanke in [1] and later used by Eternity Wall
+[2] for the same purpose. Since that time multiple different protocols for P2C
+has been developed, including OpenTimeStamps [3], Elements sidechain P2C tweaks
+[4] and LNPBP-1 [5], used in for constructing Peter Todd's single-use-seals [6]
+in client-side-validation protocols like RGB.
+
+===Motivation===
+
+P2C outputs can be detected onchain and spent only if the output owner
+not just knows the corresponding original private key, but also is aware about
+P2C tweak applied to the public key. In order to produce a valid signature, the
+same tweak value must be added (modulo group order) to the original private key
+by a signer device. This represents a challenge for external signers, which may
+not have any information about such commitment. This proposal addresses this
+issue by adding relevant fields to the PSBT input information.
+
+The proposal abstracts details of specific P2C protocols and provides universal
+method for spending previous outputs containing P2C tweaks, applied to the public
+key contained within any standard form of the scriptPubkey, including
+bare scripts and P2PK, P2PKH, P2SH, witness v0 P2WPKH, P2WSH, nested witness v0
+P2WPKH-P2SH, P2WSH-P2SH and witness v1 P2TR outputs.
+
+
+==Design==
+
+P2C-tweaked public keys are already exposed in the
+PSBT_IN_REDEEM_SCRIPT, PSBT_IN_WITNESS_SCRIPT,
+PSBT_IN_TAP_INTERNAL_KEY and PSBT_IN_TAP_LEAF_SCRIPT fields;
+the only information signer is needed to recognize which keys it should sign
+with is from which of the original keys they were generated. This is achieved by
+introducing new `PSBT_IN_P2C_TWEAK` field which has the original key as a field
+key and the tweak as a field value. The signer will recognize the keys which are
+available to it, apply the tweak to them and see in which scripts it was used --
+and use this information to apply tweaks for the corresponding private keys and
+produce valid signatures.
+
+
+==Specification==
+
+The new per-input type is defined as follows:
+
+{|
+! Name
+!
+!
+! Description
+!
+! Description
+! Versions Requiring Inclusion
+! Versions Requiring Exclusion
+! Versions Allowing Inclusion
+|-
+| P2C Key Tweak
+| PSBT_IN_P2C_TWEAK = 0x19
+|
+| 33 bytes of compact public key serialization specifying to which of keys the
+P2C tweak may be applied (i.e. this MUST be a value of a public key before the
+tweak is applied). BIP-340 keys are serialized by appending `02`
+byte.'''Why compressed public keys are not distinguished from BIP-340
+public keys'''We follow the logic of BIP32 key derivation which does not
+performs that distinguishment. The type of the key is defined by the input type,
+and adding additional PSBT field type will just create the need for handling
+errors when the input type does not match the provided key type.
+|
+| The 32 byte value which MUST be added to a private key to produce correct
+ECDSA and/or Schnorr signature ("key tweak"). Signers SHOULD remove this field
+after PSBT_IN_PARTIAL_SIG is constructed.
+|
+|
+| 0, 2
+| BIP-P2C
+|}
+
+
+==Security considerations==
+
+The scope of this proposal is deliberately kept narrow; it addresses
+only spending of transaction outputs containing P2C tweaks - and does not
+addresses construction of a new P2C commitments or transactions containing them
+in their outputs.'''Why only spending of P2C tweaked outputs is covered'''
+P2C tweaks commit to external data, some of which may represent certain value
+(like in some sidechains, single-use-seal applications like RGB etc). Creation
+of such outputs much allow hardware devices to understand the structure of such
+extra-transaction data, which may be in different formats and constantly
+involve. Thus, this should be addresses with a separate standards (or be a
+vendor-based). The current proposal only touches the question of spending an
+output which contained previously created P2C commitment, which does not creates
+a new commitment and does not provides that kind of risk of extra-blockchain
+value loses.
+
+
+==Rationale==
+
+
+
+
+==Compatibility==
+
+The proposal is compatible with the existing consensus rules and does not
+require any of their modifications.
+
+The proposed P2C PSBT fields provides sufficient information for creating a
+valid signatures for spendings of the following output types containing tweaked
+public keys:
+- bare scripts,
+- P2PK,
+- P2PKH,
+- P2SH,
+- witness v0 P2WPKH and P2WSH,
+- nested witness v0 P2WPKH-P2SH and P2WSH-P2SH,
+
+Post-0 witness versions, including taproot outputs and future witness versions,
+may not be supported or covered by this BIP and may require addition of new
+fields to the PSBT inputs.
+
+
+==Reference implementation==
+
+WIP
+
+
+==Acknowledgements==
+
+Author is grateful to Andrew Poelstra, who provided an initial set of ideas
+and information on his previous work on the topic basing on which this standard
+was designed.
+
+
+==Test vectors==
+
+TBD
+
+
+==References==
+
+[1] Ilja Gerhardt, Timo Hanke. Homomorphic Payment Addresses and the
+ Pay-to-Contract Protocol. arXiv:1212.3257 \[cs.CR\]
+
+[2] Eternity Wall's "sign-to-contract" article.
+
+[3] Peter Todd. OpenTimestamps: Scalable, Trust-Minimized, Distributed
+ Timestamping with Bitcoin.
+
+[4] Adam Back, Matt Corallo, Luke Dashjr, et al. Enabling Blockchain
+ Innovations with Pegged Sidechains (commit5620e43). Appenxix A.
+ ;.
+[5] Maxim Orlovsky, Rene Pickhardt, Federico Tenga, et al. Key
+ tweaking: collision- resistant elliptic curve-based commitments.
+ LNPBP-1 Standard.
+
+[6] Peter Todd. Single-use-seals. LNPBP-8 Standard.
+
diff --git a/bip-0373.mediawiki b/bip-0373.mediawiki
new file mode 100644
index 0000000000..006c69bad6
--- /dev/null
+++ b/bip-0373.mediawiki
@@ -0,0 +1,216 @@
+
+
+==Introduction==
+
+===Abstract===
+
+This document proposes additional fields for BIP 174 PSBTv0 and BIP 370 PSBTv2 that allow for BIP
+327 MuSig2 Multi-Signature data to be included in a PSBT of any version. These will be fields for
+the participants' keys, the public nonces, and the partial signatures produced with MuSig2.
+
+===Copyright===
+
+This BIP is licensed under the Creative Commons CC0 1.0 Universal license.
+
+===Motivation===
+
+BIP 327 specifies a way to create BIP 340 compatible public keys and signatures using the MuSig2
+Multi-Signature scheme. The existing PSBT fields are unable to support MuSig2 as it introduces new
+concepts and additional rounds of communication. Therefore new fields must be defined to allow PSBTs
+to carry the information necessary to produce a valid signature with MuSig2.
+
+==Specification==
+
+The new per-input types are defined as follows:
+
+{|
+! Name
+!
+!
+!
+! Versions Requiring Inclusion
+! Versions Requiring Exclusion
+! Versions Allowing Inclusion
+|-
+| rowspan="2"|MuSig2 Participant Public Keys
+| rowspan="2"|PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS = 0x1a
+| <33 byte aggregate pubkey (compressed)>
+| <33 byte participant pubkey (compressed)>*
+| rowspan="2"|
+| rowspan="2"|
+| rowspan="2"| 0, 2
+|-
+| The MuSig2 aggregate public key (compressed) '''Why the compressed aggregate public key instead of x-only?'''
+BIP 32 public keys can be derived from a BIP 327 MuSig2 aggregate public key (see: [[bip-0328.mediawiki|BIP 328]]).
+But since BIP 32 requires public keys to include their evenness byte, BIP 327 MuSig2 aggregate public keys must
+include their evenness byte as well. Furthermore, PSBT_IN_TAP_BIP32_DERIVATION fields include fingerprints to identify
+master keys, and these fingerprints require the y-coordinate of the public key, so x-only serialization can't be used.
+By including the aggregate key as a full public key, signers that are unaware of the MuSig2 outside of the PSBT will
+still be able to identify which keys are derived from the aggregate key by computing and then comparing the
+fingerprints. This is necessary for the signer to apply the correct tweaks to their partial signature. from the
+KeyAgg algorithm. This key may or may not appear (as x-only) in the Taproot output key, the internal key, or
+in a script. It may instead be a parent public key from which the Taproot output key, internal key, or keys in a script
+were derived.
+| A list of the compressed public keys of the participants in the MuSig2 aggregate key in the order
+required for aggregation. If sorting was done, then the keys must be in the sorted order.
+|-
+| rowspan="2"|MuSig2 Public Nonce
+| rowspan="2"|PSBT_IN_MUSIG2_PUB_NONCE = 0x1b
+| <33 byte participant pubkey (compressed)> <33 byte aggregate pubkey (compressed)> <32 byte hash or omitted>
+| <66 byte public nonce>
+| rowspan="2"|
+| rowspan="2"|
+| rowspan="2"| 0, 2
+|-
+| The compressed public key of the participant providing this nonce, followed by the compressed aggregate public
+key the participant is providing the nonce for, followed by the BIP 341 tapleaf hash of
+the Taproot leaf script that will be signed. If the aggregate key is the Taproot internal key or the
+Taproot output key, then the tapleaf hash must be omitted. The compressed participant public key must be
+the Taproot output key or found in a script. It is not the internal key nor the aggregate public key that
+it was derived from, if it was derived from an aggregate key.
+| The public nonce produced by the NonceGen algorithm.
+|-
+| rowspan="2"|MuSig2 Participant Partial Signature
+| rowspan="2"|PSBT_IN_MUSIG2_PARTIAL_SIG = 0x1c
+| <33 byte participant pubkey (compressed)> <33 byte aggregate pubkey (compressed)> <32 byte hash or omitted>
+| <32 byte partial signature>
+| rowspan="2"|
+| rowspan="2"|
+| rowspan="2"| 0, 2
+|-
+| The compressed public key of the participant providing this partial signature, followed by the
+compressed public key the participant is providing the signature for, followed by the BIP 341 tapleaf hash
+of the Taproot leaf script that will be signed. If the aggregate key is the Taproot internal key or
+the Taproot output key, then the tapleaf hash must be omitted. Note that the compressed participant public key must be
+the Taproot output key or found in a script. It is not the internal key nor the aggregate public key that
+it was derived from, if it was derived from an aggregate key.
+| The partial signature produced by the Sign algorithm.
+|}
+
+The new per-output types are defined as follows:
+
+{|
+! Name
+!
+!
+!
+! Versions Requiring Inclusion
+! Versions Requiring Exclusion
+! Versions Allowing Inclusion
+|-
+| rowspan="2"|MuSig2 Participant Public Keys
+| rowspan="2"|PSBT_OUT_MUSIG2_PARTICIPANT_PUBKEYS = 0x08
+| <33 byte aggregate pubkey (compressed)>
+| <33 byte participant pubkey (compressed)>*
+| rowspan="2"|
+| rowspan="2"|
+| rowspan="2"|0, 2
+|-
+| The MuSig2 compressed aggregate public key from the KeyAgg algorithm. This key may or may not
+appear (as x-only) in the Taproot output key, the internal key, or in a script. It may instead be a parent
+public key from which the Taproot output key, internal key, or keys in a script were derived.
+| A list of the compressed public keys of the participants in the MuSig2 aggregate key in the order
+required for aggregation. If sorting was done, then the keys must be in the sorted order.
+|}
+
+==Roles==
+
+===Updater===
+
+When an updater observes a Taproot output which involves a MuSig2 aggregate public key that it is
+aware of, it can add a PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS field containing the public keys
+of the participants. This aggregate public key may be directly in the script, the Taproot internal
+key, the Taproot output key, or a public key from which the key in the script was derived from.
+
+An aggregate public key that appears directly in the script or internal key may be from the result
+of deriving child pubkeys from participant xpubs. If the updater has this derivation information, it
+should also add PSBT_IN_TAP_BIP32_DERIVATION for each participant public key.
+
+If the public key found was derived from an aggregate public key, then all MuSig2 PSBT fields for
+that public key should contain the aggregate public key rather than the found pubkey itself. The
+updater should also add PSBT_IN_TAP_BIP32_DERIVATION that contains the derivation path used
+to derive the found pubkey from the aggregate pubkey.
+Derivation from the aggregate pubkey can be assumed to follow [[bip-0328.mediawiki|BIP 328]]
+if there is no PSBT_IN_GLOBAL_XPUB that specifies the synthetic xpub for the aggregate
+public key.
+
+Updaters should add PSBT_OUT_MUSIG2_PARTICIPANT_PUBKEYS and
+PSBT_OUT_TAP_BIP32_DERIVATION similarly to inputs to aid in change detection.
+
+===Signer===
+
+To determine whether a signer is a participant in the MuSig2 aggregate key, the signer should first
+look at all PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS and see if any key which it knows the
+private key for appears as a participant in any aggregate pubkey. Signers should also check whether
+any of the keys in PSBT_IN_TAP_BIP32_DERIVATION belong to it, and if any of those keys
+appear in as a participant in PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS.
+
+For each aggregate public key that the signer is a participant of that it wants
+to produce a signature for, if the signer does not find an existing
+PSBT_IN_MUSIG2_PUB_NONCE field for its key, then it should add one using
+the NonceGen algorithm (or one of its variations) to produce a public
+nonce that is added in a PSBT_IN_MUSIG2_PUB_NONCE field. However
+signers must keep in mind that '''improper nonce usage can compromise private
+keys.''' Please see BIP 327 for best practices on nonce generation and usage.
+
+Once all signers have added their PSBT_IN_MUSIG2_PUB_NONCE fields, each signer will perform
+the NonceAgg algorithm followed by the Sign algorithm in order to produce the
+partial signature for their key. The result will be added to the PSBT in a
+PSBT_IN_MUSIG2_PARTIAL_SIG field.
+
+Signers must remember to apply any relevant tweaks such as a tweak that is the result of performing
+BIP 32 unhardened derivation with the aggregate public key as the parent key.
+
+If all other signers have provided a PSBT_IN_MUSIG2_PARTIAL_SIG, then the final signer may
+perform the PartialSigAgg algorithm and produce a BIP 340 compatible signature that can be
+placed into a PSBT_IN_TAP_KEY_SIG or a PSBT_IN_TAP_SCRIPT_SIG.
+
+===Finalizer===
+
+A finalizer may perform the same PartialSigAgg step as the final signer if it has not
+already been done.
+
+Otherwise, the resulting signature is a BIP 340 compatible signature and finalizers should treat it
+as such.
+
+==Backwards Compatibility==
+
+These are simply new fields added to the existing PSBT format. Because PSBT is designed to be
+extensible, old software will ignore the new fields.
+
+Reusing PSBT_IN_TAP_BIP32_DERIVATION to provide derivation paths for participant public
+keys may cause software unaware of MuSig2 to produce a signature for that public key. This is still
+safe. If that public key does not directly appear in the leaf script that was signed, then the
+signature produced will not be useful and so cannot be replayed. If the public key does directly
+appear in the leaf script, then the signer will have validated the script as if it did not involve a
+MuSig2 and will have found it acceptable in order for it to have produced a signature. In either
+case, producing a signature does not give rise to the possibility of losing funds.
+
+==Test Vectors==
+
+TBD
+
+==Rationale==
+
+
+
+==Reference implementation==
+
+The reference implementation of the PSBT format is available at TBD.
+
+==Acknowledgements==
+
+Thanks to Sanket Kanjalkar whose notes on this topic formed the initial basis of this BIP. Also
+thanks to Pieter Wuille, Jonas Nick, Tim Ruffing, Marko Bencun, Salvatore Ingala, and all others who
+have participated in discussions about these fields.
diff --git a/bip-0374.mediawiki b/bip-0374.mediawiki
new file mode 100644
index 0000000000..8106f9adc7
--- /dev/null
+++ b/bip-0374.mediawiki
@@ -0,0 +1,128 @@
+
+
+== Introduction ==
+
+=== Abstract ===
+
+This document proposes a standard for 64-byte zero-knowledge ''discrete logarithm equality proofs'' (DLEQ proofs) over an elliptic curve. For given elliptic curve points ''A'', ''B'', ''C'', ''G'', and a scalar ''a'' known only to the prover where ''A = a⋅G'' and ''C = a⋅B'', the prover proves knowledge of ''a'' without revealing anything about ''a''. This can, for instance, be useful in ECDH: if ''A'' and ''B'' are ECDH public keys, and ''C'' is their ECDH shared secret computed as ''C = a⋅B'', the proof establishes that the same secret key ''a'' is used for generating both ''A'' and ''C'' without revealing ''a''.
+
+=== Copyright ===
+
+This document is licensed under the 2-clause BSD license.
+
+=== Motivation ===
+
+[https://github.com/bitcoin/bips/blob/master/bip-0352.mediawiki#specification BIP352] requires senders to compute output scripts using ECDH shared secrets from the same secret keys used to sign the inputs. Generating an incorrect signature will produce an invalid transaction that will be rejected by consensus. An incorrectly generated output script can still be consensus-valid, meaning funds may be lost if it gets broadcast.
+By producing a DLEQ proof for the generated ECDH shared secrets, the signing entity can prove to other entities that the output scripts have been generated correctly without revealing the private keys.
+
+== Specification ==
+
+All conventions and notations are used as defined in [https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki#user-content-Notation BIP327].
+
+=== Description ===
+
+The basic proof generation uses a random scalar ''k'', the secret ''a'', and the point being proven ''C = a⋅B''.
+
+* Let ''R1 = k⋅G''.
+* Let ''R2 = k⋅B''.
+* Let ''e = hash(R1 || R2)''.
+* Let ''s = (k + e⋅a)''.
+
+Providing only ''C'', ''e'' and ''s'' as a proof does not reveal ''a'' or ''k''.
+
+Verifying the proof involves recreating ''R1'' and ''R2'' with only ''e'' and ''s'' as follows:
+
+* Let ''R1 = s⋅G - e⋅A''.
+* Let ''R2 = s⋅B - e⋅C''.
+
+This can be verified by substituting ''s = (k + e⋅a)'':
+
+* ''s⋅G - e⋅A = (k + e⋅a)⋅G - e⋅A = k⋅G + e⋅(a⋅G) - e⋅A = k⋅G + e⋅A - e⋅A = k⋅G''.
+* ''s⋅B - e⋅C = (k + e⋅a)⋅B - e⋅C = k⋅B + e⋅(a⋅B) - e⋅C = k⋅B + e⋅C - e⋅C = k⋅B''.
+
+Thus verifying ''e = hash(R1 || R2)'' proves the discrete logarithm equivalency of ''A'' and ''C''.
+
+=== DLEQ Proof Generation ===
+
+The following generates a proof that the result of ''a⋅B'' and the result of ''a⋅G'' are both generated from the same scalar ''a'' without having to reveal ''a''.
+
+Input:
+* The secret key ''a'': a 256-bit unsigned integer
+* The public key ''B'': a point on the curve
+* Auxiliary random data ''r'': a 32-byte array ''' Why include auxiliary random data?''' The auxiliary random data should be set to fresh randomness for each proof. The same rationale and recommendations from [https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#default-signing BIP340] should be applied.
+* The generator point ''G'': a point on the curve ''' Why include the generator point G as an input?''' While all other BIPs have used the generator point from secp256k1, passing it as an input here lets this algorithm be used for other curves.
+* An optional message ''m'': a 32-byte array ''' Why include a message as an input?''' This could be useful for protocols that want to authorize on a compound statement, not just knowledge of a scalar. This allows the protocol to combine knowledge of the scalar and the statement.
+
+The algorithm ''GenerateProof(a, B, r, G, m)'' is defined as:
+* Fail if ''a = 0'' or ''a ≥ n''.
+* Fail if ''is_infinite(B)''.
+* Let ''A = a⋅G''.
+* Let ''C = a⋅B''.
+* Let ''t'' be the byte-wise xor of ''bytes(32, a)'' and ''hashBIP0374/aux(r)''.
+* Let ''rand = hashBIP0374/nonce(t || cbytes(A) || cbytes(C))''.
+* Let ''k = int(rand) mod n''.
+* Fail if ''k = 0''.
+* Let ''R1 = k⋅G''.
+* Let ''R2 = k⋅B''.
+* Let ''m' = m if m is provided, otherwise an empty byte array''.
+* Let ''e = int(hashBIP0374/challenge(cbytes(A) || cbytes(B) || cbytes(C) || cbytes(G) || cbytes(R1) || cbytes(R2) || m'))''.
+* Let ''s = (k + e⋅a) mod n''.
+* Let ''proof = bytes(32, e) || bytes(32, s)''.
+* If ''VerifyProof(A, B, C, proof)'' (see below) returns failure, abort.
+* Return the proof ''proof''.
+
+=== DLEQ Proof Verification ===
+
+The following verifies the proof generated in the previous section. If the following algorithm succeeds, the points ''A'' and ''C'' were both generated from the same scalar. The former from multiplying by ''G'', and the latter from multiplying by ''B''.
+
+Input:
+* The public key of the secret key used in the proof generation ''A'': a point on the curve
+* The public key used in the proof generation ''B'': a point on the curve
+* The result of multiplying the secret and public keys used in the proof generation ''C'': a point on the curve
+* A proof ''proof'': a 64-byte array
+* The generator point used in the proof generation ''G'': a point on the curve ''' Why include the generator point G as an input?''' While all other BIPs have used the generator point from Secp256k1, passing it as an input here lets this algorithm be used for other curves.
+* An optional message ''m'': a 32-byte array ''' Why include a message as an input?''' This could be useful for protocols that want to authorize on a compound statement, not just knowledge of a scalar. This allows the protocol to combine knowledge of the scalar and the statement.
+
+The algorithm ''VerifyProof(A, B, C, proof, G, m)'' is defined as:
+* Fail if any of ''is_infinite(A)'', ''is_infinite(B)'', ''is_infinite(C)'', ''is_infinite(G)''
+* Let ''e = int(proof[0:32])''.
+* Let ''s = int(proof[32:64])''; fail if ''s ≥ n''.
+* Let ''R1 = s⋅G - e⋅A''.
+* Fail if ''is_infinite(R1)''.
+* Let ''R2 = s⋅B - e⋅C''.
+* Fail if ''is_infinite(R2)''.
+* Let ''m' = m if m is provided, otherwise an empty byte array''.
+* Fail if ''e ≠ int(hashBIP0374/challenge(cbytes(A) || cbytes(B) || cbytes(C) || cbytes(G) || cbytes(R1) || cbytes(R2) || m'))''.
+* Return success iff no failure occurred before reaching this point.
+
+==Backwards Compatibility==
+
+This proposal is compatible with all older clients.
+
+== Test Vectors and Reference Code ==
+
+A reference python implementation is included [https://github.com/bitcoin/bips/blob/master/bip-0374/reference.py here].
+Test vectors can be generated by running ./bip-0374/gen_test_vectors.py which will produce a CSV file of random test vectors for both generating and verifying proofs. These can be run against the reference implementation with ./bip-0374/run_test_vectors.py.
+
+== Footnotes ==
+
+
+
+== Acknowledgements ==
+
+Thanks to josibake, Tim Ruffing, benma, stratospher, waxwing, Yuval Kogman and all others who
+participated in discussions on this topic.
diff --git a/bip-0374/gen_test_vectors.py b/bip-0374/gen_test_vectors.py
new file mode 100755
index 0000000000..aaa090a453
--- /dev/null
+++ b/bip-0374/gen_test_vectors.py
@@ -0,0 +1,126 @@
+#!/usr/bin/env python3
+"""Generate the BIP-DLEQ test vectors (limited to secp256k1 generator right now)."""
+import csv
+import os
+import sys
+from reference import (
+ TaggedHash,
+ dleq_generate_proof,
+ dleq_verify_proof,
+)
+from secp256k1 import G as GENERATOR, GE
+
+
+NUM_SUCCESS_TEST_VECTORS = 5
+DLEQ_TAG_TESTVECTORS_RNG = "BIP0374/testvectors_rng"
+
+FILENAME_GENERATE_PROOF_TEST = os.path.join(sys.path[0], 'test_vectors_generate_proof.csv')
+FILENAME_VERIFY_PROOF_TEST = os.path.join(sys.path[0], 'test_vectors_verify_proof.csv')
+
+
+def random_scalar_int(vector_i, purpose):
+ rng_out = TaggedHash(DLEQ_TAG_TESTVECTORS_RNG, purpose.encode() + vector_i.to_bytes(4, 'little'))
+ return int.from_bytes(rng_out, 'big') % GE.ORDER
+
+
+def random_bytes(vector_i, purpose):
+ rng_out = TaggedHash(DLEQ_TAG_TESTVECTORS_RNG, purpose.encode() + vector_i.to_bytes(4, 'little'))
+ return rng_out
+
+
+def create_test_vector_data(vector_i):
+ g = random_scalar_int(vector_i, "scalar_g")
+ assert g < GE.ORDER
+ assert g > 0
+ G = g * GENERATOR
+ assert not G.infinity
+ a = random_scalar_int(vector_i, "scalar_a")
+ A = a * G
+ b = random_scalar_int(vector_i, "scalar_b")
+ B = b * G
+ C = a * B # shared secret
+ assert C.to_bytes_compressed() == (b * A).to_bytes_compressed()
+ auxrand = random_bytes(vector_i, "auxrand")
+ msg = random_bytes(vector_i, "message")
+ proof = dleq_generate_proof(a, B, auxrand, G=G, m=msg)
+ return (G, a, A, b, B, C, auxrand, msg, proof)
+
+TEST_VECTOR_DATA = [create_test_vector_data(i) for i in range(NUM_SUCCESS_TEST_VECTORS)]
+
+
+def gen_all_generate_proof_vectors(f):
+ writer = csv.writer(f)
+ writer.writerow(("index", "point_G", "scalar_a", "point_B", "auxrand_r", "message", "result_proof", "comment"))
+
+ # success cases with random values
+ idx = 0
+ for i in range(NUM_SUCCESS_TEST_VECTORS):
+ G, a, A, b, B, C, auxrand, msg, proof = TEST_VECTOR_DATA[i]
+ assert proof is not None and len(proof) == 64
+ writer.writerow((idx, G.to_bytes_compressed().hex(), f"{a:064x}", B.to_bytes_compressed().hex(), auxrand.hex(), msg.hex(), proof.hex(), f"Success case {i+1}"))
+ idx += 1
+
+ # failure cases: a is not within group order (a=0, a=N)
+ a_invalid = 0
+ assert dleq_generate_proof(a_invalid, B, auxrand, G=G, m=msg) is None
+ writer.writerow((idx, G.to_bytes_compressed().hex(), f"{a_invalid:064x}", B.to_bytes_compressed().hex(), auxrand.hex(), msg.hex(), "INVALID", f"Failure case (a=0)"))
+ idx += 1
+ a_invalid = GE.ORDER
+ assert dleq_generate_proof(a_invalid, B, auxrand, G=G, m=msg) is None
+ writer.writerow((idx, G.to_bytes_compressed().hex(), f"{a_invalid:064x}", B.to_bytes_compressed().hex(), auxrand.hex(), msg.hex(), "INVALID", f"Failure case (a=N [group order])"))
+ idx += 1
+
+ # failure case: B is point at infinity
+ B_infinity = GE()
+ B_infinity_str = "INFINITY"
+ assert dleq_generate_proof(a, B_infinity, auxrand, m=msg) is None
+ writer.writerow((idx, G.to_bytes_compressed().hex(), f"{a:064x}", B_infinity_str, auxrand.hex(), msg.hex(), "INVALID", f"Failure case (B is point at infinity)"))
+ idx += 1
+
+
+def gen_all_verify_proof_vectors(f):
+ writer = csv.writer(f)
+ writer.writerow(("index", "point_G", "point_A", "point_B", "point_C", "proof", "message", "result_success", "comment"))
+
+ # success cases (same as above)
+ idx = 0
+ for i in range(NUM_SUCCESS_TEST_VECTORS):
+ G, _, A, _, B, C, _, msg, proof = TEST_VECTOR_DATA[i]
+ assert dleq_verify_proof(A, B, C, proof, G=G, m=msg)
+ writer.writerow((idx, G.to_bytes_compressed().hex(), A.to_bytes_compressed().hex(), B.to_bytes_compressed().hex(),
+ C.to_bytes_compressed().hex(), proof.hex(), msg.hex(), "TRUE", f"Success case {i+1}"))
+ idx += 1
+
+ # other permutations of A, B, C should always fail
+ for i, points in enumerate(([A, C, B], [B, A, C], [B, C, A], [C, A, B], [C, B, A])):
+ assert not dleq_verify_proof(points[0], points[1], points[2], proof, m=msg)
+ writer.writerow((idx, G.to_bytes_compressed().hex(), points[0].to_bytes_compressed().hex(), points[1].to_bytes_compressed().hex(),
+ points[2].to_bytes_compressed().hex(), proof.hex(), msg.hex(), "FALSE", f"Swapped points case {i+1}"))
+ idx += 1
+
+ # modifying proof should fail (flip one bit)
+ proof_damage_pos = random_scalar_int(idx, "damage_pos") % 256
+ proof_damaged = list(proof)
+ proof_damaged[proof_damage_pos // 8] ^= (1 << (proof_damage_pos % 8))
+ proof_damaged = bytes(proof_damaged)
+ writer.writerow((idx, G.to_bytes_compressed().hex(), A.to_bytes_compressed().hex(), B.to_bytes_compressed().hex(),
+ C.to_bytes_compressed().hex(), proof_damaged.hex(), msg.hex(), "FALSE", f"Tampered proof (random bit-flip)"))
+ idx += 1
+
+ # modifying message should fail (flip one bit)
+ msg_damage_pos = random_scalar_int(idx, "damage_pos") % 256
+ msg_damaged = list(msg)
+ msg_damaged[proof_damage_pos // 8] ^= (1 << (msg_damage_pos % 8))
+ msg_damaged = bytes(msg_damaged)
+ writer.writerow((idx, G.to_bytes_compressed().hex(), A.to_bytes_compressed().hex(), B.to_bytes_compressed().hex(),
+ C.to_bytes_compressed().hex(), proof.hex(), msg_damaged.hex(), "FALSE", f"Tampered message (random bit-flip)"))
+ idx += 1
+
+
+if __name__ == "__main__":
+ print(f"Generating {FILENAME_GENERATE_PROOF_TEST}...")
+ with open(FILENAME_GENERATE_PROOF_TEST, "w", encoding="utf-8") as fil_generate_proof:
+ gen_all_generate_proof_vectors(fil_generate_proof)
+ print(f"Generating {FILENAME_VERIFY_PROOF_TEST}...")
+ with open(FILENAME_VERIFY_PROOF_TEST, "w", encoding="utf-8") as fil_verify_proof:
+ gen_all_verify_proof_vectors(fil_verify_proof)
diff --git a/bip-0374/reference.py b/bip-0374/reference.py
new file mode 100644
index 0000000000..e375bd72f3
--- /dev/null
+++ b/bip-0374/reference.py
@@ -0,0 +1,144 @@
+"""Reference implementation of DLEQ BIP for secp256k1 with unit tests."""
+
+from hashlib import sha256
+import random
+from secp256k1 import G, GE
+import sys
+import unittest
+
+
+DLEQ_TAG_AUX = "BIP0374/aux"
+DLEQ_TAG_NONCE = "BIP0374/nonce"
+DLEQ_TAG_CHALLENGE = "BIP0374/challenge"
+
+
+def TaggedHash(tag: str, data: bytes) -> bytes:
+ ss = sha256(tag.encode()).digest()
+ ss += ss
+ ss += data
+ return sha256(ss).digest()
+
+
+def xor_bytes(lhs: bytes, rhs: bytes) -> bytes:
+ assert len(lhs) == len(rhs)
+ return bytes([lhs[i] ^ rhs[i] for i in range(len(lhs))])
+
+
+def dleq_challenge(
+ A: GE, B: GE, C: GE, R1: GE, R2: GE, m: bytes | None, G: GE,
+) -> int:
+ if m is not None:
+ assert len(m) == 32
+ m = bytes([]) if m is None else m
+ return int.from_bytes(
+ TaggedHash(
+ DLEQ_TAG_CHALLENGE,
+ A.to_bytes_compressed()
+ + B.to_bytes_compressed()
+ + C.to_bytes_compressed()
+ + G.to_bytes_compressed()
+ + R1.to_bytes_compressed()
+ + R2.to_bytes_compressed()
+ + m,
+ ),
+ "big",
+ )
+
+
+def dleq_generate_proof(
+ a: int, B: GE, r: bytes, G: GE = G, m: bytes | None = None
+) -> bytes | None:
+ assert len(r) == 32
+ if not (0 < a < GE.ORDER):
+ return None
+ if B.infinity:
+ return None
+ A = a * G
+ C = a * B
+ t = xor_bytes(a.to_bytes(32, "big"), TaggedHash(DLEQ_TAG_AUX, r))
+ rand = TaggedHash(
+ DLEQ_TAG_NONCE, t + A.to_bytes_compressed() + C.to_bytes_compressed()
+ )
+ k = int.from_bytes(rand, "big") % GE.ORDER
+ if k == 0:
+ return None
+ R1 = k * G
+ R2 = k * B
+ e = dleq_challenge(A, B, C, R1, R2, m, G)
+ s = (k + e * a) % GE.ORDER
+ proof = e.to_bytes(32, "big") + s.to_bytes(32, "big")
+ if not dleq_verify_proof(A, B, C, proof, G=G, m=m):
+ return None
+ return proof
+
+
+def dleq_verify_proof(
+ A: GE, B: GE, C: GE, proof: bytes, G: GE = G, m: bytes | None = None
+) -> bool:
+ if A.infinity or B.infinity or C.infinity or G.infinity:
+ return False
+ assert len(proof) == 64
+ e = int.from_bytes(proof[:32], "big")
+ s = int.from_bytes(proof[32:], "big")
+ if s >= GE.ORDER:
+ return False
+ # TODO: implement subtraction operator (__sub__) for GE class to simplify these terms
+ R1 = s * G + (-e * A)
+ if R1.infinity:
+ return False
+ R2 = s * B + (-e * C)
+ if R2.infinity:
+ return False
+ if e != dleq_challenge(A, B, C, R1, R2, m, G):
+ return False
+ return True
+
+
+class DLEQTests(unittest.TestCase):
+ def test_dleq(self):
+ seed = random.randrange(sys.maxsize)
+ random.seed(seed)
+ print(f"PRNG seed is: {seed}")
+ for _ in range(10):
+ # generate random keypairs for both parties
+ a = random.randrange(1, GE.ORDER)
+ A = a * G
+ b = random.randrange(1, GE.ORDER)
+ B = b * G
+
+ # create shared secret
+ C = a * B
+
+ # create dleq proof
+ rand_aux = random.randbytes(32)
+ proof = dleq_generate_proof(a, B, rand_aux)
+ self.assertTrue(proof is not None)
+ # verify dleq proof
+ success = dleq_verify_proof(A, B, C, proof)
+ self.assertTrue(success)
+
+ # flip a random bit in the dleq proof and check that verification fails
+ for _ in range(5):
+ proof_damaged = list(proof)
+ proof_damaged[random.randrange(len(proof))] ^= 1 << (
+ random.randrange(8)
+ )
+ success = dleq_verify_proof(A, B, C, bytes(proof_damaged))
+ self.assertFalse(success)
+
+ # create the same dleq proof with a message
+ message = random.randbytes(32)
+ proof = dleq_generate_proof(a, B, rand_aux, m=message)
+ self.assertTrue(proof is not None)
+ # verify dleq proof with a message
+ success = dleq_verify_proof(A, B, C, proof, m=message)
+ self.assertTrue(success)
+
+ # flip a random bit in the dleq proof and check that verification fails
+ for _ in range(5):
+ proof_damaged = list(proof)
+ proof_damaged[random.randrange(len(proof))] ^= 1 << (
+ random.randrange(8)
+ )
+ success = dleq_verify_proof(A, B, C, bytes(proof_damaged))
+ self.assertFalse(success)
diff --git a/bip-0374/run_test_vectors.py b/bip-0374/run_test_vectors.py
new file mode 100755
index 0000000000..44b4f196db
--- /dev/null
+++ b/bip-0374/run_test_vectors.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python3
+"""Run the BIP-DLEQ test vectors."""
+import csv
+import os
+import sys
+from reference import (
+ dleq_generate_proof,
+ dleq_verify_proof,
+)
+from secp256k1 import GE
+
+
+FILENAME_GENERATE_PROOF_TEST = os.path.join(sys.path[0], 'test_vectors_generate_proof.csv')
+FILENAME_VERIFY_PROOF_TEST = os.path.join(sys.path[0], 'test_vectors_verify_proof.csv')
+
+
+all_passed = True
+print("-----------------------------------------")
+print("----- Proof generation test vectors -----")
+print("-----------------------------------------")
+with open(FILENAME_GENERATE_PROOF_TEST, newline='') as csvfile:
+ reader = csv.reader(csvfile)
+ reader.__next__()
+ for row in reader:
+ (index, point_G_hex, seckey_a_hex, point_B_hex, aux_rand_hex, msg_hex, result_str, comment) = row
+ print(seckey_a_hex)
+ G = GE() if point_G_hex == 'INFINITY' else GE.from_bytes(bytes.fromhex(point_G_hex))
+ a = int.from_bytes(bytes.fromhex(seckey_a_hex), 'big')
+ B = GE() if point_B_hex == 'INFINITY' else GE.from_bytes(bytes.fromhex(point_B_hex))
+ aux_rand = bytes.fromhex(aux_rand_hex)
+ msg = bytes.fromhex(msg_hex)
+ print('Test vector', ('#' + index).rjust(3, ' ') + ':' + f' ({comment})')
+ expected_result = None if result_str == 'INVALID' else bytes.fromhex(result_str)
+ actual_result = dleq_generate_proof(a, B, aux_rand, G=G, m=msg)
+ if expected_result == actual_result:
+ print(' * Passed proof generation test.')
+ else:
+ print(' * Failed proof generation test.')
+ print(' Expected proof: ', expected_result.hex() if expected_result is not None else 'INVALID')
+ print(' Actual proof: ', actual_result.hex() if actual_result is not None else 'INVALID')
+ all_passed = False
+ print()
+
+
+print("-------------------------------------------")
+print("----- Proof verification test vectors -----")
+print("-------------------------------------------")
+with open(FILENAME_VERIFY_PROOF_TEST, newline='') as csvfile:
+ reader = csv.reader(csvfile)
+ reader.__next__()
+ for row in reader:
+ (index, point_G_hex, point_A_hex, point_B_hex, point_C_hex, proof_hex, msg_hex, result_success, comment) = row
+ G = GE() if point_G_hex == 'INFINITY' else GE.from_bytes(bytes.fromhex(point_G_hex))
+ A = GE() if point_A_hex == 'INFINITY' else GE.from_bytes(bytes.fromhex(point_A_hex))
+ B = GE() if point_B_hex == 'INFINITY' else GE.from_bytes(bytes.fromhex(point_B_hex))
+ C = GE() if point_C_hex == 'INFINITY' else GE.from_bytes(bytes.fromhex(point_C_hex))
+ proof = bytes.fromhex(proof_hex)
+ msg = bytes.fromhex(msg_hex)
+ print('Test vector', ('#' + index).rjust(3, ' ') + ':' + f' ({comment})')
+ expected_result = result_success == 'TRUE'
+ actual_result = dleq_verify_proof(A, B, C, proof, G=G, m=msg)
+ if expected_result == actual_result:
+ print(' * Passed proof verification test.')
+ else:
+ print(' * Failed proof verification test.')
+ print(' Expected verification result: ', expected_result)
+ print(' Actual verification result: ', actual_result)
+ all_passed = False
+
+
+print()
+if all_passed:
+ print('All test vectors passed.')
+ sys.exit(0)
+else:
+ print('Some test vectors failed.')
+ sys.exit(1)
diff --git a/bip-0374/secp256k1.py b/bip-0374/secp256k1.py
new file mode 100644
index 0000000000..50a46dce37
--- /dev/null
+++ b/bip-0374/secp256k1.py
@@ -0,0 +1,354 @@
+# Copyright (c) 2022-2023 The Bitcoin Core developers
+# Distributed under the MIT software license, see the accompanying
+# file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+"""Test-only implementation of low-level secp256k1 field and group arithmetic
+
+It is designed for ease of understanding, not performance.
+
+WARNING: This code is slow and trivially vulnerable to side channel attacks. Do not use for
+anything but tests.
+
+Exports:
+* FE: class for secp256k1 field elements
+* GE: class for secp256k1 group elements
+* G: the secp256k1 generator point
+"""
+
+import unittest
+from hashlib import sha256
+
+class FE:
+ """Objects of this class represent elements of the field GF(2**256 - 2**32 - 977).
+
+ They are represented internally in numerator / denominator form, in order to delay inversions.
+ """
+
+ # The size of the field (also its modulus and characteristic).
+ SIZE = 2**256 - 2**32 - 977
+
+ def __init__(self, a=0, b=1):
+ """Initialize a field element a/b; both a and b can be ints or field elements."""
+ if isinstance(a, FE):
+ num = a._num
+ den = a._den
+ else:
+ num = a % FE.SIZE
+ den = 1
+ if isinstance(b, FE):
+ den = (den * b._num) % FE.SIZE
+ num = (num * b._den) % FE.SIZE
+ else:
+ den = (den * b) % FE.SIZE
+ assert den != 0
+ if num == 0:
+ den = 1
+ self._num = num
+ self._den = den
+
+ def __add__(self, a):
+ """Compute the sum of two field elements (second may be int)."""
+ if isinstance(a, FE):
+ return FE(self._num * a._den + self._den * a._num, self._den * a._den)
+ return FE(self._num + self._den * a, self._den)
+
+ def __radd__(self, a):
+ """Compute the sum of an integer and a field element."""
+ return FE(a) + self
+
+ def __sub__(self, a):
+ """Compute the difference of two field elements (second may be int)."""
+ if isinstance(a, FE):
+ return FE(self._num * a._den - self._den * a._num, self._den * a._den)
+ return FE(self._num - self._den * a, self._den)
+
+ def __rsub__(self, a):
+ """Compute the difference of an integer and a field element."""
+ return FE(a) - self
+
+ def __mul__(self, a):
+ """Compute the product of two field elements (second may be int)."""
+ if isinstance(a, FE):
+ return FE(self._num * a._num, self._den * a._den)
+ return FE(self._num * a, self._den)
+
+ def __rmul__(self, a):
+ """Compute the product of an integer with a field element."""
+ return FE(a) * self
+
+ def __truediv__(self, a):
+ """Compute the ratio of two field elements (second may be int)."""
+ return FE(self, a)
+
+ def __pow__(self, a):
+ """Raise a field element to an integer power."""
+ return FE(pow(self._num, a, FE.SIZE), pow(self._den, a, FE.SIZE))
+
+ def __neg__(self):
+ """Negate a field element."""
+ return FE(-self._num, self._den)
+
+ def __int__(self):
+ """Convert a field element to an integer in range 0..p-1. The result is cached."""
+ if self._den != 1:
+ self._num = (self._num * pow(self._den, -1, FE.SIZE)) % FE.SIZE
+ self._den = 1
+ return self._num
+
+ def sqrt(self):
+ """Compute the square root of a field element if it exists (None otherwise).
+
+ Due to the fact that our modulus is of the form (p % 4) == 3, the Tonelli-Shanks
+ algorithm (https://en.wikipedia.org/wiki/Tonelli-Shanks_algorithm) is simply
+ raising the argument to the power (p + 1) / 4.
+
+ To see why: (p-1) % 2 = 0, so 2 divides the order of the multiplicative group,
+ and thus only half of the non-zero field elements are squares. An element a is
+ a (nonzero) square when Euler's criterion, a^((p-1)/2) = 1 (mod p), holds. We're
+ looking for x such that x^2 = a (mod p). Given a^((p-1)/2) = 1, that is equivalent
+ to x^2 = a^(1 + (p-1)/2) mod p. As (1 + (p-1)/2) is even, this is equivalent to
+ x = a^((1 + (p-1)/2)/2) mod p, or x = a^((p+1)/4) mod p."""
+ v = int(self)
+ s = pow(v, (FE.SIZE + 1) // 4, FE.SIZE)
+ if s**2 % FE.SIZE == v:
+ return FE(s)
+ return None
+
+ def is_square(self):
+ """Determine if this field element has a square root."""
+ # A more efficient algorithm is possible here (Jacobi symbol).
+ return self.sqrt() is not None
+
+ def is_even(self):
+ """Determine whether this field element, represented as integer in 0..p-1, is even."""
+ return int(self) & 1 == 0
+
+ def __eq__(self, a):
+ """Check whether two field elements are equal (second may be an int)."""
+ if isinstance(a, FE):
+ return (self._num * a._den - self._den * a._num) % FE.SIZE == 0
+ return (self._num - self._den * a) % FE.SIZE == 0
+
+ def to_bytes(self):
+ """Convert a field element to a 32-byte array (BE byte order)."""
+ return int(self).to_bytes(32, 'big')
+
+ @staticmethod
+ def from_bytes(b):
+ """Convert a 32-byte array to a field element (BE byte order, no overflow allowed)."""
+ v = int.from_bytes(b, 'big')
+ if v >= FE.SIZE:
+ return None
+ return FE(v)
+
+ def __str__(self):
+ """Convert this field element to a 64 character hex string."""
+ return f"{int(self):064x}"
+
+ def __repr__(self):
+ """Get a string representation of this field element."""
+ return f"FE(0x{int(self):x})"
+
+
+class GE:
+ """Objects of this class represent secp256k1 group elements (curve points or infinity)
+
+ Normal points on the curve have fields:
+ * x: the x coordinate (a field element)
+ * y: the y coordinate (a field element, satisfying y^2 = x^3 + 7)
+ * infinity: False
+
+ The point at infinity has field:
+ * infinity: True
+ """
+
+ # Order of the group (number of points on the curve, plus 1 for infinity)
+ ORDER = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
+
+ # Number of valid distinct x coordinates on the curve.
+ ORDER_HALF = ORDER // 2
+
+ def __init__(self, x=None, y=None):
+ """Initialize a group element with specified x and y coordinates, or infinity."""
+ if x is None:
+ # Initialize as infinity.
+ assert y is None
+ self.infinity = True
+ else:
+ # Initialize as point on the curve (and check that it is).
+ fx = FE(x)
+ fy = FE(y)
+ assert fy**2 == fx**3 + 7
+ self.infinity = False
+ self.x = fx
+ self.y = fy
+
+ def __add__(self, a):
+ """Add two group elements together."""
+ # Deal with infinity: a + infinity == infinity + a == a.
+ if self.infinity:
+ return a
+ if a.infinity:
+ return self
+ if self.x == a.x:
+ if self.y != a.y:
+ # A point added to its own negation is infinity.
+ assert self.y + a.y == 0
+ return GE()
+ else:
+ # For identical inputs, use the tangent (doubling formula).
+ lam = (3 * self.x**2) / (2 * self.y)
+ else:
+ # For distinct inputs, use the line through both points (adding formula).
+ lam = (self.y - a.y) / (self.x - a.x)
+ # Determine point opposite to the intersection of that line with the curve.
+ x = lam**2 - (self.x + a.x)
+ y = lam * (self.x - x) - self.y
+ return GE(x, y)
+
+ @staticmethod
+ def mul(*aps):
+ """Compute a (batch) scalar group element multiplication.
+
+ GE.mul((a1, p1), (a2, p2), (a3, p3)) is identical to a1*p1 + a2*p2 + a3*p3,
+ but more efficient."""
+ # Reduce all the scalars modulo order first (so we can deal with negatives etc).
+ naps = [(a % GE.ORDER, p) for a, p in aps]
+ # Start with point at infinity.
+ r = GE()
+ # Iterate over all bit positions, from high to low.
+ for i in range(255, -1, -1):
+ # Double what we have so far.
+ r = r + r
+ # Add then add the points for which the corresponding scalar bit is set.
+ for (a, p) in naps:
+ if (a >> i) & 1:
+ r += p
+ return r
+
+ def __rmul__(self, a):
+ """Multiply an integer with a group element."""
+ if self == G:
+ return FAST_G.mul(a)
+ return GE.mul((a, self))
+
+ def __neg__(self):
+ """Compute the negation of a group element."""
+ if self.infinity:
+ return self
+ return GE(self.x, -self.y)
+
+ def to_bytes_compressed(self):
+ """Convert a non-infinite group element to 33-byte compressed encoding."""
+ assert not self.infinity
+ return bytes([3 - self.y.is_even()]) + self.x.to_bytes()
+
+ def to_bytes_uncompressed(self):
+ """Convert a non-infinite group element to 65-byte uncompressed encoding."""
+ assert not self.infinity
+ return b'\x04' + self.x.to_bytes() + self.y.to_bytes()
+
+ def to_bytes_xonly(self):
+ """Convert (the x coordinate of) a non-infinite group element to 32-byte xonly encoding."""
+ assert not self.infinity
+ return self.x.to_bytes()
+
+ @staticmethod
+ def lift_x(x):
+ """Return group element with specified field element as x coordinate (and even y)."""
+ y = (FE(x)**3 + 7).sqrt()
+ if y is None:
+ return None
+ if not y.is_even():
+ y = -y
+ return GE(x, y)
+
+ @staticmethod
+ def from_bytes(b):
+ """Convert a compressed or uncompressed encoding to a group element."""
+ assert len(b) in (33, 65)
+ if len(b) == 33:
+ if b[0] != 2 and b[0] != 3:
+ return None
+ x = FE.from_bytes(b[1:])
+ if x is None:
+ return None
+ r = GE.lift_x(x)
+ if r is None:
+ return None
+ if b[0] == 3:
+ r = -r
+ return r
+ else:
+ if b[0] != 4:
+ return None
+ x = FE.from_bytes(b[1:33])
+ y = FE.from_bytes(b[33:])
+ if y**2 != x**3 + 7:
+ return None
+ return GE(x, y)
+
+ @staticmethod
+ def from_bytes_xonly(b):
+ """Convert a point given in xonly encoding to a group element."""
+ assert len(b) == 32
+ x = FE.from_bytes(b)
+ if x is None:
+ return None
+ return GE.lift_x(x)
+
+ @staticmethod
+ def is_valid_x(x):
+ """Determine whether the provided field element is a valid X coordinate."""
+ return (FE(x)**3 + 7).is_square()
+
+ def __str__(self):
+ """Convert this group element to a string."""
+ if self.infinity:
+ return "(inf)"
+ return f"({self.x},{self.y})"
+
+ def __repr__(self):
+ """Get a string representation for this group element."""
+ if self.infinity:
+ return "GE()"
+ return f"GE(0x{int(self.x):x},0x{int(self.y):x})"
+
+# The secp256k1 generator point
+G = GE.lift_x(0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798)
+
+
+class FastGEMul:
+ """Table for fast multiplication with a constant group element.
+
+ Speed up scalar multiplication with a fixed point P by using a precomputed lookup table with
+ its powers of 2:
+
+ table = [P, 2*P, 4*P, (2^3)*P, (2^4)*P, ..., (2^255)*P]
+
+ During multiplication, the points corresponding to each bit set in the scalar are added up,
+ i.e. on average ~128 point additions take place.
+ """
+
+ def __init__(self, p):
+ self.table = [p] # table[i] = (2^i) * p
+ for _ in range(255):
+ p = p + p
+ self.table.append(p)
+
+ def mul(self, a):
+ result = GE()
+ a = a % GE.ORDER
+ for bit in range(a.bit_length()):
+ if a & (1 << bit):
+ result += self.table[bit]
+ return result
+
+# Precomputed table with multiples of G for fast multiplication
+FAST_G = FastGEMul(G)
+
+class TestFrameworkSecp256k1(unittest.TestCase):
+ def test_H(self):
+ H = sha256(G.to_bytes_uncompressed()).digest()
+ assert GE.lift_x(FE.from_bytes(H)) is not None
+ self.assertEqual(H.hex(), "50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0")
diff --git a/bip-0374/test_vectors_generate_proof.csv b/bip-0374/test_vectors_generate_proof.csv
new file mode 100644
index 0000000000..118de779cc
--- /dev/null
+++ b/bip-0374/test_vectors_generate_proof.csv
@@ -0,0 +1,9 @@
+index,point_G,scalar_a,point_B,auxrand_r,message,result_proof,comment
+0,02cef38f55e78b321a1f785cb1c6e33dfcef9784c18bdc4e279801c449ccdfb88e,07ff93d43f1012a5d4a44aba55240212ed39c87b3344e46757d99f24177fc576,02dad4b35c2379ba8334c9a5dda8f6e6d5cd575a7cc9d3ca4faaac51839daaa30f,cb979b0fc8ccc7f237751e719d992fcc324b6500af33999cd54a3e5c05fb1ea4,efb07d4b382d3da1079fbf24df623ba6c2e4c764993bbfa6dd7a4fe4aaf33859,51ce8becf2726c8fed85957500de5d58e0349b8ed0fe40aee2c122288ee21f8fe4d1ca31f5e3c4833fb83a654b044298aceef34881c950efefdc7b64cb5db93e,Success case 1
+1,02464e351831efedb755223cabbf664f10564b4742c725c023034bc928ed339e0e,f4e9172285393c6ada994c811b3e50fc47e96421ea7e54f4a4e459528d4cf562,03fe589b0fa23f060f6d4d1e76b9b19d5bb3db0e56d39a4303913de0e706463008,75f12482b9209dae12230ea1f8bf69723a1b447d361db8f510dd9ab33556fd4c,76184ce9eea5b339ebf5304b57452c1ada1466610f0a58574d6c496798cee04b,be01fd4ec6ee4b08adb36ddb7b0290e09710f842f8623f1afc8c0ff00bdd6cee5256b10341c30d4f393d9b2c462b1534d06e2cff60920993c6dc240806576d80,Success case 2
+2,0222db2054fef98344352a13bc0304a71da7b5e9a2f7fd1f3c9f3519a3d9377fb7,589476913e763b60d5c2a5bfb39230ec669caac1b44312e9bcd2d3f4473abfef,03bc7a19970c812118f74ba659b491e00dade6096ff62d1afe032a92b8671498ed,4da1c4c4b0f9db4eb6b2e5cb648d7e8a0aa35aa5c4ec4d07f096e0e03deca366,66503623468a78cfcef47888c85e0010ecd897f441d263448bfc7a89b882ab20,a9e3603f2cb11c74dba678448cc5bc6ae6de372502392d1914e976229cb06c401f12bd03dbab57c2cd1a209adb51c14387f82e938a8a9d363fc8dc1e76456dac,Success case 3
+3,03dfa65bd3711eba75fa1996a0c1d95a4419bd835304152d9aa6efa590670f2af6,24d0ed3fc189eb1b64e5dc9dd4af0f3c8c143b0c79cb5fcca0dfa08a11cc60a1,03b51081323d38fb0b75f0c1ec6755fdb79c239c327ca11269fe68ba8a878b704e,31a68d6db27f6404bbceff646ff1b26a34704a0105a36c5a845d0257cea19c9b,f2996b3766d123a949e65541baf1d89d446360d05af51bd93f0445d8c472c952,0dbd32f1ecd950987bda4b163e5ea536e4e43e8e2f26bcf235ff799c12089f21d5a27f90f144aaaddf5a05390c44442aa13d9fbfec8cd53d3659942617ce5cb4,Success case 4
+4,02b15de5a3aefcfe2473916c76e619b5800ac7250ef93a9e6e0dd1505104fc58e7,73fffa796edb72d111b5e0bbda1608f098ac98120796f971b438691e1bfb7b96,03a4692be176ff89a972de9cc407083096847b950d1cae72b947665a3d5f4c2f01,1cdfb4d7cce5e50783299896a471a44e6aa2c5e2100d6c37987c6b40503c6162,0ceb45f560f2cf6b76a139ffe2c47c5ca6d26d6a3a210e59f197413bbec040b4,5bd36d18c6e75e50f1fbba27596591ef3506b841ce65c8f3489fa1b31e074f0f511400ad72a06b023727809c6c16c78c5d53ff14e848184462cd357660894d3d,Success case 5
+5,02b15de5a3aefcfe2473916c76e619b5800ac7250ef93a9e6e0dd1505104fc58e7,0000000000000000000000000000000000000000000000000000000000000000,03a4692be176ff89a972de9cc407083096847b950d1cae72b947665a3d5f4c2f01,1cdfb4d7cce5e50783299896a471a44e6aa2c5e2100d6c37987c6b40503c6162,0ceb45f560f2cf6b76a139ffe2c47c5ca6d26d6a3a210e59f197413bbec040b4,INVALID,Failure case (a=0)
+6,02b15de5a3aefcfe2473916c76e619b5800ac7250ef93a9e6e0dd1505104fc58e7,fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141,03a4692be176ff89a972de9cc407083096847b950d1cae72b947665a3d5f4c2f01,1cdfb4d7cce5e50783299896a471a44e6aa2c5e2100d6c37987c6b40503c6162,0ceb45f560f2cf6b76a139ffe2c47c5ca6d26d6a3a210e59f197413bbec040b4,INVALID,Failure case (a=N [group order])
+7,02b15de5a3aefcfe2473916c76e619b5800ac7250ef93a9e6e0dd1505104fc58e7,73fffa796edb72d111b5e0bbda1608f098ac98120796f971b438691e1bfb7b96,INFINITY,1cdfb4d7cce5e50783299896a471a44e6aa2c5e2100d6c37987c6b40503c6162,0ceb45f560f2cf6b76a139ffe2c47c5ca6d26d6a3a210e59f197413bbec040b4,INVALID,Failure case (B is point at infinity)
diff --git a/bip-0374/test_vectors_verify_proof.csv b/bip-0374/test_vectors_verify_proof.csv
new file mode 100644
index 0000000000..aa15d5baaf
--- /dev/null
+++ b/bip-0374/test_vectors_verify_proof.csv
@@ -0,0 +1,13 @@
+index,point_G,point_A,point_B,point_C,proof,message,result_success,comment
+0,02cef38f55e78b321a1f785cb1c6e33dfcef9784c18bdc4e279801c449ccdfb88e,02b540b22c2c5ef0dc886abdaad27498453d893265560bc08a187319af6f845f58,02dad4b35c2379ba8334c9a5dda8f6e6d5cd575a7cc9d3ca4faaac51839daaa30f,03fefe00951dcd0ef10b12523393c2b8113119de4fdeeab320694e96bdccd2775b,51ce8becf2726c8fed85957500de5d58e0349b8ed0fe40aee2c122288ee21f8fe4d1ca31f5e3c4833fb83a654b044298aceef34881c950efefdc7b64cb5db93e,efb07d4b382d3da1079fbf24df623ba6c2e4c764993bbfa6dd7a4fe4aaf33859,TRUE,Success case 1
+1,02464e351831efedb755223cabbf664f10564b4742c725c023034bc928ed339e0e,032baaf1b10845a51b551196984a91efe2adf9d41b92bec3927218e6e4ca344002,03fe589b0fa23f060f6d4d1e76b9b19d5bb3db0e56d39a4303913de0e706463008,031f59aa1df22190e00380d8c5941adf899f596593765a1251005fd24f2bf7c884,be01fd4ec6ee4b08adb36ddb7b0290e09710f842f8623f1afc8c0ff00bdd6cee5256b10341c30d4f393d9b2c462b1534d06e2cff60920993c6dc240806576d80,76184ce9eea5b339ebf5304b57452c1ada1466610f0a58574d6c496798cee04b,TRUE,Success case 2
+2,0222db2054fef98344352a13bc0304a71da7b5e9a2f7fd1f3c9f3519a3d9377fb7,026aa26fcd626f8f55295859e9f8dd1f103149dd64d77c2bbba1bcf33bb37ebaa2,03bc7a19970c812118f74ba659b491e00dade6096ff62d1afe032a92b8671498ed,035628d1a69910daef614c7cae68d71ece55c5908af2360629e25c1b7de21eeb4b,a9e3603f2cb11c74dba678448cc5bc6ae6de372502392d1914e976229cb06c401f12bd03dbab57c2cd1a209adb51c14387f82e938a8a9d363fc8dc1e76456dac,66503623468a78cfcef47888c85e0010ecd897f441d263448bfc7a89b882ab20,TRUE,Success case 3
+3,03dfa65bd3711eba75fa1996a0c1d95a4419bd835304152d9aa6efa590670f2af6,031bf61ba89009ee1266c9003a72e8e07d77877678ccda7f15325aadcd64ed186b,03b51081323d38fb0b75f0c1ec6755fdb79c239c327ca11269fe68ba8a878b704e,02d1b1f37a80217ba73785babfa63251052775f9d3ca65060054033288b7a3f66b,0dbd32f1ecd950987bda4b163e5ea536e4e43e8e2f26bcf235ff799c12089f21d5a27f90f144aaaddf5a05390c44442aa13d9fbfec8cd53d3659942617ce5cb4,f2996b3766d123a949e65541baf1d89d446360d05af51bd93f0445d8c472c952,TRUE,Success case 4
+4,02b15de5a3aefcfe2473916c76e619b5800ac7250ef93a9e6e0dd1505104fc58e7,0296c8e00dda60bb5565b77371ff913091978646b58ccf218bc591f68a75232e6e,03a4692be176ff89a972de9cc407083096847b950d1cae72b947665a3d5f4c2f01,03a7a7f9527fd387c2b2ce0c76669d646c78a3b470a4b34d3a2dabafc8505ef472,5bd36d18c6e75e50f1fbba27596591ef3506b841ce65c8f3489fa1b31e074f0f511400ad72a06b023727809c6c16c78c5d53ff14e848184462cd357660894d3d,0ceb45f560f2cf6b76a139ffe2c47c5ca6d26d6a3a210e59f197413bbec040b4,TRUE,Success case 5
+5,02b15de5a3aefcfe2473916c76e619b5800ac7250ef93a9e6e0dd1505104fc58e7,0296c8e00dda60bb5565b77371ff913091978646b58ccf218bc591f68a75232e6e,03a7a7f9527fd387c2b2ce0c76669d646c78a3b470a4b34d3a2dabafc8505ef472,03a4692be176ff89a972de9cc407083096847b950d1cae72b947665a3d5f4c2f01,5bd36d18c6e75e50f1fbba27596591ef3506b841ce65c8f3489fa1b31e074f0f511400ad72a06b023727809c6c16c78c5d53ff14e848184462cd357660894d3d,0ceb45f560f2cf6b76a139ffe2c47c5ca6d26d6a3a210e59f197413bbec040b4,FALSE,Swapped points case 1
+6,02b15de5a3aefcfe2473916c76e619b5800ac7250ef93a9e6e0dd1505104fc58e7,03a4692be176ff89a972de9cc407083096847b950d1cae72b947665a3d5f4c2f01,0296c8e00dda60bb5565b77371ff913091978646b58ccf218bc591f68a75232e6e,03a7a7f9527fd387c2b2ce0c76669d646c78a3b470a4b34d3a2dabafc8505ef472,5bd36d18c6e75e50f1fbba27596591ef3506b841ce65c8f3489fa1b31e074f0f511400ad72a06b023727809c6c16c78c5d53ff14e848184462cd357660894d3d,0ceb45f560f2cf6b76a139ffe2c47c5ca6d26d6a3a210e59f197413bbec040b4,FALSE,Swapped points case 2
+7,02b15de5a3aefcfe2473916c76e619b5800ac7250ef93a9e6e0dd1505104fc58e7,03a4692be176ff89a972de9cc407083096847b950d1cae72b947665a3d5f4c2f01,03a7a7f9527fd387c2b2ce0c76669d646c78a3b470a4b34d3a2dabafc8505ef472,0296c8e00dda60bb5565b77371ff913091978646b58ccf218bc591f68a75232e6e,5bd36d18c6e75e50f1fbba27596591ef3506b841ce65c8f3489fa1b31e074f0f511400ad72a06b023727809c6c16c78c5d53ff14e848184462cd357660894d3d,0ceb45f560f2cf6b76a139ffe2c47c5ca6d26d6a3a210e59f197413bbec040b4,FALSE,Swapped points case 3
+8,02b15de5a3aefcfe2473916c76e619b5800ac7250ef93a9e6e0dd1505104fc58e7,03a7a7f9527fd387c2b2ce0c76669d646c78a3b470a4b34d3a2dabafc8505ef472,0296c8e00dda60bb5565b77371ff913091978646b58ccf218bc591f68a75232e6e,03a4692be176ff89a972de9cc407083096847b950d1cae72b947665a3d5f4c2f01,5bd36d18c6e75e50f1fbba27596591ef3506b841ce65c8f3489fa1b31e074f0f511400ad72a06b023727809c6c16c78c5d53ff14e848184462cd357660894d3d,0ceb45f560f2cf6b76a139ffe2c47c5ca6d26d6a3a210e59f197413bbec040b4,FALSE,Swapped points case 4
+9,02b15de5a3aefcfe2473916c76e619b5800ac7250ef93a9e6e0dd1505104fc58e7,03a7a7f9527fd387c2b2ce0c76669d646c78a3b470a4b34d3a2dabafc8505ef472,03a4692be176ff89a972de9cc407083096847b950d1cae72b947665a3d5f4c2f01,0296c8e00dda60bb5565b77371ff913091978646b58ccf218bc591f68a75232e6e,5bd36d18c6e75e50f1fbba27596591ef3506b841ce65c8f3489fa1b31e074f0f511400ad72a06b023727809c6c16c78c5d53ff14e848184462cd357660894d3d,0ceb45f560f2cf6b76a139ffe2c47c5ca6d26d6a3a210e59f197413bbec040b4,FALSE,Swapped points case 5
+10,02b15de5a3aefcfe2473916c76e619b5800ac7250ef93a9e6e0dd1505104fc58e7,0296c8e00dda60bb5565b77371ff913091978646b58ccf218bc591f68a75232e6e,03a4692be176ff89a972de9cc407083096847b950d1cae72b947665a3d5f4c2f01,03a7a7f9527fd387c2b2ce0c76669d646c78a3b470a4b34d3a2dabafc8505ef472,5bd36d18c6e75e50f1fbbaa7596591ef3506b841ce65c8f3489fa1b31e074f0f511400ad72a06b023727809c6c16c78c5d53ff14e848184462cd357660894d3d,0ceb45f560f2cf6b76a139ffe2c47c5ca6d26d6a3a210e59f197413bbec040b4,FALSE,Tampered proof (random bit-flip)
+11,02b15de5a3aefcfe2473916c76e619b5800ac7250ef93a9e6e0dd1505104fc58e7,0296c8e00dda60bb5565b77371ff913091978646b58ccf218bc591f68a75232e6e,03a4692be176ff89a972de9cc407083096847b950d1cae72b947665a3d5f4c2f01,03a7a7f9527fd387c2b2ce0c76669d646c78a3b470a4b34d3a2dabafc8505ef472,5bd36d18c6e75e50f1fbba27596591ef3506b841ce65c8f3489fa1b31e074f0f511400ad72a06b023727809c6c16c78c5d53ff14e848184462cd357660894d3d,0ceb45f560f2cf6b76a139f7e2c47c5ca6d26d6a3a210e59f197413bbec040b4,FALSE,Tampered message (random bit-flip)
diff --git a/bip-0379.md b/bip-0379.md
new file mode 100644
index 0000000000..c8e6b160b6
--- /dev/null
+++ b/bip-0379.md
@@ -0,0 +1,423 @@
+
+
+## Abstract
+
+This document specifies Miniscript, a language for writing (a subset of) Bitcoin Scripts in a
+structured way, enabling analysis, composition, generic signing and more.
+
+## Copyright
+
+This document is licensed under the Creative Commons CC0 1.0 Universal license.
+
+## Motivation
+
+Bitcoin Script is an unusual stack-based language with many edge cases, designed for implementing
+spending conditions consisting of various combinations of signatures, hash locks, and time locks.
+Yet, despite being limited in functionality, it is still highly nontrivial to:
+
+* Given a combination of spending conditions, finding the most economical script to implement it.
+* Given two scripts, construct a script that implements a composition of their spending conditions (e.g. a multisig where one of the "keys" is another multisig).
+* Given a script, find out what spending conditions it permits.
+* Given a script and access to a sufficient set of private keys, construct a general satisfying witness for it.
+* Given a script, be able to predict the cost of spending an output.
+* Given a script, know whether particular resource limitations like the ops limit might be hit when spending.
+
+Miniscript functions as a representation for scripts that makes this sort of operations possible.
+It has a structure that allows composition. It is very easy to statically analyze for various
+properties (spending conditions, correctness, security properties, malleability, ...). It can be
+targeted by spending policy compilers. Finally, compatible scripts can easily be converted to
+Miniscript form - avoiding the need for additional metadata for e.g. signing devices that support
+it.
+
+## Specification
+
+These specifications apply to P2WSH ([BIP 141](bip-0141.mediawiki)) and Tapscript ([BIP 342](bip-0342.mediawiki)) scripts, with only minor
+variations between the two. Differences are noted inline. Unless explicitly stated otherwise,
+specifications apply to both. P2SH and bare scripts are excluded from this specification.
+
+### Translation Table
+
+Miniscript consists of a set of script *fragments* which are designed to be safely and correctly composable.
+
+This table shows all Miniscript *fragments* and their associated semantics and Bitcoin Script.
+Fragments that do not change the semantics of their subexpressions are called *wrappers*. Normal
+fragments use a `fragment(arg1,arg2,...)` notation, while wrappers are written using
+prefixes separated from other fragments by a colon. The colon is dropped between subsequent
+wrappers; e.g. `dv:older(144)` is the `d:` wrapper applied to the
+`v:` wrapper applied to the `older` fragment for 144 blocks.
+
+The `pk`, `pkh`, and `and_n` fragments and `t:`,
+`l:`, and `u:` wrappers are syntactic sugar for other Miniscripts, as listed
+in the table below. Note that `<20>` are in hex representation in this document.
+
+Miniscript fragments are expected to be used in [BIP 382](bip-0382.mediawiki) `wsh()` descriptors
+and [BIP 386](bip-0386.mediawiki) `tr()` descriptors. Key expressions are specified in
+[BIP 380](bip-0380.mediawiki#user-content-Key_Expressions). Additionally, BIPs 382 and 386 specify
+restrictions on key expressions and what they resolve to - these apply to key expressions in
+Miniscript. BIP 382's key expression restrictions apply to Miniscript in P2WSH contexts, and BIP
+386's key expression restrictions apply to Miniscript in P2TR contexts. From a user's perspective,
+Miniscript is not a separate language, but rather a significant expansion of the descriptor language.
+
+| Semantics | Miniscript Fragment | Bitcoin Script
+|----------------------------------------------------------|-------------------------------|---------------
+| false | `0` | `0`
+| true | `1` | `1`
+| check(key) | `pk_k(key)` | ``
+| | `pk_h(key)` | `DUP HASH160 EQUALVERIFY `
+| | `pk(key)` = `c:pk_k(key)` | ` CHECKSIG`
+| | `pkh(key)` = `c:pk_h(key)` | `DUP HASH160 EQUALVERIFY CHECKSIG`
+| nSequence ≥ n (and compatible) | `older(n)` | ` CHECKSEQUENCEVERIFY`
+| nLockTime ≥ n (and compatible) | `after(n)` | ` CHECKLOCKTIMEVERIFY`
+| len(x) = 32 and SHA256(x) = h | `sha256(h)` | `SIZE <20> EQUALVERIFY SHA256 EQUAL`
+| len(x) = 32 and HASH256(x) = h | `hash256(h)` | `SIZE <20> EQUALVERIFY HASH256 EQUAL`
+| len(x) = 32 and RIPEMD160(x) = h | `ripemd160(h)` | `SIZE <20> EQUALVERIFY RIPEMD160 EQUAL`
+| len(x) = 32 and HASH160(x) = h | `hash160(h)` | `SIZE <20> EQUALVERIFY HASH160 EQUAL`
+| (X and Y) or Z | `andor(X,Y,Z)` | `[X] NOTIF [Z] ELSE [Y] ENDIF`
+| X and Y | `and_v(X,Y)` | `[X] [Y]`
+| | `and_b(X,Y)` | `[X] [Y] BOOLAND`
+| | `and_n(X,Y)` = `andor(X,Y,0)` | `[X] NOTIF 0 ELSE [Y] ENDIF`
+| X or Z | `or_b(X,Z)` | `[X] [Z] BOOLOR`
+| | `or_c(X,Z)` | `[X] NOTIF [Z] ENDIF`
+| | `or_d(X,Z)` | `[X] IFDUP NOTIF [Z] ENDIF`
+| | `or_i(X,Z)` | `IF [X] ELSE [Z] ENDIF`
+| X_1 + ... + X_n = k | `thresh(k,X_1,...,X_n)` | `[X_1] [X_2] ADD ... [X_n] ADD ... EQUAL`
+| check(key_1) + ... + check(key_n) = k *(P2WSH only)* | `multi(k,key_1,...,key_n)` | ` ... CHECKMULTISIG`
+| check(key_1) + ... + check(key_n) = k *(Tapscript only)* | `multi_a(k,key_1,...,key_n)` | ` CHECKSIG CHECKSIGADD ... CHECKSIGADD NUMEQUAL`
+| X (identities) | `a:X` | `TOALTSTACK [X] FROMALTSTACK`
+| | `s:X` | `SWAP [X]`
+| | `c:X` | `[X] CHECKSIG`
+| | `t:X` = `and_v(X,1)` | `[X] 1`
+| | `d:X` | `DUP IF [X] ENDIF`
+| | `v:X` | `[X] VERIFY (or VERIFY version of last opcode in [X])`
+| | `j:X` | `SIZE 0NOTEQUAL IF [X] ENDIF`
+| | `n:X` | `[X] 0NOTEQUAL`
+| | `l:X` = `or_i(0,X)` | `IF 0 ELSE [X] ENDIF`
+| | `u:X` = `or_i(X,0)` | `IF [X] ELSE 0 ENDIF`
+
+### Type System
+
+Not every Miniscript expression can be composed with every other. Some return their result by
+putting true or false on the stack; others can only abort or continue. Some require subexpressions
+that consume an exactly known number of arguments, while others need a subexpression that has a
+nonzero top stack element to satisfy. To model all these properties, we define a correctness type
+system for Miniscript.
+
+#### Correctness
+
+Every miniscript expression has one of four basic types: "**B**" (base), "**V**" (verify),
+"**K**" (key) and "**W**" (wrapped). Then there are 5 type modifiers that guarantee additional
+properties: "**z**" (zero-arg), "**o**" (one-arg), "**n**" (nonzero), "**d**"
+(dissatisfiable), and "**u**" (unit).
+
+The following table lists the correctness requirements for each of the Miniscript expressions, and
+its type properties in function of those of their subexpressions.
+
+| Miniscript | Requires | Type | Properties
+|------------------------------|-------------------------------------------------------|-------------|-----------
+| `0` | | B | z; u; d
+| `1` | | B | z; u
+| `pk_k(key)` | | K | o; n; d; u
+| `pk_h(key)` | | K | n; d; u
+| `older(n)`, `after(n)` | 1 ≤ n < 231 | B | z
+| `sha256(h)` | | B | o; n; d; u
+| `ripemd160(h)` | | B | o; n; d; u
+| `hash256(h)` | | B | o; n; d; u
+| `hash160(h)` | | B | o; n; d; u
+| `andor(X,Y,Z)` | X is Bdu; Y and Z are both B, K, or V | same as Y/Z | z=zXzYzZ; o=zXoYoZ or oXzYzZ; u=uYuZ; d=dZ
+| `and_v(X,Y)` | X is V; Y is B, K, or V | same as Y | z=zXzY; o=zXoY or zYoX; n=nX or zXnY; u=uY
+| `and_b(X,Y)` | X is B; Y is W | B | z=zXzY; o=zXoY or zYoX; n=nX or zXnY; d=dXdY; u
+| `or_b(X,Z)` | X is Bd; Z is Wd | B | z=zXzZ; o=zXoZ or zZoX; d; u
+| `or_c(X,Z)` | X is Bdu; Z is V | V | z=zXzZ; o=oXzZ
+| `or_d(X,Z)` | X is Bdu; Z is B | B | z=zXzZ; o=oXzZ; d=dZ; u=uZ
+| `or_i(X,Z)` | both are B, K, or V | same as X/Z | o=zXzZ; u=uXuZ; d=dX or dZ
+| `thresh(k,X_1,...,X_n)` | 1 ≤ k ≤ n; X1 is Bdu; others are Wdu | B | z=all are z; o=all are z except one is o; d; u
+| `multi(k,key_1,...,key_n)` | 1 ≤ k ≤ n ≤ 20 | B | n; d; u
+| `multi_a(k,key_1,...,key_n)` | 1 ≤ k ≤ n | B | d; u
+| `a:X` | X is B | W | d=dX; u=uX
+| `s:X` | X is Bo | W | d=dX; u=uX
+| `c:X` | X is K | B | o=oX; n=nX; d=dX; u
+| `d:X` | X is Vz | B | o; n; d; *(Tapscript only)* u
+| `v:X` | X is B | V | z=zX; o=oX; n=nX
+| `j:X` | X is Bn | B | o=oX; n; d; u=uX
+| `n:X` | X is B | B | z=zX; o=oX; n=nX; d=dX; u
+
+#### Timelock Type Mixing
+
+There is one additional correctness property that Miniscript expressions must satisfy:
+the four timelock types (absolute time based, absolute height based, relative time based, and
+relative height based) must not be mixed in an incompatible way.
+
+Within `and` combinators and the `thresh` combinator where k >= 2, it is illegal for both absolute
+height based and time based timelocks to appear, or for both relative height based and time based
+timelocks to appear.
+
+For all other combinators, it is legal to mix timelock types. It is also always legal to
+mix absolute and relative timelocks (even if one is height based and the other is time based).
+
+#### Malleability
+
+Malleability is the ability for a third party (someone who does *not* hold a participating private
+key) to modify an existing satisfaction into another valid satisfaction. To analyze the
+malleability guarantees of a script we define three additional type properties: "**s**" (signed),
+"**f**" (forced) and "**e**" (expressive).
+
+The following table lists the malleability properties and requirement of each fragment.
+
+| Miniscript | Requires | Properties
+|------------------------------|---------------------------------------------------------------------|-----------
+| `0` | | s, e
+| `1` | | f
+| `pk_k(key)` | | s, e
+| `pk_h(key)` | | s, e
+| `older(n)` | | f
+| `after(n)` | | f
+| `sha256(h)` | |
+| `ripemd160(h)` | |
+| `hash256(h)` | |
+| `hash160(h)` | |
+| `andor(X,Y,Z)` | eX and (sX or sY or sZ) | s=sZ and (sX or sY); f=fZ and (sX or fY); e=eZ and (sX or fY)
+| `and_v(X,Y)` | | s=sX or sY; f=sX or fY
+| `and_b(X,Y)` | | s=sX or sY; f=fXfY or sXfX or sYfY; e=eXeYsXsY
+| `or_b(X,Z)` | eXeZ and (sX or sZ) | s=sXsZ; e
+| `or_c(X,Z)` | eX and (sX or sZ) | s=sXsZ; f
+| `or_d(X,Z)` | eX and (sX or sZ) | s=sXsZ; f=fZ; e=eZ
+| `or_i(X,Z)` | sX or sZ | s=sXsZ; f=fXfZ; e=eXfZ or eZfX
+| `thresh(k,X_1,...,X_n)` | all are e; at most k are non-s | s=at most k-1 are non-s; e=all are s
+| `multi(k,key_1,...,key_n)` | | s; e
+| `multi_a(k,key_1,...,key_n)` | | s; e
+| `a:X` | | s=sX; f=fX; e=eX
+| `s:X` | | s=sX; f=fX; e=eX
+| `c:X` | | s; f=fX; e=eX
+| `d:X` | | s=sX; e
+| `v:X` | | s=sX; f
+| `j:X` | | s=sX; e=fX
+| `n:X` | | s=sX; f=fX; e=eX
+
+### Satisfaction
+
+The following table shows all valid satisfactions and dissatisfactions for every Miniscript, using
+satisfactions and dissatisfactions of its subexpressions. Multiple possibilities are separated by
+semicolons. Some options are inefficient and provably unnecessary to the satisfaction algorithm
+described below, but are valid according to script rules and could be used by a malleator or other
+non-standard actor. These are called *non-canonical* options, and are listed for completeness, but
+~~[struckthrough]~~. The fragments where a satisfaction or dissatisfaction does not exist will
+contain *(none)*. The fragments where the satisfaction or dissatisfaction is to provide no data
+will contain *(empty)*.
+
+| Miniscript | Dissatisfactions (dsat) | Satisfactions (sat)
+|------------------------------|---------------------------------------------------------|--------------------
+| `0` | *(empty)* | *(none)*
+| `1` | *(none)* | *(empty)*
+| `pk_k(key)` | 0 | sig
+| `pk_h(key)` | 0 key | sig key
+| `older(n)` | *(none)* | *(empty)*
+| `after(n)` | *(none)* | *(empty)*
+| `sha256(h)` | any 32-byte vector except the preimage | preimage
+| `ripemd160(h)` | any 32-byte vector except the preimage | preimage
+| `hash256(h)` | any 32-byte vector except the preimage | preimage
+| `hash160(h)` | any 32-byte vector except the preimage | preimage
+| `andor(X,Y,Z)` | dsat(Z) dsat(X); ~~[dsat(Y) sat(X)]~~ | sat(Y) sat(X); sat(Z) dsat(X)
+| `and_v(X,Y)` | *(none)*; ~~[dsat(Y) sat(X)]~~ | sat(Y) sat(X)
+| `and_b(X,Y)` | dsat(Y) dsat(X); ~~[sat(Y) dsat(X)]; [dsat(Y) sat(X)]~~ | sat(Y) sat(X)
+| `or_b(X,Z)` | dsat(Z) dsat(X) | dsat(Z) sat(X); sat(Z) dsat(X); ~~[sat(Z) sat(X)]~~
+| `or_c(X,Z)` | *(none)* | sat(X); sat(Z) dsat(X)
+| `or_d(X,Z)` | dsat(Z) dsat(X) | sat(X); sat(Z) dsat(X)
+| `or_i(X,Z)` | dsat(X) 1; dsat(Z) 0 | sat(X) 1; sat(Z) 0
+| `thresh(k,X_1,...,X_n)` | All dsats; ~~[Sats/dsats with 1 ≤ #(sats) ≠ k]~~ | Sats/dsats with #(sats) = k
+| `multi(k,key_1,...,key_n)` | 0 0 ... 0 (k+1 times) | 0 sig ... sig
+| `multi_a(k,key_1,...,key_n)` | 0 ... 0 (n times); ~~[sig/0 with #(sig) ≠ k]~~ | sig/0 with #(sig) = k and #(sigs/0) = n
+| `a:X` | dsat(X) | sat(X)
+| `s:X` | dsat(X) | sat(X)
+| `c:X` | dsat(X) | sat(X)
+| `d:X` | 0 | sat(X) 1
+| `v:X` | *(none)* | sat(X)
+| `j:X` | 0; ~~[dsat(X) (if nonzero top stack)]~~ | sat(X)
+| `n:X` | dsat(X) | sat(X)
+
+#### Non-malleable Satisfaction Algorithm
+
+In order to produce non-malleable satisfactions we make use of a function that returns the optimal
+satisfaction and dissatisfaction for a given expression (if any exist), or a special DONTUSE ("don't use") value,
+together with an optional HASSIG ("has signature") marker that tracks whether the solution contains at least one
+signature. To implement the function:
+* Invoke the function recursively for all subexpressions, obtaining all their satisfactions/dissatisfactions.
+* Iterate over all the valid satisfactions/dissatisfactions in the table above (including the non-canonical ones), taking into account:
+ * The dissatisfactions for `sha256`, `ripemd160`, `hash256`, and `hash160` are always malleable, so instead use DONTUSE there.
+ * The non-canonical options for `and_b`, `or_b`, and `thresh` are always overcomplete, so instead use DONTUSE there as well (with HASSIG flag if the original non-canonical solution had one).
+ * The satisfactions for `pk_k`, `pk_h`, and `multi` can be marked HASSIG.
+ * When constructing solutions by combining results for subexpressions, the result is DONTUSE if any of the constituent results is DONTUSE. Furthermore, the result gets the HASSIG tag if any of the constituents does.
+* If among all valid solutions (including DONTUSE ones) more than one does not have the HASSIG marker, return DONTUSE.
+* If instead exactly one does not have the HASSIG marker, return that solution.
+* If all valid solutions have the HASSIG marker, but all of them are DONTUSE, return DONTUSE-HASSIG. The HASSIG marker is important because while this represents a choice between multiple options that would cause malleability if used, they are not available to the attacker, and we may be able to avoid them entirely still.
+* Otherwise, all not-DONTUSE options are valid, so return the smallest one (in terms of witness size).
+
+To produce an overall satisfaction, invoke the function on the toplevel expression. If no valid
+satisfaction is returned, or it is DONTUSE, fail. Otherwise, if any timelocking is used in the
+script but the result does not have the HASSIG flag, also fail. If the satisfaction is both not
+DONTUSE and HASSIG, return it.
+
+
+## Discussion
+
+## Security
+
+Miniscript primarily aims to provide guarantees on the correctness of a Bitcoin Script. That is, to
+guarantee **consensus soundness** and **standardness completeness**. Consensus soundness means
+it is not possible to construct a consensus-valid witness for a Bitcoin Script unless the Miniscript
+spending conditions are met. Standardness completeness means a standardness-valid witness can be
+created for all spending paths of a Miniscript, assuming the resource limits are respected and there
+is no timelock mixing.
+
+Additionally, Miniscript can guarantee the non-malleability and maximum size of a witness. These can
+assist in assessing the soundness of protocols where transaction fees (and therefore transaction
+size) are security-critical parameters.
+
+Hash preimages are constrained to 32 bytes to disallow various forms of griefing, including making
+non-standard (un-relayable) transactions, consensus-invalid swaps across blockchains, as well as
+ensure that satisfaction cost can be accurately calculated.
+
+In order for these properties to not just apply to script, but to an entire transaction, it's
+important that the witness commits to all data relevant for verification. In practice this means
+that scripts whose conditions can be met without any digital signature are insecure. Besides being
+trivially insecure, note how a transaction lacking a signature check allows an attacker to change
+its nLockTime and nSequence fields to meet additional timelock conditions.
+
+### Type System
+
+To statically verify the correctness and malleability guarantees discussed in the previous section,
+we define a type system. See the specifications above for a reference of each fragment's
+requirements and properties. Here we give more information about each type.
+
+Every expression has one of four basic types:
+* "**B**" Base expressions. These take their inputs from the top of the stack. When satisfied, they push a nonzero value of up to 4 bytes onto the stack. When dissatisfied, they push an exact 0 onto the stack (if dissatisfaction without aborting is possible at all). This type is used for most expressions, and required for the top level expression. An example is `older(n)` = ` CHECKSEQUENCEVERIFY`.
+* "**V**" Verify expressions. Like "B", these take their inputs from the top of the stack. Upon satisfaction however, they continue without pushing anything. They cannot be dissatisfied (will abort instead). A "V" can be obtained using the `v:` wrapper on a "B" expression, or by combining other "V" expressions using `and_v`, `or_i`, `or_c`, or `andor`. An example is `v:pk(key)` = ` CHECKSIGVERIFY`.
+* "**K**" Key expressions. They again take their inputs from the top of the stack, but instead of verifying a condition directly they always push a public key onto the stack, for which a signature is still required to satisfy the expression. A "K" can be converted into a "B" using the `c:` wrapper. An example is `pk_h(key)` = `DUP HASH160 EQUALVERIFY`.
+* "**W**" Wrapped expressions. They take their inputs from one below the top of the stack, and push a nonzero (in case of satisfaction) or zero (in case of dissatisfaction) either on top of the stack, or one below. So for example a 3-input "W" would take the stack "A B C D E F" and turn it into "A B F 0" or "A B 0 F" in case of dissatisfaction, and "A B F n" or "A B n F" in case of satisfaction (with n a nonzero value). Every "W" is either `s:B` (SWAP B) or `a:B` (TOALTSTACK B FROMALTSTACK). An example is `s:pk(key)` = `SWAP CHECKSIG`.
+
+Then there are 6 type modifiers, which guarantee additional properties:
+* "**z**" Zero-arg: this expression always consumes exactly 0 stack elements.
+* "**o**" One-arg: this expression always consumes exactly 1 stack element.
+* "**n**" Nonzero: this expression always consumes at least 1 stack element, no satisfaction for this expression requires the top input stack element to be zero.
+* "**d**" Dissatisfiable: a dissatisfaction for this expression can unconditionally be constructed. This implies the dissatisfaction cannot include any signature or hash preimage, and cannot rely on timelocks being satisfied.
+* "**u**" Unit: when satisfied, this expression will put an exact 1 on the stack (as opposed to any nonzero value).
+* "**k**" No timelock mixing. This expression does not contain a mix of heightlock and timelock of the same type. If the miniscript does not have the "k" property, the miniscript template will not match the user expectation of the corresponding spending policy.
+
+Finally to analyze malleability guarantees we introduce 3 new type modifiers:
+* "**s**" Signed: satisfying this expression always requires a signature (predicting whether all satisfactions will be HASSIG).
+* "**f**" Forced: dissatisfying this expression always requires a signature (predicting whether all dissatisfactions will be HASSIG).
+* "**e**" Expressive: this requires a unique unconditional dissatisfaction to exist, and forces all conditional dissatisfactions (if any) to require a signature.
+
+
+### Malleability
+
+Since Segwit, malleating a transaction no longer breaks the validity of unconfirmed descendant
+transactions. However, unintentional malleability may still have a number of much weaker undesirable
+effects. If a witness can be stuffed with additional data, the transaction's feerate will go down,
+potentially to the point where its ability to propagate and get confirmed is impacted. Additionally,
+malleability can be exploited to add roundtrips to BIP152 block propagation, by trying to get
+different miners to mine different versions of the same transaction. Finally, malleability may
+interfere with the usage of hash locks as a mechanism for publishing preimages.
+
+Using the malleability type properties it is possible to determine statically whether a script can
+be non-malleably satisfied under all circumstances. In many cases it is reasonable to only accept
+such guaranteed-non-malleable scripts, as unexpected behavior can occur when using other scripts.
+
+For example, when running the non-malleable satisfaction algorithm above, adding available
+preimages, or increasing the nLockTime/nSequence values actually may make it fail where it succeeded
+before. This is because a larger set of met conditions may mean an existing satisfaction goes from
+non-malleable to malleable. Restricting things to scripts that are guaranteed to be satisfiable in a
+non-malleable way avoids this problem.
+
+When analysing Miniscripts for resource limits, restricting yourself to just non-malleable solutions
+(or even non-malleable scripts) also leads to tighter bounds, as all non-canonical satisfactions and
+dissatisfactions can be left out of consideration.
+
+The malleability analysis makes the following assumptions:
+* The attacker does not have access to any of the private keys of public keys that participate in the Script. Participants with private keys inherently have the ability to produce different satisfactions by creating multiple signatures. While it is also interesting to study the impact rogue participants can have, we treat it as a distinct problem.
+* The attacker only has access to hash preimages that honest users have access to as well. This is a reasonable assumption because hash preimages are revealed once globally, and then available to everyone. On the other hand, making the assumption that attackers may have access to more preimages than honest users makes a large portion of scripts impossible to satisfy in a non-malleable way.
+* The attacker gets to see exactly one satisfying witness of any transaction. If he sees multiple, it becomes possible for the attacker to mix and match different satisfactions. This is very hard to reason about.
+* We restrict this analysis to scripts where no public key is repeated. If signatures constructed for one part of the script can be bound to other checks in the same script, a variant of the mixing from the previous point becomes available that is equally hard to reason about. Furthermore this situation can be avoided by using separate keys.
+* The attacker is constrained by common standardness rules. A miner may be able to malleate a witness considered non-malleable by Miniscript.
+
+#### Non-Malleable Satisfaction
+
+Malleable satisfactions or dissatisfactions appear whenever options are available to attackers distinct from the one taken by honest users. This can happen for multiple reasons:
+1. Two or more options for a satisfaction or dissatisfaction are listed in the table above which are both available to attackers directly. Regardless of which option is used in the honest solution, the attacker can change the solution to the other one.
+2. Two or more options for a satisfaction or dissatisfaction are listed in the table above, only one of which is available to attackers, but the honest solution uses another one. In that case, the attacker can modify the solution to pick the one available to him.
+3. The honest users pick a solution that contains a satisfaction which can be turned into a dissatisfaction without invalidating the overall witness. Those are called overcomplete solutions.
+
+Because we assume attackers never have access to private keys, we can treat any solution that
+includes a signature as one that is unavailable to attackers. For others, the worst case is that the
+attacker has access to every solution the honest users have, but no others: for preimages this is an
+explicit assumption, while timelock availability is determined by the nLockTime and nSequence fields
+in the transaction. As long as the overall satisfaction includes at least one signature, those
+values are fixed, and timelock availability is identical for attackers and honest users.
+
+The description of the non-malleable satisfaction algorithm can be used to show that no
+non-canonical solutions listed in the satisfaction table can occur inside non-malleable
+satisfaction:
+* Some of the non-canonical options (the `or_b`, `and_b`, and `thresh` ones) are overcomplete, and thus can clearly not appear in non-malleable satisfactions.
+* The fact that non-"d" expressions cannot be dissatisfied in valid witnesses rules out the usage of the non-canonical `and_v` dissatisfaction.
+* "d" expressions are defined to be unconditionally dissatisfiable, which implies that for those a non-HASSIG dissatisfaction must exist. Non-HASSIG solutions must be preferred over HASSIG ones (reason 2), and when multiple non-HASSIG ones exist, none can be used (reason 1). This lets us rule out the other non-canonical options in the table:
+ * `j:X` is always "d", its non-HASSIG dissatisfaction "0" always exists, and thus rules out any usage of "dsat(X)".
+ * If `andor(X,Y,Z)` is "d", a non-HASSIG dissatisfaction "dsat(Z) dsat(X)" must exist, and thus rules out any usage of "dsat(Y) sat(X)".
+ * If `and_b(X,Y)` is "d", a non-HASSIG dissatisfaction "dsat(Y) dsat(X)" must exist, and thus rules out any usage of "dsat(Y) sat(X)" and "sat(Y) dsat(X)". Those are also overcomplete.
+ * `thresh(k,...)` is always "d", a non-HASSIG dissatisfaction with just dissatisfactions must exist due to typing rules, and thus rules out usage of the other dissatisfactions. They are also overcomplete.
+
+
+### Resource Limits
+
+Various types of Bitcoin Scripts have different resource limitations, either through consensus or standardness. Some of them affect otherwise valid Miniscripts:
+* In P2WSH, scripts larger than 3600 bytes are invalid by standardness. In Tapscript, scripts are implicitly bounded by the maximum size of a block (1 million virtual bytes).
+* In P2WSH, script satisfactions where the total number of non-push opcodes plus the number of keys participating in all executed `CHECKMULTISIG` is above 201 are invalid by consensus.
+* In both Tapscript and P2WSH, script satisfactions which make the stack exceed 1000 elements before or during execution are invalid.
+* In P2WSH, satisfactions with a witness consisting of over 100 stack elements (excluding the script itself) are invalid by standardness.
+
+A static analysis can be performed on a Miniscript to verify if none, all or any of the spending
+paths hit any of the limits.
+
+
+## Test Vectors
+
+TBD
+
+## Backwards Compatibility
+
+Miniscript's syntax is compatible with BIP 380 Output Script Descriptors, and should be considered
+an extension to it that provides a new type of Script expression that is only valid in
+`wsh()` and `tr()` contexts. As these are wholly new expressions, they are not
+compatible with any existing implementation of descriptors. Additionally, the scripts produced are
+unlikely to be standard scripts.
+
+The `pk()`, `pkh()`, `multi()`, and `multi_a()`
+fragments overlap with existing descriptors. These parse to the same semantic meanings as those
+descriptors and produce the same scripts.
+
+## Reference Implementation
+
+A first reference implementation and documentation for Miniscript in P2WSH was originally published at
+https://github.com/sipa/miniscript .
+
+The reference implementation for Miniscript in P2WSH was introduced in Bitcoin Core through PRs
+[24147](https://github.com/bitcoin/bitcoin/pull/24147), [24148](https://github.com/bitcoin/bitcoin/pull/24148), and
+[24149](https://github.com/bitcoin/bitcoin/pull/24149). The last one to be merged was released in Bitcoin
+Core version 25.0.
+
+The reference implementation for Miniscript in Tapscript was introduced in Bitcoin Core in PR
+[27255](https://github.com/bitcoin/bitcoin/pull/27255). This PR was merged and released in Bitcoin Core
+version 26.0.
diff --git a/bip-0380.mediawiki b/bip-0380.mediawiki
new file mode 100644
index 0000000000..eea5ce144e
--- /dev/null
+++ b/bip-0380.mediawiki
@@ -0,0 +1,338 @@
+
+
+==Abstract==
+
+Output Script Descriptors are a simple language which can be used to describe collections of output scripts.
+There can be many different descriptor fragments and functions.
+This document describes the general syntax for descriptors, descriptor checksums, and common expressions.
+
+==Copyright==
+
+This BIP is licensed under the BSD 2-clause license.
+
+==Motivation==
+
+Bitcoin wallets traditionally have stored a set of keys which are later serialized and mutated to produce the output scripts that the wallet watches and the addresses it provides to users.
+Typically backups have consisted of solely the private keys, nowadays primarily in the form of BIP 39 mnemonics.
+However this backup solution is insufficient, especially since the introduction of Segregated Witness which added new output types.
+Given just the private keys, it is not possible for restored wallets to know which kinds of output scripts and addresses to produce.
+This has lead to incompatibilities between wallets when restoring a backup or exporting data for a watch only wallet.
+
+Further complicating matters are BIP 32 derivation paths.
+Although BIPs 44, 49, and 84 have specified standard BIP 32 derivation paths for different output scripts and addresses, not all wallets support them nor use those derivation paths.
+The lack of derivation path information in these backups and exports leads to further incompatibilities between wallets.
+
+Current solutions to these issues have not been generic and can be viewed as being layer violations.
+Solutions such as introducing different version bytes for extended key serialization both are a layer violation (key derivation should be separate from script type meaning) and specific only to a particular derivation path and script type.
+
+Output Script Descriptors introduces a generic solution to these issues.
+Script types are specified explicitly through the use of Script Expressions.
+Key derivation paths are specified explicitly in Key Expressions.
+These allow for creating wallet backups and exports which specify the exact scripts, subscripts (redeemScript, witnessScript, etc.), and keys to produce.
+With the general structure specified in this BIP, new Script Expressions can be introduced as new script types are added.
+Lastly, the use of common terminology and existing standards allow for Output Script Descriptors to be engineer readable so that the results can be understood at a glance.
+
+==Specification==
+
+Descriptors consist of several types of expressions.
+The top level expression is a SCRIPT.
+This expression may be followed by #CHECKSUM, where CHECKSUM is an 8 character alphanumeric descriptor checksum.
+Although the checksum is optional for parsing, applications may choose to reject descriptors that do not contain a checksum.
+
+===Script Expressions===
+
+Script Expressions (denoted SCRIPT) are expressions which correspond directly with a Bitcoin script.
+These expressions are written as functions and take arguments.
+Such expressions have a script template which is filled with the arguments correspondingly.
+Expressions are written with a human readable identifier string with the arguments enclosed with parentheses.
+The identifier string should be alphanumeric and may include underscores.
+
+The arguments to a script expression are defined by that expression itself.
+They could be a script expression, a key expression, or some other expression entirely.
+
+===Key Expressions===
+
+A common expression used as an argument to script expressions are key expressions (denoted KEY).
+These represent a public or private key and, optionally, information about the origin of that key.
+Key expressions can only be used as arguments to script expressions.
+
+Key expressions consist of:
+* Optionally, key origin information, consisting of:
+** An open bracket [
+** Exactly 8 hex characters for the fingerprint of the key where the derivation starts (see BIP 32 for details)
+** Followed by zero or more /NUM or /NUMh path elements to indicate the unhardened or hardened derivation steps between the fingerprint and the key that follows.
+** A closing bracket ]
+* Followed by the actual key, which is either:
+** A hex encoded public key, which depending the script expression, may be either:
+*** 66 hex character string beginning with 02 or 03 representing a compressed public key
+*** 130 hex character string beginning with 04 representing an uncompressed public key
+** A [[https://en.bitcoin.it/wiki/Wallet_import_format|WIF]] encoded private key
+** xpub encoded extended public key or xprv encoded extended private key (as defined in BIP 32)
+*** Followed by zero or more /NUM or /NUMh path elements indicating BIP 32 derivation steps to be taken after the given extended key.
+*** Optionally followed by a single /* or /*h final step to denote all direct unhardened or hardened children.
+
+If the KEY is a BIP 32 extended key, before output scripts can be created, child keys must be derived using the derivation information that follows the extended key.
+When the final step is /* or /*', an output script will be produced for every child key index.
+The derived key must be not be serialized as an uncompressed public key.
+Script Expressions may have further requirements on how derived public keys are serialized for script creation.
+
+In the above specification, the hardened indicator h may be replaced with alternative hardened indicators of H or '.
+
+====Normalization of Key Expressions with Hardened Derivation====
+
+When a descriptor is exported without private keys, it is necessary to do additional derivation to remove any intermediate hardened derivation steps for the exported descriptor to be useful.
+The exporter should derive the extended public key at the last hardened derivation step and use that extended public key as the key in the descriptor.
+The derivation steps that were taken to get to that key must be added to the previous key origin information.
+If there is no key origin information, then one must be added for the newly derived extended public key.
+If the final derivation is hardened, then it is not necessary to do additional derivation.
+
+===Character Set===
+
+The expressions used in descriptors must only contain characters within this character set so that the descriptor checksum will work.
+
+The allowed characters are:
+
+Note that on the last line is a space character.
+
+This character set is written as 3 groups of 32 characters in this specific order so that the checksum below can identify more errors.
+The first group are the most common "unprotected" characters (i.e. things such as hex and keypaths that do not already have their own checksums).
+Case errors cause an offset that is a multiple of 32 while as many alphabetic characters are in the same group while following the previous restrictions.
+
+===Checksum===
+
+Following the top level script expression is a single octothorpe (#) followed by the 8 character checksum.
+The checksum is an error correcting checksum similar to bech32.
+
+The checksum has the following properties:
+* Mistakes in a descriptor string are measured in "symbol errors". The higher the number of symbol errors, the harder it is to detect:
+** An error substituting a character from 0123456789()[],'/*abcdefgh@:$%{} for another in that set always counts as 1 symbol error.
+*** Note that hex encoded keys are covered by these characters. Extended keys (xpub and xprv) use other characters too, but also have their own checksum mechanism.
+*** SCRIPT expression function names use other characters, but mistakes in these would generally result in an unparsable descriptor.
+** A case error always counts as 1 symbol error.
+** Any other 1 character substitution error counts as 1 or 2 symbol errors.
+* Any 1 symbol error is always detected.
+* Any 2 or 3 symbol error in a descriptor of up to 49154 characters is always detected.
+* Any 4 symbol error in a descriptor of up to 507 characters is always detected.
+* Any 5 symbol error in a descriptor of up to 77 characters is always detected.
+* Is optimized to minimize the chance of a 5 symbol error in a descriptor up to 387 characters is undetected
+* Random errors have a chance of 1 in 240 of being undetected.
+
+The checksum itself uses the same character set as bech32: qpzry9x8gf2tvdw0s3jn54khce6mua7l
+
+Valid descriptor strings with a checksum must pass the criteria for validity specified by the Python3 code snippet below.
+The function descsum_check must return true when its argument s is a descriptor consisting in the form SCRIPT#CHECKSUM.
+
+
+INPUT_CHARSET = "0123456789()[],'/*abcdefgh@:$%{}IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~ijklmnopqrstuvwxyzABCDEFGH`#\"\\ "
+CHECKSUM_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
+GENERATOR = [0xf5dee51989, 0xa9fdca3312, 0x1bab10e32d, 0x3706b1677a, 0x644d626ffd]
+
+def descsum_polymod(symbols):
+ """Internal function that computes the descriptor checksum."""
+ chk = 1
+ for value in symbols:
+ top = chk >> 35
+ chk = (chk & 0x7ffffffff) << 5 ^ value
+ for i in range(5):
+ chk ^= GENERATOR[i] if ((top >> i) & 1) else 0
+ return chk
+
+def descsum_expand(s):
+ """Internal function that does the character to symbol expansion"""
+ groups = []
+ symbols = []
+ for c in s:
+ if not c in INPUT_CHARSET:
+ return None
+ v = INPUT_CHARSET.find(c)
+ symbols.append(v & 31)
+ groups.append(v >> 5)
+ if len(groups) == 3:
+ symbols.append(groups[0] * 9 + groups[1] * 3 + groups[2])
+ groups = []
+ if len(groups) == 1:
+ symbols.append(groups[0])
+ elif len(groups) == 2:
+ symbols.append(groups[0] * 3 + groups[1])
+ return symbols
+
+def descsum_check(s):
+ """Verify that the checksum is correct in a descriptor"""
+ if s[-9] != '#':
+ return False
+ if not all(x in CHECKSUM_CHARSET for x in s[-8:]):
+ return False
+ symbols = descsum_expand(s[:-9]) + [CHECKSUM_CHARSET.find(x) for x in s[-8:]]
+ return descsum_polymod(symbols) == 1
+
+
+This implements a BCH code that has the properties described above.
+The entire descriptor string is first processed into an array of symbols.
+The symbol for each character is its position within its group.
+After every 3rd symbol, a 4th symbol is inserted which represents the group numbers combined together.
+This means that a change that only affects the position within a group, or only a group number change, will only affect a single symbol.
+
+To construct a valid checksum given a script expression, the code below can be used:
+
+
+def descsum_create(s):
+ """Add a checksum to a descriptor without"""
+ symbols = descsum_expand(s) + [0, 0, 0, 0, 0, 0, 0, 0]
+ checksum = descsum_polymod(symbols) ^ 1
+ return s + '#' + ''.join(CHECKSUM_CHARSET[(checksum >> (5 * (7 - i))) & 31] for i in range(8))
+
+
+
+==Test Vectors==
+
+The following tests cover the checksum and character set:
+
+* Valid checksum: raw(deadbeef)#89f8spxm
+* No checksum: raw(deadbeef)
+* Missing checksum: raw(deadbeef)#
+* Too long checksum (9 chars): raw(deadbeef)#89f8spxmx
+* Too short checksum (7 chars): raw(deadbeef)#89f8spx
+* Error in payload: raw(deedbeef)#89f8spxm
+* Error in checksum: raw(deedbeef)##9f8spxm
+* Invalid characters in payload: raw(Ü)#00000000
+
+The following tests cover key expressions:
+
+Valid expressions:
+
+* Compressed public key: 0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600
+* Uncompressed public key: 04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235
+* Public key with key origin: [deadbeef/0h/0h/0h]0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600
+* Public key with key origin (' as hardened indicator): [deadbeef/0'/0'/0']0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600
+* Public key with key origin (mixed hardened indicator): [deadbeef/0'/0h/0']0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600
+* WIF uncompressed private key 5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss
+* WIF compressed private key L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1
+* Extended public key: xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL
+* Extended public key with key origin: [deadbeef/0h/1h/2h]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL
+* Extended public key with derivation: [deadbeef/0h/1h/2h]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/3/4/5
+* Extended public key with derivation and children: [deadbeef/0h/1h/2h]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/3/4/5/*
+* Extended public key with hardened derivation and unhardened children: xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/3h/4h/5h/*
+* Extended public key with hardened derivation and children: xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/3h/4h/5h/*h
+* Extended public key with key origin, hardened derivation and children: [deadbeef/0h/1h/2]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/3h/4h/5h/*h
+* Extended private key: xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc
+* Extended private key with key origin: [deadbeef/0h/1h/2h]xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc
+* Extended private key with derivation: [deadbeef/0h/1h/2h]xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc/3/4/5
+* Extended private key with derivation and children: [deadbeef/0h/1h/2h]xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc/3/4/5/*
+* Extended private key with hardened derivation and unhardened children: xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc/3h/4h/5h/*
+* Extended private key with hardened derivation and children: xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc/3h/4h/5h/*h
+* Extended private key with key origin, hardened derivation and children: [deadbeef/0h/1h/2]xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc/3h/4h/5h/*h
+
+Invalid expression:
+
+* Children indicator in key origin: [deadbeef/0h/0h/0h/*]0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600
+* Trailing slash in key origin: [deadbeef/0h/0h/0h/]0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600
+* Too short fingerprint: [deadbef/0h/0h/0h]0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600
+* Too long fingerprint: [deadbeeef/0h/0h/0h]0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600
+* Invalid hardened indicators: [deadbeef/0f/0f/0f]0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600
+* Invalid hardened indicators: [deadbeef/0H/0H/0H]0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600
+* Invalid hardened indicators: [deadbeef/-0/-0/-0]0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600
+* Private key with derivation: L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1/0
+* Private key with derivation children: L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1/*
+* Derivation index out of range: xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/2147483648
+* Invalid derivation index: xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/1aa
+* Multiple key origins: [aaaaaaaa][aaaaaaaa]xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/2147483647'/0
+* Missing key origin start: aaaaaaaa]xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/2147483647'/0
+* Non hex fingerprint: [gaaaaaaa]xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/2147483647'/0
+* Key origin with no public key: [deadbeef]
+
+==Backwards Compatibility==
+
+Output script descriptors are an entirely new language which is not compatible with any existing software.
+However many components of the expressions reuse encodings and serializations defined by previous BIPs.
+
+Output script descriptors are designed for future extension with further fragment types and new script expressions.
+These will be specified in additional BIPs.
+
+==Reference Implementation==
+
+Descriptors have been implemented in Bitcoin Core since version 0.17.
+
+==Appendix A: Index of Expressions==
+
+Future BIPs may specify additional types of expressions.
+All available expression types are listed in this table.
+
+{|
+! Name
+! Denoted As
+! BIP
+|-
+| Script
+| SCRIPT
+| 380
+|-
+| Key
+| KEY
+| 380
+|-
+| Tree
+| TREE
+| [[bip-0386.mediawiki|386]]
+|}
+
+==Appendix B: Index of Script Expressions==
+
+Script expressions will be specified in additional BIPs.
+This Table lists all available Script expressions and the BIPs specifying them.
+
+{|
+! Expression
+! BIP
+|-
+| pk(KEY)
+| [[bip-0381.mediawiki|381]]
+|-
+| pkh(KEY)
+| [[bip-0381.mediawiki|381]]
+|-
+| sh(SCRIPT)
+| [[bip-0381.mediawiki|381]]
+|-
+| wpkh(KEY)
+| [[bip-0382.mediawiki|382]]
+|-
+| wsh(SCRIPT)
+| [[bip-0382.mediawiki|382]]
+|-
+| multi(NUM, KEY, ..., KEY)
+| [[bip-0383.mediawiki|383]]
+|-
+| sortedmulti(NUM, KEY, ..., KEY)
+| [[bip-0383.mediawiki|383]]
+|-
+| combo(KEY)
+| [[bip-0384.mediawiki|384]]
+|-
+| raw(HEX)
+| [[bip-0385.mediawiki|385]]
+|-
+| addr(ADDR)
+| [[bip-0385.mediawiki|385]]
+|-
+| tr(KEY), tr(KEY, TREE)
+| [[bip-0386.mediawiki|386]]
+|-
+| musig(KEY, KEY, ..., KEY)
+| [[bip-0390.mediawiki|390]]
+|}
diff --git a/bip-0381.mediawiki b/bip-0381.mediawiki
new file mode 100644
index 0000000000..8d12c7a4d8
--- /dev/null
+++ b/bip-0381.mediawiki
@@ -0,0 +1,125 @@
+
+
+==Abstract==
+
+This document specifies pk(), pkh(), and sh() output script descriptors.
+pk() descriptors take a key and produces a P2PK output script.
+pkh() descriptors take a key and produces a P2PKH output script.
+sh() descriptors take a script and produces a P2SH output script.
+
+==Copyright==
+
+This BIP is licensed under the BSD 2-clause license.
+
+==Motivation==
+
+Prior to the activation of Segregated Witness, there were 3 main standard output script formats: P2PK, P2PKH, and P2SH.
+These expressions allow specifying those formats as a descriptor.
+
+==Specification==
+
+Three new script expressions are defined: pk(), pkh(), and sh().
+
+===pk()===
+
+The pk(KEY) expression can be used in any context or level of a descriptor.
+It takes a single key expression as an argument and produces a P2PK output script.
+Depending on the higher level descriptors, there may be restrictions on the type of public keys that can be included.
+Such restrictions will be specified by those descriptors.
+
+The output script produced is:
+
+ OP_CHECKSIG
+
+
+===pkh()===
+
+The pkh(KEY) expression can be used as a top level expression, or inside of either a sh() or wsh() descriptor.
+It takes a single key expression as an argument and produces a P2PKH output script.
+Depending on the higher level descriptors, there may be restrictions on the type of public keys that can be included.
+Such restrictions will be specified by those descriptors.
+
+The output script produced is:
+
+OP_DUP OP_HASH160 OP_EQUALVERIFY OP_CHECKSIG
+
+
+===sh()===
+
+The sh(SCRIPT) expression can only be used as a top level expression.
+It takes a single script expression as an argument and produces a P2SH output script.
+sh() expressions also create a redeemScript which is required in order to spend outputs which use its output script.
+This redeemScript is the output script produced by the SCRIPT argument to sh().
+
+The output script produced is:
+
+OP_HASH160 OP_EQUAL
+
+
+==Test Vectors==
+
+Valid descriptors followed by the scripts they produce. Descriptors involving derived child keys will have the 0th, 1st, and 2nd scripts listed.
+
+* pk(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)
+** 2103a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bdac
+* pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)
+** 2103a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bdac
+* pkh([deadbeef/1/2'/3/4']L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)
+** 76a9149a1c78a507689f6f54b847ad1cef1e614ee23f1e88ac
+* pkh([deadbeef/1/2'/3/4']03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)
+** 76a9149a1c78a507689f6f54b847ad1cef1e614ee23f1e88ac
+* pkh([deadbeef/1/2h/3/4h]03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)
+** 76a9149a1c78a507689f6f54b847ad1cef1e614ee23f1e88ac
+* pk(5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)
+** 4104a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235ac
+* pk(04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)
+** 4104a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235ac
+* pkh(5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)
+** 76a914b5bd079c4d57cc7fc28ecf8213a6b791625b818388ac
+* pkh(04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)
+** 76a914b5bd079c4d57cc7fc28ecf8213a6b791625b818388ac
+* sh(pk(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))
+** a9141857af51a5e516552b3086430fd8ce55f7c1a52487
+* sh(pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))
+** a9141857af51a5e516552b3086430fd8ce55f7c1a52487
+* sh(pkh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))
+** a9141a31ad23bf49c247dd531a623c2ef57da3c400c587
+* sh(pkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))
+** a9141a31ad23bf49c247dd531a623c2ef57da3c400c587
+* pkh(xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/2147483647'/0)
+** 76a914ebdc90806a9c4356c1c88e42216611e1cb4c1c1788ac
+* pkh([bd16bee5/2147483647h]xpub69H7F5dQzmVd3vPuLKtcXJziMEQByuDidnX3YdwgtNsecY5HRGtAAQC5mXTt4dsv9RzyjgDjAQs9VGVV6ydYCHnprc9vvaA5YtqWyL6hyds/0)
+** 76a914ebdc90806a9c4356c1c88e42216611e1cb4c1c1788ac
+* pk(xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L/0)
+** 210379e45b3cf75f9c5f9befd8e9506fb962f6a9d185ac87001ec44a8d3df8d4a9e3ac
+* pk(xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/0)
+** 210379e45b3cf75f9c5f9befd8e9506fb962f6a9d185ac87001ec44a8d3df8d4a9e3ac
+
+Invalid descriptors
+
+* pk() only accepts key expressions: pk(pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))
+* pkh() only accepts key expressions: pkh(pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))
+* sh() only acceps script expressions: sh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)
+* sh() is top level only: sh(sh(pkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)))
+
+==Backwards Compatibility==
+
+pk(), pkh(), and sh() descriptors use the format and general operation specified in [[bip-0380.mediawiki|380]].
+As these are a wholly new descriptors, they are not compatible with any implementation.
+However the scripts produced are standard scripts so existing software are likely to be familiar with them.
+
+==Reference Implementation==
+
+pk(), pkh(), and sh() descriptors have been implemented in Bitcoin Core since version 0.17.
diff --git a/bip-0382.mediawiki b/bip-0382.mediawiki
new file mode 100644
index 0000000000..261b7e31b4
--- /dev/null
+++ b/bip-0382.mediawiki
@@ -0,0 +1,115 @@
+
+
+==Abstract==
+
+This document specifies wpkh(), and wsh() output script descriptors.
+wpkh() descriptors take a key and produces a P2WPKH output script.
+wsh() descriptors take a script and produces a P2WSH output script.
+
+==Copyright==
+
+This BIP is licensed under the BSD 2-clause license.
+
+==Motivation==
+
+Segregated Witness added 2 additional standard output script formats: P2WPKH and P2WSH.
+These expressions allow specifying those formats as a descriptor.
+
+==Specification==
+
+Two new script expressions are defined: wpkh(), and wsh().
+
+===wpkh()===
+
+The wpkh(KEY) expression can be used as a top level expression, or inside of a sh() descriptor.
+It takes a single key expression as an argument and produces a P2WPKH output script.
+Only keys which are/has compressed public keys can be contained in a wpkh() expression.
+
+The output script produced is:
+
+OP_0
+
+
+===wsh()===
+
+The wsh(SCRIPT) expression can be used as a top level expression, or inside of a sh() descriptor.
+It takes a single script expression as an argument and produces a P2WSH output script.
+wsh() expressions also create a witnessScript which is required in order to spend outputs which use its output script.
+This redeemScript is the output script produced by the SCRIPT argument to wsh().
+Any key expression found in any script expression contained by a wsh() expression must only produce compressed public keys.
+
+The output script produced is:
+
+OP_0
+
+
+==Test Vectors==
+
+Valid descriptors followed by the scripts they produce. Descriptors involving derived child keys will have the 0th, 1st, and 2nd scripts listed.
+
+* wpkh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)
+** 00149a1c78a507689f6f54b847ad1cef1e614ee23f1e
+* wpkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)
+** 00149a1c78a507689f6f54b847ad1cef1e614ee23f1e
+* wpkh([ffffffff/13']xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt/1/2/0)
+** 0014326b2249e3a25d5dc60935f044ee835d090ba859
+* wpkh([ffffffff/13']xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH/1/2/*)
+** 0014326b2249e3a25d5dc60935f044ee835d090ba859
+** 0014af0bd98abc2f2cae66e36896a39ffe2d32984fb7
+** 00141fa798efd1cbf95cebf912c031b8a4a6e9fb9f27
+* sh(wpkh(xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi/10/20/30/40/*'))
+** a9149a4d9901d6af519b2a23d4a2f51650fcba87ce7b87
+** a914bed59fc0024fae941d6e20a3b44a109ae740129287
+** a9148483aa1116eb9c05c482a72bada4b1db24af654387
+* sh(wpkh(xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi/10/20/30/40/*h))
+** a9149a4d9901d6af519b2a23d4a2f51650fcba87ce7b87
+** a914bed59fc0024fae941d6e20a3b44a109ae740129287
+** a9148483aa1116eb9c05c482a72bada4b1db24af654387
+* wsh(pkh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))
+** 0020338e023079b91c58571b20e602d7805fb808c22473cbc391a41b1bd3a192e75b
+* wsh(pkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))
+** 0020338e023079b91c58571b20e602d7805fb808c22473cbc391a41b1bd3a192e75b
+* wsh(pk(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))
+** 00202e271faa2325c199d25d22e1ead982e45b64eeb4f31e73dbdf41bd4b5fec23fa
+* wsh(pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))
+** 00202e271faa2325c199d25d22e1ead982e45b64eeb4f31e73dbdf41bd4b5fec23fa
+* sh(wsh(pkh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)))
+** a914b61b92e2ca21bac1e72a3ab859a742982bea960a87
+* sh(wsh(pkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)))
+** a914b61b92e2ca21bac1e72a3ab859a742982bea960a87
+
+Invalid descriptors with descriptions
+
+* Uncompressed public key in wpkh(): wpkh(5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)
+* Uncompressed public key in wpkh(): sh(wpkh(5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss))
+* Uncompressed public key in wpkh(): wpkh(04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)
+* Uncompressed public key in wpkh(): sh(wpkh(04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235))
+* Uncompressed public keys under wsh(): wsh(pk(5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss))
+* Uncompressed public keys under wsh(): wsh(pk(04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235))
+* wpkh() nested in wsh(): wsh(wpkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))
+* wsh() nested in wsh(): wsh(wsh(pkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)))
+* wsh() nested in wsh(): sh(wsh(wsh(pkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))))
+* Script in wpkh(): wpkh(wsh(pkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)))
+* Key in wsh(): wsh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)
+
+==Backwards Compatibility==
+
+wpkh(), and wsh() descriptors use the format and general operation specified in [[bip-0380.mediawiki|380]].
+As these are a wholly new descriptors, they are not compatible with any implementation.
+However the scripts produced are standard scripts so existing software are likely to be familiar with them.
+
+==Reference Implementation==
+
+wpkh(), and wsh() descriptors have been implemented in Bitcoin Core since version 0.17.
diff --git a/bip-0383.mediawiki b/bip-0383.mediawiki
new file mode 100644
index 0000000000..522eb0cc72
--- /dev/null
+++ b/bip-0383.mediawiki
@@ -0,0 +1,108 @@
+
+
+==Abstract==
+
+This document specifies multi(), and sortedmulti() output script descriptors.
+Both functions take a threshold and one or more public keys and produce a multisig output script.
+multi() specifies the public keys in the output script in the order given in the descriptor while sortedmulti() sorts the public keys lexicographically when the output script is produced.
+
+==Copyright==
+
+This BIP is licensed under the BSD 2-clause license.
+
+==Motivation==
+
+The most common complex script used in Bitcoin is a threshold multisig.
+These expressions allow specifying multisig scripts as a descriptor.
+
+==Specification==
+
+Two new script expressions are defined: multi(), and sortedmulti().
+Both expressions produce the scripts of the same template and take the same arguments.
+They are written as multi(k,KEY_1,KEY_2,...,KEY_n).
+k is the threshold - the number of keys that must sign the input for the script to be valid.
+KEY_1,KEY_2,...,KEY_n are the key expressions for the multisig. k must be less than or equal to n.
+
+multi() and sortedmulti() expressions can be used as a top level expression, or inside of either a sh() or wsh() descriptor.
+Depending on the higher level descriptors, there may be restrictions on the type of public keys that can be included.
+
+Depending on the higher level descriptors, there are also restrictions on the number of keys that can be present, i.e. the maximum value of n.
+When used at the top level, there can only be at most 3 keys.
+When used inside of a sh() expression, there can only be most 15 compressed public keys (this is limited by the P2SH script limit).
+Otherwise the maximum number of keys is 20.
+
+The output script produced also depends on the value of k. If k is less than or equal to 16:
+
+OP_k KEY_1 KEY_2 ... KEY_n OP_CHECKMULTISIG
+
+
+if k is greater than 16:
+
+k KEY_1 KEY_2 ... KEY_n OP_CHECKMULTISIG
+
+
+===sortedmulti()===
+
+The only change for sortedmulti() is that the keys are sorted lexicographically prior to the creation of the output script.
+This sorting is on the keys that are to be put into the output script, i.e. after all extended keys are derived.
+
+===Multiple Extended Keys
===
+
+When one or more the key expressions in a multi() or sortedmulti() expression are extended keys, the derived keys use the same child index.
+This changes the keys in lockstep and allows for output scripts to be indexed in the same way that the derived keys are indexed.
+
+==Test Vectors==
+
+Valid descriptors followed by the scripts they produce. Descriptors involving derived child keys will have the 0th, 1st, and 2nd scripts listed.
+
+* multi(1,L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1,5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)
+** 512103a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd4104a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea23552ae
+* multi(1,03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd,04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)
+** 512103a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd4104a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea23552ae
+* sortedmulti(1,04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235,03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)
+** 512103a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd4104a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea23552ae
+* sh(multi(2,[00000000/111'/222]xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc,xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L/0))
+** a91445a9a622a8b0a1269944be477640eedc447bbd8487
+* sortedmulti(2,xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/*,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/0/0/*)
+** 5221025d5fc65ebb8d44a5274b53bac21ff8307fec2334a32df05553459f8b1f7fe1b62102fbd47cc8034098f0e6a94c6aeee8528abf0a2153a5d8e46d325b7284c046784652ae
+** 52210264fd4d1f5dea8ded94c61e9641309349b62f27fbffe807291f664e286bfbe6472103f4ece6dfccfa37b211eb3d0af4d0c61dba9ef698622dc17eecdf764beeb005a652ae
+** 5221022ccabda84c30bad578b13c89eb3b9544ce149787e5b538175b1d1ba259cbb83321024d902e1a2fc7a8755ab5b694c575fce742c48d9ff192e63df5193e4c7afe1f9c52ae
+* wsh(multi(2,xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/2147483647'/0,xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt/1/2/*,xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi/10/20/30/40/*'))
+** 0020b92623201f3bb7c3771d45b2ad1d0351ea8fbf8cfe0a0e570264e1075fa1948f
+** 002036a08bbe4923af41cf4316817c93b8d37e2f635dd25cfff06bd50df6ae7ea203
+** 0020a96e7ab4607ca6b261bfe3245ffda9c746b28d3f59e83d34820ec0e2b36c139c
+* sh(wsh(multi(16,03669b8afcec803a0d323e9a17f3ea8e68e8abe5a278020a929adbec52421adbd0,0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600,0362a74e399c39ed5593852a30147f2959b56bb827dfa3e60e464b02ccf87dc5e8,0261345b53de74a4d721ef877c255429961b7e43714171ac06168d7e08c542a8b8,02da72e8b46901a65d4374fe6315538d8f368557dda3a1dcf9ea903f3afe7314c8,0318c82dd0b53fd3a932d16e0ba9e278fcc937c582d5781be626ff16e201f72286,0297ccef1ef99f9d73dec9ad37476ddb232f1238aff877af19e72ba04493361009,02e502cfd5c3f972fe9a3e2a18827820638f96b6f347e54d63deb839011fd5765d,03e687710f0e3ebe81c1037074da939d409c0025f17eb86adb9427d28f0f7ae0e9,02c04d3a5274952acdbc76987f3184b346a483d43be40874624b29e3692c1df5af,02ed06e0f418b5b43a7ec01d1d7d27290fa15f75771cb69b642a51471c29c84acd,036d46073cbb9ffee90473f3da429abc8de7f8751199da44485682a989a4bebb24,02f5d1ff7c9029a80a4e36b9a5497027ef7f3e73384a4a94fbfe7c4e9164eec8bc,02e41deffd1b7cce11cde209a781adcffdabd1b91c0ba0375857a2bfd9302419f3,02d76625f7956a7fc505ab02556c23ee72d832f1bac391bcd2d3abce5710a13d06,0399eb0a5487515802dc14544cf10b3666623762fbed2ec38a3975716e2c29c232)))
+** a9147fc63e13dc25e8a95a3cee3d9a714ac3afd96f1e87
+* wsh(multi(20,KzoAz5CanayRKex3fSLQ2BwJpN7U52gZvxMyk78nDMHuqrUxuSJy,KwGNz6YCCQtYvFzMtrC6D3tKTKdBBboMrLTsjr2NYVBwapCkn7Mr,KxogYhiNfwxuswvXV66eFyKcCpm7dZ7TqHVqujHAVUjJxyivxQ9X,L2BUNduTSyZwZjwNHynQTF14mv2uz2NRq5n5sYWTb4FkkmqgEE9f,L1okJGHGn1kFjdXHKxXjwVVtmCMR2JA5QsbKCSpSb7ReQjezKeoD,KxDCNSST75HFPaW5QKpzHtAyaCQC7p9Vo3FYfi2u4dXD1vgMiboK,L5edQjFtnkcf5UWURn6UuuoFrabgDQUHdheKCziwN42aLwS3KizU,KzF8UWFcEC7BYTq8Go1xVimMkDmyNYVmXV5PV7RuDicvAocoPB8i,L3nHUboKG2w4VSJ5jYZ5CBM97oeK6YuKvfZxrefdShECcjEYKMWZ,KyjHo36dWkYhimKmVVmQTq3gERv3pnqA4xFCpvUgbGDJad7eS8WE,KwsfyHKRUTZPQtysN7M3tZ4GXTnuov5XRgjdF2XCG8faAPmFruRF,KzCUbGhN9LJhdeFfL9zQgTJMjqxdBKEekRGZX24hXdgCNCijkkap,KzgpMBwwsDLwkaC5UrmBgCYaBD2WgZ7PBoGYXR8KT7gCA9UTN5a3,KyBXTPy4T7YG4q9tcAM3LkvfRpD1ybHMvcJ2ehaWXaSqeGUxEdkP,KzJDe9iwJRPtKP2F2AoN6zBgzS7uiuAwhWCfGdNeYJ3PC1HNJ8M8,L1xbHrxynrqLKkoYc4qtoQPx6uy5qYXR5ZDYVYBSRmCV5piU3JG9,KzRedjSwMggebB3VufhbzpYJnvHfHe9kPJSjCU5QpJdAW3NSZxYS,Kyjtp5858xL7JfeV4PNRCKy2t6XvgqNNepArGY9F9F1SSPqNEMs3,L2D4RLHPiHBidkHS8ftx11jJk1hGFELvxh8LoxNQheaGT58dKenW,KyLPZdwY4td98bKkXqEXTEBX3vwEYTQo1yyLjX2jKXA63GBpmSjv))
+** 0020376bd8344b8b6ebe504ff85ef743eaa1aa9272178223bcb6887e9378efb341ac
+* sh(wsh(multi(20,KzoAz5CanayRKex3fSLQ2BwJpN7U52gZvxMyk78nDMHuqrUxuSJy,KwGNz6YCCQtYvFzMtrC6D3tKTKdBBboMrLTsjr2NYVBwapCkn7Mr,KxogYhiNfwxuswvXV66eFyKcCpm7dZ7TqHVqujHAVUjJxyivxQ9X,L2BUNduTSyZwZjwNHynQTF14mv2uz2NRq5n5sYWTb4FkkmqgEE9f,L1okJGHGn1kFjdXHKxXjwVVtmCMR2JA5QsbKCSpSb7ReQjezKeoD,KxDCNSST75HFPaW5QKpzHtAyaCQC7p9Vo3FYfi2u4dXD1vgMiboK,L5edQjFtnkcf5UWURn6UuuoFrabgDQUHdheKCziwN42aLwS3KizU,KzF8UWFcEC7BYTq8Go1xVimMkDmyNYVmXV5PV7RuDicvAocoPB8i,L3nHUboKG2w4VSJ5jYZ5CBM97oeK6YuKvfZxrefdShECcjEYKMWZ,KyjHo36dWkYhimKmVVmQTq3gERv3pnqA4xFCpvUgbGDJad7eS8WE,KwsfyHKRUTZPQtysN7M3tZ4GXTnuov5XRgjdF2XCG8faAPmFruRF,KzCUbGhN9LJhdeFfL9zQgTJMjqxdBKEekRGZX24hXdgCNCijkkap,KzgpMBwwsDLwkaC5UrmBgCYaBD2WgZ7PBoGYXR8KT7gCA9UTN5a3,KyBXTPy4T7YG4q9tcAM3LkvfRpD1ybHMvcJ2ehaWXaSqeGUxEdkP,KzJDe9iwJRPtKP2F2AoN6zBgzS7uiuAwhWCfGdNeYJ3PC1HNJ8M8,L1xbHrxynrqLKkoYc4qtoQPx6uy5qYXR5ZDYVYBSRmCV5piU3JG9,KzRedjSwMggebB3VufhbzpYJnvHfHe9kPJSjCU5QpJdAW3NSZxYS,Kyjtp5858xL7JfeV4PNRCKy2t6XvgqNNepArGY9F9F1SSPqNEMs3,L2D4RLHPiHBidkHS8ftx11jJk1hGFELvxh8LoxNQheaGT58dKenW,KyLPZdwY4td98bKkXqEXTEBX3vwEYTQo1yyLjX2jKXA63GBpmSjv)))
+** a914c2c9c510e9d7f92fd6131e94803a8d34a8ef675e87
+
+Invalid descriptors
+
+* More than 15 keys in P2SH multisig: sh(multi(16,03669b8afcec803a0d323e9a17f3ea8e68e8abe5a278020a929adbec52421adbd0,0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600,0362a74e399c39ed5593852a30147f2959b56bb827dfa3e60e464b02ccf87dc5e8,0261345b53de74a4d721ef877c255429961b7e43714171ac06168d7e08c542a8b8,02da72e8b46901a65d4374fe6315538d8f368557dda3a1dcf9ea903f3afe7314c8,0318c82dd0b53fd3a932d16e0ba9e278fcc937c582d5781be626ff16e201f72286,0297ccef1ef99f9d73dec9ad37476ddb232f1238aff877af19e72ba04493361009,02e502cfd5c3f972fe9a3e2a18827820638f96b6f347e54d63deb839011fd5765d,03e687710f0e3ebe81c1037074da939d409c0025f17eb86adb9427d28f0f7ae0e9,02c04d3a5274952acdbc76987f3184b346a483d43be40874624b29e3692c1df5af,02ed06e0f418b5b43a7ec01d1d7d27290fa15f75771cb69b642a51471c29c84acd,036d46073cbb9ffee90473f3da429abc8de7f8751199da44485682a989a4bebb24,02f5d1ff7c9029a80a4e36b9a5497027ef7f3e73384a4a94fbfe7c4e9164eec8bc,02e41deffd1b7cce11cde209a781adcffdabd1b91c0ba0375857a2bfd9302419f3,02d76625f7956a7fc505ab02556c23ee72d832f1bac391bcd2d3abce5710a13d06,0399eb0a5487515802dc14544cf10b3666623762fbed2ec38a3975716e2c29c232))
+* Invalid threshold: multi(a,03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd,04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)
+* Threshold of 0: multi(0,03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd,04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)
+* Threshold larger than keys: multi(3,L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1,5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)
+
+==Backwards Compatibility==
+
+multi(), and sortedmulti() descriptors use the format and general operation specified in [[bip-0380.mediawiki|380]].
+As these are a wholly new descriptors, they are not compatible with any implementation.
+However the scripts produced are standard scripts so existing software are likely to be familiar with them.
+
+==Reference Implementation==
+
+multi(), and sortedmulti() descriptors have been implemented in Bitcoin Core since version 0.17.
diff --git a/bip-0384.mediawiki b/bip-0384.mediawiki
new file mode 100644
index 0000000000..585af5e71b
--- /dev/null
+++ b/bip-0384.mediawiki
@@ -0,0 +1,79 @@
+
+
+==Abstract==
+
+This document specifies combo() output script descriptors.
+These take a key and produce P2PK, P2PKH, P2WPKH, and P2SH-P2WPKH output scripts if applicable to the key.
+
+==Copyright==
+
+This BIP is licensed under the BSD 2-clause license.
+
+==Motivation==
+
+In order to make the transition from traditional key based wallets to descriptor based wallets easier, it is useful to be able to take a key and produce the scripts which have traditionally been produced by wallet software.
+
+==Specification==
+
+A new top level script expression is defined: combo(KEY).
+This expression can only be used as a top level expression.
+It takes a single key expression as an argument and produces either 2 or 4 output scripts, depending on the key.
+A combo() expression always produces a P2PK and P2PKH script, the same as putting the key in both a pk() and a pkh() expression.
+If the key is/has a compressed public key, then P2WPKH and P2SH-P2WPKH scripts are also produced, the same as putting the key in both a wpkh() and sh(wpkh()) expression.
+
+==Test Vectors==
+
+Valid descriptors followed by the scripts they produce. Descriptors involving derived child keys will have the 0th, and 1st scripts in additional sub-bullets.
+
+* combo(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)
+** 2103a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bdac
+** 76a9149a1c78a507689f6f54b847ad1cef1e614ee23f1e88ac
+** 00149a1c78a507689f6f54b847ad1cef1e614ee23f1e
+** a91484ab21b1b2fd065d4504ff693d832434b6108d7b87
+* combo(04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)
+** 4104a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235ac
+** 76a914b5bd079c4d57cc7fc28ecf8213a6b791625b818388ac
+* combo([01234567]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL)
+** 2102d2b36900396c9282fa14628566582f206a5dd0bcc8d5e892611806cafb0301f0ac
+** 76a91431a507b815593dfc51ffc7245ae7e5aee304246e88ac
+** 001431a507b815593dfc51ffc7245ae7e5aee304246e
+** a9142aafb926eb247cb18240a7f4c07983ad1f37922687
+* combo(xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334/*)
+** Child 0
+*** 2102df12b7035bdac8e3bab862a3a83d06ea6b17b6753d52edecba9be46f5d09e076ac
+*** 76a914f90e3178ca25f2c808dc76624032d352fdbdfaf288ac
+*** 0014f90e3178ca25f2c808dc76624032d352fdbdfaf2
+*** a91408f3ea8c68d4a7585bf9e8bda226723f70e445f087
+** Child 1
+*** 21032869a233c9adff9a994e4966e5b821fd5bac066da6c3112488dc52383b4a98ecac
+*** 76a914a8409d1b6dfb1ed2a3e8aa5e0ef2ff26b15b75b788ac
+*** 0014a8409d1b6dfb1ed2a3e8aa5e0ef2ff26b15b75b7
+*** a91473e39884cb71ae4e5ac9739e9225026c99763e6687
+
+Invalid descriptors
+
+* combo() in sh : sh(combo(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))
+* combo() in wsh : wsh(combo(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))
+* Script in combo(): combo(pkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))
+
+==Backwards Compatibility==
+
+combo() descriptors use the format and general operation specified in [[bip-0380.mediawiki|380]].
+As this is a wholly new descriptor, it is not compatible with any implementation.
+However the scripts produced are standard scripts so existing software are likely to be familiar with them.
+
+==Reference Implementation==
+
+combo() descriptors have been implemented in Bitcoin Core since version 0.17.
diff --git a/bip-0385.mediawiki b/bip-0385.mediawiki
new file mode 100644
index 0000000000..1686ef7da5
--- /dev/null
+++ b/bip-0385.mediawiki
@@ -0,0 +1,75 @@
+
+
+==Abstract==
+
+This document specifies raw() and addr() output script descriptors.
+raw() encapsulates a raw script as a descriptor.
+addr() encapsulates an address as a descriptor.
+
+==Copyright==
+
+This BIP is licensed under the BSD 2-clause license.
+
+==Motivation==
+
+In order to make descriptors maximally compatible with scripts in use today, it is useful to be able to wrap any arbitrary output script or an address into a descriptor.
+
+==Specification==
+
+Two new script expressions are defined: raw() and addr().
+
+===raw()===
+
+The raw(HEX) expression can only be used as a top level descriptor.
+As the argument, it takes a hex string representing a Bitcoin script.
+The output script produced by this descriptor is the script represented by HEX.
+
+===addr()===
+
+The addr(ADDR) expression can only be used as a top level descriptor.
+It takes an address as its single argument.
+The output script produced by this descriptor is the output script produced by the address ADDR.
+
+==Test Vectors==
+
+Valid descriptors followed by the scripts they produce.
+
+* raw(deadbeef)
+** deadbeef
+* raw(512103a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd4104a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea23552ae)
+** 512103a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd4104a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea23552ae
+* raw(a9149a4d9901d6af519b2a23d4a2f51650fcba87ce7b87)
+** a9149a4d9901d6af519b2a23d4a2f51650fcba87ce7b87
+* addr(3PUNyaW7M55oKWJ3kDukwk9bsKvryra15j)
+** a914eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee87
+
+Invalid descriptors
+
+* Non-hex script: raw(asdf)
+* Invalid address: addr(asdf)
+* raw nested in sh: sh(raw(deadbeef))
+* raw nested in wsh: wsh(raw(deadbeef))
+* addr nested in sh: sh(addr(3PUNyaW7M55oKWJ3kDukwk9bsKvryra15j))
+* addr nested in wsh: wsh(addr(3PUNyaW7M55oKWJ3kDukwk9bsKvryra15j))
+
+==Backwards Compatibility==
+
+raw() and addr() descriptors use the format and general operation specified in [[bip-0380.mediawiki|380]].
+As this is a wholly new descriptor, it is not compatible with any implementation.
+The reuse of existing Bitcoin addresses allows for this to be more easily implemented.
+
+==Reference Implementation==
+
+raw() and addr() descriptors have been implemented in Bitcoin Core since version 0.17.
diff --git a/bip-0386.mediawiki b/bip-0386.mediawiki
new file mode 100644
index 0000000000..600d14ea6a
--- /dev/null
+++ b/bip-0386.mediawiki
@@ -0,0 +1,122 @@
+
+
+==Abstract==
+
+This document specifies tr() output script descriptors.
+tr() descriptors take a key and optionally a tree of scripts and produces a P2TR output script.
+
+==Copyright==
+
+This BIP is licensed under the BSD 2-clause license.
+
+==Motivation==
+
+Taproot added one additional standard output script format: P2TR.
+These expressions allow specifying those formats as a descriptor.
+
+==Specification==
+
+A new script expression is defined: tr().
+A new expression is defined: Tree Expressions
+
+===Tree Expression===
+
+A Tree Expression (denoted TREE) is an expression which represents a tree of scripts.
+The way the tree is represented in an output script is dependent on the higher level expressions.
+
+A Tree Expression is:
+* Any Script Expression that is allowed at the level this Tree Expression is in.
+* A pair of Tree Expressions consisting of:
+** An open brace {
+** A Tree Expression
+** A comma ,
+** A Tree Expression
+** A closing brace }
+
+===tr()===
+
+The tr(KEY) or tr(KEY, TREE) expression can only be used as a top level expression.
+All key expressions under any tr() expression must create x-only public keys.
+
+tr(KEY) takes a single key expression as an argument and produces a P2TR output script which does not have a script path.
+Each key produced by the key expression is used as the internal key of a P2TR output as specified by [[bip-0341.mediawiki#cite_ref-22-0|BIP 341]].
+Specifically, "If the spending conditions do not require a script path, the output key should commit to an unspendable script path instead of having no script path.
+This can be achieved by computing the output key point as ''Q = P + int(hashTapTweak(bytes(P)))G''."
+
+
+
+tr(KEY, TREE) takes a key expression as the first argument, and a tree expression as the second argument and produces a P2TR output script which has a script path.
+The keys produced by the first key expression are used as the internal key as specified by [[bip-0341.mediawiki#Constructing_and_spending_Taproot_outputs|BIP 341]].
+The Tree expression becomes the Taproot script tree as described in BIP 341.
+A merkle root is computed from this tree and combined with the internal key to create the Taproot output key.
+
+
+
+===Modified Key Expression===
+
+Key Expressions within a tr() expression must only create x-only public keys.
+Uncompressed public keys are not allowed, but compressed public keys would be implicitly converted to x-only public keys.
+The keys derived from extended keys must be serialized as x-only public keys.
+An additional key expression is defined only for use within a tr() descriptor:
+
+* A 64 hex character string representing an x-only public key
+
+==Test Vectors==
+
+Valid descriptors followed by the scripts they produce. Descriptors involving derived child keys will have the 0th, 1st, and 2nd scripts listed.
+
+* tr(a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)
+** 512077aab6e066f8a7419c5ab714c12c67d25007ed55a43cadcacb4d7a970a093f11
+* tr(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)
+** 512077aab6e066f8a7419c5ab714c12c67d25007ed55a43cadcacb4d7a970a093f11
+* tr(xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc/0/*,pk(xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc/1/*))
+** 512078bc707124daa551b65af74de2ec128b7525e10f374dc67b64e00ce0ab8b3e12
+** 512001f0a02a17808c20134b78faab80ef93ffba82261ccef0a2314f5d62b6438f11
+** 512021024954fcec88237a9386fce80ef2ced5f1e91b422b26c59ccfc174c8d1ad25
+* tr(a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd,pk(669b8afcec803a0d323e9a17f3ea8e68e8abe5a278020a929adbec52421adbd0))
+** 512017cf18db381d836d8923b1bdb246cfcd818da1a9f0e6e7907f187f0b2f937754
+* tr(a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd,{pk(xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334/0),{{pk(xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL),pk(02df12b7035bdac8e3bab862a3a83d06ea6b17b6753d52edecba9be46f5d09e076)},pk(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)}})
+** 512071fff39599a7b78bc02623cbe814efebf1a404f5d8ad34ea80f213bd8943f574
+
+Invalid Descriptors
+
+* Uncompressed private key: tr(5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)
+* Uncompressed public key: tr(04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)
+* tr() nested in wsh: wsh(tr(a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))
+* tr() nested in sh: sh(tr(a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))
+* pkh() nested in tr: tr(a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd, pkh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))
+
+==Backwards Compatibility==
+
+tr() descriptors use the format and general operation specified in [[bip-0380.mediawiki|380]].
+As these are a set of wholly new descriptors, they are not compatible with any implementation.
+However the scripts produced are standard scripts so existing software are likely to be familiar with them.
+
+Tree Expressions are largely incompatible with existing script expressions due to the restrictions in those expressions.
+As of 2021-06-27, the only allowed script expression that can be used in a tree expression is pk().
+However there will be future BIPs that specify script expressions that can be used in tree expressions.
+
+==Reference Implementation==
+
+tr() descriptors have been implemented in Bitcoin Core since version 22.0.
diff --git a/bip-0387.mediawiki b/bip-0387.mediawiki
new file mode 100644
index 0000000000..0f8c88d3a7
--- /dev/null
+++ b/bip-0387.mediawiki
@@ -0,0 +1,101 @@
+
+
+==Abstract==
+
+This document specifies multi_a() and sortedmulti_a() output script descriptors.
+Like BIP 383's multi() and sortedmulti(), both functions take a threshold and one
+or more public keys and produce a multisig script. The primary distinction is that multi_a()
+and sortedmulti_a() only produce tapscripts and are only allowed in a tapscript context.
+
+==Copyright==
+
+This BIP is licensed under the BSD 2-clause license.
+
+==Motivation==
+
+The most common complex script used in Bitcoin is a threshold multisig.
+These expressions allow specifying multisig scripts as a descriptor.
+
+==Specification==
+
+Two new script expressions are defined: multi_a() and sortedmulti_a().
+Both expressions produce the scripts of the same template and take the same arguments.
+They are written as multi_a(k,KEY_1,KEY_2,...,KEY_n).
+k is the threshold - the number of keys that must sign the input for the script to be valid.
+KEY_1,KEY_2,...,KEY_n are the key expressions for the multisig. k must be less than or equal to n.
+
+multi_a() and sortedmulti_a() expressions can only be used inside of a tr() descriptor.
+The maximum number of keys is 999.
+
+The output script produced also depends on the value of k. If k is less than or equal to 16:
+
+KEY_1 OP_CHECKSIG KEY_2 OP_CHECKSIGADD ... KEY_n OP_CHECKSIGADD k OP_NUMEQUAL
+
+
+===sortedmulti_a()===
+
+The only change for sortedmulti_a() is that the x-only public keys are sorted lexicographically prior to the creation of the output script.
+This sorting is on the keys that are to be put into the output script, i.e. after all extended keys are derived.
+
+===Multiple Extended Keys===
+
+When one or more of the key expressions in a multi_a() or sortedmulti_a() expression are extended keys, the derived keys use the same child index.
+This changes the keys in lockstep and allows for output scripts to be indexed in the same way that the derived keys are indexed.
+
+==Test Vectors==
+
+Valid descriptors followed by the scripts they produce. Descriptors involving derived child keys will have the 0th, 1st, and 2nd scripts listed.
+
+* tr(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1,multi_a(1,KzoAz5CanayRKex3fSLQ2BwJpN7U52gZvxMyk78nDMHuqrUxuSJy))
+** 5120eb5bd3894327d75093891cc3a62506df7d58ec137fcd104cdd285d67816074f3
+* tr(a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd,multi_a(1,669b8afcec803a0d323e9a17f3ea8e68e8abe5a278020a929adbec52421adbd0))
+** 5120eb5bd3894327d75093891cc3a62506df7d58ec137fcd104cdd285d67816074f3
+* tr(50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0,multi_a(2,[00000000/111'/222]xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc,xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L/0))
+** 51202eea93581594a43c0c8423b70dc112e5651df63984d108d4fc8ccd3b63b4eafa
+* tr(50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0,sortedmulti_a(2,[00000000/111'/222]xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc,xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L/0))
+** 512016fa6a6ba7e98c54b5bf43b3144912b78a61b60b02f6a74172b8dcb35b12bc30
+* tr(50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0,sortedmulti_a(2,xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/*,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/0/0/*))
+** 5120abd47468515223f58a1a18edfde709a7a2aab2b696d59ecf8c34f0ba274ef772
+** 5120fe62e7ed20705bd1d3678e072bc999acb014f07795fa02cb8f25a7aa787e8cbd
+** 51201311093750f459039adaa2a5ed23b0f7a8ae2c2ffb07c5390ea37e2fb1050b41
+* tr(50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0,multi_a(2,xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/2147483647'/0,xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt/1/2/*,xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi/10/20/30/40/*'))
+** 5120e4c8f2b0a7d3a688ac131cb03248c0d4b0a59bbd4f37211c848cfbd22a981192
+** 5120827faedaa21e52fca2ac83b53afd1ab7d4d1e6ce67ff42b19f2723d48b5a19ab
+** 5120647495ed09de61a3a324704f9203c130d655bf3141f9b748df8f7be7e9af55a4
+
+Invalid descriptors
+
+* Unsupported top level: multi_a(1,03669b8afcec803a0d323e9a17f3ea8e68e8abe5a278020a929adbec52421adbd0)
+* Unsupported sh() context: sh(multi_a(1,03669b8afcec803a0d323e9a17f3ea8e68e8abe5a278020a929adbec52421adbd0))
+* Unsupported wsh() context: wsh(multi_a(1,03669b8afcec803a0d323e9a17f3ea8e68e8abe5a278020a929adbec52421adbd0))
+* Invalid threshold: tr(50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0,multi_a(a,03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))
+* Threshold of 0: tr(50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0,multi_a(0,03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))
+* Uncompressed pubkey: tr(50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0,multi_a(1,04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235))
+* Threshold larger than keys: tr(50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0,multi_a(3,L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1,5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss))
+
+==Backwards Compatibility==
+
+multi_a() and sortedmulti_a() descriptors use the format and general operation specified in [[bip-0380.mediawiki|380]].
+As these are wholly new descriptors, they are not compatible with any implementation.
+However, the scripts produced are standard scripts, so existing software are likely to be familiar with them.
+
+==Reference Implementation==
+
+multi_a() and sortedmulti_a() descriptors were implemented in Bitcoin Core in https://github.com/bitcoin/bitcoin/pull/24043 and have been available since version 24.0.
diff --git a/bip-0388.mediawiki b/bip-0388.mediawiki
new file mode 100644
index 0000000000..a16690ecdd
--- /dev/null
+++ b/bip-0388.mediawiki
@@ -0,0 +1,348 @@
+
+
+== Abstract ==
+
+Software wallets and hardware signing devices typically partition funds into separate "accounts". When signing or visualizing a transaction, aggregate flows of funds of all accounts affected by the transaction may (and should) be displayed to the user.
+
+Wallet policies build on top of output script descriptors to represent such accounts in a compact, reviewable way.
+An account encompasses a logical group of receive and change addresses, and each wallet policy represents all descriptors necessary to describe an account in its entirety.
+
+We simplify the language to suit devices with limited memory, where even keeping the entire descriptor in memory could be a major hurdle, by reducing the generality of descriptors to just the essential features and by separating the extended pubkeys and other key information from the descriptor.
+
+This results in a more compact representation and simplifies the inspection of the policy by the user.
+
+The compilation of wallet policies to the corresponding descriptor is trivial, and the reverse process is easy for supported descriptors, because the language is kept similar to that of output script descriptors.
+
+== Copyright ==
+
+This BIP is licensed under the BSD 2-clause license.
+
+== Motivation ==
+
+''[[bip-0380.mediawiki|Output Script Descriptors]]'' were introduced in Bitcoin Core as a way to represent collections of output scripts. It is a general and flexible language, designed to catch all the possible use-cases of bitcoin wallets (that is, if you know the script and you have the necessary keys, it will be possible to sign transactions with any descriptor-based software wallet).
+
+Unfortunately, descriptors are not a perfect match for the typical usage of hardware signing devices (often also called ''hardware wallets''). Most of them have some of the following limitations when compared to a general-purpose machine running Bitcoin Core:
+
+* they are embedded devices with limited RAM, and computational power;
+* they cannot import additional private keys (that is, they can only sign with keys derived from a single seed via [[bip-0032.mediawiki|BIP-32]]);
+* they have limited storage, or they might not have persistent storage at all (''stateless design'').
+
+Moreover, other limitations like the limited size of the screen might affect what design choices are available in practice. Therefore, minimizing the amount of information shown on-screen is important for a good user experience. The ability for the user to completely validate on-screen the kind of script used (and each of the involved keys) is crucial for secure usage, as the machine that is interacting with the hardware signer (and running the software wallet) is considered untrusted.
+
+A more native, compact representation of the wallet receive and change addresses might also benefit the UX of software wallets when they use descriptors (possibly with miniscript) for representing complex locking conditions.
+
+We remark that wallet policies are not related to the ''policy'' language, a higher level language that can be compiled to [[bip-0379.md|miniscript]].
+
+=== Security, privacy and UX concerns for hardware signing devices ===
+
+The usage of complex scripts presents challenges in terms of both security and user experience for a hardware signing device.
+
+==== Security issues ====
+
+Hardware signing devices strive to guarantee that no action can be performed without the user’s consent as long as the user correctly verifies the information that is shown on the device’s screen before approving.
+
+This must hold even in scenarios where the attacker has full control of the machine that is connected to the signing device, and can execute arbitrary requests, or tamper with the legitimate user's requests.
+
+Therefore, it is not at all trivial to allow complex scripts, especially if they contain keys that belong to third parties.
+The hardware signing device must guarantee that the user knows precisely what "policy" is being used to spend the funds, and that any "unspent" funds (if any) that is sent to a change address will be protected by the same policy.
+
+This makes it impossible for an attacker to surreptitiously modify the policy, therefore stealing or burning the user's funds.
+
+==== Avoiding key reuse ====
+
+Reusing public keys within a script is a source of malleability when using miniscript policies, which has potential security implications.
+
+Reusing keys across different UTXOs harms user privacy by allowing external parties to link these UTXOs to the same entity once they are spent.
+
+By constraining the derivation path patterns to have a uniform structure, wallet policies prevent key reuse among the same or different UTXOs of the same account.
+
+It is strongly recommended to avoid key reuse across accounts. Distinct public keys per account can be guaranteed by using distinct hardened derivation paths. This specification does not mandate hardened derivation in order to maintain compatibility with existing deployments that do not adhere to this recommendation.
+
+It is out of scope for this document to guarantee that users do not reuse extended public keys among different wallet accounts. This is still very important, but the responsibility is left to the users and their software wallet.
+
+==== UX issues ====
+
+Miniscript (and taproot trees) allow substantially more complex spending policies. It is a challenge to ensure that the user can practically verify such spending policies per the screen.
+
+We set two fundamental design goals:
+* Minimize the amount of information that is shown on screen - so that the user can actually validate it.
+* Minimize the number of times the user has to validate such information.
+
+Designing a secure protocol for the coordination of a descriptor wallet among distant parties is also a challenging problem that is out of the scope of this document. See [[bip-0129.mediawiki|BIP-129 (Bitcoin Secure Multisig Setup)]] for an approach designed for multisig wallets. Regardless of the approach, the ability for the user to carefully verify all the details of the spending policies using the hardware signer's screen is a prerequisite for security in adversarial environments.
+
+=== Policy registration as a solution ===
+
+A solution to address the security concerns, and part of the UX concerns, is to have a registration flow for the wallet policy in the hardware signing device. The ''wallet policy'' must contain enough information to generate all the relevant addresses/scripts, and for the hardware signing device to identify the keys that it controls and that are needed to spend the funds sent to those addresses.
+
+Before a new policy is used for the first time, the user will register a wallet policy into the hardware device. While the details of the process are out of scope in this document, the flow should be something similar to the following:
+
+# The software wallet initiates a ''wallet policy registration'' on the hardware signing device; the information should include the wallet policy, but also a unique ''name'' that identifies the policy.
+# The device shows the wallet policy to the user using the secure screen.
+# After inspecting the policy and comparing it with a trusted source (for example a printed backup), the user approves the policy.
+# If stateful, the hardware signing device persists the policy in its permanent memory; if stateless, it returns a "proof of registration".
+
+The '''proof of registration''' will allow the hardware signer to verify that a certain policy was indeed previously approved by the user, and is therefore safe to use without repeating the expensive user verification procedure. The details of how to create a proof of registration are out of scope for this document; using a Message Authentication Code on a hash committing to the wallet policy, its name and any additional metadata is an effective solution if correctly executed.
+
+Once a policy is registered, the hardware signing device can perform the typical operations securely:
+* generating receive and change addresses;
+* showing addresses on the secure screen;
+* sign transactions spending from a wallet, while correctly identifying change addresses and computing the transaction fees.
+
+Before any of the actions mentioned above, the hardware signing device will retrieve the policy from its permanent storage if stateful; if stateless it will validate the proof of registration before using the wallet policy provided by the client.
+
+Once the previously registered policy is correctly identified and approved by the user (for example by showing its name), and as long as the policy registration was executed securely, hardware signing devices can provide a user experience similar to the usual one for single-signature transactions.
+
+=== Avoiding blowup in descriptor size ===
+
+While reusing a pubkey in different branches of a miniscript is explicitly forbidden by miniscript (as it has certain negative security implications), it is still reasonable to reuse the same xpub in multiple places, albeit with different final steps of derivation (so that the actual pubkeys that are used in the script are indeed different).
+
+In fact, there are many reasonable spending policies with a quadratic size in the number of participants. For example, using Taproot, a 3-of-5 threshold wallet could use:
+* a key path with a 5-of-5 [[bip-0327.mediawiki|MuSig2]] aggregated key
+* a script tree with 11 leaves:
+** 10 different scripts using a 3-of-3 MuSig2 aggregated key, plus
+** a final leaf with a fallback 3-of-5 multisig using multi_a (in case interactive signing is not available).
+
+With each xpub being 118 bytes long, the repetition of xpubs makes the descriptor become extremely large.
+
+Replacing the common part of the key with a short key placeholder and organizing all the key expressions in a separate list helps to keep the size of the wallet policy small, which is crucial to allow human inspection during the registration flow.
+
+== Specification ==
+
+This section formally defines wallet policies, and how they relate to output script descriptors.
+
+=== Formal definition ===
+
+A ''wallet policy'' is composed by a ''wallet descriptor template'', together with a vector of ''key information items''.
+
+==== Wallet descriptor template ====
+
+A ''wallet descriptor template'' is a SCRIPT expression.
+
+SCRIPT expressions:
+* sh(SCRIPT) (top level only): P2SH embed the argument.
+* wsh(SCRIPT) (top level or inside sh only): P2WSH embed the argument.
+* pkh(KEY) (not inside tr): P2PKH output for the given public key.
+* wpkh(KEY) (top level or inside sh only): P2WPKH output for the given compressed pubkey.
+* multi(k,KEY_1,KEY_2,...,KEY_n) (inside sh or wsh only): ''k''-of-''n'' multisig script.
+* sortedmulti(k,KEY_1,KEY_2,...,KEY_n) (inside sh or wsh only): ''k''-of-''n'' multisig script with keys sorted lexicographically in the resulting script.
+* tr(KEY) or tr(KEY,TREE) (top level only): P2TR output with the specified key as internal key, and optionally a tree of script paths.
+* any valid miniscript template (inside wsh or tr only).
+
+See [[bip-0379.md|BIP-379]] for a precise specification of all the valid miniscript SCRIPT expressions.
+
+TREE expressions:
+* any SCRIPT expression
+* An open brace {, a TREE expression, a comma ,, a TREE expression, and a closing brace }
+
+
+KEY expressions consist of
+* a KP expression
+* ''always'' followed by either:
+** the string /**, or
+** a string of the form //*, for two distinct decimal numbers NUM representing unhardened derivations, or
+** any of the additional, implementation-specific valid derivation path patterns (see [[#optional-derivation-paths|Optional derivation paths]] below).
+
+KP expressions (key placeholders) consist of either:
+* a KI (key index) expression, or
+* (only inside tr): musig(KI_1,KI_2,...,KI_n)
+
+A KI (key index) expression consists of:
+* a single character @
+* followed by a non-negative decimal number, with no leading zeros (except for @0)
+
+The /** in the placeholder template represents commonly used paths for receive/change addresses, and is equivalent to <0;1>/*.
+
+Note that while [[bip-0389.mediawiki|BIP-389]] allows multipath / expressions with an arbitrary number of options, this specification restricts it to exactly 2 choices (with the typical meaning of receive/change addresses).
+
+SCRIPT, TREE and KEY expressions map directly to the corresponding concepts defined in [[bip-0380.mediawiki|BIP-380]] for output script descriptors.
+
+Each KEY expression always corresponds to a precise public key in the final bitcoin Script. Therefore, all the derivation steps in the BIP-32 hierarchy are included in a KEY expression.
+
+Each KP (key placeholder) expression, on the other hand, maps to the root of all the corresponding public keys for all the possible UTXOs that belong to the account represented in the wallet policy. Therefore, no derivation steps are allowed in a KP expression.
+
+A KI (key index) @i for some number ''i'' represents the ''i''-th key in the vector of key information items (which must be of size at least ''i + 1'', or the wallet policy is invalid).
+
+Note: while descriptor templates for miniscript are not formally defined in this version of the document (pending standardization), it is straightforward to adapt this approach by adding additional SCRIPT expressions.
+
+==== Key information vector ====
+
+Each element of the key origin information vector is a KEY_INFO expression, containing an extended public key, and (optionally) its key origin.
+
+* Optionally, key origin information, consisting of:
+** An open bracket [
+** Exactly 8 hex characters for the fingerprint of the master key from which this key is derived from (see [[bip-0032.mediawiki|BIP-32]] for details)
+** Followed by zero or more /NUM' or /NUM path elements to indicate hardened or unhardened derivation steps between the fingerprint and the xpub that follows
+** A closing bracket ]
+* Followed by the actual key, which is a serialized extended public key (as defined in [[bip-0032.mediawiki|BIP-32]]).
+
+==== Additional rules ====
+
+A wallet policy must have at least one key placeholder and the corresponding key.
+
+The public keys obtained by deserializing elements of the key information vector must be pairwise distinct'''Why must public keys be distinct?''' Reusing pubkeys could be insecure in the context of wallet policies containing [https://bitcoin.sipa.be/miniscript/ miniscript]. Avoiding repeated public keys altogether avoids the problem at the source..
+
+If two KEY are KP//* and KP/
/* for the same key placeholder KP, then the sets {M, N} and {P, Q} must be disjoint. Two musig key placeholders are the same if they have exactly the same set of key indexes (regardless of the order).
+
+Repeated KI expressions are not allowed inside a musig placeholder.
+
+The key information vector should be ordered so that placeholder @i never appears for the first time before an occurrence of @j for some j < i; for example, the first placeholder is always @0, the next one is @1, etc.
+
+=== Descriptor derivation ===
+
+From a wallet descriptor template (and the associated vector of key information items), one can therefore obtain the corresponding multipath descriptor by:
+
+* replacing each key placeholder with the corresponding key origin information;
+* replacing every /** with /<0;1>/*.
+
+For example, the wallet descriptor pkh(@0/**) with key information
+["[d34db33f/44'/0'/0']xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL"]
+produces the following multipath descriptor:
+
+pkh([d34db33f/44'/0'/0']xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/<0;1>/*)
+
+=== Implementation guidelines ===
+
+It is acceptable to implement only a subset of the possible wallet policies defined by this standard. It is recommended that any limitations are clearly documented.
+
+Implementations can add additional metadata that is stored together with the wallet policy for the purpose of wallet policy registration and later usage. Metadata can be vendor-specific and is out of the scope of this document.
+
+Any implementation in a software wallet that allows wallet policies not matching any of the specifications in [[bip-0044.mediawiki|BIP-44]], [[bip-0049.mediawiki|BIP-49]], [[bip-0084.mediawiki|BIP-84]], [[bip-0086.mediawiki|BIP-86]] (especially if involving external cosigners) should put great care into a process for backing up the wallet policy that represents the account. In fact, unlike standard single-signature scenarios, the seed alone is no longer enough to discover wallet policies with existing funds, and the loss of the backup is likely to lead to permanent loss of funds. Unlike the seed, leaking such backups only affects the privacy of the user, but it does not allow the attacker to steal funds.
+
+=== Optional derivation paths ===
+
+In order to allow supporting legacy derivation schemes (for example, using simply /* instead of the more common //* scheme most software wallets use today), or other schemes that are not covered in this document, implementations might choose to permit additional derivation patterns for the key placeholder (KP) expressions.
+
+However, care needs to be taken in view of the following considerations:
+
+* Allowing derivation schemes with a different length or cardinality in the same wallet policy would make it difficult to guarantee that there are no repeated pubkeys for every possible address generated by the policy. For example, @0/<0;1>/* and @1/* would generate the same pubkeys if the second public key in the key information vector is one of the first two unhardened children of the first public key. This could cause malleability with potential security implications (for example, in policies containing miniscript).
+* Allowing naked pubkeys with no /* suffix (for example a descriptor template like wsh(multi(2,@0,@1/<0;1>/*))) would cause a pubkey to be repeated in every output generated from the policy, which would result in a total loss of privacy.
+
+== Examples ==
+
+In the examples in this section, the vector of key information items is omitted. See the test vectors below for complete examples.
+
+Common single-signature account patterns:
+* pkh(@0/**) (legacy).
+* wpkh(@0/**) (native segwit).
+* sh(wpkh(@0/**)) (nested segwit).
+* tr(@0/**) (taproot single-signature account).
+
+Common multisig schemes:
+* wsh(multi(2,@0/**,@1/**)) - SegWit 2-of-2 multisig, keys in order.
+* sh(sortedmulti(2,@0/**,@1/**,@2/**)) - Legacy 2-of-3 multisig, sorted keys.
+* tr(musig(@0/**,@1/**)) - MuSig2 2-of-2 in the taproot keypath
+
+Some miniscript policies in wsh:
+* wsh(and_v(v:pk(@0/**),or_d(pk(@1/**),older(12960)))) - Trust-minimized second factor, degrading to a single signature after about 90 days.
+* wsh(thresh(3,pk(@0/**),s:pk(@1/**),s:pk(@2/**),sln:older(12960))) - A 3-of-3 wallet that becomes a 2-of-3 if coins are not spent for about 90 days.
+* wsh(or_d(pk(@0/**),and_v(v:multi(2,@1/**,@2/**,@3/**),older(65535)))) - A singlesig wallet with automatic inheritance to a timelocked 2-of-3 multisig of family members.
+
+== Test Vectors ==
+
+=== Valid policies ===
+
+[[bip-0044.mediawiki|BIP-44]], first account
+ Descriptor template: pkh(@0/**)
+ Keys info: ["[6738736c/44'/0'/0']xpub6Br37sWxruYfT8ASpCjVHKGwgdnYFEn98DwiN76i2oyY6fgH1LAPmmDcF46xjxJr22gw4jmVjTE2E3URMnRPEPYyo1zoPSUba563ESMXCeb"]
+ Descriptor: pkh([6738736c/44'/0'/0']xpub6Br37sWxruYfT8ASpCjVHKGwgdnYFEn98DwiN76i2oyY6fgH1LAPmmDcF46xjxJr22gw4jmVjTE2E3URMnRPEPYyo1zoPSUba563ESMXCeb/<0;1>/*)
+
+[[bip-0049.mediawiki|BIP-49]], second account
+ Descriptor template: sh(wpkh(@0/**))
+ Keys info: ["[6738736c/49'/0'/1']xpub6Bex1CHWGXNNwGVKHLqNC7kcV348FxkCxpZXyCWp1k27kin8sRPayjZUKDjyQeZzGUdyeAj2emoW5zStFFUAHRgd5w8iVVbLgZ7PmjAKAm9"]
+ Descriptor: sh(wpkh([6738736c/49'/0'/1']xpub6Bex1CHWGXNNwGVKHLqNC7kcV348FxkCxpZXyCWp1k27kin8sRPayjZUKDjyQeZzGUdyeAj2emoW5zStFFUAHRgd5w8iVVbLgZ7PmjAKAm9/<0;1>/*))
+
+[[bip-0084.mediawiki|BIP-84]], third account
+ Descriptor template: wpkh(@0/**)
+ Keys info: ["[6738736c/84'/0'/2']xpub6CRQzb8u9dmMcq5XAwwRn9gcoYCjndJkhKgD11WKzbVGd932UmrExWFxCAvRnDN3ez6ZujLmMvmLBaSWdfWVn75L83Qxu1qSX4fJNrJg2Gt"]
+ Descriptor: wpkh([6738736c/84'/0'/2']xpub6CRQzb8u9dmMcq5XAwwRn9gcoYCjndJkhKgD11WKzbVGd932UmrExWFxCAvRnDN3ez6ZujLmMvmLBaSWdfWVn75L83Qxu1qSX4fJNrJg2Gt/<0;1>/*)
+
+[[bip-0086.mediawiki|BIP-86]], first account
+ Descriptor template: tr(@0/**)
+ Keys info: ["[6738736c/86'/0'/0']xpub6CryUDWPS28eR2cDyojB8G354izmx294BdjeSvH469Ty3o2E6Tq5VjBJCn8rWBgesvTJnyXNAJ3QpLFGuNwqFXNt3gn612raffLWfdHNkYL"]
+ Descriptor: tr([6738736c/86'/0'/0']xpub6CryUDWPS28eR2cDyojB8G354izmx294BdjeSvH469Ty3o2E6Tq5VjBJCn8rWBgesvTJnyXNAJ3QpLFGuNwqFXNt3gn612raffLWfdHNkYL/<0;1>/*)
+
+[[bip-0048.mediawiki|BIP-48]] P2WSH multisig
+ Descriptor template: wsh(sortedmulti(2,@0/**,@1/**))
+ Keys info: ["[6738736c/48'/0'/0'/2']xpub6FC1fXFP1GXLX5TKtcjHGT4q89SDRehkQLtbKJ2PzWcvbBHtyDsJPLtpLtkGqYNYZdVVAjRQ5kug9CsapegmmeRutpP7PW4u4wVF9JfkDhw", "[b2b1f0cf/48'/0'/0'/2']xpub6EWhjpPa6FqrcaPBuGBZRJVjzGJ1ZsMygRF26RwN932Vfkn1gyCiTbECVitBjRCkexEvetLdiqzTcYimmzYxyR1BZ79KNevgt61PDcukmC7"]
+ Descriptor: wsh(sortedmulti(2,[6738736c/48'/0'/0'/2']xpub6FC1fXFP1GXLX5TKtcjHGT4q89SDRehkQLtbKJ2PzWcvbBHtyDsJPLtpLtkGqYNYZdVVAjRQ5kug9CsapegmmeRutpP7PW4u4wVF9JfkDhw/<0;1>/*,[b2b1f0cf/48'/0'/0'/2']xpub6EWhjpPa6FqrcaPBuGBZRJVjzGJ1ZsMygRF26RwN932Vfkn1gyCiTbECVitBjRCkexEvetLdiqzTcYimmzYxyR1BZ79KNevgt61PDcukmC7/<0;1>/*))
+
+Miniscript: A 3-of-3 that becomes a 2-of-3 after 90 days
+ Descriptor template: wsh(thresh(3,pk(@0/**),s:pk(@1/**),s:pk(@2/**),sln:older(12960)))
+ Keys info: ["[6738736c/48'/0'/0'/100']xpub6FC1fXFP1GXQpyRFfSE1vzzySqs3Vg63bzimYLeqtNUYbzA87kMNTcuy9ubr7MmavGRjW2FRYHP4WGKjwutbf1ghgkUW9H7e3ceaPLRcVwa", "[b2b1f0cf/44'/0'/0'/100']xpub6EYajCJHe2CK53RLVXrN14uWoEttZgrRSaRztujsXg7yRhGtHmLBt9ot9Pd5ugfwWEu6eWyJYKSshyvZFKDXiNbBcoK42KRZbxwjRQpm5Js", "[a666a867/44'/0'/0'/100']xpub6Dgsze3ujLi1EiHoCtHFMS9VLS1UheVqxrHGfP7sBJ2DBfChEUHV4MDwmxAXR2ayeytpwm3zJEU3H3pjCR6q6U5sP2p2qzAD71x9z5QShK2"]
+ Descriptor: wsh(thresh(3,pk([6738736c/48'/0'/0'/100']xpub6FC1fXFP1GXQpyRFfSE1vzzySqs3Vg63bzimYLeqtNUYbzA87kMNTcuy9ubr7MmavGRjW2FRYHP4WGKjwutbf1ghgkUW9H7e3ceaPLRcVwa/<0;1>/*),s:pk([b2b1f0cf/44'/0'/0'/100']xpub6EYajCJHe2CK53RLVXrN14uWoEttZgrRSaRztujsXg7yRhGtHmLBt9ot9Pd5ugfwWEu6eWyJYKSshyvZFKDXiNbBcoK42KRZbxwjRQpm5Js/<0;1>/*),s:pk([a666a867/44'/0'/0'/100']xpub6Dgsze3ujLi1EiHoCtHFMS9VLS1UheVqxrHGfP7sBJ2DBfChEUHV4MDwmxAXR2ayeytpwm3zJEU3H3pjCR6q6U5sP2p2qzAD71x9z5QShK2/<0;1>/*),sln:older(12960)))
+
+Miniscript: A singlesig wallet with automatic inheritance to a timelocked 2-of-3 multisig
+ Descriptor template: wsh(or_d(pk(@0/**),and_v(v:multi(2,@1/**,@2/**,@3/**),older(65535))))
+ Keys info: ["[6738736c/48'/0'/0'/100']xpub6FC1fXFP1GXQpyRFfSE1vzzySqs3Vg63bzimYLeqtNUYbzA87kMNTcuy9ubr7MmavGRjW2FRYHP4WGKjwutbf1ghgkUW9H7e3ceaPLRcVwa", "[b2b1f0cf/44'/0'/0'/100']xpub6EYajCJHe2CK53RLVXrN14uWoEttZgrRSaRztujsXg7yRhGtHmLBt9ot9Pd5ugfwWEu6eWyJYKSshyvZFKDXiNbBcoK42KRZbxwjRQpm5Js", "[a666a867/44'/0'/0'/100']xpub6Dgsze3ujLi1EiHoCtHFMS9VLS1UheVqxrHGfP7sBJ2DBfChEUHV4MDwmxAXR2ayeytpwm3zJEU3H3pjCR6q6U5sP2p2qzAD71x9z5QShK2", "[bb641298/44'/0'/0'/100']xpub6Dz8PHFmXkYkykQ83ySkruky567XtJb9N69uXScJZqweYiQn6FyieajdiyjCvWzRZ2GoLHMRE1cwDfuJZ6461YvNRGVBJNnLA35cZrQKSRJ"]
+ Descriptor: wsh(or_d(pk([6738736c/48'/0'/0'/100']xpub6FC1fXFP1GXQpyRFfSE1vzzySqs3Vg63bzimYLeqtNUYbzA87kMNTcuy9ubr7MmavGRjW2FRYHP4WGKjwutbf1ghgkUW9H7e3ceaPLRcVwa/<0;1>/*),and_v(v:multi(2,[b2b1f0cf/44'/0'/0'/100']xpub6EYajCJHe2CK53RLVXrN14uWoEttZgrRSaRztujsXg7yRhGtHmLBt9ot9Pd5ugfwWEu6eWyJYKSshyvZFKDXiNbBcoK42KRZbxwjRQpm5Js/<0;1>/*,[a666a867/44'/0'/0'/100']xpub6Dgsze3ujLi1EiHoCtHFMS9VLS1UheVqxrHGfP7sBJ2DBfChEUHV4MDwmxAXR2ayeytpwm3zJEU3H3pjCR6q6U5sP2p2qzAD71x9z5QShK2/<0;1>/*,[bb641298/44'/0'/0'/100']xpub6Dz8PHFmXkYkykQ83ySkruky567XtJb9N69uXScJZqweYiQn6FyieajdiyjCvWzRZ2GoLHMRE1cwDfuJZ6461YvNRGVBJNnLA35cZrQKSRJ/<0;1>/*),older(65535))))
+
+Taproot wallet policy with sortedmulti_a and a miniscript leaf
+ Descriptor template: tr(@0/**,{sortedmulti_a(1,@0/<2;3>/*,@1/**),or_b(pk(@2/**),s:pk(@3/**))})
+ Keys info: ["[6738736c/48'/0'/0'/100']xpub6FC1fXFP1GXQpyRFfSE1vzzySqs3Vg63bzimYLeqtNUYbzA87kMNTcuy9ubr7MmavGRjW2FRYHP4WGKjwutbf1ghgkUW9H7e3ceaPLRcVwa", "xpub6Fc2TRaCWNgfT49nRGG2G78d1dPnjhW66gEXi7oYZML7qEFN8e21b2DLDipTZZnfV6V7ivrMkvh4VbnHY2ChHTS9qM3XVLJiAgcfagYQk6K", "xpub6GxHB9kRdFfTqYka8tgtX9Gh3Td3A9XS8uakUGVcJ9NGZ1uLrGZrRVr67DjpMNCHprZmVmceFTY4X4wWfksy8nVwPiNvzJ5pjLxzPtpnfEM", "xpub6GjFUVVYewLj5no5uoNKCWuyWhQ1rKGvV8DgXBG9Uc6DvAKxt2dhrj1EZFrTNB5qxAoBkVW3wF8uCS3q1ri9fueAa6y7heFTcf27Q4gyeh6"]
+ Descriptor: tr([6738736c/48'/0'/0'/100']xpub6FC1fXFP1GXQpyRFfSE1vzzySqs3Vg63bzimYLeqtNUYbzA87kMNTcuy9ubr7MmavGRjW2FRYHP4WGKjwutbf1ghgkUW9H7e3ceaPLRcVwa/<0;1>/*,{sortedmulti_a(1,xpub6FC1fXFP1GXQpyRFfSE1vzzySqs3Vg63bzimYLeqtNUYbzA87kMNTcuy9ubr7MmavGRjW2FRYHP4WGKjwutbf1ghgkUW9H7e3ceaPLRcVwa/<2;3>/*,xpub6Fc2TRaCWNgfT49nRGG2G78d1dPnjhW66gEXi7oYZML7qEFN8e21b2DLDipTZZnfV6V7ivrMkvh4VbnHY2ChHTS9qM3XVLJiAgcfagYQk6K/<0;1>/*),or_b(pk(xpub6GxHB9kRdFfTqYka8tgtX9Gh3Td3A9XS8uakUGVcJ9NGZ1uLrGZrRVr67DjpMNCHprZmVmceFTY4X4wWfksy8nVwPiNvzJ5pjLxzPtpnfEM/<0;1>/*),s:pk(xpub6GjFUVVYewLj5no5uoNKCWuyWhQ1rKGvV8DgXBG9Uc6DvAKxt2dhrj1EZFrTNB5qxAoBkVW3wF8uCS3q1ri9fueAa6y7heFTcf27Q4gyeh6/<0;1>/*))})
+
+Taproot MuSig2 3-of-3 in the key path, with three 2-of-2 MuSig2 recovery paths after 90 days in the script paths
+ Descriptor template: tr(musig(@0,@1,@2)/**,{and_v(v:pk(musig(@0,@1)/**),older(12960)),{and_v(v:pk(musig(@0,@2)/**),older(12960)),and_v(v:pk(musig(@1,@2)/**),older(12960))}})
+ Keys info: ["[6738736c/48'/0'/0'/100']xpub6FC1fXFP1GXQpyRFfSE1vzzySqs3Vg63bzimYLeqtNUYbzA87kMNTcuy9ubr7MmavGRjW2FRYHP4WGKjwutbf1ghgkUW9H7e3ceaPLRcVwa", "[b2b1f0cf/44'/0'/0'/100']xpub6EYajCJHe2CK53RLVXrN14uWoEttZgrRSaRztujsXg7yRhGtHmLBt9ot9Pd5ugfwWEu6eWyJYKSshyvZFKDXiNbBcoK42KRZbxwjRQpm5Js", "[a666a867/44'/0'/0'/100']xpub6Dgsze3ujLi1EiHoCtHFMS9VLS1UheVqxrHGfP7sBJ2DBfChEUHV4MDwmxAXR2ayeytpwm3zJEU3H3pjCR6q6U5sP2p2qzAD71x9z5QShK2"]
+ Descriptor: tr(musig([6738736c/48'/0'/0'/100']xpub6FC1fXFP1GXQpyRFfSE1vzzySqs3Vg63bzimYLeqtNUYbzA87kMNTcuy9ubr7MmavGRjW2FRYHP4WGKjwutbf1ghgkUW9H7e3ceaPLRcVwa,[b2b1f0cf/44'/0'/0'/100']xpub6EYajCJHe2CK53RLVXrN14uWoEttZgrRSaRztujsXg7yRhGtHmLBt9ot9Pd5ugfwWEu6eWyJYKSshyvZFKDXiNbBcoK42KRZbxwjRQpm5Js,[a666a867/44'/0'/0'/100']xpub6Dgsze3ujLi1EiHoCtHFMS9VLS1UheVqxrHGfP7sBJ2DBfChEUHV4MDwmxAXR2ayeytpwm3zJEU3H3pjCR6q6U5sP2p2qzAD71x9z5QShK2)/<0;1>/*,{and_v(v:pk(musig([6738736c/48'/0'/0'/100']xpub6FC1fXFP1GXQpyRFfSE1vzzySqs3Vg63bzimYLeqtNUYbzA87kMNTcuy9ubr7MmavGRjW2FRYHP4WGKjwutbf1ghgkUW9H7e3ceaPLRcVwa,[b2b1f0cf/44'/0'/0'/100']xpub6EYajCJHe2CK53RLVXrN14uWoEttZgrRSaRztujsXg7yRhGtHmLBt9ot9Pd5ugfwWEu6eWyJYKSshyvZFKDXiNbBcoK42KRZbxwjRQpm5Js)/<0;1>/*),older(12960)),{and_v(v:pk(musig([6738736c/48'/0'/0'/100']xpub6FC1fXFP1GXQpyRFfSE1vzzySqs3Vg63bzimYLeqtNUYbzA87kMNTcuy9ubr7MmavGRjW2FRYHP4WGKjwutbf1ghgkUW9H7e3ceaPLRcVwa,[a666a867/44'/0'/0'/100']xpub6Dgsze3ujLi1EiHoCtHFMS9VLS1UheVqxrHGfP7sBJ2DBfChEUHV4MDwmxAXR2ayeytpwm3zJEU3H3pjCR6q6U5sP2p2qzAD71x9z5QShK2)/<0;1>/*),older(12960)),and_v(v:pk(musig([b2b1f0cf/44'/0'/0'/100']xpub6EYajCJHe2CK53RLVXrN14uWoEttZgrRSaRztujsXg7yRhGtHmLBt9ot9Pd5ugfwWEu6eWyJYKSshyvZFKDXiNbBcoK42KRZbxwjRQpm5Js,[a666a867/44'/0'/0'/100']xpub6Dgsze3ujLi1EiHoCtHFMS9VLS1UheVqxrHGfP7sBJ2DBfChEUHV4MDwmxAXR2ayeytpwm3zJEU3H3pjCR6q6U5sP2p2qzAD71x9z5QShK2)/<0;1>/*),older(12960))}})
+
+=== Invalid policies ===
+
+The following descriptor templates are invalid:
+
+* pkh(@0): Key placeholder with no path following it
+* pkh(@0/0/**): Key placeholder with an explicit path present
+* sh(multi(1,@1/**,@0/**)): Key placeholders out of order
+* sh(multi(1,@0/**,@2/**)): Skipped key placeholder @1
+* sh(multi(1,@0/**,@0/**)): Repeated keys with the same path expression
+* sh(multi(1,@0/<0;1>/*,@0/<1;2>/*)): Non-disjoint multipath expressions (@0/1/* appears twice)
+* sh(multi(1,@0/**,xpub6AHA9hZDN11k2ijHMeS5QqHx2KP9aMBRhTDqANMnwVtdyw2TDYRmF8PjpvwUFcL1Et8Hj59S3gTSMcUQ5gAqTz3Wd8EsMTmF3DChhqPQBnU/<0;1>/*)): Expression with a non-KP key present
+* pkh(@0/<0;1;2>/*): Solved cardinality > 2
+* tr(musig(@0/**,@1/**)): Derivation before aggregation is not allowed in wallet policies (despite being allowed in [[bip-0390.mediawiki|BIP-390]])
+
+Remark: some of the examples of invalid descriptor templates may be valid via optional extensions.
+
+== Backwards Compatibility ==
+
+The @ character used for key placeholders is not part of the syntax of output script descriptors, therefore any valid descriptor with at least one KEY expression is not a valid descriptor template. Vice versa, any descriptor template with at least one key placeholder is not a valid output script descriptor.
+
+Adoption of wallet policies in software and hardware wallets is opt-in. Conversion from wallet policies to the corresponding descriptors is programmatically extremely easy, and conversion from descriptors to wallet policies (when respecting the required patterns) can be automated. See the reference implementation below for some examples of conversion.
+
+Software wallets are recommended to allow exporting plain descriptors for the purposes of interoperability with software not using wallet policies.
+
+== Reference Implementation ==
+
+Wallet policies are implemented in
+* the [https://github.com/LedgerHQ/app-bitcoin-new Ledger bitcoin application] since version 2.1.0;
+* the [https://github.com/digitalbitbox/bitbox02-firmware BitBox02 firmware] since version v9.15.0;
+* [https://github.com/Blockstream/Jade Blockstream Jade] since version v1.0.24, via [https://github.com/ElementsProject/libwally-core libwally-core] v1.0.0.
+
+For development and testing purposes, we provide a [[bip-0388/wallet_policies.py|Python 3.7 reference implementation]] of simple classes to handle wallet policies, and the conversion to/from output script descriptors.
+The reference implementation is for demonstration purposes only and not to be used in production environments.
+
+== Change Log ==
+
+* '''1.1.0''' (2024-11):
+** Added support for musig key placeholders in descriptor templates.
+* '''1.0.0''' (2024-05):
+** Initial version.
+
+== Footnotes ==
+
+
+
+== Acknowledgments ==
+
+The authors would like to thank the people who provided feedback in the bitcoin-dev list, and in person.
diff --git a/bip-0388/wallet_policies.py b/bip-0388/wallet_policies.py
new file mode 100755
index 0000000000..754d201058
--- /dev/null
+++ b/bip-0388/wallet_policies.py
@@ -0,0 +1,202 @@
+#!/usr/bin/env python3
+
+from typing import Iterable, List, Mapping, Tuple, Generator
+
+
+def find_all(text: str, pattern: str, start: int = 0) -> Generator[int, None, None]:
+ """Generates all the positions of `pattern` as a substring of `text`, starting from index at least `start`."""
+ while True:
+ start = text.find(pattern, start)
+ if start == -1:
+ return
+ yield start
+ start += len(pattern)
+
+
+def find_first(text: str, start_pos: int, patterns: Iterable[str]) -> int:
+ """Returns the position of the first occurrence of any of the elements in `patterns` as a substring of `text`,
+ or -1 if none of the patterns is found."""
+ matches = (text.find(x, start_pos) for x in patterns)
+ return min((x for x in matches if x != -1), default=-1)
+
+
+def find_key_end_position(desc: str, start_pos: int) -> int:
+ """Assuming that `start_pos` is the beginning of a KEY expression (and not musig), finds the position of the end
+ of the key expression, excluding (if present) the final derivation steps after an xpub. This is the information
+ that goes into an entry of the vector of key information of the wallet policy."""
+
+ has_orig_info = True if desc[start_pos] == '[' else False
+
+ if has_orig_info:
+ closing_bracket_pos = desc.find("]", start_pos)
+ if closing_bracket_pos == -1:
+ raise Exception("Invalid descriptor: could not find closing ']'")
+ key_pos_start = closing_bracket_pos + 1
+ else:
+ key_pos_start = start_pos
+
+ # find the earliest occurrence of ",", a ")" or a "/" (it must find at least 1)
+ end_pos = find_first(desc, key_pos_start, [",", ")", "/"])
+ if end_pos == -1:
+ raise Exception(
+ "Invalid descriptor: cannot find the end of key expression")
+
+ return end_pos
+
+
+class WalletPolicy(object):
+ """Simple class to represent wallet policies. This is a toy implementation that does not parse the descriptor
+ template. A more robust implementation would build the abstract syntax tree of the template and of the descriptor,
+ allowing one to detect errors, and manipulate it semantically instead of relying on string manipulation."""
+
+ def __init__(self, descriptor_template: str, keys_info: List[str]):
+ self.descriptor_template = descriptor_template
+ self.keys_info = keys_info
+
+ def to_descriptor(self) -> str:
+ """Converts a wallet policy into the descriptor (with the / syntax, if present)."""
+
+ desc = self.descriptor_template
+
+ # replace each "/**" with "/<0;1>/*"
+ desc = desc.replace("/**", "/<0;1>/*")
+
+ # process all the @N expressions in decreasing order. This guarantees that string replacements
+ # works as expected (as any prefix expression is processed after).
+ for i in reversed(range(len(self.keys_info))):
+ desc = desc.replace(f"@{i}", self.keys_info[i])
+
+ # there should not be any remaining "@" expressions
+ if desc.find("@") != -1:
+ return Exception("Invalid descriptor template: contains invalid key index")
+
+ return desc
+
+ @classmethod
+ def from_descriptor(cls, descriptor: str) -> 'WalletPolicy':
+ """Converts a "reasonable" descriptor (with the / syntax) into the corresponding wallet policy."""
+
+ # list of pairs of integers, where the tuple (m,n) with m < n means a key expression starts at
+ # m (inclusive) and at n (exclusive)
+ key_expressions: List[Tuple[int, int]] = []
+
+ key_with_orig_pos_start = None
+
+ def parse_key_expressions(only_first=False, handle_musig=False):
+ # Starting at the position in `key_with_orig_pos_start`, parses a number of key expressions, and updates
+ # the `key_expressions` array accordingly.
+ # If `only_first` is `True`, it stops after parsing a single key expression.
+ # If `handle_musig` is `True`, and a key expression is a `musig` operator, it recursively parses
+ # the keys in the musig expression. `musig` inside `musig` is not allowed.
+
+ nonlocal key_with_orig_pos_start
+ if key_with_orig_pos_start is None:
+ raise Exception("Unexpected error")
+
+ while True:
+ if handle_musig and descriptor[key_with_orig_pos_start:].startswith("musig"):
+ closing_parenthesis_pos = find_first(
+ descriptor, key_with_orig_pos_start, [")"])
+ if closing_parenthesis_pos == -1:
+ raise Exception(
+ "Invalid descriptor: musig without closing parenthesis")
+ key_with_orig_pos_start = key_with_orig_pos_start + \
+ len("musig(")
+ parse_key_expressions(
+ only_first=False, handle_musig=False)
+
+ key_pos_end = closing_parenthesis_pos + 1
+ else:
+ key_pos_end = find_key_end_position(
+ descriptor, key_with_orig_pos_start)
+ key_expressions.append(
+ (key_with_orig_pos_start, key_pos_end))
+
+ if descriptor[key_pos_end] == '/':
+ # find the actual end (comma or closing parenthesis)
+ key_pos_end = find_first(
+ descriptor, key_pos_end, [",", ")"])
+ if key_pos_end == -1:
+ raise Exception(
+ "Invalid descriptor: unterminated key expression")
+
+ if descriptor[key_pos_end] == ',':
+ # There is another key expression, repeat from after the comma
+ key_with_orig_pos_start = key_pos_end + 1
+ else:
+ break
+
+ if only_first:
+ break
+
+ # operators for which the KEY is the first argument
+ operators_key_first = ["pk", "pkh", "pk_h", "pk_k", "tr"]
+ # operators for which the KEY is everything except the first argument
+ operators_key_all_but_first = [
+ "multi", "sortedmulti", "multi_a", "sortedmulti_a"]
+ for op in operators_key_first + operators_key_all_but_first:
+ for op_pos_start in find_all(descriptor, op + "("):
+
+ # ignore if not a whole word (otherwise "sortedmulti" would be found inside "multi")
+ if op_pos_start > 0 and 'a' <= desc[op_pos_start - 1] <= 'z':
+ continue
+
+ if op in operators_key_all_but_first:
+ # skip the first argument (we know it's not a KEY expression, so it does not have a comma)
+ first_comma_pos = descriptor.find(",", op_pos_start)
+ if first_comma_pos == -1:
+ raise Exception(
+ "Invalid descriptor: multi, sortedmulti, multi_a and sortedmulti_a must have at least two arguments")
+ key_with_orig_pos_start = 1 + first_comma_pos
+ else:
+ # other operators, the first argument is already a KEY expression
+ key_with_orig_pos_start = op_pos_start + len(op) + 1
+
+ only_first = op in operators_key_first
+ parse_key_expressions(
+ only_first=only_first, handle_musig=True)
+
+ result: List[str] = []
+ keys: List[str] = []
+ keys_to_idx: Mapping[str, int] = {}
+
+ prev_end = 0
+ for start, end in sorted(key_expressions):
+ result.append(descriptor[prev_end:start])
+
+ key = descriptor[start:end]
+ if key not in keys_to_idx:
+ idx = len(keys)
+ keys.append(key)
+ keys_to_idx[key] = idx
+ else:
+ idx = keys_to_idx[key]
+ result.append(f"@{idx}")
+
+ prev_end = end
+
+ result.append(descriptor[prev_end:])
+
+ return cls("".join(result), keys)
+
+
+if __name__ == "__main__":
+ descriptors = [
+ "pkh([d34db33f/44'/0'/0']xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/**)",
+ "wsh(multi(1,xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB/**,xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH/**))",
+ "tr([12345678/44'/0'/0']xpub6BVZ6JrGsWsUbpP74S8rnz13hVFDtYtKyuTTEYPNSF6GFpDFpL1YXWg3BpwpUWAnsZZ7Qe3XKz7GL3BEx3RQVq61cxqSkjceq25S1xFKFVa,{pk(xpub6AGdromjXf5yf3m7ndaCoR9Ac3UjwTvQ7QQkZoyoh2vfGE9i1AwB2vCbvjTpBL1KRERUsGszg63SVNXsHZU3CiykQqtZPrdXKMdaG2vs6uu),pk(xpub6AnhdkteWC4kPQvkY3QQXGmDCMfmFoYzEQ7FwRFa4BQ1a22k4VL4BD3Jdcog2Sf2KzBscXXAdPRMgjCBDeq6bAryqnMaWX2FaVUGPxWMLDh)})",
+ "tr(xpub6AEWqA1MNRzBBXenkug4NtNguDKTNcXoKQj8fU9VQyid38yikruFRffjoDm9UEaHGEJ6jQxjYdWWZRxR7Xy5ePrQNjohXJuNzkRNSiiBUcE,sortedmulti_a(2,[11223344/44'/0'/0']xpub6AyJhEKxcPaPnYNuA7VBeUQ24v6mEzzPSX5AJm3TSyg1Zsti7rnGKy1Hg6JAdXKF4QUmFZbby9p97AjBNm2VFCEec2ip5C9JntyxosmCeMW,xpub6AQVHBgieCHpGo4GhpGAo4v9v7hfr2Kr4D8ZQJqJwbEyZwtW3pWYSLRQyrNYbTzpoq6XpFtaKZGnEGUMtiydCgqsJDAZNqs9L5QDNKqUBsV))",
+ "tr([11111111/44'/0'/0']xpub6CLZSUDtcUhJVDoPSY8pSRKi4W1RSSLBgwZ2AYmwTH9Yv5tPVFHZxJBUQ27QLLwHej6kfo9DQQbwaHmpXsQq59CjtsE2gNLHmojwgMrsQNe/**,{and_v(v:pk([22222222/44'/0'/0']xpub6CiztfGsUxmpwkWe6gvz8d5VHyFLDoiPpeUfWmQ2vWAhQL3Z1hhEc6PE4irFs4bzjS7dCB4yyinaubrCpFJq4bcKGCD4jjqTxaWiKAJ7mvJ/**),older(52596)),multi_a(2,[33333333/44'/0'/0']xpub6DTZd6od7is2wxXndmE7zaUifzFPwVKshVSGEZedfTJtUjfLyhy4hgCW15hvxRpGaDmtiFoJKaCEaSRfXrQBuYRx18zwquy46dwBsJnsrz2/**,[44444444/44'/0'/0']xpub6BnK4wFbPeLZM4VNjoUA4yLCru6kCT3bhDJNBhbzHLGp1fmgK6muz27h4drixJZeHG8vSS5U5EYyE3gE8ozG94iNg3NDYE8M5YafvhzhMR9/**)})",
+ "tr(musig([33333333/44'/0'/0']xpub6DTZd6od7is2wxXndmE7zaUifzFPwVKshVSGEZedfTJtUjfLyhy4hgCW15hvxRpGaDmtiFoJKaCEaSRfXrQBuYRx18zwquy46dwBsJnsrz2,[44444444/44'/0'/0']xpub6BnK4wFbPeLZM4VNjoUA4yLCru6kCT3bhDJNBhbzHLGp1fmgK6muz27h4drixJZeHG8vSS5U5EYyE3gE8ozG94iNg3NDYE8M5YafvhzhMR9)/**,{and_v(v:pk([22222222/44'/0'/0']xpub6CiztfGsUxmpwkWe6gvz8d5VHyFLDoiPpeUfWmQ2vWAhQL3Z1hhEc6PE4irFs4bzjS7dCB4yyinaubrCpFJq4bcKGCD4jjqTxaWiKAJ7mvJ/**),older(52596)),pk([11111111/44'/0'/0']xpub6CLZSUDtcUhJVDoPSY8pSRKi4W1RSSLBgwZ2AYmwTH9Yv5tPVFHZxJBUQ27QLLwHej6kfo9DQQbwaHmpXsQq59CjtsE2gNLHmojwgMrsQNe/**)})",
+ ]
+
+ for desc in descriptors:
+ # Demoes the conversion from a "sane" descriptor to a wallet policy
+ print(f"Descriptor:\n{desc}")
+ wp = WalletPolicy.from_descriptor(desc)
+ print(f"Policy descriptor template:\n{wp.descriptor_template}")
+ print(f"Keys:\n{wp.keys_info}")
+ print("======================================================\n")
+
+ # Converting back to descriptors also works, as long as we take care of /**
+ assert wp.to_descriptor().replace("/<0;1>/*", "/**") == desc
diff --git a/bip-0389.mediawiki b/bip-0389.mediawiki
new file mode 100644
index 0000000000..6c88a89aff
--- /dev/null
+++ b/bip-0389.mediawiki
@@ -0,0 +1,110 @@
+
+
+==Abstract==
+
+This document specifies a modification to Key Expressions of Descriptors that are described in BIP 380.
+This modification allows Key Expressions to indicate BIP 32 derivation path steps that can have multiple values.
+
+==Copyright==
+
+This BIP is licensed under the BSD 2-clause license.
+
+==Motivation==
+
+Descriptors can describe the scripts that are used in a wallet, but wallets often require at least two descriptors for all of the scripts that they watch for.
+Wallets typically have one descriptor for producing receiving addresses, and the other for change addresses.
+These descriptors are often extremely similar - they produce the same types of scripts, derive keys from the same master key, and use derivation paths that are almost identical.
+The only differences are in the derivation path where one of the steps will be different between the descriptors.
+Thus it is useful to have a notation to represent both descriptors as a single descriptor where one of the derivation steps is a pair of values.
+
+==Specification==
+
+For extended keys and their derivations paths in a Key Expression, BIP 380 states:
+
+* xpub encoded extended public key or xprv encoded extended private key (as defined in BIP 32)
+** Followed by zero or more /NUM or /NUMh path elements indicating BIP 32 derivation steps to be taken after the given extended key.
+** Optionally followed by a single /* or /*h final step to denote all direct unhardened or hardened children.
+
+This is modified to state:
+
+* xpub encoded extended public key or xprv encoded extended private key (as defined in BIP 32)
+** Followed by zero or more /NUM (may be followed by h, H, or ' to indicate a hardened step) path elements indicating BIP 32 derivation steps to be taken after the given extended key.
+** Followed by zero or one / (each NUM may be followed by h, H, or ' to indicate a hardened step) path element indicating a tuple of BIP 32 derivation steps to be taken after the given extended key.
+*** Followed by zero or more ;NUM (may be followed by h, H, or ' to indicate a hardened step) additional tuple values of BIP 32 derivation steps
+*** Followed by a single >/
+** Followed by zero or more /NUM (may be followed by h, H, or ' to indicate a hardened step) path elements indicating BIP 32 derivation steps to be taken after the given extended key.
+** Optionally followed by a single /* (may be followed by h, H, or ' to indicate a hardened step) final step to denote all direct unhardened or hardened children.
+
+When a / is encountered, parsers should account for a presence of multiple descriptors where the first descriptor uses the first NUM, and a second descriptor uses the second NUM, and so on, until each NUM is accounted for in the production of public keys, scripts, and addresses, as well as descriptor import and export operations.
+Descriptors that contain multiple Key Expressions that each have a / must have tuples of exactly the same length so that they are derived in lockstep in the same way that /* paths in multiple Key expressions are handled.
+Duplicate NUMs within a tuple are not allowed.
+
+The common use case for this is to represent descriptors for producing receiving and change addresses.
+When interpreting for this use case, wallets should use the first descriptor for producing receiving addresses, and the second descriptor for producing change addresses.
+For this use case, the element will commonly be the value /<0;1>
+
+Note that only one / specifier is allowed in a Key Expression.
+
+==Test Vectors==
+
+Valid multipath descriptors followed by the descriptors they expand into as sub-bullets
+
+* pk(xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/<0;1>)
+** pk(xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/0)
+** pk(xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/1)
+* pkh(xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/<2147483647h;0>/0)
+** pkh(xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/2147483647h/0)
+** pkh(xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/0/0)
+* wpkh([ffffffff/13h]xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH/<1;3>/2/*
+** wpkh([ffffffff/13h]xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH/1/2/*)
+** wpkh([ffffffff/13h]xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH/3/2/*)
+* multi(2,xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/<1;2>/*,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/<3;4>/0/*)
+** multi(2,xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/1/*,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/3/0/*)
+** multi(2,xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/2/*,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/4/0/*)
+* pkh(xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB/<0;1;2>)
+** pkh(xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB/0)
+** pkh(xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB/1)
+** pkh(xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB/2)
+* sh(multi(2,xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/<1;2;3>/0/*,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/0/*,xpub661MyMwAqRbcGDZQUKLqmWodYLcoBQnQH33yYkkF3jjxeLvY8qr2wWGEWkiKFaaQfJCoi3HeEq3Dc5DptfbCyjD38fNhSqtKc1UHaP4ba3t/0/0/<3;4;5>/*))
+** sh(multi(2,xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/1/0/*,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/0/*,xpub661MyMwAqRbcGDZQUKLqmWodYLcoBQnQH33yYkkF3jjxeLvY8qr2wWGEWkiKFaaQfJCoi3HeEq3Dc5DptfbCyjD38fNhSqtKc1UHaP4ba3t/0/0/3/*))
+** sh(multi(2,xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/2/0/*,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/0/*,xpub661MyMwAqRbcGDZQUKLqmWodYLcoBQnQH33yYkkF3jjxeLvY8qr2wWGEWkiKFaaQfJCoi3HeEq3Dc5DptfbCyjD38fNhSqtKc1UHaP4ba3t/0/0/4/*))
+** sh(multi(2,xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/3/0/*,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/0/*,xpub661MyMwAqRbcGDZQUKLqmWodYLcoBQnQH33yYkkF3jjxeLvY8qr2wWGEWkiKFaaQfJCoi3HeEq3Dc5DptfbCyjD38fNhSqtKc1UHaP4ba3t/0/0/5/*))
+
+Invalid descriptors
+
+* Multiple multipath specifiers: pkh(xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/<0;1>/<2;3>)
+* Multipath specifier in origin: pkh([deadbeef/<0;1>]xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB/0)
+* Multipath specifiers of mismatched lengths: tr(xpub661MyMwAqRbcF3yVrV2KyYetLMYA5mCbv4BhrKwUrFE9LZM6JRR1AEt8Jq4V4C8LwtTke6YEEdCZqgXp85YRk2j74EfJKhe3QybQ9kcUjs4/<6;7;8;9>/*,{pk(xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/<1;2;3>/0/*),pk(xpub661MyMwAqRbcGDZQUKLqmWodYLcoBQnQH33yYkkF3jjxeLvY8qr2wWGEWkiKFaaQfJCoi3HeEq3Dc5DptfbCyjD38fNhSqtKc1UHaP4ba3t/0/0/<3;4;5>/*)})
+* Multipath specifiers of mismatched lengths: sh(multi(2,xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc/<1;2;3>/0/*,xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L/0/*,xprv9s21ZrQH143K3jUwNHoqQNrtzJnJmx4Yup8NkNLdVQCymYbPbJXnPhwkfTfxZfptcs3rLAPUXS39oDLgrNKQGwbGsEmJJ8BU3RzQuvShEG4/0/0/<3;4>/*))
+* Empty multipath specifier: wpkh(xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB/<>/*)
+* Missing multipath start: wpkh(xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB/0>/*)
+* Missing multipath end: wpkh(xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB/<0/*)
+* Missing index in multipath specifier: wpkh(xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB/<0;>/*)
+
+==Backwards Compatibility==
+
+This is an addition to the Key Expressions defined in BIP 380.
+Key Expressions using the format described in BIP 380 are compatible with this modification and parsers that implement this will still be able to parse such descriptors.
+However as this is an addition to Key Expressions, older parsers will not be able to understand such descriptors.
+
+This modification to Key Expressions uses two new characters: < and ;.
+These are part of the descriptor character set and so are covered by the checksum algorithm.
+As these are previously unused characters, old parsers will not accidentally mistake them for indicating something else.
+
+This proposal is in contrast to similar proposals such as BIP 88 which allow for multiple derivation indexes in a single element.
+This limitation exists in order to reduce the number of descriptors that are expanded, avoid confusion about how to expand the descriptor, and avoid having expanded descriptors that users are not expecting.
+
+==Reference Implementation==
+
+https://github.com/bitcoin/bitcoin/pull/22838
diff --git a/bip-0390.mediawiki b/bip-0390.mediawiki
new file mode 100644
index 0000000000..8dcecab7b2
--- /dev/null
+++ b/bip-0390.mediawiki
@@ -0,0 +1,117 @@
+
+
+==Abstract==
+
+This document specifies a musig() key expression for output script descriptors.
+musig() expressions take multiple keys and produce an aggregate public key using BIP 327.
+
+==Copyright==
+
+This BIP is licensed under the Creative Commons CC0 1.0 Universal license.
+
+==Motivation==
+
+BIP 327 introduces the MuSig2 Multi-Signature scheme. It is useful to have a way for keys to be used
+in a MuSig2 aggregate key to be expressed in descriptors so that wallets can more easily use MuSig2.
+
+==Specification==
+
+A new key expression is defined: musig().
+
+===musig(KEY, KEY, ..., KEY)===
+
+The musig(KEY, KEY, ..., KEY) expression can only be used inside of a tr()
+expression as a key expression. It additionally cannot be nested within another musig()
+expression. Repeated participant public keys are not allowed. The aggregate public key is produced
+by using the KeyAgg algorithm on all KEYs specified in the expression after performing all
+specified derivation. As with script expressions, KEY can contain child derivation specified by
+/*. A new aggregate public key will be computed for each child index. Keys must be sorted
+with the KeySort algorithm after all derivation and prior to aggregation'''Why must
+the keys be sorted prior to aggregation?''' Although the descriptor's written form sets an order
+for the keys that could be used for aggregation, the order should not matter as MuSig2 philosophically
+operates over a set of keys, with the order merely being an implementation detail in aggregation
+itself. Requiring sorting of keys prior to aggregation enforces this philosophy as keys can be
+written in the descriptor in any order with the end result still being the same. Furthermore, this
+aids with recovery where the descriptor was not backed up as users will not need to also have
+backed up, or guess, the correct order of keys..
+
+===musig(KEY, KEY, ..., KEY)/NUM/.../*===
+
+musig(KEY, KEY, ..., KEY)/NUM/.../* expressions are also allowed, with the same usage
+restrictions as in the previous section. The aggregate public key
+is first computed as described above, with the keys also being sorted after all derivation and prior
+to aggregation. Then further BIP 32 derivation will be performed on the aggregate public key as described in
+[[bip-0328.mediawiki|BIP 328]]. As there is no aggregate private key,
+only unhardened derivation from the aggregate public key is allowed, and thus the derivation steps
+following the musig() expression cannot contain
+/NUMh or /NUM' derivation steps nor /*h, or /*' child derivation.
+For these musig() expressions, the KEY expressions contained within must be xpubs or derived from
+xpubs, and cannot contain child derivation as specified by a /*, /*', or /*h.
+
+==Test Vectors==
+
+Valid descriptors containing followed by the scripts they produce. Descriptors involving derived child keys
+will have the 0th, 1st, and 2nd scripts listed.
+
+* rawtr(musig(KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU74sHUHy8S,03dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659,023590a94e768f8e1815c2f24b4d80a8e3149316c3518ce7b7ad338368d038ca66))
+** 5120789d937bade6673538f3e28d8368dda4d0512f94da44cf477a505716d26a1575
+* tr(musig(02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9,03dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659,023590a94e768f8e1815c2f24b4d80a8e3149316c3518ce7b7ad338368d038ca66))
+** 512079e6c3e628c9bfbce91de6b7fb28e2aec7713d377cf260ab599dcbc40e542312
+* rawtr(musig(xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y)/0/*)
+** 51209508c08832f3bb9d5e8baf8cb5cfa3669902e2f2da19acea63ff47b93faa9bfc
+** 51205ca1102663025a83dd9b5dbc214762c5a6309af00d48167d2d6483808525a298
+** 51207dbed1b89c338df6a1ae137f133a19cae6e03d481196ee6f1a5c7d1aeb56b166
+* tr(musig(xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y)/0/*,pk(f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9))
+** 51201d377b637b5c73f670f5c8a96a2c0bb0d1a682a1fca6aba91fe673501a189782
+** 51208950c83b117a6c208d5205ffefcf75b187b32512eb7f0d8577db8d9102833036
+** 5120a49a477c61df73691b77fcd563a80a15ea67bb9c75470310ce5c0f25918db60d
+* tr(f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9,pk(musig(xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y)/0/*))
+** 512068983d461174afc90c26f3b2821d8a9ced9534586a756763b68371a404635cc8
+** 5120368e2d864115181bdc8bb5dc8684be8d0760d5c33315570d71a21afce4afd43e
+** 512097a1e6270b33ad85744677418bae5f59ea9136027223bc6e282c47c167b471d5
+
+Invalid descriptors
+
+* musig() is not allowed in top-level pk(): pk(musig(02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9,03dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659,023590a94e768f8e1815c2f24b4d80a8e3149316c3518ce7b7ad338368d038ca66))
+* musig() is not allowed in top-level pkh(): pkh(musig(02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9,03dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659,023590a94e768f8e1815c2f24b4d80a8e3149316c3518ce7b7ad338368d038ca66))
+* musig() is not allowed in wpkh(): wpkh(musig(02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9,03dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659,023590a94e768f8e1815c2f24b4d80a8e3149316c3518ce7b7ad338368d038ca66))
+* musig() is not allowed in combo(): combo(musig(02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9,03dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659,023590a94e768f8e1815c2f24b4d80a8e3149316c3518ce7b7ad338368d038ca66))
+* musig() is not allowed in sh(wpkh()): sh(wpkh(musig(02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9,03dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659,023590a94e768f8e1815c2f24b4d80a8e3149316c3518ce7b7ad338368d038ca66)))
+* musig() is not allowed in sh(wsh()): sh(wsh(pk(musig(02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9,03dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659,023590a94e768f8e1815c2f24b4d80a8e3149316c3518ce7b7ad338368d038ca66))))
+* musig() is not allowed in wsh(): wsh(musig(02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9,03dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659,023590a94e768f8e1815c2f24b4d80a8e3149316c3518ce7b7ad338368d038ca66))
+* musig() is not allowed in sh(): sh(musig(02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9,03dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659,023590a94e768f8e1815c2f24b4d80a8e3149316c3518ce7b7ad338368d038ca66))
+* Ranged musig() requires all participants to be xpubs: tr(musig(02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9,03dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659,023590a94e768f8e1815c2f24b4d80a8e3149316c3518ce7b7ad338368d038ca66)/0/0)
+* Cannot have ranged participants if musig() is also ranged: tr(musig(xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/*,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y)/0/*)
+* musig() cannot have hardened derivation steps: tr(musig(xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y)/0h/*)
+* musig() cannot have hardened child derivation: tr(musig(xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y)/0/*h)
+
+==Backwards Compatibility==
+
+musig() expressions use the format and general operation specified in
+[[bip-0380.mediawiki|BIP 380]]. As these are a set of wholly new expressions, they are not compatible
+with any implementation. However the keys are produced using a standard process so existing software
+are likely to be familiar with them.
+
+==Rationale==
+
+
+
+==Reference Implementation==
+
+TBD
+
+==Acknowledgements==
+
+Thanks to Pieter Wuille, Andrew Poelstra, Sanket Kanjalkar, Salvatore Ingala, and all others who
+participated in discussions on this topic.
diff --git a/bip-0431.mediawiki b/bip-0431.mediawiki
new file mode 100644
index 0000000000..2af0e53c26
--- /dev/null
+++ b/bip-0431.mediawiki
@@ -0,0 +1,291 @@
+
+
+==Abstract==
+
+This document describes pinning problems that can arise from limitations in mempool policy.
+
+It also describes a type of policy with adjusted topology limits which, combined with other policy rules, helps minimize the potential pinning problems. These restrictions simplify the assessment of incentive compatibility of accepting or replacing such transactions, thus helping ensure any replacements are more profitable for the node. Within the context of nodes that implement this policy, fee-bumping is more reliable for users.
+
+==Motivation==
+
+Mempools typically accept and relay transactions that spend outputs from other unconfirmed transactions, but restrict package sizes through ancestor and descendant limits
+https://github.com/bitcoin/bitcoin/blob/632a2bb731804dffe52bd4cbd90bfee352d25ede/doc/policy/mempool-limits.md
+to limit the computational complexity of mempool operations and mitigate Denial of Service attacks.
+
+Users may also create unconfirmed transactions that conflict with -- or are "double spends" of -- each other by spending the same input(s) in both.
+Instead of always keeping the first-seen transaction, many mempools also have some kind of Replace by Fee (RBF) policy
+
+[https://github.com/bitcoin/bitcoin/blob/632a2bb731804dffe52bd4cbd90bfee352d25ede/doc/policy/mempool-replacements.md Bitcoin Core's RBF policy] at the time of writing. It is slightly different from what is described in BIP 125.
+
+to keep the more incentive compatible transaction, i.e. one that would earn a miner more fees. Users utilize these rules when they create higher feerate double-spends (replacements) to expedite confirmation of their transactions.
+
+However, these policies make imperfect trade-offs between incentive compatibility and DoS-resistance. For example, malicious actors may sometimes exploit limitations to prevent incentive-compatible transactions from being accepted or fee-bumped (''pinning'').
+
+Pinning is consequential to contracting protocols in which untrusted parties construct and sign time-sensitive transactions to be broadcast on-chain later
+Posts about pinning in LN and LN-Symmetry:
+* [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2022-May/020458.html "Bringing a nuke to a knife fight: Transaction introspection to stop RBF pinning"]
+* [https://lists.linuxfoundation.org/pipermail/lightning-dev/2020-April/002639.html "RBF Pinning with Counterparties and Competing Interest"]
+* [https://lists.linuxfoundation.org/pipermail/lightning-dev/2020-June/002758.html "Pinning : The Good, The Bad, The Ugly"]
+* [https://github.com/t-bast/lightning-docs/blob/master/pinning-attacks.md "Pinning Attacks"]
+* [https://gist.github.com/instagibbs/60264606e181451e977e439a49f69fe1 "Eltoo Pinning"]
+.
+When the funds available to be redeemed by each party depend on a transaction confirming within a specific time window, a malicious party may be able to steal money if the honest party cannot get their transaction confirmed. As such, the ability to fee-bump a transaction to entice miners to include it in their blocks is crucial to the security of the protocol.
+
+===RBF pinning through absolute fees===
+
+Imagine that counterparties Alice and Mallory have transactions (or packages) A and B, respectively, which conflict with each other. Alice broadcasts A and Mallory broadcasts B. RBF rules require the replacement transaction pay a higher absolute fee than the aggregate fees paid by all original transactions ([https://github.com/bitcoin/bitcoin/blob/master/doc/policy/mempool-replacements.md#current-replace-by-fee-policy "Rule 3"]). This means Mallory may increase the fees required to replace B beyond what Alice was planning to pay for A's fees.
+
+1. Adding transaction(s) that descend from B and pay a low feerate (too low to fee-bump B through CPFP)Example: https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2023-December/022216.html.
+
+2. Adding a high-fee descendant of B that also spends from another large, low-feerate mempool transaction (where the fee of the descendant is too low to fee-bump both B and its other parent through CPFP)Example: https://github.com/bitcoin/bitcoin/pull/25038#issuecomment-1320295394.
+
+===RBF pinning through number of conflicts===
+
+RBF rules require that no replacement trigger the removal of more than 100 transactions ([https://github.com/bitcoin/bitcoin/blob/master/doc/policy/mempool-replacements.md#current-replace-by-fee-policy "Rule 5"]). This number includes the descendants of the conflicted mempool transactions. Mallory can make it more difficult to replace transactions by attaching lots of descendants to them. For example, if Alice wants to batch-replace 5 transactions but each has 21 descendants, her replacement will be rejected regardless of its fees.
+
+===RBF incentive compatibility requirements===
+
+There is currently no effective rule to enforce that a replacement transaction would be more incentive compatible to keep in the mempool. It is difficult to quantify the incentive compatibility of a set of transactions, especially in comparison with another set of transactionshttps://delvingbitcoin.org/t/mempool-incentive-compatibility/553, but the requirement of a feerate increase ([https://github.com/bitcoin/bitcoin/blob/master/doc/policy/mempool-replacements.md#current-replace-by-fee-policy "Rule 6"]) is far too simplistic.
+
+For example, a user could create a replacement transaction that pays more fees and is higher feerate, but has a low feerate ancestor and would confirm slower than the original transaction. As a result, all transactions signed with SIGHASH_ANYONECANPAY are vulnerable to being replaced by a transaction that will confirm later than the originalhttps://github.com/bitcoin/bitcoin/pull/23121#pullrequestreview-766271585.
+
+===Child fees don't count towards RBF rules===
+
+A transaction must meet all fee-related requirements (Rules 3, 4, 6) alone; its child's fees cannot be used. A ''Package RBF'' policy would allow a transaction's child to be used for its RBF requirements.
+
+In LN Penalty, conflicting commitment transactions signed with the same fees cannot replace each other, even if accompanied by a fee-bumping child. This limitation necessitates the presence of two anchor outputs, allowing both parties to fee-bump either commitment transaction that enters their mempool.
+
+===Package limit pinning and replacing CPFP Carve Out===
+
+Mempool policies limit the number and total virtual size of an unconfirmed transaction's descendants. A fee-bumping child of an unconfirmed transaction (CPFP) may be rejected for exceeding the descendant limit. When a transaction has multiple outputs owned by different parties, a malicious party can prevent the other(s) from CPFPing their transaction by attaching enough descendants to monopolize the descendant limit (''package limit pinning'').
+
+LN commitment transactions rely on CPFP carve out [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-November/016518.html "CPFP Carve-Out for Fee-Prediction Issues in Contracting Applications (eg Lightning)"] to avoid package limit pinning.
+
+There are weaknesses with this approach of using 2 anchors and CPFP Carve Out. This proposal helps address a few of them (see Related Work for how other weaknesses are addressed):
+
+* Cluster Mempool necessitates the removal of CPFP Carve Out https://delvingbitcoin.org/t/an-overview-of-the-cluster-mempool-proposal/393#the-cpfp-carveout-rule-can-no-longer-be-supported-12.
+* CPFP Carve Out only allows ''one more'' child to be added to the transaction. This means it cannot guarantee the ability to CPFP for more than 2 parties of a shared transaction.
+
+==Topologically Restricted Until Confirmation==
+
+This section describes one approach for opt-in policy rules that can realistically be deployed today and is useful to today's applications.
+It is based on the idea that most limitations stem from existing ancestor/descendant package limits being too permissive for the majority of use cases.
+
+The scope of the policy's anti-pinning benefits is limited to the individual node's mempool, and the degree to which a user's transaction is safe from pinning depends how much of the network has adopted this policy.
+
+Similarly, there are multiple approaches to creating a policy to minimize pinning, more may become available over time (see Related Work section), and the details of this approach can be tweaked if conditions change. For example, if loosening one of the topology restrictions enables a new use case while still providing acceptable pinning bounds, it can be changed.
+
+===Specification===
+
+Senders can signal that they want a transaction to be Topologically Restricted Until Confirmation (TRUC). Specifically, set nVersion=3.
+A node that implements this policy would apply their existing standardness and policy rules, along with the following set of rules, to TRUC transactions:
+
+1. A TRUC transaction signals replaceability, even if it does not signal BIP125 replaceability.
+
+2. Any TRUC transaction's unconfirmed ancestors must all be TRUC. Any descendant of an unconfirmed TRUC transaction must also be TRUC.
+Rationale:
+* Requiring packages to be all-or-none TRUC makes it possible to enforce the topology limits. For example, the TRUC descendant limit would not be very meaningful if it could be bypassed by creating a non-TRUC child.
+* Combined with Rule 1, this requirement creates "inherited signaling" when descendants of unconfirmed transactions are created. Checking whether a transaction signals replaceability this way does not require mempool traversal, and does not change based on what transactions are mined.
+
+Note: A TRUC transaction can spend outputs from ''confirmed'' non-TRUC transactions. A non-TRUC transaction can spend outputs from ''confirmed'' TRUC transactions.
+
+3. An unconfirmed TRUC transaction cannot have more than 1 unconfirmed ancestor. An unconfirmed TRUC transaction cannot have more than 1 unconfirmed descendant. CPFP Carve Out is not granted to TRUC transactions.
+Rationale:
+* The larger the descendant limit, the more transactions may need to be replaced. See #1 in Rule 3 Pinning section above. This also makes pinning using Rule 5 more difficult, since a directly conflicting transaction has fewer possible descendants.
+* These two limits (ancestor count 2, descendant count 2) effectively create a cluster limit using the existing ancestor and descendant limits. Increasing them to 3 would imply an infinite cluster count limit.
+* This 1-parent-1-child topology makes it possible to use ancestor score (minimum of ancestor feerate and individual feerate) as a measure of incentive compatibility.
+
+ Q: Why not allow multiple parents to enable batched fee-bumping?
+ To mitigate pinning through absolute fees, we need to prevent a child of an unconfirmed TRUC transaction from bringing in more unconfirmed ancestors. See #2 in "RBF pinning through absolute fees" section above.
+
+ Q: Why not allow another child?
+ Allowing another child disables the ability to use ancestor score to measure incentive compatibility. Imagine the original transaction, A, has a child B and co-parent C (i.e. B spends from A and C). C also has another child, D. B is one of the original transactions and thus its ancestor feerate must be lower than the package's feerate. However, this may be an underestimation because D can bump C without B's help. This is resolved if TRUC transactions can only have TRUC ancestors, as then C cannot have another child.
+
+ Q: Why allow any descendants at all?
+ At least 1 descendant is required to allow CPFP of the presigned transaction. Without package RBF, multiple anchor outputs would be required to allow each counterparty to fee-bump any presigned transaction. With package RBF, since the presigned transactions can replace each other, 1 anchor output is sufficient.
+
+
+4. A TRUC transaction cannot have a sigop-adjusted virtual size larger than 10,000 vB.
+Rationale: Limit the amount of virtual bytes (and thus fees) that may need to be replaced, while leaving a comfortable amount of space for payments, HTLCs, or other uses of the transaction. Generally, having a smaller maximum size helps to better define bounds for algorithms and memory usage, and the existing limit of 100,000 vB seems much larger than necessary.
+
+
+5. A TRUC transaction that has an unconfirmed TRUC ancestor cannot have a sigop-adjusted virtual size larger than 1000 vB.
+Rationale: Limit the amount of virtual bytes (and thus fees) that may need to be replaced, while leaving a comfortable amount of space for inputs to fund the transaction.
+ Q: Why not bigger?
+ The larger the descendant size limit, the more vbytes may need to be replaced. With default limits, if the child is e.g. 100,000 vB, that might be an additional 100,000 sats (at 1 sat/vbyte) or more, depending on the feerate. Restricting all children to 1000 vB reduces the upper bound of the additional fees by a factor of 100.
+
+ This rule is also easily tacked on to existing logic for policy and wallets. A maximum size standard transaction (100 kvB) can have up to 1000 vB of descendants to be within the default descendant limit (101 kvB).
+
+ Q: Why not smaller?
+ The smaller this limit, the fewer UTXOs a child may use to fund this fee-bump. For example, only allowing the TRUC child to have 2 inputs would require wallets to maintain a pool of high-value confirmed UTXOs. However, as the fee-bumping child only needs to fund fees (as opposed to payments), just a few UTXOs should suffice. With a limit of 1000 vB and usage of taproot outputs, the child can have 15 inputs and 2 outputs (calculated using [https://bitcoinops.org/en/tools/calc-size/ this tool]).
+
+
+6. An individual TRUC transaction is permitted to be below the mempool min relay feerate, assuming it is considered within a package that meets the mempool's feerate requirements.
+Rationale: This allows contracting protocols to create presigned transactions with 0 fees and fee-bump them using CPFP at broadcast time.
+
+
+====Implementation====
+
+* https://github.com/bitcoin/bitcoin/pull/28948
+* https://github.com/bitcoin/bitcoin/pull/29873
+* https://github.com/bitcoin/bitcoin/pull/29496
+
+====Related Work====
+
+This 1-parent-1-child (aka cluster size 2) topology restriction makes the transactions much easier to reason about, which enables additional features like
+feerate diagram comparisons
+
+[https://github.com/bitcoin/bitcoin/pull/29242 this PR] implements feerate diagram creation and comparison for sets of transactions in which the maximum cluster size is 2, e.g. all TRUC transactions.
+,
+package RBF
+
+[https://github.com/bitcoin/bitcoin/pull/28984 this PR] implements package RBF, enforcing incentive compatibility by comparing the feerate diagrams of the mempool before and after replacement. The feerate diagrams are easy to build when the relevant clusters are of size 2 and below, so package RBF is restricted to those scenarios. As TRUC transactions always have this property, package RBF is enabled for TRUC transactions.
+,
+and sibling eviction
+
+[https://github.com/bitcoin/bitcoin/pull/29306 This PR] implements sibling eviction for TRUC transactions: if a new transaction would exceed a transaction's descendant limit, it considers evicting the existing descendant using replacement rules. Sibling eviction is feasible for TRUC transactions because there is no difficulty in identifying which descendant to evict (there can only be 1).
+.
+
+The [https://github.com/bitcoin/bips/pull/1524 Ephemeral Anchors] proposal builds on top of this one to add more features.
+It changes the anchor script to be anyone can spend, allowing anybody to add fees and reducing the onchain footprint and fee costs.
+It also allows anchor outputs to have 0 value, eliminating the need to deduct value from the input amount in order to create anchors.
+
+The [https://delvingbitcoin.org/t/an-overview-of-the-cluster-mempool-proposal/393/7 Cluster Mempool] proposal makes fundamental changes to mempool structure and policy rules, enabling the accurate assessment of the incentive compatibility of accepting or removing a transaction, among other things. Notably, Cluster Mempool introduces a limit to all transactions' cluster size to make incentive compatibility calculations feasible. This cluster limit is similar to TRUC limits in that it bounds computation to enable improved policies, but is applied to all transactions (not just ones that opt in) and is much less restrictive than TRUC limits.
+
+Cluster Mempool provides a more holistic solution to some of the problems listed (such as adding an incentive compatibility requirement to RBF and safely enabling package RBF for more complex topologies). However, it does not help resolve all problems (such as RBF Pinning through absolute fees and number of conflicts). Also, since Cluster Mempool is incompatible with CPFP Carve Outhttps://delvingbitcoin.org/t/an-overview-of-the-cluster-mempool-proposal/393#the-cpfp-carveout-rule-can-no-longer-be-supported-12, TRUC with sibling eviction and package RBF provide an alternative solution to applications that rely on it.
+
+Building on top of Cluster Mempool, there are also various ideas for extending TRUC transactions and creating another anti-pinning policy
+https://delvingbitcoin.org/t/v3-and-some-possible-futures/523/3.
+
+[https://bitcoinops.org/en/topics/package-relay Package Relay] includes changes in p2p protocol, transaction relay logic, and mempool policy to enable nodes to accept and relay packages of transactions. Much of this proposal's utility relies on the existence of package relay for 1-parent-1-child packages (the topology TRUC supports).
+
+====Backward Compatibility====
+
+Transactions with nVersion=3 were previously nonstandard. There are no known conflicts with previous usage.
+
+====Intended Usage====
+
+Generally, users with no interest in spending unconfirmed outputs from a transaction can make them TRUC transactions for more robust RBF abilities.
+
+This proposal allows for a different solution to fee-bumping in LN, in which commitment transactions are signed with 0 fees and include a single anchor that can later be used to add fees at broadcast time
+Proposals for changes to LN commitment transaction format using TRUC and a single anchor:
+* [https://delvingbitcoin.org/t/lightning-transactions-with-v3-and-ephemeral-anchors/418 "Lightning transactions with v3 and ephemeral anchors"]
+* [https://github.com/instagibbs/bolts/commits/zero_fee_commitment bolts proposal branch]
+* See "Intended usage for LN" section in [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2022-September/020937.html "New transaction policies (nVersion=3) for contracting protocols"]
+.
+A similar fee-bumping model can also be used in other contracting protocols
+Examples of non-LN protocols that have shown interest in, designed, or built fee-bumping using TRUC:
+* A LN-Symmetry implementation using TRUC and ephemeral anchors: [https://delvingbitcoin.org/t/ln-symmetry-project-recap/359 LN-Symmetry Project Recap] [https://github.com/instagibbs/lightning/tree/eltoo_support branch]
+* See "Managing Fees Safely" mentioning ephemeral anchors in [https://jameso.be/vaults.pdf "Vaults and Covenants"]
+.
+
+==Alternatives==
+
+Various alternatives for RBF
+Proposals and discussions dedicated to improving RBF:
+* [https://gist.github.com/glozow/25d9662c52453bd08b4b4b1d3783b9ff "RBF Improvements"]
+* [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2022-January/019817.html "Improving RBF Policy"]
+* [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2019-June/016998.html "[PROPOSAL] Emergency RBF (BIP 125)"]
+
+and new fee-bumping mechanisms
+
+ Proposals and discussions dedicated to improving or creating new fee-bumping mechanisms:
+* [https://github.com/lightning/bolts/pull/1036 "Add option to sign commitments at various feerates"]
+* [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2021-July/019243.html "A Stroll through Fee-Bumping Techniques : Input-Based vs Child-Pay-For-Parent"]
+* [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2020-September/018168.html "A Replacement for RBF and CPFP: Non-Destructive TXID Dependencies for Fee Sponsoring"]
+* [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2022-February/019879.html "Thoughts on fee bumping"]
+
+have been proposed across multiple discussion threads.
+Most alternatives do not conflict with TRUC, and some work in conjunction with this proposal - see Related Work.
+A few popular ideas that were not incorporated into this work are summarized here.
+
+===Alternatives: add static incentive compatibility rule in RBF policy===
+
+Add incentive compatibility requirement to RBF policy using some existing score or static calculation
+Examples of incentive compatibility score proposals and suggestions:
+* [https://github.com/bitcoin/bitcoin/pull/23121 "check ancestor feerate in RBF, remove BIP125 Rule2"]
+* [https://github.com/bitcoin/bitcoin/pull/26451 "Enforce incentive compatibility for all RBF replacements"]
+* https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2022-January/019841.html
+* https://gist.github.com/glozow/25d9662c52453bd08b4b4b1d3783b9ff?permalink_comment_id=4081349#gistcomment-4081349
+.
+
+As the incentive compatibility "score" of a transaction must be dynamically calculated given the structure of mempools today, there is no satisfactory solution. A full calculation is too computationally expensive. Static values can overestimate or underestimate, leading to more pinning problems Four examples of static calculations and an example in which they are all inaccurate: https://gist.github.com/glozow/25d9662c52453bd08b4b4b1d3783b9ff#mining-score-of-a-mempool-transaction.
+The ability to calculate incentive compatibility scores efficiently is a primary feature and motivation for both TRUC transactions and Cluster Mempool.
+
+===Alternatives: replace by feerate===
+
+"Instead of using Rule 3 and/or 4 (requiring an increase in absolute fees), allow replacements with a higher feerate."
+
+One variation of this proposal is to apply this rule in certain exceptional scenarios or when the replacement would confirm "soon"
+Examples of Replace by Feerate proposals and suggestions:
+* [https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2019-June/016998.html "[PROPOSAL] Emergency RBF (BIP 125)"]
+* [https://gist.github.com/glozow/25d9662c52453bd08b4b4b1d3783b9ff#fees-in-next-block-and-feerate-for-the-rest-of-the-mempool]
+* [https://petertodd.org/2024/one-shot-replace-by-fee-rate "One-Shot Replace-by-Fee-Rate"]
+.
+
+The primary problem with these proposals is the potential for free relay and DDoS attacks.
+
+Removing Rule 3 and 4 in general would allow free relay
+Examples of free relay with the removal of Rule 3 and/or 4:
+ Consider a rule where the fee can be decreased (remove Rule 3 and 4) but the feerate must double. In this scenario, a 100 kvB transaction can be replaced by a 100 vB transaction paying 200 sats. That's 200 sats to relay 100,200 vB of transaction data, which is less than 0.002 sat/vB. It becomes quite cheap to replace large portions of the mempool, decreasing both its average feerate and total absolute fees.
+
+ Consider a rule where the fee can stay the same (keep Rule 3 but drop Rule 4) but the feerate must double. The attacker can start out with 100 kvB transaction, paying 1 sat/vB. A user can reduce its size over and over again, doubling the feerate each time until it gets too small, and end up paying 100 ksat for 100 kvB(1 + 1/2 + 1/4 + ... + log2(mintxsize)) -> approaches 200 kvB. This means the attacker pays a rate of 0.5 sat/vB to relay transactions, which is below our "free relay" threshold of 1 sat/vB.
+.
+
+Another issue is the complexity of defining and implementing a "would confirm soon" or "is in the top N portion of the mempool." These proposals require an efficient way to assess the incentive compatibility score of a transaction and where it ranks amongst the other mempool transactions. This isn't feasible without something like cluster mempool (also see the "add static incentive compatibility rule in RBF policy" section above)
+Concerns about Replace by Feerate proposals
+* https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2019-June/017020.html
+* https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2019-June/017002.html
+* https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2022-February/019879.html
+* https://gist.github.com/glozow/25d9662c52453bd08b4b4b1d3783b9ff?permalink_comment_id=4044451#gistcomment-4044451
+.
+
+===Alternatives: implement rate-limiting without fee rules===
+"Since Rule 3 and 4 (requiring an increase in absolute fees) are for rate-limiting, replace them with a mempool-wide or per-peer rate limits on replacements by outpoint and/or bandwidth
+Examples of general rate-limiting proposals and suggestions:
+* https://gist.github.com/glozow/25d9662c52453bd08b4b4b1d3783b9ff?permalink_comment_id=4081349#gistcomment-4081349
+* https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2022-January/019820.html
+* https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2019-June/017024.html
+ Related proposal for changing the amount of bandwidth that replacement transactions use:
+* https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2022-January/019820.html
+."
+
+A problem with any global rate limit is that, in the absence of reputation or identities, the limit could be exhausted by an attacker, thus restricting replacements for honest users. For example, an outpoint-based rate limit could be exhausted by one dishonest participant of a shared transaction, preventing the other participants from making any replacements. There are also other concerns about implementation complexity, free relay issues, and other unresolved edge cases
+Concerns
+* https://gist.github.com/glozow/25d9662c52453bd08b4b4b1d3783b9ff?permalink_comment_id=4081559#gistcomment-4081559
+* https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2022-February/019921.html
+* https://docs.google.com/document/d/1LpYF17HdbXPGHKSl3WYdxG4XTJBNJKSn-c2UJ2yphhE/edit?usp=sharing
+.
+
+
+==Acknowledgements==
+
+Thank you to everyone who contributed to this proposal and document, including
+Jon Atack,
+Matt Corallo,
+Suhas Daftuar,
+Mark Erhardt,
+Antoine Poinsot,
+Antoine Riard,
+Gregory Sanders,
+and Bastien Teinturier.
+
+==References and Rationale==
+
+
+
diff --git a/scripts/buildtable.pl b/scripts/buildtable.pl
new file mode 100755
index 0000000000..4923a9ed4f
--- /dev/null
+++ b/scripts/buildtable.pl
@@ -0,0 +1,208 @@
+#!/usr/bin/perl
+use strict;
+use warnings;
+
+my $topbip = 9999;
+my $include_layer = 1;
+
+my %RequiredFields = (
+ BIP => undef,
+ Title => undef,
+ Author => undef,
+ 'Comments-URI' => undef,
+ Status => undef,
+ Type => undef,
+ Created => undef,
+ # License => undef, (has exceptions)
+);
+my %MayHaveMulti = (
+ Author => undef,
+ 'Comments-URI' => undef,
+ License => undef,
+ 'License-Code' => undef,
+ 'Post-History' => undef,
+);
+my %DateField = (
+ Created => undef,
+);
+my %EmailField = (
+ Author => undef,
+ Editor => undef,
+);
+my %MiscField = (
+ 'Comments-Summary' => undef,
+ 'Discussions-To' => undef,
+ 'Post-History' => undef,
+ 'Replaces' => undef,
+ 'Requires' => undef,
+ 'Superseded-By' => undef,
+);
+
+my %ValidLayer = (
+ 'Consensus (soft fork)' => undef,
+ 'Consensus (hard fork)' => undef,
+ 'Peer Services' => undef,
+ 'API/RPC' => undef,
+ 'Applications' => undef,
+);
+my %ValidStatus = (
+ Draft => undef,
+ Deferred => undef,
+ Proposed => "background-color: #ffffcf",
+ Rejected => "background-color: #ffcfcf",
+ Withdrawn => "background-color: #ffcfcf",
+ Final => "background-color: #cfffcf",
+ Active => "background-color: #cfffcf",
+ Replaced => "background-color: #ffcfcf",
+ Obsolete => "background-color: #ffcfcf",
+);
+my %ValidType = (
+ 'Standards Track' => 'Standard',
+ 'Informational' => undef,
+ 'Process' => undef,
+);
+my %RecommendedLicenses = (
+ 'BSD-2-Clause' => undef,
+ 'BSD-3-Clause' => undef,
+ 'CC0-1.0' => undef,
+ 'GNU-All-Permissive' => undef,
+);
+my %AcceptableLicenses = (
+ %RecommendedLicenses,
+ 'Apache-2.0' => undef,
+ 'BSL-1.0' => undef,
+ 'CC-BY-4.0' => undef,
+ 'CC-BY-SA-4.0' => undef,
+ 'MIT' => undef,
+ 'AGPL-3.0' => undef,
+ 'AGPL-3.0+' => undef,
+ 'FDL-1.3' => undef,
+ 'GPL-2.0' => undef,
+ 'GPL-2.0+' => undef,
+ 'LGPL-2.1' => undef,
+ 'LGPL-2.1+' => undef,
+);
+my %DefinedLicenses = (
+ %AcceptableLicenses,
+ 'OPL' => undef,
+ 'PD' => undef,
+);
+my %GrandfatheredPD = map { $_ => undef } qw(9 36 37 38 42 49 50 60 65 67 69 74 80 81 83 90 99 105 107 109 111 112 113 114 122 124 125 126 130 131 132 133 140 141 142 143 144 146 147 150 151 152);
+my %TolerateMissingLicense = map { $_ => undef } qw(1 10 11 12 13 14 15 16 21 31 33 34 35 39 43 44 45 47 61 64 68 70 71 72 73 101 102 106 120 121);
+my %TolerateTitleTooLong = map { $_ => undef } qw(39 44 45 47 49 60 67 68 69 73 74 75 80 81 99 105 106 109 113 122 126 131 143 145 147 173 327);
+
+my %emails;
+
+my $bipnum = 0;
+while (++$bipnum <= $topbip) {
+ my $fn = sprintf "bip-%04d.mediawiki", $bipnum;
+ if (!-e $fn) {
+ $fn = sprintf "bip-%04d.md", $bipnum;
+ }
+ -e $fn || next;
+ open my $F, "<$fn";
+ while (<$F> !~ m[^(?:\xef\xbb\xbf)?
$]) {
+ die "No
in $fn" if eof $F;
+ }
+ my %found;
+ my ($title, $author, $status, $type, $layer);
+ my ($field, $val);
+ while (<$F>) {
+ m[^
$] && last;
+ if (m[^ ([\w-]+)\: (.*\S)$]) {
+ $field = $1;
+ $val = $2;
+ die "Duplicate $field field in $fn" if exists $found{$field};
+ die "Too many spaces in $fn" if $val =~ /^\s/;
+ } elsif (m[^ ( +)(.*\S)$]) {
+ die "Continuation of non-field in $fn" unless defined $field;
+ die "Too many spaces in $fn" if length $1 != 2 + length $field;
+ die "Not allowed for multi-value in $fn" unless exists $MayHaveMulti{$field};
+ $val = $2;
+ } else {
+ die "Bad line in $fn preamble";
+ }
+ die "Extra spaces in $fn" if $val =~ /^\s/;
+ if ($field eq 'BIP') {
+ die "$fn claims to be BIP $val" if $val ne $bipnum;
+ } elsif ($field eq 'Title') {
+ $title = $val;
+ my $title_len = length($title);
+ die "$fn has too-long Title ($title_len > 44 char max)" if $title_len > 44 and not exists $TolerateTitleTooLong{$bipnum};
+ } elsif ($field eq 'Author') {
+ $val =~ m/^(\S[^<@>]*\S) \<([^@>]*\@[\w.-]+\.\w+)\>$/ or die "Malformed Author line in $fn";
+ my ($authorname, $authoremail) = ($1, $2);
+ $authoremail =~ s/(?<=\D)$bipnum(?=\D)//g;
+ $emails{$authorname}->{$authoremail} = undef;
+ if (defined $author) {
+ $author .= ", $authorname";
+ } else {
+ $author = $authorname;
+ }
+ } elsif ($field eq 'Status') {
+ if ($bipnum == 38) { # HACK
+ $val =~ s/\s+\(.*\)$//;
+ }
+ die "Invalid status in $fn" unless exists $ValidStatus{$val};
+ $status = $val;
+ } elsif ($field eq 'Type') {
+ die "Invalid type in $fn" unless exists $ValidType{$val};
+ if (defined $ValidType{$val}) {
+ $type = $ValidType{$val};
+ } else {
+ $type = $val;
+ }
+ } elsif ($field eq 'Layer') { # BIP 123
+ die "Invalid layer $val in $fn" unless exists $ValidLayer{$val};
+ $layer = $val;
+ } elsif ($field =~ /^License(?:\-Code)?$/) {
+ die "Undefined license $val in $fn" unless exists $DefinedLicenses{$val};
+ if (not $found{$field}) {
+ die "Unacceptable license $val in $fn" unless exists $AcceptableLicenses{$val} or ($val eq 'PD' and exists $GrandfatheredPD{$bipnum});
+ }
+ } elsif ($field eq 'Comments-URI') {
+ if (not $found{'Comments-URI'}) {
+ my $first_comments_uri = sprintf('https://github.com/bitcoin/bips/wiki/Comments:BIP-%04d', $bipnum);
+ die "First Comments-URI must be exactly \"$first_comments_uri\" in $fn" unless $val eq $first_comments_uri;
+ }
+ } elsif (exists $DateField{$field}) {
+ die "Invalid date format in $fn" unless $val =~ /^20\d{2}\-(?:0\d|1[012])\-(?:[012]\d|30|31)$/;
+ } elsif (exists $EmailField{$field}) {
+ $val =~ m/^(\S[^<@>]*\S) \<[^@>]*\@[\w.]+\.\w+\>$/ or die "Malformed $field line in $fn";
+ } elsif (not exists $MiscField{$field}) {
+ die "Unknown field $field in $fn";
+ }
+ ++$found{$field};
+ }
+ if (not $found{License}) {
+ die "Missing License in $fn" unless exists $TolerateMissingLicense{$bipnum};
+ }
+ for my $field (keys %RequiredFields) {
+ die "Missing $field in $fn" unless $found{$field};
+ }
+ print "|-";
+ if (defined $ValidStatus{$status}) {
+ print " style=\"" . $ValidStatus{$status} . "\"";
+ }
+ print "\n";
+ print "| [[${fn}|${bipnum}]]\n";
+ if ($include_layer) {
+ if (defined $layer) {
+ print "| ${layer}\n";
+ } else {
+ print "|\n";
+ }
+ }
+ print "| ${title}\n";
+ print "| ${author}\n";
+ print "| ${type}\n";
+ print "| ${status}\n";
+ close $F;
+}
+
+for my $author (sort keys %emails) {
+ my @emails = sort keys %{$emails{$author}};
+ my $email_count = @emails;
+ next unless $email_count > 1;
+ warn "NOTE: $author has $email_count email addresses: @emails\n";
+}
diff --git a/scripts/diffcheck.sh b/scripts/diffcheck.sh
new file mode 100755
index 0000000000..aa9f557cf2
--- /dev/null
+++ b/scripts/diffcheck.sh
@@ -0,0 +1,16 @@
+#!/bin/bash
+
+scripts/buildtable.pl >/tmp/table.mediawiki 2> /dev/null
+diff README.mediawiki /tmp/table.mediawiki | grep '^[<>] |' >/tmp/after.diff || true
+if git checkout HEAD^ && scripts/buildtable.pl >/tmp/table.mediawiki 2>/dev/null; then
+ diff README.mediawiki /tmp/table.mediawiki | grep '^[<>] |' >/tmp/before.diff || true
+ newdiff=$(diff -s /tmp/before.diff /tmp/after.diff -u | grep '^+')
+ if [ -n "$newdiff" ]; then
+ echo "$newdiff"
+ exit 1
+ fi
+ echo "README table matches expected table from BIP files"
+else
+ echo 'Cannot build previous commit table for comparison'
+ exit 1
+fi
diff --git a/scripts/link-format-chk.sh b/scripts/link-format-chk.sh
new file mode 100755
index 0000000000..9493765d99
--- /dev/null
+++ b/scripts/link-format-chk.sh
@@ -0,0 +1,21 @@
+#!/usr/bin/env bash
+#
+# Copyright (c) 2019 The Bitcoin Core developers
+# Distributed under the MIT software license, see the accompanying
+# file COPYING or http://www.opensource.org/licenses/mit-license.php.
+#
+# Check wrong mediawiki link format
+
+ECODE=0
+FILES=""
+for fname in *.mediawiki; do
+ GRES=$(grep -n '](http' $fname)
+ if [ "$GRES" != "" ]; then
+ if [ $ECODE -eq 0 ]; then
+ >&2 echo "Github Mediawiki format writes link as [URL text], not as [text](url):"
+ fi
+ ECODE=1
+ echo "- $fname:$GRES"
+ fi
+done
+exit $ECODE