Compare commits

..

No commits in common. "master" and "gg" have entirely different histories.
master ... gg

424 changed files with 4014 additions and 54699 deletions

View File

@ -5,27 +5,15 @@ jobs:
Link-Format-Checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v3
- run: scripts/link-format-chk.sh
Build-Table-Checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v3
- 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@v5
with:
fetch-depth: 2
- uses: actions/checkout@v3
- run: scripts/diffcheck.sh
Typo-Checks:
name: "Typo Checks"
runs-on: ubuntu-latest
steps:
- name: Checkout Actions Repository
uses: actions/checkout@v5
- name: Check spelling
uses: crate-ci/typos@master

6
.gitignore vendored
View File

@ -1,6 +0,0 @@
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

View File

@ -1,44 +0,0 @@
[default]
extend-ignore-re = [
# NOTE: use here for regex patterns
"xpub.*",
"xprv.*",
"3.*", # address
"5.*", # address
"private_key .*",
"privkey .*",
"tt.*", # <tt> tags
"code.*", # <code> tags
"\\w*<sub>", # prefix for <sub> tags
"OP_SUCCESSx|\\d+",
"pay.*",
"ser.*",
"prefix.*",
"value: .*",
"pqNTRUsign",
"Strnad",
]
[default.extend-words]
# NOTE: use here for false-positives
anc = "anc"
PSBT = "PSBT"
ser = "ser"
# Names
Atack = "Atack"
Falke = "Falke"
Meni = "Meni"
Ono = "Ono"
Toom = "Toom"
[files]
extend-exclude = [
"/*/*.csv",
"/*/*.d*",
"/*/*.go",
"/*/*.json",
"/*/*/*.json",
"/*/*/*/*/*/*.o",
"/*/*/*/*/*/*/*/*.o",
"/*/*.t*",
]

View File

@ -1,12 +0,0 @@
# Contributing Guidelines
## Typos
Among other tasks, the CI verifies that changes do not contain common typos.
This check is done using [`typos`](https://github.com/crate-ci/typos).
To run this task locally, install [`typos`](https://github.com/crate-ci/typos)
and then run in the root directory:
```bash
typos
```

File diff suppressed because it is too large Load Diff

View File

@ -1,11 +1,13 @@
<pre>
BIP: 1
Title: BIP Purpose and Guidelines
Authors: Amir Taaki <genjix@riseup.net>
Status: Closed
Author: Amir Taaki <genjix@riseup.net>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0001
Status: Replaced
Type: Process
Assigned: 2011-09-19
Proposed-Replacement: 2
Created: 2011-09-19
Superseded-By: 2
</pre>
==What is a BIP?==
@ -21,7 +23,7 @@ Because the BIPs are maintained as text files in a versioned repository, their r
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.
* 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 implementers are free to ignore Informational BIPs or follow their advice.
* 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 Work Flow==
@ -36,7 +38,7 @@ BIP authors are responsible for collecting community feedback on both the initia
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.
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.
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.
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.
@ -177,9 +179,6 @@ This document was derived heavily from Python's PEP-0001. In many places text wa
==Changelog==
* 2016-12-14:
** Closed: [https://github.com/bitcoin/bips/pull/478 Superseded by BIP2]
* 2016-01-01:
** Clarified early stages of BIP idea championing, collecting community feedback, etc.
* 2015-10-10:
** Added clarifications about submission 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.

View File

@ -1,13 +1,15 @@
<pre>
BIP: 2
Title: BIP process, revised
Authors: Luke Dashjr <luke+bip@dashjr.org>
Status: Closed
Author: Luke Dashjr <luke+bip@dashjr.org>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0002
Status: Active
Type: Process
Assigned: 2016-02-03
License: BSD-2-Clause OR OPUBL-1.0
Created: 2016-02-03
License: BSD-2-Clause
OPL
Replaces: 1
Proposed-Replacement: 3
</pre>
==Abstract==
@ -65,12 +67,8 @@ If you are interested in assuming ownership of a BIP, send a message asking to t
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]])
* Kalle Alm ([[mailto:karljohan-alm@garage.co.jp|karljohan-alm@garage.co.jp]])
===BIP Editor Responsibilities & Workflow===
@ -100,8 +98,6 @@ The BIP editor will:
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===
@ -110,11 +106,11 @@ 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]]).
* 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]]).
* 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.
@ -181,7 +177,7 @@ BIPs may include auxiliary files such as diagrams. Auxiliary files should be inc
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 implementers are free to ignore Informational BIPs or follow their advice.
* 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==
@ -357,40 +353,40 @@ In this case, only the acceptable license(s) should be listed in the License and
====Recommended licenses====
* BSD-2-Clause: [https://opensource.org/license/BSD-2-Clause OSI-approved BSD 2-clause license]
* BSD-3-Clause: [https://opensource.org/license/BSD-3-Clause OSI-approved BSD 3-clause license]
* 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]
* FSFAP: [https://www.gnu.org/prep/maintain/html_node/License-Notices-for-Other-Files.html FSF All Permissive License]
* GNU-All-Permissive: [http://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]
* Apache-2.0: [http://www.apache.org/licenses/LICENSE-2.0 Apache License, version 2.0]
* BSL-1.0: [http://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/license/MIT The MIT 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]
* MIT: [https://opensource.org/licenses/MIT Expat/MIT/X11 license]
* AGPL-3.0+: [http://www.gnu.org/licenses/agpl-3.0.en.html GNU Affero General Public License (AGPL), version 3 or newer]
* FDL-1.3: [http://www.gnu.org/licenses/fdl-1.3.en.html GNU Free Documentation License, version 1.3]
* GPL-2.0+: [http://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html GNU General Public License (GPL), version 2 or newer]
* LGPL-2.1+: [http://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:
* OPUBL-1.0: [https://opencontent.org/openpub/ Open Publication License, version 1.0]
* OPL: [http://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 OPUBL-1.0 is generally regarded as obsolete, and not a license suitable for new publications.
* Many are unfamiliar with the OPUBL-1.0 terms, and may just prefer to use the public domain rather than license under uncertain terms.
* The OPUBL-1.0 license terms allowed for the author to prevent publication and derived works, which was widely considered inappropriate for Bitcoin standards.
* 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?
@ -413,6 +409,7 @@ Why is Public Domain no longer acceptable for new BIPs?
* 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.
* Markdown format is no longer permitted for BIPs.
* 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==

View File

@ -1,802 +0,0 @@
```
BIP: 3
Title: Updated BIP Process
Authors: Murch <murch@murch.one>
Status: Deployed
Type: Process
Assigned: 2025-01-09
License: BSD-2-Clause
Discussion: https://github.com/murchandamus/bips/pull/2
https://gnusha.org/pi/bitcoindev/59fa94cea6f70e02b1ce0da07ae230670730171c.camel@timruffing.de/#t
Version: 1.4.0
Requires: 123
Replaces: 2
```
## Abstract
This _Bitcoin Improvement Proposal (BIP)_ provides information about the preparation of BIPs and policies relating to
the publication of BIPs. It replaces [BIP2](bip-0002.mediawiki) with a streamlined process, and may be amended to
address the evolving needs of the BIP process.
## Motivation
BIP2 was written in 2016.
This BIP revisits aspects of the BIP2 process
that did not achieve broad adoption, reduces the judgment calls assigned to the BIP Editor role, delineates the
BIPtypes more clearly, and generalizes the BIP process to fit the communitys use of the repository.
## Fundamentals
### What is a BIP?
BIPs are improvement proposals for Bitcoin. The main topic is information and technologies that support and expand the utility of the Bitcoin
currency. Most BIPs provide a concise, self-contained, technical description of one new concept, feature, or standard.
Some BIPs describe processes, implementation guidelines, best practices, incident reports (e.g.,
[BIP50](bip-0050.mediawiki)), or other information relevant to the Bitcoin community. However, any topics related to
the Bitcoin protocol, peer-to-peer network, and client software may be acceptable.
BIPs are intended to be a means for proposing new protocol features, coordinating client standards, and
documenting design decisions that have gone into implementations. BIPs may be submitted by anyone, provided the
content is of high quality, e.g., does not waste the communitys time.
The scope of the BIPs
repository is limited to BIPs that do not oppose the fundamental principle that Bitcoin constitutes a peer-to-peer
electronic cash system for the Bitcoin currency.
### BIP Ownership
Each BIP is primarily owned by its authors and represents the authors opinion or recommendation. The authors are
expected to foster discussion, address feedback and dissenting opinions, and, if applicable, advance the adoption of
their proposal within the Bitcoin community. As a BIP progresses through the workflow, it becomes increasingly
co-owned by the Bitcoin community.
#### Authors and Deputies
Authors may want additional help with the BIP process after writing an initial draft. In that case, they may assign
one or more Deputies to their BIP. Deputies are stand-in owners of a BIP who were not involved in writing the
document. They support the authors in advancing the proposal, or act as a point of contact for the BIP in the absence of the
authors. Deputies may perform the role of Authors for any aspect of the BIP process unless overruled by an Author.
Deputies share ownership of the BIP at the discretion of the Authors.
### What is the Significance of BIPs?
BIPs do not define what Bitcoin is: individual BIPs do not represent Bitcoin community consensus or a general
recommendation for implementation. A BIP represents a personal recommendation by the BIP authors to the Bitcoin
community. Some BIPs may never be adopted. Some BIPs may be adopted by one or more Bitcoin clients or other related
software. Some may even end up changing the consensus rules that the Bitcoin ecosystem jointly enforces.
### What is the Purpose of the BIPs Repository?
The [BIPs repository](https://github.com/bitcoin/bips/) serves as a publication medium and archive for mature proposals.
Through its high visibility, it facilitates the community-wide consideration of BIPs and provides a well-established
source to retrieve the latest version of any BIP. The repository transparently records all changes to each BIP and
allows any community member to retain a complete copy of the archive easily.
The BIPs repository neither tracks community sentiment[^acceptance] nor ecosystem adoption[^adoption] of BIPs beyond
the brief overview provided via the BIP status (see [Workflow](#workflow) below).
Proposals are published in this repository if they are on-topic and fulfill the editorial criteria.
No formal or informal decision body governs Bitcoin development or decides adoption of BIPs.
## BIP Format and Structure
### Specification
Authors may choose to submit BIPs in MediaWiki or Markdown[^markdown] format.
Each BIP must have a _Preamble_, an _Abstract_, a _Copyright_, and a _Motivation_ section. Authors should consider all issues in the
following list and address each as appropriate.
* Preamble — Headers containing metadata about the BIP (see the section [BIP Header Preamble](#bip-header-preamble)
below).
* Abstract — A short description of the issue being addressed.
* Motivation — Why is this BIP being written? Clearly explain how the existing situation presents a problem and why the proposed idea resolves the
issue or improves upon the current situation.
* Specification — The technical specification should describe the syntax and semantics of any new feature. The
specification should be detailed enough to enable any Bitcoin project to create an interoperable implementation.
* Rationale — The rationale fleshes out the specification by describing what inspired the design and why particular
design decisions were made. It should describe related work and alternate designs that were considered. The rationale
should record relevant objections or important concerns that were raised and addressed as this proposal was developed.
* Backward Compatibility — Any BIP that introduces incompatibilities must include a section describing these incompatibilities and their severity as well as provide instructions on how
implementers and users should deal with these incompatibilities.
* Reference Implementation — Where applicable, a reference implementation, test vectors, and documentation must be
finished before the BIP can be given the status "Complete". Test vectors must be provided in the BIP or
as auxiliary files (see [Auxiliary Files](#auxiliary-files)) under an acceptable license. The reference implementation
can be provided in the BIP, as an auxiliary file, or per linking another code reference that is expected to remain
available permanently such as a pull request, a dedicated branch, a new repository, or similar.
* Changelog — A section to track modifications to a BIP after reaching Complete status.
* Copyright — The BIP must be placed under an acceptable license (see [BIP Licensing](#bip-licensing) below).
#### BIP Header Preamble
Each BIP must begin with an [RFC 822-style header preamble](https://www.w3.org/Protocols/rfc822/). The headers must
appear in the following order. Headers marked with "\*" are optional. All other headers are required.
##### Overview
```
BIP: <BIP number, or "?" before assignment>
* Layer: <Consensus (soft fork) | Consensus (hard fork) | Peer Services | API/RPC | Applications>
Title: <BIP title (50 characters)>
Authors: <Authors names and email addresses>
* Deputies: <Deputies names and email addresses>
Status: <Draft | Complete | Deployed | Closed>
Type: <Specification | Informational | Process>
Assigned: <Date of number assignment (yyyy-mm-dd), or "?" before assignment>
License: <SPDX License Expression>
* Discussion: <Noteworthy discussion threads in "yyyy-mm-dd: URL" format>
* Version: <MAJOR.MINOR.PATCH>
* Requires: <BIP number(s)>
* Replaces: <BIP number(s)>
* Proposed-Replacement: <BIP number(s)>
```
##### Header Descriptions
* BIP — The assigned number of the BIP (without leading zeros). Please use "?" before a number has been assigned by the BIP Editors.
* Layer — The layer of Bitcoin the BIP applies to using the BIP classification defined in [BIP123](bip-0123.mediawiki).
* Authors — The names (or pseudonyms) and email addresses of all authors of the BIP. The format of each authors header
value must be
Random J. User <address@dom.ain>
Multiple authors are recorded on separate lines:
Authors: Random J. User <address@dom.ain>
Anata Sample <anata@domain.example>
* Deputies — Additional owners of the BIP that are not authors. The Deputies header uses the same format as the
Authors header. See the [BIP Ownership](#bip-ownership) section above.
* Status — The stage of the workflow of the proposal. See the [Workflow](#workflow) section below.
* Type — See the [BIP Types](#bip-types) section below for a description of the three BIP types.
* Assigned The date a BIP was assigned its number. Please use "?" before a number has been assigned by the BIP Editors.
* License — The License header specifies SPDX License Expressions describing the terms under which the
BIP and its auxiliary files are available. See the [BIP Licensing](#bip-licensing) section below.
* Discussion — The Discussion header points the audience to relevant discussions of the BIP, e.g., the mailing list
thread in which the idea for the BIP was discussed, a thread where a new version of the BIP was presented, or relevant
discussion threads on other platforms. Entries take the format "yyyy-mm-dd: URL", e.g., `2009-01-09:
https://www.mail-archive.com/cryptography@metzdowd.com/msg10142.html`, using the date and URL of the start of the
conversation. Multiple discussions should be listed on separate lines.
* Version — The current version number of this BIP. See the [Changelog](#changelog-section-and-version-header) section below.
* Requires — A list of existing BIPs the new proposal depends on. If multiple BIPs
are required, they should be listed in one line separated by a comma and space (e.g., "1, 2").
* Replaces[^proposes-to-replace] — BIP authors may put the numbers of one or more prior BIPs in the Replaces header to recommend that their
BIP succeeds, supersedes, or renders obsolete those prior BIPs.
* Proposed-Replacement[^superseded-by-proposed-replacement] — When a later BIP indicates that it intends to supersede an
existing BIP, the later BIPs number is added to the Proposed-Replacement header of the existing BIP to indicate the
potential successor BIP.
#### Auxiliary Files
BIPs may include auxiliary files such as diagrams and source code. Auxiliary files must be included in a subdirectory
for that BIP named `bip-XXXX`, where "XXXX" is the BIP number zero-padded to four digits. File names in the subdirectory
do not need to adhere to a specific convention.
### BIP Types
* A **Specification BIP** defines a set of technical rules describing a new feature or affecting the interoperability of implementations. The
distinguishing characteristic of a Specification BIP is that it can be implemented, and implementations can be compliant with
it. Specification BIPs must have a Specification section, must have a Backward Compatibility section (if incompatibilities are introduced), and can only be advanced to Complete after they contain or refer to a reference implementation and test vectors.
* An **Informational BIP** describes a Bitcoin design issue, or provides general guidelines or other information to the
Bitcoin community.
* A **Process BIP** describes a process surrounding Bitcoin, or proposes a change to (or an event in) a process. Process
BIPs are like Specification BIPs, but apply to topics other than the Bitcoin protocol and Bitcoin implementations.
They often require community consensus and are typically binding for the corresponding process. Examples include
procedures, guidelines, and changes to decision-making processes such as the BIP process.
## Workflow
The BIP process starts with a new idea for Bitcoin. Each potential BIP must have authors—people who write the BIP,
gather feedback, shepherd the discussion in the appropriate forums, and finally recommend a mature proposal to the
community.
![Status Diagram](bip-0003/status-diagram.png "Status Diagram for the BIP Workflow")
### Ideation
After having an idea, the authors should evaluate whether it meets the criteria to become a BIP, as described in this
BIP. The idea must be of interest to the broader community or relevant to multiple software projects. Minor improvements
and matters concerning only a single project usually do not require standardization and should instead be brought up directly to
the relevant project.
The authors should first research whether their idea has been considered before. Ideas in Bitcoin are often rediscovered,
and prior related discussions may inform the authors of the issues that may arise in its progression. After some investigation,
the novelty and viability of the idea should be tested by posting a new, dedicated thread about the idea to the [Bitcoin Development Mailing
List](https://groups.google.com/g/bitcoindev). Prior correspondence can be found in the [mailing list
archive](https://gnusha.org/pi/bitcoindev/).
It is recommended that authors establish before or at the start of working on a draft whether their idea may be of
interest to the Bitcoin community.
Authors should avoid opening a pull request with a BIP draft out of the blue.
Vetting an idea publicly before investing time and effort to formally describe the idea is meant to save time for both the authors and
the community. Not only may someone point out relevant discussion topics that were missed in the authors
research, or that an idea is guaranteed to be rejected based on prior discussions, but describing an idea publicly also
tests whether it is of interest to more people beside the authors.
As a first sketch of the proposal is taking shape, the authors should present it to the [Bitcoin Development Mailing
List](https://groups.google.com/g/bitcoindev). This gives the authors a chance to collect initial feedback and address
fundamental concerns. If the authors wish to work in public on the proposal at this stage, it is recommended that they
open a pull request against one of their forks of the BIPs repository instead of the main BIPs repository.
It is recommended that complicated proposals be split into separate BIPs that each focus on a specific component of the
overall proposal.
### Progression through BIP Statuses
The following sections refer to BIP Status field values. The BIP Status field is defined in the Header Preamble
specification above.
#### Draft
After fleshing out the proposal further and ensuring that it is of high quality and properly formatted, the authors
should open a pull request to the [BIPs repository](https://github.com/bitcoin/bips). The document must adhere to the
formatting requirements specified above and should be provided as a file named with a working title of the form
"bip-title.[md|mediawiki]". Only BIP Editors may assign BIP numbers. Until one has done so, authors should refer to their
BIP by name only.
BIPs that (1) adhere to the formatting requirements, (2) are on-topic, and (3) have materially progressed beyond the
ideation phase, e.g., by generating substantial public discussion and commentary from diverse contributors, by
independent Bitcoin projects working on adopting the proposal, or by the authors working for an extended period toward
improving the proposal based on community feedback, will be assigned a number by a BIP Editor. A number may be
considered assigned only after it has been publicly announced in the pull request by a BIP Editor. The BIP Editors should
not assign a number when they perceive a proposal being met with lack of interest: number assignment facilitates the
distributed discussion of ideas, but before a proposal garners some interest in the Bitcoin community, there is no need
to refer to it by a number.
Proposals are also not ready for number assignment if they duplicate efforts, disregard formatting rules, are too
unfocused or too broad, fail to provide proper motivation, fail to address backward compatibility where necessary, or
fail to specify the feature clearly and comprehensively. Reviewers and BIP Editors should provide guidance on how the
proposal may be improved to progress toward readiness. Pull requests that are proposing off-topic ideas or
have stopped making progress may be closed.
When the proposal is ready and has been assigned a number, a BIP Editor will merge it into the BIPs repository. After the
BIP has been merged to the repository, its main focus should no longer shift significantly, even while the authors may
continue to update the proposal as necessary. Updates to merged documents by the authors should also be submitted as
pull requests.
#### Complete[^complete]
When the authors have concluded all planned work on their proposal, are confident that their BIP represents a net
improvement, is clear, comprehensive, and is
ready for adoption by the Bitcoin community, they may update the BIPs status to Complete to indicate that they
recommend adoption, implementation, or deployment of the BIP. Where applicable, the authors must ensure that any
proposed specification is solid, not unduly complicated, and definitive. Specification BIPs must come with or refer to a working reference implementation and comprehensive test vectors before they can be moved to Complete. Subsequently, the BIPs content should only be
adjusted in minor details, e.g., to improve language, clarify ambiguities, backfill omissions in the specification, add
test vectors for edge cases, or address other issues discovered as the BIP is being adopted.
A Complete BIP can only move to Deployed or Closed. Any necessary changes to the specification should be minimal and
interfere as little as possible with ongoing adoption. If a Complete BIP is found to need substantial functional
changes, it may be preferable to move it to Closed[^new-BIP], and to start a new BIP with the changes instead.
Otherwise, it could cause confusion as to what being compliant with the BIP means.
A BIP may remain in the Complete status indefinitely unless its authors or deputies decide to move it to Closed or it is advanced to
Deployed.
Complete is the final status for most successful Informational BIPs.
#### Deployed
A Complete BIP should only be moved to Deployed once it is settled: after its approach has solidified, its
Specification has been put through its paces, feedback from early adopters has been processed, and amendments to the BIP have stopped.
Then, a BIP may be advanced to Deployed upon request by any community member with evidence[^evidence] that
the BIP is in active use. Convincing evidence includes for example: an established project having deployed support
for the BIP in mainnet software releases, a soft fork proposals activation criteria having been met on the network, or
rough consensus for the BIP having been demonstrated.
Once Deployed, the BIP is considered final.
Any modifications to the BIP beyond bug fixes, other minor amendments, additions to the test vectors, or editorial
changes should be avoided.
Any breaking changes to the BIPs Specification should be proposed as a new separate BIP.[^new-BIP]
##### Process BIPs
A Process BIP may change status from Complete to Deployed when it achieves rough consensus on the Bitcoin Development Mailing List. A
proposal is said to have rough consensus if its advancement has been open to discussion on the mailing list for at least
one month, the discussion achieved meaningful engagement, 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. Deployed Process BIPs may be modified indefinitely as long as a proposed modification has
rough consensus per the same criteria.[^living-documents]
#### Closed[^closed]
A BIP that is of historical interest only, and is not being actively worked on, promoted or in active use, should be
marked as Closed. The reason for moving the
proposal to (or from) Closed should be recorded in the Changelog section in the same commit that updates the status.
BIPs do not get deleted, they are retained even after being updated to Closed.
Transitions involving the Closed state are:
##### Draft ↦ Closed
BIP authors may decide on their own to change their BIPs status from Draft to Closed. If a Draft BIP stops making
progress, sees accumulated feedback unaddressed, or otherwise appears stalled for a year, anyone may propose the BIP
status be updated to Closed. The BIP is then updated to Closed unless the authors assert that they intend to continue work within four weeks of being contacted.
##### Complete ↦ Closed
BIPs that had attained the Complete status, i.e., that had been recommended for adoption, may be moved to Closed per the
authors announcement to the Bitcoin Development Mailing List[^bip-announcements-to-list]. However, if someone volunteers to adopt the proposal
within four weeks, they become the BIP's author or deputy (see [Transferring BIP Ownership](#transferring-bip-ownership) below), and the BIP will
remain Complete instead.
##### Deployed ↦ Closed
A BIP may evolve from Deployed to Closed when it is no longer in active use. Any community member may initiate this
Status update by announcing it to the mailing list[^bip-announcements-to-list], and proceed if no objections have been raised for four weeks.
##### Closed ↦ Draft
The Closed status is generally intended to be a final status for BIPs,
and if BIP authors decide to make another attempt at a previously Closed BIP, it is generally recommended to create a new
proposal. (Obviously, the authors may borrow any amount of inspiration or actual text from any prior BIPs as licensing
permits.) The authors should take special care to address the issues that caused the prior attempts abandonment. Even
if the prior attempt had been assigned a number, the new BIP will generally be assigned a distinct number. However, if it is
obvious that the new attempt directly continues work on the same idea, it may be reasonable to return the
Closed BIP to Draft status.
### Changelog Section and Version Header
To help implementers understand updates to a BIP, any changes after it has reached Complete must be tracked with version,
date, and description in a Changelog section sorted by most recent version first. The version number is inspired by semantic versioning (MAJOR.MINOR.PATCH).
The MAJOR version is incremented if changes to the BIPs Specification are introduced that are incompatible with prior
versions (which should be rare after a BIP is Complete, and only happen in well-grounded exceptional cases to a BIP that
is Deployed). The MINOR version is incremented whenever the specification of the BIP is changed or extended in a
backward-compatible way. The PATCH version is incremented for other changes to the BIP that are noteworthy (bug fixes,
test vectors, important clarifications, etc.). Version 1.0.0 is used to label the promotion to
Complete. A Changelog section may be introduced during the Draft phase to record significant changes (using versions 0.x.y).
Example:
> __Changelog__
>
> * __2.0.0__ (2025-01-22):
> * Introduce a breaking change in the specification to fix a bug.
> * __1.1.0__ (2025-01-17):
> * Add a backward compatible extension to the BIP.
> * __1.0.1__ (2025-01-15):
> * Clarify an edge case and add corresponding test vectors.
> * __1.0.0__ (2025-01-14):
> * Complete planned work on the BIP.
After a BIP receives a Changelog, the
Preamble must indicate the latest version in the Version header. The Changelog highlights revisions to BIPs to human readers. A single
BIP shall not recommend more than one variant of an idea at the same time. A different or
competing variant of an existing BIP must be published as a separate BIP.
### Adoption of Proposals
The BIPs repository does not track the sentiment on proposals and does not track the adoption of BIPs beyond whether they
are in active use or not. It is not intended for BIPs to list additional implementations beyond the reference
implementation: the BIPs repository is not a signpost where to find implementations.[^OtherImplementations] After a BIP
is advanced to Complete, it is up to the Bitcoin community to evaluate, adopt, ignore, or reject a BIP. Individual
Bitcoin projects are encouraged to publish a list of BIPs they implement. A good example of this at the time of writing
this BIP can be observed in Bitcoin Cores [doc/bips.md](https://github.com/bitcoin/bitcoin/blob/master/doc/bips.md)
file.
### Transferring BIP Ownership
It occasionally becomes necessary to transfer ownership of BIPs to new owners. In general, it would be preferable to
retain the original authors of the transferred BIP, but that is up to the original authors. A good reason to transfer
ownership is because the original authors no longer have the time or interest in updating it or following through with
the BIP process, or are unreachable or unresponsive. A bad reason
to transfer ownership is because someone doesn't agree with the direction of the BIP. The community tries to build
consensus around a BIP, but if that's not possible, rather than fighting over control, the dissenters should supply a
competing BIP.
If someone is interested in assuming ownership of a BIP, they should send an email asking to take over, addressed to the
original authors, the BIPEditors, and the Bitcoin Development Mailing List[^bip-announcements-to-list]. If the authors are unreachable or do not respond in a timely
manner (e.g., four weeks), the BIP Editors will make a unilateral decision whether to appoint the applicants as
[Authors or Deputies](#authors-and-deputies) (which may be amended should the original authors make a delayed reappearance).
## BIP Licensing
The Bitcoin project develops a global peer-to-peer digital cash system. Open standards are indispensable for continued
interoperability. Open standards reduce friction, and encourage anybody and everyone to contribute, compete, and
innovate on a level playing field. Only freely licensed contributions are accepted to the BIPs repository.
### Specification
Each new BIP must specify in two ways under which license terms it is made available. First, it must specify an [SPDX
License Expression](https://spdx.dev/ids/) in the License field in the preamble. Second, it must include a matching
Copyright section, possibly providing further details on licensing.
For example, a preamble might include the following License header:
License: CC0-1.0 OR MIT
In this case, the BIP (including all auxiliary files) is made available under the terms of both CC0 1.0 Universal as well as the
MIT License, and anyone may modify and redistribute it provided they comply with the terms of
*either* license, at their option. In other words, the license list is an "OR choice", not an "AND also" requirement. See the [SPDX
documentation](https://spdx.dev/ids/) and the [SPDX License List](https://spdx.org/licenses/) for further details.
Wherever different from those specified in the License header, an auxiliary file or directory should specify the license terms under which it is made available as is common in
software (e.g., with a [`SPDX-License-Identifier: <SPDX License Expression>` comment](https://spdx.dev/ids/),
a license header, or a LICENSE/COPYING file). Such exceptions should also be mentioned in the Copyright section. It is recommended to make any test vectors available
under CC0-1.0 or FSFAP in addition to any other licenses to allow anyone to copy test vectors into their
implementations without introducing license hindrances.
A few BIP2-era BIPs (98, 116, 117, 330, 340) have a no longer used "License-Code" header indicating the license terms applicable to auxiliary source code files. For such cases, please refer to BIP2.
It is recommended that source code included in a BIP (whether within the text or in auxiliary files) be licensed under the same license terms as the project it
is proposed to modify, if any. For example, changes intended for Bitcoin Core would ideally be licensed (also) under the MIT
License.
In all cases, details of the licensing terms must be provided in the Copyright section of the BIP.
#### Acceptable Licenses[^licenses]
Each new BIP must be made available under at least one acceptable license as listed below. BIPs are not required to be
*exclusively* licensed under approved terms, and may also be licensed under other licenses *in addition to* at least one
acceptable license.
In other words, a new BIP must specify an SPDX License Expression that is either "L" or equivalent to "L OR E" for some
acceptable license L from the following list and another SPDX License Expression E.
* BSD-2-Clause: [BSD 2-Clause License](https://opensource.org/license/BSD-2-Clause)
* BSD-3-Clause: [BSD 3-Clause License](https://opensource.org/license/BSD-3-Clause)
* CC0-1.0: [CC0 1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/)
* FSFAP: [FSF All Permissive License](https://www.gnu.org/prep/maintain/html_node/License-Notices-for-Other-Files.html)
* CC-BY-4.0: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0/)
* MIT: [The MIT License](https://opensource.org/license/MIT)
* MIT-0: [MIT No Attribution License](https://opensource.org/license/MIT-0)
* Apache-2.0: [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0)
* BSL-1.0: [Boost Software License 1.0](https://www.boost.org/LICENSE_1_0.txt)
#### Not Acceptable Licenses
All licenses not explicitly included in the above lists are not acceptable terms for a Bitcoin Improvement Proposal.
However, BIPs predating this proposal were accepted under other terms, and should use one of the following identifiers.
* LicenseRef-PD: Placed into the public domain
* OPUBL-1.0: [Open Publication License 1.0](https://opencontent.org/openpub/)
## BIP Editors
The current BIP Editors are:
* Bryan Bishop ([kanzure@gmail.com](mailto:kanzure@gmail.com))
* Jon Atack ([jon@atack.com](mailto:jon@atack.com))
* Luke Dashjr ([luke_bipeditor@dashjr.org](mailto:luke_bipeditor@dashjr.org))
* Mark "Murch" Erhardt ([murch@murch.one](mailto:murch@murch.one))
* Olaoluwa Osuntokun ([laolu32@gmail.com](mailto:laolu32@gmail.com))
* Ruben Somsen ([rsomsen@gmail.com](mailto:rsomsen@gmail.com))
### BIP Editor Responsibilities and Workflow
The BIP Editors subscribe to the Bitcoin Development Mailing List and watch the [BIPs
repository](https://github.com/bitcoin/bips).
When either a new BIP idea or an early draft is submitted to the mailing list, BIP Editors or other community members should comment in regard
to:
* Novelty of the idea
* Viability, utility, and relevance of the concept
* Readiness of the proposal
* On-topic for the Bitcoin community
Discussion in pull request comments can often be hard to follow as feedback gets marked as resolved when it is addressed
by authors. Substantive discussion of ideas may be more accessible to a broader audience on the mailing list, where it
is also more likely to be retained by the community memory.
If the BIP needs more work, an editor should ensure that constructive, actionable feedback is provided to the authors
for revision. Once the BIP is ready it should be submitted as a "pull request" to the [BIPs
repository](https://github.com/bitcoin/bips) where it may get further feedback.
For each new BIP pull request that comes in, an editor checks the following:
* The idea has been previously proposed to the Bitcoin Development Mailing List and discussed there
* The described idea is on-topic for the repository
* A draft of the BIP by one of the authors has been previously discussed on the Bitcoin Development Mailing List
* Title accurately describes the content
* Proposal is of general interest and/or pertains to more than one Bitcoin project/implementation
* Document is properly formatted
* Licensing terms are acceptable
* Motivation, Rationale, and Backward Compatibility have been addressed
* Specification provides sufficient detail for implementation
* The defined Layer and Type headers must be correctly assigned for the given specification
* The BIP is ready: it is comprehensible, technically feasible and sound, and all aspects are addressed as necessary
Editors do NOT evaluate whether the proposal is likely to be adopted.
Then, a BIP Editor will:
* Assign a BIP number in the pull request
* Ensure that the BIP is listed in the [README](README.mediawiki)
* Merge the pull request when it is ready
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, mending grammar mistakes, fixing broken links, etc. as long as they do not change the meaning or conflict with the
original intent of the authors. Such a change must be recorded in the Changelog if its noteworthy per the criteria
mentioned in the [Changelog](#changelog) section.
## Backward Compatibility
### Changes from BIP2
#### Workflow
- Status field values are reduced from nine to four:
- Deferred, Obsolete, Rejected, Replaced, and Withdrawn are gathered up into Closed.[^closed]
- Final and Active are collapsed into Deployed.
- Proposed is renamed to Complete.
- The remaining statuses are Draft, Complete, Deployed, and Closed.
- The comment system is abolished.[^comments]
- A BIP in Draft or Complete status may no longer be closed solely on grounds of not making progress for three years.[^rejection]
- A BIP in Draft status may be updated to Closed status if it appears to have stopped making progress for at least a
year and its authors do not assert within four weeks of being contacted that they intend to continue working on it.
- Complete BIPs can only be moved to Closed by its authors and may remain in Complete indefinitely.
- A Changelog section is introduced to track significant changes to BIPs after they have reached the Complete status.
- Process BIPs are living documents that do not ossify and may be modified indefinitely.
- Some judgment calls previously required from BIP Editors are reassigned either to the BIP authors or the repositorys
audience.
#### BIP Format
- The Standards Track type is superseded by the similar Specification type.[^standard-track]
- Many sections are declared optional; it is up to the authors and reviewers to judge whether all relevant topics have
been comprehensively addressed and which topics require a designated section to do so.
- "Other Implementations" sections are discouraged.[^OtherImplementations]
- Auxiliary files are only permitted in the corresponding BIPs subdirectory, as no one used the alternative of labeling
them with the BIP number.
- Tracking of community consensus and adoption is out of scope for the BIPs repository, except to determine
whether a BIP is in active use for the move into or out of the Deployed status.
- The distinction between recommended and acceptable licenses was dropped.
- Most licenses that have not been used in the BIP process have been dropped from the list of acceptable licenses.
#### Preamble
- "Comments-URI" and "Comments-Summary" headers are dropped from the preamble.[^comments]
- The "Superseded-By" header is replaced with the "Proposed-Replacement" header.
- The "Post-History" header is replaced with the "Discussion" header.
- The optional "Version" header is introduced.
- The "Discussions-To" header is dropped, as it has never been used in any BIP.
- The "License-Code" header has been sunset, as it was used by only five BIPs (98, 116, 117, 330, 340) and created more ambiguity than clarity.
- The "Created" header is renamed to "Assigned", as the headers value is the date of number assignment.[^assigned]
- Introduce Deputies and optional "Deputies" header.
- The BIP "Title" header may now contain up to 50 characters (increased from 44 in BIP2).
- The "Layer" header is optional for Specification BIPs or Informational BIPs, as it does not make sense for all BIPs.[^layer]
- Rename the "Author" field to "Authors".
### Updates to Existing BIPs should this BIP be Activated
#### Previous BIP Process
This BIP replaces BIP2 as the guideline for the BIPprocess.
#### BIP Types
Standards Track BIPs and eligible Informational BIPs are assigned the Specification type. The Standards Track type is
considered obsolete. Specification BIPs use the Layer header rules specified in [BIP123](bip-0123.mediawiki).
#### Comments
The Comments-URI and Comments-Summary headers should be removed from all BIPs whose comment page in the wiki is empty.
For existing BIPs whose comment page has content, BIP Authors may keep both headers or remove both headers at their
discretion. It is recommended that existing wiki pages are not modified due to the activation of this BIP.
#### Status Field
After the activation of this BIP, the Status fields of existing BIPs that do not fit the specification in this BIP are
updated to the corresponding values prescribed in this BIP. BIPs that have had Draft status for extended periods will be
moved to Complete or Deployed as applicable in collaboration with their authors. The authors of incomplete Draft BIPs
will be contacted to learn whether the BIPs are still in progress toward Complete, and will otherwise be updated to
Closed as described in the [Workflow](#workflow) section above.
#### Authors Header
The Author header is replaced with the Authors header in all BIPs.
#### Discussion Header
The Post-History header is replaced with the Discussion header in all BIPs.
#### Proposed-Replacement Header
The Superseded-By header is replaced with the Proposed-Replacement header in all BIPs.
#### Licenses
Existing BIPs retain their license terms unchanged.
The License and License-Code headers of BIPs are updated to express those terms using SPDX License Expressions.
## Changelog
* __1.4.0__ (2025-12-09):
* Revert AI guidance, add Changelog section, broaden reference implementation formats, move Type header responsibility to authors, other editorial changes
* __1.3.1__ (2025-11-10):
* Reiterate that numbers are assigned by BIP Editors in pull requests
* __1.3.0__ (2025-10-22):
* Restrict use of AI/LLM tools, require original work.
* __1.2.1__ (2025-09-19):
* Clarify that idea should be discussed on dedicated mailing list thread
* __1.2.0__ (2025-09-19):
* Rename Created header to Assigned to clarify that it holds the date of number assignment
* __1.1.0__ (2025-07-18):
* Switch to SPDX License Expressions, drop License-Code header, and make editorial changes to BIP Licensing section.
* __1.0.1__ (2025-06-27):
* Improve description of acceptance, purpose of the BIPs repository, when Draft BIPs can be closed due to not
making progress, and make other minor improvements to phrasing.
* __1.0.0__ (2025-03-18):
* Complete planned work and move to Proposed.
## Copyright
This BIP is licensed under the [BSD-2-Clause License](https://opensource.org/licenses/BSD-2-Clause). Some content was
adapted from [BIP2](bip-0002.mediawiki) which was also licensed under the BSD-2-Clause.
## Related Work
- [BIP1: BIP Purpose and Guidelines](bip-0001.mediawiki)
- [BIP2: BIP Process, revised](bip-0002.mediawiki)
- [BIP123: BIP Classification](bip-0123.mediawiki)
- [RFC 822: Standard for ARPA Internet Text Messages](https://datatracker.ietf.org/doc/html/rfc822)
- [RFC 2223: Instructions to RFC Authors](https://datatracker.ietf.org/doc/html/rfc2223)
- [RFC 7282: On Consensus and Humming in the IETF](https://tools.ietf.org/html/rfc7282)
## Acknowledgements
We thank AJ Towns, Jon Atack, Jonas Nick, Larry Ruane, Pieter Wuille, Tim Ruffing, and others for their review,
feedback, and helpful comments.
## Rationale
[^assigned]: **Why was the Created header renamed to Assigned?**
Both BIP1 and BIP2 described the Created header as "date created on" in the preamble template, but followed that
up with "Created header records the date that the BIP was assigned a number" as the description of the field. This
has frequently led to confusion, with authors using the date of opening the pull request, the date they started
writing their proposal, the date of number assignment (as prescribed), or various other dates. Aligning the name of
the header and the text in the preamble template with the descriptions will reduce the confusion.
[^standard-track]: **Why was the Specification type introduced?**
The definitions of Informational and Standards Track BIPs caused some confusion in the past. Due to Informational
BIPs being described as optional, Standards Track BIPs were sometimes misunderstood to be generally recommended.
This has led to a number of BIPs that propose new features affecting interoperability of implementations being
assigned the Informational type. The situation is remedied by introducing a new _Specification BIP_ type that is
inclusive of any BIPs that can be implemented and affect interoperability of Bitcoin applications. Since all BIPs
are individual recommendations by the authors (even if some may eventually achieve endorsement by the majority of
the community), the prior reminder that Informational BIPs are optional is dropped.
[^comments]: **Why were comments, Comments-URI, and Comments-Summary removed from the process?**
The comments feature saw insignificant adoption. Few BIPs received any comments and barely any more than two with
only a handful of contributors commenting at all. This led to many situations in which one or two comments ended up
dominating the comment summary. While some of those comments may have been representative of broadly held opinions,
it also overstated the importance of individual comments directly in the Preamble of BIPs. As collecting feedback in
this accessible fashion failed, the new process puts the burden back on the audience to make their own evaluation.
[^layer]: **Why is the layer header now permitted for other BIP types?**
The layer header had already been used by many Informational BIPs, so the rule that it is only available to
Standards Track BIPs is dropped.
[^OtherImplementations]: **What is the issue with "Other Implementations" sections in BIPs?**
In the past, some BIPs had "Other Implementations" sections that caused frequent change requests to existing BIPs.
This put a burden on the BIP authors and BIP Editors, and frequently led to lingering pull requests due to the corresponding BIPs
authors no longer participating in the process. Many of these alternative implementations eventually became
unmaintained or were low-quality to begin with. Therefore, "Other Implementations" sections are heavily discouraged.
[^complete]: **Why was the Proposed status renamed to Complete?**
Some reviewers of this BIP raised that in a process which outlines the workflow of Bitcoin Improvement _Proposals_
using "Proposed" as a status field value was overloading the term: clearly _proposals_ are proposed at all stages of
the process. "Complete" expresses that the authors have concluded planned work on all parts of the proposal and are
ready to recommend their BIP for adoption. The term "ready" was also considered, but considered too subjective.
[^rejection]: **Why can proposals remain in Draft or Complete indefinitely?**
The automatic 3-year timeout of BIPs has led to some disagreement in the past and seems unnecessary in cases where
the authors remain active in the community and still consider their idea worth pursuing. On the other hand,
Draft proposals that appear stale may be closed after only one year, which should achieve the main goal of
the original rule by limiting the effort and attention spent on proposals that never reach Complete.
[^closed]: **Why was the Closed Status introduced?**
The Closed Status provides value to the audience by indicating which documents are only of historical significance.
Previously, the process had Deferred, Obsolete, Rejected, Replaced, and Withdrawn, which all meant some flavor of
"work has stopped on this." The many statuses complicated the process, may have contributed to process fatigue, and
may have resulted in BIPs statuses not being maintained well. The author of this BIP feels that all of the
aforementioned can be represented by _Closed_ without significantly impacting the information quality of the
overview table. Where the many Status variants provided minuscule additional information, the simplification is more
valuable and the Changelog section now collects specific details.
[^acceptance]: **When is a BIP "accepted"?**
Many standards processes such as the PEPs or the IETF have a mechanism for a proposal to be formally accepted by
some council or committee. The BIP Process does not have such a decision body. Bitcoin development and "acceptance"
of BIPs emerges from the participation of stakeholders across the ecosystem, and refers to some vague notion of community
interest and support for a proposal.
BIP2 had made an attempt to gather community feedback into comment summaries in BIPs directly. Given the low
participation and corresponding low information quality of the summaries that resulted from that feature, this BIP
instead intends to leave the evaluation of BIPs to the reviewers and users.
[^adoption]: **Why does the BIPs repository no longer track adoption?**
In the past, some BIPs maintained lists of projects that had implemented the BIP. These lists generated
noise for subscribers of the repository, often listed implementations of questionable quality, and quickly
grew outdated, therefore providing little value. The repository no longer tracks which projects have implemented
BIPs. Instead, it is recommended that projects publish a list of the BIPs they implement.
[^markdown]: **Which flavor of Markdown is allowed?**
The author of this proposal has no opinion on Markdown flavors, but recommends that proposals stick to the basic
Markdown syntax features commonly shared across Markdown dialects.
[^living-documents]: **Why are Process BIPs living documents?**
In the past years, the existing BIPs process has not always provided a clear approach to all situations. For
example, the content of BIP2 appears to have been penned especially with fork proposals in mind. It seems clear
that Bitcoin development will evolve in many surprising ways in the future. Instead of mandating the effort of
writing a new process document every time new situations arise, it seems preferable to allow the process to adapt to
the concerns of the future in specific aspects. Therefore, Process BIPs are defined as living documents that remain
open to amendment. If a Process BIP requires large modifications or even a complete overhaul, a new BIP should be
preferred.
[^new-BIP]: **Why should the specification of an implemented BIP no longer be changed?**
After a Complete or Deployed BIP has been deployed by one or more implementations, breaking changes to the
specification could lead to a situation where multiple "compliant" implementations fail at being interoperable,
because they implemented different versions of the same BIP. Therefore, even changes to the specification of
Complete BIPs should be avoided, but Deployed BIPs should never be subject to breaking changes to their
specification.
[^bip-announcements-to-list]: **Why are some BIP status changes announced to the mailing list?**
The BIPs repository does not and cannot track who might be interested in or has deployed a BIP. While concerns were
raised that making announcements to the Bitcoin Developer Mailing List would introduce unnecessary noise, our
rationale is that 1) moving Complete and Deployed BIPs to the Closed status will be a rare occurrence, 2) status
updates will usually not generate a lot of discussion, 3) while the mailing list should preferably only used for
getting review for new BIPs, it is the only channel available to us that can be considered a public announcement to
the audience of the BIPs repository: even if the authors, implementers, or other parties interested in a BIP do not
see the announcement themselves, they may be made aware by someone that does see it.
[^superseded-by-proposed-replacement]: **Why is Superseded-By replaced with Proposed-Replacement?**
Reviewers asked who should get to decide whether a BIP is superseded in case of a disagreement among the authors of
the original BIP, the authors of the new BIP, the editors, or the community? This is addressed by making the
"Replaces" header part of the recommendation of the authors of the new document, and replacing the "Superseded-By"
header with the "Proposed-Replacement" header that lists any proposals that recommend replacing the original document.
[^proposes-to-replace]: **Why was "Replaces" retained instead of changing it to "Proposes-to-Replace"?**
When one BIP proposes to supersede another, it is on the original BIP where things get complicated. The BIP is an
author document, but depending on its progress through the workflow, it may meanwhile be co-owned by the community. Who may decide
whether the original document should endorse a potential replacement BIP? Is it the original authors, the authors of the new
proposal, the BIP Editors, some sort of community process, or a mix of all of the above?
On the new BIP these problems dont exist in the same manner. As it is freshly written, it is wholly owned by its
authors. The community is not yet invested and the original BIPs authors do not have a privileged role
in determining the content of the new BIP. The authors of the new BIP can unilaterally recommend that it be
considered a replacement for a prior BIP. From there, the community can evaluate the proposal and adopt or
reject it, thus establishing whether it is successful in superseding the original or not.
[^evidence]: **How is evidence for advancing to Deployed evaluated?**
Whether evidence is deemed convincing to move a BIP to Deployed is up to the BIP Editors and Bitcoin community.
Running a single instance of a personal fork of a software project might be rejected, while a small software project with
dozens of users may be sufficient. The main point of the Deployed status is to indicate that changes to the BIP
could negatively impact users of projects that have already implemented support.
[^licenses]: **Why were some licenses dropped?**
Among the 141 BIPs with licenses in the repository, only nine licenses have ever been used to license BIPs
(although, some BIPs were made available under more than one license) and only one license has been used to license
code:
Licenses used:
* BSD-2-Clause: 55
* PD: 42
* CC0-1.0: 23
* BSD-3-Clause: 19
* OPUBL-1.0: 5
* CC-BY-SA-4.0: 4
* FSFAP: 3
* MIT: 2
* CC-BY-4.0: 1
License-Code used (previous BIP2 format):
* BSD-2-Clause: 1
* CC0-1.0: 1
* MIT: 5
The following previously acceptable licenses were retained per request of reviewers, even though they have so far
never been used in the BIPs process:
* Apache-2.0: [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0)
* BSL-1.0: [Boost Software License 1.0](https://www.boost.org/LICENSE_1_0.txt)
The following previously acceptable licenses have never been used in the BIPs Process and have been dropped:
* AGPL-3.0+: [GNU Affero General Public License (AGPL) 3](https://www.gnu.org/licenses/agpl-3.0.en.html)
* FDL-1.3: [GNU Free Documentation License 1.3](https://www.gnu.org/licenses/fdl-1.3.en.html)
* GPL-2.0+: [GNU General Public License (GPL) 2 or newer](https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html)
* LGPL-2.1+: [GNU Lesser General Public License (LGPL) 2.1 or newer](https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html)
Why are software licenses included?
* Some BIPs, in particular those concerning the consensus layer, may include literal code in the BIP itself which
may not be available under the license terms the authors wish to use for the BIP.
* The author of this BIP has been provided with a learned opinion indicating that software licenses are perfectly
acceptable for licensing "human code" i.e., text as well as Markdown or MediaWiki code.
Why is CC-BY-SA-4.0 no longer acceptable for new BIPs?
* Specification BIPs are required to have a Reference Implementation and Test Vectors to be advanced to Complete. As
the BIPs repository is aiming to make proposals easily adoptable, the intention is for the reference
implementation and test vectors to be as accessible as possible. Copyleft licenses may introduce friction here,
and therefore CC-BY-SA-4.0 (and the GPL-flavors) is no longer considered acceptable for new BIPs. As mentioned
above, existing BIPs will retain their original licensing.
Why are Open Publication License and Public Domain no longer acceptable for new BIPs?
* Public domain is not universally recognised as a legitimate action, thus it is inadvisable.
* The Open Publication License is generally regarded as obsolete, and not a license suitable for new publications.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 91 KiB

View File

@ -1,12 +1,15 @@
<pre>
BIP: 8
Title: Version bits with lock-in by height
Authors: Shaolin Fry <shaolinfry@protonmail.ch>
Luke Dashjr <luke+bip@dashjr.org>
Author: Shaolin Fry <shaolinfry@protonmail.ch>
Luke Dashjr <luke+bip@dashjr.org>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0008
Status: Draft
Type: Informational
Assigned: 2017-02-01
License: BSD-3-Clause OR CC0-1.0
Created: 2017-02-01
License: BSD-3-Clause
CC0-1.0
</pre>
==Abstract==

View File

@ -1,13 +1,15 @@
<pre>
BIP: 9
Title: Version bits with timeout and delay
Authors: Pieter Wuille <pieter.wuille@gmail.com>
Peter Todd <pete@petertodd.org>
Greg Maxwell <greg@xiph.org>
Rusty Russell <rusty@rustcorp.com.au>
Status: Deployed
Author: Pieter Wuille <pieter.wuille@gmail.com>
Peter Todd <pete@petertodd.org>
Greg Maxwell <greg@xiph.org>
Rusty Russell <rusty@rustcorp.com.au>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0009
Status: Final
Type: Informational
Assigned: 2015-10-04
Created: 2015-10-04
License: PD
</pre>
@ -117,7 +119,7 @@ other one simultaneously transitions to STARTED, which would mean both would dem
Note that a block's state never depends on its own nVersion; only on that of its ancestors.
case STARTED:
case STARTED:
if (GetMedianTimePast(block.parent) >= timeout) {
return FAILED;
}

View File

@ -1,22 +0,0 @@
/* 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;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

After

Width:  |  Height:  |  Size: 30 KiB

View File

@ -2,10 +2,12 @@
BIP: 10
Layer: Applications
Title: Multi-Sig Transaction Distribution
Authors: Alan Reiner <etotheipi@gmail.com>
Status: Closed
Author: Alan Reiner <etotheipi@gmail.com>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0010
Status: Withdrawn
Type: Informational
Assigned: 2011-10-28
Created: 2011-10-28
</pre>
A multi-signature transaction is one where a certain number of Bitcoins are "encumbered" with more than one recipient address. The subsequent transaction that spends these coins will require each party involved (or some subset, depending on the script), to see the proposed transaction and sign it with their private key. This necessarily requires collaboration between all parties -- to propose a distribution of encumbered funds, collect signatures from all necessary participants, and then broadcast the completed transaction.
@ -26,7 +28,7 @@ This BIP proposes the following process, with terms in quotes referring to recom
# One party will initiate this process by creating a "Distribution Proposal", which could be abbreviated DP, or TxDP
# The user creating the TxDP (the preparer) will create the transaction as they would like to see it spent, but with blank TxIn scripts (where the signatures scripts will eventually go).
# The proposed transaction will be spending a set of unspent TxOuts available in the blockchain. The full transactions containing these TxOuts will be serialized and included, as well. This so that the values of the TxIns can be verified before signing (the prev-tx-hash is part of the data being signed, but the value is not). By including the full tx, the signing party can verify that the tx matches the OutPoint hash, and then verify input values, all without any access to the blockchain.
# The TxDP will have an "DP ID" or "Unsigned ID" which is the hash of the proposed transaction with blanked scripts, in Base58. This is a specific naming convention to make sure it is not confused with the actual transaction ID that it will have after it is broadcast (the transaction ID cannot be determined until after all signatures are collected). The final Tx ID can be referred to as its "Broadcast ID", in order to distinguish it from the pre-signed ID.
# The TxDP will have an "DP ID" or "Unsigned ID" which is the hash of the proposed transaction with blanked scripts, in Base58. This is a specific naming convention to make sure it is not confused with the actual the transaction ID that it will have after it is broadcast (the transaction ID cannot be determined until after all signatures are collected). The final Tx ID can be referred to as its "Broadcast ID", in order to distinguish it from the pre-signed ID.
# The TxDP will have a potentially-unordered list of sig-pubkey pairs which represent collected signatures. If you receive a TxDP missing only your signature, you can broadcast it as soon as you sign it.
# Identical TxDP objects with different signatures can be easily combined. This allows one party to send out all the requests for signatures at once, and combine them all when they are received (instead of having to "pass it around".
# For cases where the TxDP might be put into a file or sent via email, it should use .txdp or .btcdp suffix
@ -91,17 +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 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.
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.
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 _SIG_ lines between serializations, though it is not the recommended method for combining TxDPs.
== Changelog ==
* 2014-11-26:
** Withdrawn after Armory stopped using BIP10 and no other projects were known to implement support (see [https://github.com/bitcoin/bips/pull/125 bips#125]).
* 2011-10-28:
** Original Draft published.
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 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.
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.

View File

@ -2,11 +2,13 @@
BIP: 11
Layer: Applications
Title: M-of-N Standard Transactions
Authors: Gavin Andresen <gavinandresen@gmail.com>
Status: Deployed
Type: Specification
Assigned: 2011-10-18
Discussion: 2011-10-02
Author: Gavin Andresen <gavinandresen@gmail.com>
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
</pre>
==Abstract==

View File

@ -2,10 +2,12 @@
BIP: 12
Layer: Consensus (soft fork)
Title: OP_EVAL
Authors: Gavin Andresen <gavinandresen@gmail.com>
Status: Closed
Type: Specification
Assigned: 2011-10-18
Author: Gavin Andresen <gavinandresen@gmail.com>
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
</pre>
==Abstract==

View File

@ -2,10 +2,12 @@
BIP: 13
Layer: Applications
Title: Address Format for pay-to-script-hash
Authors: Gavin Andresen <gavinandresen@gmail.com>
Status: Deployed
Type: Specification
Assigned: 2011-10-18
Author: Gavin Andresen <gavinandresen@gmail.com>
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
</pre>
==Abstract==

View File

@ -2,13 +2,14 @@
BIP: 14
Layer: Peer Services
Title: Protocol Version and User Agent
Authors: Amir Taaki <genjix@riseup.net>
Patrick Strateman <bitcoin-bips@covertinferno.org>
Status: Deployed
Type: Specification
Assigned: 2011-11-10
Discussion: 2011-11-02: https://gnusha.org/pi/bitcoindev/1320268981.72296.YahooMailNeo@web121003.mail.ne1.yahoo.com/
2011-11-10: https://gnusha.org/pi/bitcoindev/1320959761.36702.YahooMailNeo@web121014.mail.ne1.yahoo.com/
Author: Amir Taaki <genjix@riseup.net>
Patrick Strateman <bitcoin-bips@covertinferno.org>
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
</pre>
In this document, bitcoin will be used to refer to the protocol while Satoshi will refer to the current client in order to prevent confusion.
@ -27,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 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).
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).
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.

View File

@ -2,15 +2,17 @@
BIP: 15
Layer: Applications
Title: Aliases
Authors: Amir Taaki <genjix@riseup.net>
Status: Closed
Type: Specification
Assigned: 2011-12-10
Author: Amir Taaki <genjix@riseup.net>
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
</pre>
[[bip-0070.mediawiki|BIP 0070]] (payment protocol) may be seen as the alternative to Aliases.
Using vanilla bitcoin, to send funds to a destination, an address in the form 1Hd44nkJfNAcPJeZyrGC5sKJS1TzgmCTjjZ is needed. The problem with using addresses is that they are not easy to remember. An analogy can be thought if one were required to enter the IP address of their favourite websites if domain names did not exist.
Using vanilla bitcoin, to send funds to a destination, an address in the form 1Hd44nkJfNAcPJeZyrGC5sKJS1TzgmCTjjZ is needed. The problem with using addresses is they are not easy to remember. An analogy can be thought if one were required to enter the IP address of their favourite websites if domain names did not exist.
This document aims to layout through careful argument, a bitcoin alias system. This is a big modification to the protocol that is not easily changed in the future and has big ramifications. There is impetus in getting it correct the first time. Aliases have to be robust and secure.
@ -34,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 (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|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.
@ -206,7 +208,7 @@ NameResolutionService::~NameResolutionService()
void NameResolutionService::ExplodeHandle(const string& strHandle, string& strNickname, string& strDomain)
{
// split address at @ furthest to the right
// split address at @ furthrest to the right
size_t nPosAtsym = strHandle.rfind('@');
strNickname = strHandle.substr(0, nPosAtsym);
strDomain = strHandle.substr(nPosAtsym + 1, strHandle.size());
@ -346,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 retrieves 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 retreives 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).
@ -399,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 information.
See the specification of [http://dot-bit.org/Namespace:Identity Namecoin ID] for more informations.

View File

@ -2,10 +2,12 @@
BIP: 16
Layer: Consensus (soft fork)
Title: Pay to Script Hash
Authors: Gavin Andresen <gavinandresen@gmail.com>
Status: Deployed
Type: Specification
Assigned: 2012-01-03
Author: Gavin Andresen <gavinandresen@gmail.com>
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
</pre>
==Abstract==
@ -56,7 +58,7 @@ Examples:
+3 signature operations:
{2 [pubkey1] [pubkey2] [pubkey3] 3 OP_CHECKMULTISIG}
+22 signature operations:
+22 signature operations
{OP_CHECKSIG OP_IF OP_CHECKSIGVERIFY OP_ELSE OP_CHECKMULTISIGVERIFY OP_ENDIF}
==Rationale==
@ -72,7 +74,7 @@ The signature operation counting rules are intended to be easy and quick to impl
There is a 1-confirmation attack on old implementations, but it is expensive and difficult in practice. The attack is:
# Attacker creates a pay-to-script-hash transaction that is valid as seen by old software, but invalid for new implementation, and sends themselves some coins using it.
# Attacker also creates a standard transaction that spends the pay-to-script-hash transaction, and pays the victim who is running old software.
# Attacker also creates a standard transaction that spends the pay-to-script transaction, and pays the victim who is running old software.
# Attacker mines a block that contains both transactions.
If the victim accepts the 1-confirmation payment, then the attacker wins because both transactions will be invalidated when the rest of the network overwrites the attacker's invalid block.
@ -114,5 +116,4 @@ https://gist.github.com/gavinandresen/3966071
* [[bip-0016/qa.mediawiki|Quality Assurance test checklist]]
== References ==
<references/>
<references>

View File

@ -2,10 +2,12 @@
BIP: 17
Layer: Consensus (soft fork)
Title: OP_CHECKHASHVERIFY (CHV)
Authors: Luke Dashjr <luke+bip17@dashjr.org>
Status: Closed
Type: Specification
Assigned: 2012-01-18
Author: Luke Dashjr <luke+bip17@dashjr.org>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0017
Status: Withdrawn
Type: Standards Track
Created: 2012-01-18
License: BSD-2-Clause
</pre>
@ -84,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.

View File

@ -2,10 +2,12 @@
BIP: 18
Layer: Consensus (soft fork)
Title: hashScriptCheck
Authors: Luke Dashjr <luke+bip17@dashjr.org>
Status: Complete
Type: Specification
Assigned: 2012-01-27
Author: Luke Dashjr <luke+bip17@dashjr.org>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0018
Status: Proposed
Type: Standards Track
Created: 2012-01-27
License: BSD-2-Clause
</pre>

View File

@ -2,10 +2,12 @@
BIP: 19
Layer: Applications
Title: M-of-N Standard Transactions (Low SigOp)
Authors: Luke Dashjr <luke+bip17@dashjr.org>
Status: Closed
Type: Specification
Assigned: 2012-01-30
Author: Luke Dashjr <luke+bip17@dashjr.org>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0019
Status: Rejected
Type: Standards Track
Created: 2012-01-30
License: BSD-2-Clause
</pre>

View File

@ -2,12 +2,13 @@
BIP: 20
Layer: Applications
Title: URI Scheme
Authors: Luke Dashjr <luke+bip@dashjr.org>
Status: Closed
Type: Specification
Assigned: 2011-01-10
Author: Luke Dashjr <luke+bip@dashjr.org>
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
Proposed-Replacement: 21
</pre>
BIP 0020 is based off an earlier document by Nils Schneider. '''And has been replaced by BIP 0021'''
@ -33,7 +34,7 @@ Graphical bitcoin clients SHOULD register themselves as the handler for the "bit
=== BNF grammar ===
(See also [[#simpler-syntax|a simpler representation of syntax]])
(See also [[#Simpler syntax|a simpler representation of syntax]])
bitcoinurn = "bitcoin:" bitcoinaddress [ ";version=" bitcoinversion ] [ "?" bitcoinparams ]
bitcoinaddress = base58 *base58
@ -53,8 +54,8 @@ Graphical bitcoin clients SHOULD register themselves as the handler for the "bit
*label: Label for that address (e.g. name of receiver)
*address: bitcoin address
*message: message that is shown to the user after scanning the QR code
*size: amount of base bitcoin units ([[#transfer-amountsize|see below]])
*message: message that shown to the user after scanning the QR code
*size: amount of base bitcoin units ([[#Transfer amount/size|see below]])
*send: used to send bitcoin, rather than to request them
*(others): optional, for future extensions
@ -96,7 +97,7 @@ Make it possible for later generations to improve our work, to mend our errors,
=== Simpler syntax ===
This section is non-normative and does not cover all possible syntax.
Please see the [[#bnf-grammar|BNF grammar]] above for the normative syntax.
Please see the [[#BNF grammar|BNF grammar]] above for the normative syntax.
[foo] means optional, &lt;bar&gt; are placeholders

View File

@ -2,21 +2,15 @@
BIP: 21
Layer: Applications
Title: URI Scheme
Authors: Nils Schneider <nils.schneider@gmail.com>
Matt Corallo <bip21@bluematt.me>
Status: Closed
Type: Specification
Assigned: 2012-01-29
Replaces: 20
Proposed-Replacement: 321
Author: Nils Schneider <nils.schneider@gmail.com>
Matt Corallo <bip21@bluematt.me>
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
</pre>
=Superseded by BIP 321=
This BIP has been superseded and replaced with BIP 321. Please see [[bip-0321.mediawiki|BIP 321]] instead.
=Original BIP=
This BIP is a modification of an earlier [[bip-0020.mediawiki|BIP 0020]] by Luke Dashjr. BIP 0020 was based off an earlier document by Nils Schneider. The alternative payment amounts in BIP 0020 have been removed.
==Abstract==
@ -43,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
@ -63,7 +57,7 @@ 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]])
*message: message that describes the transaction to the user ([[#Examples|see examples below]])
*(others): optional, for future extensions
==== Transfer amount ====
@ -106,8 +100,6 @@ Please see the BNF grammar above for the normative syntax.
=== Examples ===
Note: The addresses used in these examples are intentionally invalid to prevent accidental transactions.
Just the address:
bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W
@ -128,6 +120,11 @@ Some future version that has variables which are (currently) not understood but
Characters must be URI encoded properly.
== Reference Implementation ==
== 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.
Bitcoin-Qt supports the old version of Bitcoin URIs (ie without the req- prefix), with Windows and KDE integration as of commit 70f55355e29c8e45b607e782c5d76609d23cc858.
=== Libraries ===
* Javascript - https://github.com/bitcoinjs/bip21
* Java - https://github.com/SandroMachado/BitcoinPaymentURI
* Swift - https://github.com/SandroMachado/BitcoinPaymentURISwift

View File

@ -2,10 +2,12 @@
BIP: 22
Layer: API/RPC
Title: getblocktemplate - Fundamentals
Authors: Luke Dashjr <luke+bip22@dashjr.org>
Status: Deployed
Type: Specification
Assigned: 2012-02-28
Author: Luke Dashjr <luke+bip22@dashjr.org>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0022
Status: Final
Type: Standards Track
Created: 2012-02-28
License: BSD-2-Clause
</pre>
@ -24,7 +26,7 @@ This BIP is licensed under the BSD 2-clause license.
A JSON-RPC method is defined, called "getblocktemplate".
It accepts exactly one argument, which MUST be an Object of request parameters.
If the request parameters include a "mode" key, that is used to explicitly select between the default "template" request or a [[bip-0023.mediawiki#block-proposal|"proposal"]].
If the request parameters include a "mode" key, that is used to explicitly select between the default "template" request or a [[bip-0023.mediawiki#Block Proposal|"proposal"]].
Block template creation can be influenced by various parameters:
{| class="wikitable"
@ -32,7 +34,7 @@ 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
|}
@ -55,17 +57,17 @@ getblocktemplate MUST return a JSON Object containing the following keys:
|-
| sizelimit || No || Number || number of bytes allowed in blocks
|-
| transactions || 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)
|-
| 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 || this or ↓ || Object || [[#transactions-object-format|information for coinbase transaction]]
| coinbasetxn || this or ↓ || Object || [[#Transactions Object Format|information for coinbase transaction]]
|-
| 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 ====

View File

@ -2,10 +2,12 @@
BIP: 23
Layer: API/RPC
Title: getblocktemplate - Pooled Mining
Authors: Luke Dashjr <luke+bip22@dashjr.org>
Status: Deployed
Type: Specification
Assigned: 2012-02-28
Author: Luke Dashjr <luke+bip22@dashjr.org>
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
</pre>
@ -27,15 +29,15 @@ Something can be said to have BIP 23 Level 1 support if it implements at least:
* [http://www.ietf.org/rfc/rfc1945.txt RFC 1945]
* [http://json-rpc.org/wiki/specification JSON-RPC 1.0]
* [[bip-0022.mediawiki|BIP 22 (non-optional sections)]]
* [[bip-0022.mediawiki#optional-long-polling|BIP 22 Long Polling]]
* [[#basic-pool-extensions|BIP 23 Basic Pool Extensions]]
* [[#mutations|BIP 23 Mutation "coinbase/append"]]
* [[#submission-abbreviation|BIP 23 Submission Abbreviation "submit/coinbase"]]
* [[#mutations|BIP 23 Mutation "time/increment"]] (only required for servers)
* [[bip-0022.mediawiki#Optional: Long Polling|BIP 22 Long Polling]]
* [[#Basic Pool Extensions|BIP 23 Basic Pool Extensions]]
* [[#Mutations|BIP 23 Mutation "coinbase/append"]]
* [[#Submission Abbreviation|BIP 23 Submission Abbreviation "submit/coinbase"]]
* [[#Mutations|BIP 23 Mutation "time/increment"]] (only required for servers)
It can be said to have BIP 23 Level 2 support if it also implements:
* [[#mutations|BIP 23 Mutation "transactions/add"]]
* [[#block-proposals|BIP 23 Block Proposals]]
* [[#Mutations|BIP 23 Mutation "transactions/add"]]
* [[#Block Proposals|BIP 23 Block Proposals]]
===Basic Pool Extensions===

View File

@ -2,10 +2,12 @@
BIP: 30
Layer: Consensus (soft fork)
Title: Duplicate transactions
Authors: Pieter Wuille <pieter.wuille@gmail.com>
Status: Deployed
Type: Specification
Assigned: 2012-02-22
Author: Pieter Wuille <pieter.wuille@gmail.com>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0030
Status: Final
Type: Standards Track
Created: 2012-02-22
License: BSD-2-Clause
</pre>

View File

@ -2,10 +2,12 @@
BIP: 31
Layer: Peer Services
Title: Pong message
Authors: Mike Hearn <hearn@google.com>
Status: Deployed
Type: Specification
Assigned: 2012-04-11
Author: Mike Hearn <hearn@google.com>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0031
Status: Final
Type: Standards Track
Created: 2012-04-11
</pre>
==Abstract==

View File

@ -10,10 +10,12 @@ RECENT CHANGES:
BIP: 32
Layer: Applications
Title: Hierarchical Deterministic Wallets
Authors: Pieter Wuille <pieter.wuille@gmail.com>
Status: Deployed
Author: Pieter Wuille <pieter.wuille@gmail.com>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0032
Status: Final
Type: Informational
Assigned: 2012-02-11
Created: 2012-02-11
License: BSD-2-Clause
</pre>
@ -23,7 +25,7 @@ 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 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.
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.
==Copyright==
@ -35,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 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.
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.
==Specification: Key derivation==
@ -50,10 +52,10 @@ Addition (+) of two coordinate pair is defined as application of the EC group op
Concatenation (||) is the operation of appending one byte sequence onto another.
As standard conversion functions, we assume:
* point(p): returns the coordinate pair resulting from EC point multiplication (repeated application of the EC group operation) of the secp256k1 base point with the integer p (i.e., the operation used to compute a public key from a private key).
* point(p): returns the coordinate pair resulting from EC point multiplication (repeated application of the EC group operation) of the secp256k1 base point with the integer p.
* ser<sub>32</sub>(i): serialize a 32-bit unsigned integer i as a 4-byte sequence, most significant byte first.
* ser<sub>256</sub>(p): serializes the integer p as a 32-byte sequence, most significant byte first.
* ser<sub>P</sub>(P): serializes the coordinate pair P = (x,y) (i.e., the public key) as a byte sequence using [https://www.secg.org/sec1-v2.pdf SEC1]'s compressed form: (0x02 or 0x03) || ser<sub>256</sub>(x), where the header byte depends on the parity of the omitted y coordinate.
* ser<sub>P</sub>(P): serializes the coordinate pair P = (x,y) as a byte sequence using SEC1's compressed form: (0x02 or 0x03) || ser<sub>256</sub>(x), where the header byte depends on the parity of the omitted y coordinate.
* parse<sub>256</sub>(p): interprets a 32-byte sequence as a 256-bit number, most significant byte first.
@ -102,7 +104,7 @@ The function N((k, c)) &rarr; (K, c) computes the extended public key correspond
To compute the public child key of a parent private key:
* N(CKDpriv((k<sub>par</sub>, c<sub>par</sub>), i)) (works always).
* CKDpub(N(k<sub>par</sub>, c<sub>par</sub>), 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 below 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 for more information.
====Public parent key &rarr; private child key====
@ -128,14 +130,14 @@ The first 32 bits of the identifier are called the key fingerprint.
===Serialization format===
Extended public and private keys are serialized as follows:
* 4 bytes: version bytes (mainnet: 0x0488B21E public, 0x0488ADE4 private; testnet: 0x043587CF public, 0x04358394 private)
* 4 byte: version bytes (mainnet: 0x0488B21E public, 0x0488ADE4 private; testnet: 0x043587CF public, 0x04358394 private)
* 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 derived keys, ....
* 4 bytes: the fingerprint of the parent's key (0x00000000 if master key)
* 4 bytes: child number. This is ser<sub>32</sub>(i) for i in x<sub>i</sub> = x<sub>par</sub>/i, with x<sub>i</sub> the key being serialized. (0x00000000 if master key)
* 32 bytes: the chain code
* 33 bytes: the public key or private key data (ser<sub>P</sub>(K) for public keys, 0x00 || ser<sub>256</sub>(k) for private keys)
This 78 byte structure can be encoded like other Bitcoin data in Base58, by first adding 32 checksum bits (derived from the double SHA-256 checksum), and then converting to the Base58 representation. This results in a Base58-encoded string of exactly 111 characters. Because of the choice of the version bytes, the Base58 representation will start with "xprv" or "xpub" on mainnet, "tprv" or "tpub" on testnet.
This 78 byte structure can be encoded like other Bitcoin data in Base58, by first adding 32 checksum bits (derived from the double SHA-256 checksum), and then converting to the Base58 representation. This results in a Base58-encoded string of up to 112 characters. Because of the choice of the version bytes, the Base58 representation will start with "xprv" or "xpub" on mainnet, "tprv" or "tpub" on testnet.
Note that the fingerprint of the parent only serves as a fast way to detect parent and child nodes in software, and software must be willing to deal with collisions. Internally, the full 160-bit identifier could be used.
@ -182,7 +184,7 @@ When a business has several independent offices, they can all use wallets derive
====Recurrent business-to-business transactions: N(m/i<sub>H</sub>/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 a variable payout address.
Such a mechanism could also be used by mining pool operators as variable payout address.
====Unsecure money receiver: N(m/i<sub>H</sub>/0)====
@ -210,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 keys 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 key never risks compromising the master or other accounts.
==Test Vectors==

View File

@ -2,10 +2,12 @@
BIP: 33
Layer: Peer Services
Title: Stratized Nodes
Authors: Amir Taaki <genjix@riseup.net>
Status: Closed
Type: Specification
Assigned: 2012-05-15
Author: Amir Taaki <genjix@riseup.net>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0033
Status: Rejected
Type: Standards Track
Created: 2012-05-15
</pre>
== Abstract ==

View File

@ -2,10 +2,12 @@
BIP: 34
Layer: Consensus (soft fork)
Title: Block v2, Height in Coinbase
Authors: Gavin Andresen <gavinandresen@gmail.com>
Status: Deployed
Type: Specification
Assigned: 2012-07-06
Author: Gavin Andresen <gavinandresen@gmail.com>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0034
Status: Final
Type: Standards Track
Created: 2012-07-06
</pre>
==Abstract==

View File

@ -2,10 +2,12 @@
BIP: 35
Layer: Peer Services
Title: mempool message
Authors: Jeff Garzik <jgarzik@exmulti.com>
Status: Deployed
Type: Specification
Assigned: 2012-08-16
Author: Jeff Garzik <jgarzik@exmulti.com>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0035
Status: Final
Type: Standards Track
Created: 2012-08-16
</pre>
==Abstract==
@ -14,7 +16,7 @@ Make a network node's transaction memory pool accessible via a new "mempool" mes
==Motivation==
Several use cases make it desirable to expose a network node's transaction memory pool:
Several use cases make it desireable 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.
@ -22,7 +24,7 @@ Several use cases make it desirable to expose a network node's transaction memor
==Specification==
# The mempool message is defined as an empty message where pchCommand == "mempool"
# Upon receipt of a "mempool" message, the node will respond with an "inv" message containing MSG_TX hashes of all the transactions in the node's transaction memory pool, if any.
# Upon receipt of a "mempool" message, the node will respond with an "inv" message containing MSG_TX hashes of all the transactions in the node's transaction memory pool, if any.
# The typical node behavior in response to an "inv" is "getdata". However, the reference Satoshi implementation ignores requests for transaction hashes outside that which is recently relayed. To support "mempool", an implementation must extend its "getdata" message support to querying the memory pool.
# Feature discovery is enabled by checking two "version" message attributes:
## Protocol version >= 60002

View File

@ -2,10 +2,12 @@
BIP: 36
Layer: Peer Services
Title: Custom Services
Authors: Stefan Thomas <justmoon@members.fsf.org>
Status: Closed
Type: Specification
Assigned: 2012-08-03
Author: Stefan Thomas <justmoon@members.fsf.org>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0036
Status: Rejected
Type: Standards Track
Created: 2012-08-03
License: PD
</pre>
@ -24,7 +26,7 @@ Two new fields are added to the <code>version</code> command, after <code>extra_
{|class="wikitable"
! Field Size !! Description !! Data type !! Comments
|-
| 1+ || service_count || [[Protocol_specification#variable-length-integer|var_int]] || Number of extra services
| 1+ || service_count || [[Protocol_specification#Variable_length_integer|var_int]] || Number of extra services
|-
| ? || service_list || service[] || List of service definitions
|}
@ -34,11 +36,11 @@ The service definitions <code>service[]</code> are given in the following format
{|class="wikitable"
! Field Size !! Description !! Data type !! Comments
|-
| ? || service_name || [[#variable-length-string|var_str]] || Unique service identifier
| ? || service_name || [[#Variable length string|var_str]] || Unique service identifier
|-
| 4 || service_version || uint32_t || Identifies service version being used by the node
|-
| ? || service_data || [[#variable-length-string|var_str]] || Additional service-specific data
| ? || service_data || [[#Variable length string|var_str]] || Additional service-specific data
|}
A node MUST NOT announce two services with the same <code>service_name</code>. If a remote node sends such a <code>version</code> message the client MAY disconnect.

View File

@ -2,13 +2,13 @@
BIP: 37
Layer: Peer Services
Title: Connection Bloom filtering
Authors: Mike Hearn <hearn@google.com>
Matt Corallo <bip37@bluematt.me>
Author: Mike Hearn <hearn@google.com>
Matt Corallo <bip37@bluematt.me>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0037
Status: Deployed
Type: Specification
Assigned: 2012-10-24
Status: Final
Type: Standards Track
Created: 2012-10-24
License: PD
</pre>
@ -159,7 +159,7 @@ A ''Merkle tree'' is a way of arranging a set of items as leaf nodes of tree in
** Check whether this node corresponds to a leaf node (transaction) that is to be included OR any parent thereof:
*** If so, append a '1' bit to the flag bits
*** Otherwise, append a '0' bit.
** Check whether this node is an internal node (non-leaf) AND is the parent of an included leaf node:
** Check whether this node is a internal node (non-leaf) AND is the parent of an included leaf node:
*** If so:
**** Descend into its left child node, and process the subtree beneath it entirely (depth-first).
**** If this node has a right child node too, descend into it as well.

View File

@ -2,13 +2,13 @@
BIP: 38
Layer: Applications
Title: Passphrase-protected private key
Authors: Mike Caldwell <mcaldwell@swipeclock.com>
Aaron Voisine <voisine@gmail.com>
Author: Mike Caldwell <mcaldwell@swipeclock.com>
Aaron Voisine <voisine@gmail.com>
Comments-Summary: Unanimously Discourage for implementation
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0038
Status: Deployed
Type: Specification
Assigned: 2012-11-20
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
</pre>
@ -36,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:
@ -47,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.
@ -64,7 +64,7 @@ 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 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.
@ -75,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)
@ -170,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 specified 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 specifid in ''flagbyte''.
=====Decryption=====
# Collect encrypted private key and passphrase from user.
@ -184,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.
@ -209,10 +209,14 @@ 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:
* https://github.com/casascius/Bitcoin-Address-Utility
* via https: https://casascius.com/btcaddress-alpha.zip
* at github: https://github.com/casascius/Bitcoin-Address-Utility
Click "Tools" then "PPEC Keygen" (provisional name)
==Other implementations==
* Javascript - https://github.com/bitcoinjs/bip38
==Test vectors==
===No compression, no EC multiply===
@ -272,7 +276,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
@ -280,9 +284,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

View File

@ -2,16 +2,15 @@
BIP: 39
Layer: Applications
Title: Mnemonic code for generating deterministic keys
Authors: Marek Palatinus <slush@satoshilabs.com>
Pavol Rusnak <stick@satoshilabs.com>
Aaron Voisine <voisine@gmail.com>
Sean Bowe <ewillbefull@gmail.com>
Author: Marek Palatinus <slush@satoshilabs.com>
Pavol Rusnak <stick@satoshilabs.com>
Aaron Voisine <voisine@gmail.com>
Sean Bowe <ewillbefull@gmail.com>
Comments-Summary: Unanimously Discourage for implementation
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0039
Status: Deployed
Type: Specification
Assigned: 2013-09-10
License: MIT
Status: Proposed
Type: Standards Track
Created: 2013-09-10
</pre>
==Abstract==
@ -23,10 +22,6 @@ 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.
==Copyright==
This BIP falls under the MIT License.
==Motivation==
A mnemonic code or sentence is superior for human interaction compared to the
@ -143,3 +138,69 @@ Also see https://github.com/bip32JP/bip32JP.github.io/blob/master/test_JP_BIP39.
Reference implementation including wordlists is available from
http://github.com/trezor/python-mnemonic
==Other Implementations==
Go:
* https://github.com/tyler-smith/go-bip39
Python:
* https://github.com/meherett/python-hdwallet
Elixir:
* https://github.com/aerosol/mnemo
Objective-C:
* https://github.com/nybex/NYMnemonic
Haskell:
* https://github.com/haskoin/haskoin
.NET (Standard):
* https://www.nuget.org/packages/dotnetstandard-bip39/
.NET C# (PCL):
* https://github.com/Thashiznets/BIP39.NET
.NET C# (PCL):
* https://github.com/NicolasDorier/NBitcoin
JavaScript:
* https://github.com/bitpay/bitcore/tree/master/packages/bitcore-mnemonic
* https://github.com/bitcoinjs/bip39 (used by [[https://github.com/blockchain/My-Wallet-V3/blob/v3.8.0/src/hd-wallet.js#L121-L146|blockchain.info]])
* https://github.com/dashhive/DashPhrase.js
* https://github.com/hujiulong/web-bip39
Java:
* https://github.com/bitcoinj/bitcoinj/blob/master/core/src/main/java/org/bitcoinj/crypto/MnemonicCode.java
Ruby:
* https://github.com/sreekanthgs/bip_mnemonic
Rust:
* https://github.com/maciejhirsz/tiny-bip39/
* https://github.com/koushiro/bip0039-rs
Smalltalk:
* https://github.com/eMaringolo/pharo-bip39mnemonic
Swift:
* https://github.com/CikeQiu/CKMnemonic
* https://github.com/yuzushioh/WalletKit
* https://github.com/pengpengliu/BIP39
* https://github.com/matter-labs/web3swift/blob/develop/Sources/web3swift/KeystoreManager/BIP39.swift
* https://github.com/zcash-hackworks/MnemonicSwift
* https://github.com/ShenghaiWang/BIP39
* https://github.com/anquii/BIP39
C++:
* https://github.com/libbitcoin/libbitcoin-system/blob/master/include/bitcoin/system/wallet/mnemonic.hpp
C (with Python/Java/Javascript bindings):
* https://github.com/ElementsProject/libwally-core
Python:
* https://github.com/scgbckbone/btc-hd-wallet
Dart:
* https://github.com/dart-bitcoin/bip39

View File

@ -28,7 +28,7 @@ for two smaller words (This would be a problem with any of the 3 character sets
### Spanish
1. Words can be uniquely determined by typing the first 4 characters (sometimes less).
1. Words can be uniquely determined typing the first 4 characters (sometimes less).
2. Special Spanish characters like 'ñ', 'ü', 'á', etc... are considered equal to 'n', 'u', 'a', etc... in terms of identifying a word. Therefore, there is no need to use a Spanish keyboard to introduce the passphrase, an application with the Spanish wordlist will be able to identify the words after the first 4 chars have been typed even if the chars with accents have been replaced with the equivalent without accents.
@ -50,10 +50,10 @@ Credits: @Kirvx @NicolasDorier @ecdsa @EricLarch
4. Only infinitive verbs, adjectives and nouns.
5. No pronouns, no adverbs, no prepositions, no conjunctions, no interjections (unless a noun/adjective is also popular than its interjection like "mince;chouette").
6. No numeral adjectives.
7. No words in the plural (except invariable words like "univers", or same spelling as singular like "heureux").
7. No words in the plural (except invariable words like "univers", or same spelling than singular like "heureux").
8. No female adjectives (except words with same spelling for male and female adjectives like "magique").
9. No words with several senses AND different spelling in speaking like "verre-vert", unless a word has a meaning much more popular than another like "perle" and "pairle".
10. No very similar words with only 1 letter of difference.
10. No very similar words with 1 letter of difference.
11. No essentially reflexive verbs (unless a verb is also a noun like "souvenir").
12. No words with "ô;â;ç;ê;œ;æ;î;ï;û;ù;à;ë;ÿ".
13. No words ending by "é;ée;è;et;ai;ait".
@ -76,7 +76,7 @@ Words chosen using the following rules:
6. No plural words.
7. No words that remind negative/sad/bad things.
8. If both female/male words are available, choose male version.
9. No words with double vowels (like: lineetta).
9. No words with double vocals (like: lineetta).
10. No words already used in other language mnemonic sets.
11. If 3 of the first 4 letters are already used in the same sequence in another mnemonic word, there must be at least other 3 different letters.
12. If 3 of the first 4 letters are already used in the same sequence in another mnemonic word, there must not be the same sequence of 3 or more letters.
@ -92,26 +92,26 @@ Credits: @zizelevak (Jan Lansky zizelevak@gmail.com)
Words chosen using the following rules:
1. Words are 4-8 letters long.
2. Words can be uniquely determined by typing the first 4 letters.
3. Only words containing all letters without diacritical marks. (It was the hardest task, because one third of all Czech letters has diacritical marks.)
2. Words can be uniquely determined typing the first 4 letters.
3. Only words containing all letters without diacritical marks. (It was the hardest task, because in one third of all Czech letters has diacritical marks.)
4. Only nouns, verbs and adverbs, no other word types. All words are in basic form.
5. No personal names or geographical names.
6. No very similar words with 1 letter of difference.
7. Words are sorted according to English alphabet (Czech sorting has difference in "ch").
8. No words already used in other language mnemonic sets (english, italian, french, spanish). Letters with diacritical marks from these sets are counted as analogous letters without diacritical marks.
7. Words are sorting according English alphabet (Czech sorting has difference in "ch").
8. No words already used in other language mnemonic sets (english, italian, french, spanish). Letters with diacritical marks from these sets are counted as analogous letters without diacritical marks.
### Portuguese
Credits: @alegotardo @bitmover-studio @brenorb @kuthullu @ninjastic @sabotag3x @Trimegistus
1. Words can be uniquely determined by typing the first 4 characters.
1. Words can be uniquely determined typing the first 4 characters.
2. No accents or special characters.
3. No complex verb forms.
4. No plural words, unless there's no singular form.
5. No words with double spelling.
6. No words with the exact sound as another word with different spelling.
6. No words with the exact sound of another word with different spelling.
7. No offensive words.
8. No words already used in other language mnemonic sets.
9. The words which have not the same spelling in Brazil and in Portugal are excluded.
10. No words that remind one of negative/sad/bad things.
11. No very similar words with only 1 letter of difference.
10. No words that remind negative/sad/bad things.
11. No very similar words with 1 letter of difference.

View File

@ -2,20 +2,20 @@
BIP: 42
Layer: Consensus (soft fork)
Title: A finite monetary supply for Bitcoin
Authors: Pieter Wuille <pieter.wuille@gmail.com>
Author: Pieter Wuille <pieter.wuille@gmail.com>
Comments-Summary: Unanimously Recommended for implementation
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0042
Status: Deployed
Type: Specification
Assigned: 2014-04-01
Status: Final
Type: Standards Track
Created: 2014-04-01
License: PD
</pre>
==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 mibillennium (1024 years), with equal intervals between them, each one being depleted over the course of 140 years.
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.
@ -42,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===

View File

@ -2,11 +2,13 @@
BIP: 43
Layer: Applications
Title: Purpose Field for Deterministic Wallets
Authors: Marek Palatinus <slush@satoshilabs.com>
Pavol Rusnak <stick@satoshilabs.com>
Status: Deployed
Type: Specification
Assigned: 2014-04-24
Author: Marek Palatinus <slush@satoshilabs.com>
Pavol Rusnak <stick@satoshilabs.com>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0043
Status: Final
Type: Informational
Created: 2014-04-24
</pre>
==Abstract==
@ -18,7 +20,7 @@ based on algorithm described in BIP-0032 (BIP32 from now on).
Although Hierarchical Deterministic Wallet structure as described by BIP32
is an important step in user experience and security of the cryptocoin wallets,
the BIP32 specification offers implementers too many degrees of freedom.
the BIP32 specification offers implementors too many degrees of freedom.
Multiple implementations may claim they are BIP32 compatible, but in fact
they can produce wallets with different logical structures making them
non-interoperable. This situation unfortunately renders "BIP32 compatible"

View File

@ -2,14 +2,13 @@
BIP: 44
Layer: Applications
Title: Multi-Account Hierarchy for Deterministic Wallets
Authors: Marek Palatinus <slush@satoshilabs.com>
Pavol Rusnak <stick@satoshilabs.com>
Author: Marek Palatinus <slush@satoshilabs.com>
Pavol Rusnak <stick@satoshilabs.com>
Comments-Summary: Mixed review (one person)
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0044
Status: Deployed
Type: Specification
Assigned: 2014-04-24
Requires: 32, 43
Status: Proposed
Type: Standards Track
Created: 2014-04-24
</pre>
==Abstract==

View File

@ -2,12 +2,14 @@
BIP: 45
Layer: Applications
Title: Structure for Deterministic P2SH Multisignature Wallets
Authors: Manuel Araoz <manu@bitpay.com>
Ryan X. Charles <ryan@bitpay.com>
Matias Alejo Garcia <matias@bitpay.com>
Status: Complete
Type: Specification
Assigned: 2014-04-25
Author: Manuel Araoz <manu@bitpay.com>
Ryan X. Charles <ryan@bitpay.com>
Matias Alejo Garcia <matias@bitpay.com>
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
</pre>
==Abstract==

View File

@ -1,192 +0,0 @@
<pre>
BIP: 46
Layer: Applications
Title: Address Scheme for Timelocked Fidelity Bonds
Authors: Chris Belcher <belcher@riseup.net>
Thebora Kompanioni <theborakompanioni+bip46@gmail.com>
Status: Draft
Type: Specification
Assigned: 2022-04-01
License: CC0-1.0
Discussion: 2022-05-01: https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2022-May/020389.html
</pre>
== 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 <tt>change</tt> set to <tt>2</tt>.
<pre>
m / 84' / 0' / 0' / 2 / index
</pre>
A key derived with this derivation path pattern will be referred to as <tt>derived_key</tt> further
in this document.
For <tt>index</tt>, addresses are numbered from 0 in a sequentially increasing manner with a fixed upper bound: The index only goes up to <tt>959</tt> 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 <tt>index</tt>. 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 <tt>index</tt> 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.
<pre>
year = 2020 + index // 12
month = 1 + index % 12
</pre>
=== Address derivation ===
To derive the address from the above calculated public key and timelock, we create a <tt>witness script</tt> which locks the funds until the <tt>timelock</tt>, and then checks the signature of the <tt>derived_key</tt>. The <tt>witness script</tt> is hashed with SHA256 to produce a 32-byte hash value that forms the <tt>witness program</tt> in the output script of the P2WSH address.
witnessScript: <timelock> OP_CHECKLOCKTIMEVERIFY OP_DROP <derived_key> OP_CHECKSIG
witness: <signature> <witnessScript>
scriptSig: (empty)
scriptPubKey: 0 <32-byte-hash>
(0x0020{32-byte-hash})
=== Message signing ===
In order to support signing of certificates, implementers 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 <tt>derived_key</tt>. 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 ==
<pre>
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 implementers 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=
</pre>
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]]

View File

@ -1,26 +1,20 @@
RECENT CHANGES:
* (15 Feb 2021) Finalize specification
* (28 Sep 2017) Adjust text to match test vectors
* (19 Apr 2016) Define version 2 payment codes
* (17 Apr 2016) Clarify usage of outpoints in notification transactions
* (18 Dec 2015) Update explanations to resolve FAQs
<pre>
BIP: 47
Layer: Applications
Title: Reusable Payment Codes for Hierarchical Deterministic Wallets
Authors: Justus Ranvier <justus@openbitcoinprivacyproject.org>
Author: Justus Ranvier <justus@openbitcoinprivacyproject.org>
Comments-Summary: Unanimously Discourage for implementation
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0047
Status: Deployed
Status: Draft
Type: Informational
Assigned: 2015-04-24
Created: 2015-04-24
</pre>
==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.
@ -156,7 +150,7 @@ It is assumed that Alice can easily obtain Bob's payment code via a suitable met
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.
Note: this procedure is used if Bob uses a version 1 payment code (regardless of the 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
@ -164,7 +158,7 @@ Note: this procedure is used if Bob uses a version 1 payment code (regardless of
## Alice selects the private key corresponding to the designated pubkey: <pre>a</pre>
## Alice selects the public key associated with Bob's notification address: <pre>B, where B = bG</pre>
## Alice calculates a secret point: <pre>S = aB</pre>
## Alice calculates a 64 byte blinding factor: <pre>s = HMAC-SHA512(o, x)</pre>
## Alice calculates a 64 byte blinding factor: <pre>s = HMAC-SHA512(x, o)</pre>
### "x" is the x value of the secret point
### "o" is the outpoint being spent by the designated input
# Alice serializes her payment code in binary form.
@ -235,7 +229,7 @@ The following actions are recommended to reduce this risk:
<img src="bip-0047/reusable_payment_codes-04.png" />
<img src="bip-0047/reusable_payment_codes-05.png" />
# 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 0<sup>th</sup> 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 n shared secrets with Alice, using the 0<sup>th</sup> 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 the ephemeral deposit addresses using the same procedure as Alice: <pre>B' = B + sG</pre>
## Bob calculate the private key for each ephemeral address as: <pre>b' = b + s</pre>
<img src="bip-0047/reusable_payment_codes-02.png" />
@ -275,7 +269,7 @@ 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-queryable blockchain explorer.
The required data may be obtained from copy of the blockchain under the control of the user, or via a publicly-queriable 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.
@ -350,12 +344,12 @@ Version 2 payment codes behave identifically to version 1 payment codes, except
====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
* Notification change output: the change output from a notification transaction which 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.
Note: this procedure is used if Bob uses a version 2 payment code (regardless of the 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:

View File

@ -2,10 +2,12 @@
BIP: 48
Layer: Applications
Title: Multi-Script Hierarchy for Multi-Sig Wallets
Authors: Fontaine <dentondevelopment@protonmail.com>
Status: Deployed
Type: Specification
Assigned: 2020-12-16
Author: Fontaine <dentondevelopment@protonmail.com>
Comments-Summary: No comments
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0048
Status: Proposed
Type: Standards Track
Created: 2020-12-16
License: MIT
</pre>
@ -111,6 +113,9 @@ The following path represents Native Segwit (p2wsh) mainnet, account 0:
The recommended default for wallets is pay to witness script hash <code>m/48'/0'/0'/2'</code>.
To add new script types submit a PR to this specification and include it in the list above:
<code>X'</code>: Future script type <code>m/48'/0'/0'/X'</code></br>
===Change===
Constant 0 is used for external chain and constant 1 for internal chain (also
@ -140,13 +145,6 @@ Public derivation is used at this level.
|-
|mainnet
|first
|p2sh-p2wsh
|external
|first
|m / 48' / 0' / 0' / 1' / 0 / 0
|-
|mainnet
|first
|p2wsh
|external
|first

View File

@ -2,12 +2,12 @@
BIP: 49
Layer: Applications
Title: Derivation scheme for P2WPKH-nested-in-P2SH based accounts
Authors: Daniel Weigl <DanielWeigl@gmx.at>
Author: Daniel Weigl <DanielWeigl@gmx.at>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0049
Status: Deployed
Type: Specification
Assigned: 2016-05-19
Status: Final
Type: Informational
Created: 2016-05-19
License: PD
</pre>
@ -92,10 +92,10 @@ This BIP is not backwards compatible by design as described under [[#considerati
// Account 0, first receiving private key = m/49'/1'/0'/0/0
account0recvPrivateKey = cULrpoZGXiuC19Uhvykx7NugygA3k86b3hmdCeyvHYQZSxojGyXJ
account0recvPrivateKeyHex = 0xc9bdb49cfbaedca21c4b1f3a7803c34636b1d7dc55a717132443fc3f4c5867e8
account0recvPublicKeyHex = 0x03a1af804ac108a8a51782198c2d034b28bf90c8803f5a53f76276fa69a4eae77f
account0recvPublickKeyHex = 0x03a1af804ac108a8a51782198c2d034b28bf90c8803f5a53f76276fa69a4eae77f
// Address derivation
keyhash = HASH160(account0recvPublicKeyHex) = 0x38971f73930f6c141d977ac4fd4a727c854935b3
keyhash = HASH160(account0recvPublickKeyHex) = 0x38971f73930f6c141d977ac4fd4a727c854935b3
scriptSig = <0 <keyhash>> = 0x001438971f73930f6c141d977ac4fd4a727c854935b3
addressBytes = HASH160(scriptSig) = 0x336caa13e08b96080a32b5d818d59b4ab3b36742

View File

@ -1,10 +1,12 @@
<pre>
BIP: 50
Title: March 2013 Chain Fork Post-Mortem
Authors: Gavin Andresen <gavinandresen@gmail.com>
Status: Deployed
Author: Gavin Andresen <gavinandresen@gmail.com>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0050
Status: Final
Type: Informational
Assigned: 2013-03-20
Created: 2013-03-20
License: PD
</pre>

View File

@ -2,12 +2,15 @@
BIP: 52
Layer: Consensus (hard fork)
Title: Durable, Low Energy Bitcoin PoW
Authors: Michael Dubrovsky <mike+bip@powx.org>
Bogdan Penkovsky <bogdan+bip@powx.org>
Status: Closed
Type: Specification
Assigned: 2021-05-13
License: BSD-2-Clause OR OPUBL-1.0
Author: Michael Dubrovsky <mike+bip@powx.org>
Bogdan Penkovsky <bogdan+bip@powx.org>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0052
Status: Draft
Type: Standards Track
Created: 2021-05-13
License: BSD-2-Clause
OPL
</pre>
@ -22,7 +25,7 @@ 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.
environmental impact.
<img src="bip-0052/btc_energy-small.png"></img>
@ -115,7 +118,7 @@ The HeavyHash is performed in three stages:
# Keccak hash
# Matrix-vector multiplication
# Keccak of the result xored with the hashed input
# 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
@ -134,7 +137,7 @@ x1 <- keccak(input)
x2 <- reshape(x1, 64)
// Perform a matrix-vector multiplication.
// The result is 64-vector of 14-bit unsigned.
// The result is 64-vector of 14-bit unsigned.
x3 <- vector_matrix_mult(x2, M)
// Truncate all values to 4 most significant bits.
@ -284,15 +287,13 @@ With significant progress in optical and analog matrix-vector-multiplication chi
PoWx will also be publishing the designs of the current optical miner prototypes in the near term under an open-source hardware license.
== Changelog ==
* 2026-06-18:
** Updated to Closed after the proposal has not made progress for several years and [https://groups.google.com/g/bitcoindev/c/Vrh7oED9b9Q/m/TrCEKRjNAAAJ attempts to contact the authors] did not succeed.
== 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

View File

@ -1,159 +0,0 @@
<pre>
BIP: 53
Layer: Consensus (soft fork)
Title: Disallow 64-byte transactions
Authors: Chris Stewart <stewart.chris1234@gmail.com>
Status: Draft
Type: Specification
Assigned: 2025-04-11
License: BSD-3-Clause
</pre>
==Abstract==
This BIP describes the rationale for disallowing transactions that are serialized to 64 bytes without the transaction's witness.
We describe the weaknesses to the Merkle tree included in Bitcoin block headers, and various exploits for those weaknesses.
==Specification==
This BIP disallows Bitcoin transactions that are serialized to 64 bytes in length without their witness.
==Motivation==
Bitcoin block headers include a commitment to the set of transactions in a given
block, which is implemented by constructing a Merkle tree of transaction ids
(double-SHA256 hash of a transaction) and including the root of the tree in the
block header. This in turn allows for proving to a Bitcoin light client that a
given transaction is in a given block by providing a path through the tree to the
transaction. However, Bitcoins particular construction of the Merkle tree has
several security weaknesses, including at least two forms of block malleability
that have an impact on the consensus logic of Bitcoin Core, and an attack on
light clients, where an invalid transaction could be ”proven” to appear in a block
by doing substantially less work than a SHA256 hash collision would require.
This has been mitigated by Bitcoin Core's relay policy and the RPC interface since 2018<ref>[https://github.com/bitcoin/bitcoin/pull/11423/commits/7485488e907e236133a016ba7064c89bf9ab6da3 PR #11423 disallows transactions that are less than 82 bytes in size from Bitcoin Core relay and RPC interface]</ref><ref>[https://github.com/bitcoin/bitcoin/commit/8c5b3646b5afe8a61f5c66478d8e11f0d2ce5108 Reduces the minimum transaction size required for a transaction to be considered standard from 82 bytes to 65 bytes]</ref>.
=== Block malleability ===
64-byte transactions introduce block malleability. Malicious peers can construct consensus valid and invalid 64-byte
transactions that have the same serialization as the concatenation of 2 hashes in the Merkle tree.
Assume we have a valid Bitcoin block with 2 transactions in it with Txid<sub>0</sub> and Txid<sub>1</sub>.
The Merkle root for this block is H(Txid<sub>0</sub>||Txid<sub>1</sub>).
A malicious user could find a 64-byte transaction T<sub>m</sub> that serializes to Txid<sub>0</sub>||Txid<sub>1</sub>.
Next that user relays the block containing the malicious T<sub>m</sub> rather than the
valid Bitcoin transactions that correspond to Txid<sub>0</sub> and Txid<sub>1</sub>.
==== Block malleability with consensus INVALID transactions ====
The peer receiving the malicious block marks the block as invalid, as T<sub>m</sub>
is not a valid transaction according to network consensus rules.
Other peers on the network receive the valid block containing T<sub>0</sub> and T<sub>1</sub>
and add the block to their blockchain. Peers that receive the invalid block before the valid block
will never come to consensus with their peers due to the malicious user finding a collision
within the block's Merkle root. Finding this collision is approximately 22 bits worth of work.<ref>[[bip-0053/2-BitcoinMerkle.pdf|to produce a block having a Merkle root that
is a hash of a 64-byte quantity that deserializes validly, its enough
to just do 8 bits of work to find a workable coinbase (which will hash to the first
32 bytes), plus another ≈22 bits of work ((1/5) 224, so slightly less) to find
a workable second transaction that will hash to the second 32 bytes) a very
small amount of computation.]]</ref>
This attack vector was fixed in Bitcoin Core 0.6.2<ref>[https://bitcoin.org/en/alert/2012-05-14-dos#risks CVE-2012-2459]</ref>, re-introduced in 0.13.x<ref>[https://github.com/bitcoin/bitcoin/pull/7225 #7225]</ref> and patched again in
0.14<ref>[https://github.com/bitcoin/bitcoin/pull/9765 #9765]</ref>.
==== Block malleability with consensus VALID transactions ====
Producing a valid Bitcoin transaction T<sub>m</sub> that adheres to network consensus
rules requires 224 bits of work<ref>[[bip-0053/2-BitcoinMerkle.pdf|Note that the first transaction in a block must be a coinbase, and as discussed
above, that largely constrains the first 32 bytes of the first transaction: only
the 4 version bytes are unconstrained. So it would take at least 28*8= 224 bits
of work to find the first node in a given row of the tree that would match the
first half of a coinbase, in addition to the amount of work required to grind the
second half of the transaction to something meaningful (which is much easier
only 16 bytes or so are constrained, so approximately 128 bits of work to find a collision). Of course, any of the rows in the Merkle tree could be used, but it nevertheless seems clear that this should be computationally infeasible.]]</ref>.
This is computationally and financially expensive but theoretically possible. This can lead to a persistent chain split on the network.
=== Attack on SPV clients ===
BIP37<ref>[https://github.com/bitcoin/bips/blob/master/bip-0037.mediawiki BIP37]</ref>provides a partial Merkle tree format<ref>[https://github.com/bitcoin/bips/blob/master/bip-0037.mediawiki#partial-merkle-branch-format Partial Merkle Tree Format]</ref>
that allows you to verify that your Bitcoin transaction is included in a Merkle root embedded in a Bitcoin block header.
Notably this format does not commit to the height of the Merkle tree.
Suppose a (valid) 64-byte transaction T is included in a block with the property that the second 32 bytes (which
are less constrained than the first 32 bytes) are constructed so that they collide
with the hash of some other fake, invalid transaction F. The attacker can fool the SPV client into believing that F
was included in a Bitcoin block rather than T with 81 bits<ref>[[bip-0053/2-BitcoinMerkle.pdf|An attacker who can do 81 bits of work (followed by another 40 bits of work, to
construct the funding transaction whose coins will be spent by this one) is able
to fool an SPV client in this way.]]</ref> of work. Disallowing 64-byte transactions reduces implementation complexity for SPV wallets<ref>[https://delvingbitcoin.org/t/great-consensus-cleanup-revival/710/43 The steps needed to make sure a Merkle proof for a 64-byte transaction is secure.]</ref>.
==Rationale==
===SPV clients===
Attacks on SPV clients could be mitigated by knowing the depth of the Merkle tree. Requiring SPV clients to request both the coinbase and payment transaction could mitigate this attack.
To produce a valid coinbase transaction at the same depth that our fake transaction F occurs at would require 224 bits of work.
As mentioned above, this is computationally and financially expensive, but theoretically possible. This design would increase the size
of SPV proofs by 70%.<ref>[https://delvingbitcoin.org/t/great-consensus-cleanup-revival/710/29 Base proof: 80-byte header + 448-byte partial Merkle tree = 528 bytes. Proof with coinbase tx, assuming the coinbase tx is in the left half of the tree and the tx to prove is in the right half of the tree: 80-byte header + 416 bytes partial Merkle tree for coinbase tx + 416 bytes partial Merkle tree for tx = 912 bytes.]</ref>
==Backward compatibility==
There have been 5 64-byte transactions that have occurred in the Bitcoin blockchain as of this
writing <ref>[[bip-0053/64byte-tx-mainnet.txt|64-byte transactions in the Bitcoin blockchain]]</ref>
with the last transaction 7f2efc6546011ad3227b2da678be0d30c7f4b08e2ce57b5edadd437f9e27a612<ref>[https://mempool.space/tx/7f2efc6546011ad3227b2da678be0d30c7f4b08e2ce57b5edadd437f9e27a612 Last 64-byte transaction in the Bitcoin blockchain]</ref>
occurring at block height 419,606<ref>[https://mempool.space/block/000000000000000000308f1efc24419f34a3bafcc2b53c32dd57e4502865fd84 Block 419,606]</ref>.
====Pre-segwit 64-byte transactions====
Pre-segwit 64-byte transactions cannot spend a UTXO protected by a digital signature.<ref>[https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki After BIP66 was activated on the Bitcoin network, Bitcoin transactions cannot have a digital signature smaller than 9 bytes.]</ref>
The largest scriptSig a pre-segwit 64-byte transaction can have is 4 bytes.<ref>[https://delvingbitcoin.org/t/great-consensus-cleanup-revival/710/73]</ref>
There are 6<ref>[[bip-0053/non-standard-hashlock-utxos.txt|As of block `00000000000000000001194ae6be942619bf61aa70822b9643d01c1a441bf2b7` there exist 6 non-standard hashlock UTXOs that could theoretically have a 0-3 byte pre-image. None of them have a 0-3 byte pre-image.]]</ref>
non standard hashlock UTXOs in the Bitcoin blockchain. None of them have a 0-3 byte pre-image. This means they cannot be spent by a 64-byte transaction.
Pre-segwit 64-byte transactions that spend a non-standard UTXO that are inherently malleable.<ref>[https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#trust-free-unconfirmed-transaction-dependency-chain Details on how to malleate a pre-segwit transaction]</ref>
Policy rules such as CLEANSTACK, MINIMALDATA, PUSHONLY are not consensus rules. If a user has a way to confirm an already non-standard
64-byte transaction - they can malleate the transaction by violating policy rules to change the size of the transaction to a size other than 64 bytes.
====Segwit 64-byte transactions====
This BIP disallows single-input single-output segwit transactions that pay to a 2-byte witness program.<ref>[https://delvingbitcoin.org/t/great-consensus-cleanup-revival/710/73#p-4382-future-segwit-versions-10 BIP141 says witness programs can be 2 bytes in size, which makes the scriptPubKey a total of 4 bytes]</ref>
The only known use case<ref>[https://bitcoin.stackexchange.com/a/110664 Why do we have 2-byte witness programs? The original rationale for the lower end of the range of valid witness program lengths is that 2 bytes is enough to guarantee no ambiguity of how the program would be pushed (some 1-byte values can - and according to standardness, must - be pushed with OP_n, and dealing with those would have complicated the matter).]</ref>
for this type of transaction is ephemeral anchor outputs.<ref>[https://bitcoinops.org/en/topics/ephemeral-anchors/ What are ephemeral anchor outputs? This allows anyone on the network to use that output as the input to a child transaction. This allows anyone to create the fee-paying child, even if they dont receive any of the other outputs from the parent transaction. This allows ephemeral anchors to function as fee sponsorship but without requiring any consensus changes.]</ref>
==Reference implementation==
<source lang="cpp">
/**
* We want to enforce certain rules (specifically the 64-byte transaction check)
* before we call CheckBlock to check the Merkle root. This allows us to enforce
* malleability checks which may interact with other CheckBlock checks.
* This is currently called both in AcceptBlock prior to writing the block to
* disk and in ConnectBlock.
* Note that as this function is called before merkle-tree checks, it must never return a
* non-malleable error condition.
*/
static bool ContextualBlockPreCheck(const CBlock& block, BlockValidationState& state, const ChainstateManager& chainman, const CBlockIndex* pindexPrev)
{
if (DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_64BYTETX)) {
for (const auto& tx : block.vtx) {
if (::GetSerializeSize(TX_NO_WITNESS(tx)) == 64) {
return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "64-byte-transaction", strprintf("size of tx %s without witness is 64 bytes", tx->GetHash().ToString()));
}
}
}
return true;
}
</source>
The sample implementation is currently open here:
https://github.com/bitcoin-inquisition/bitcoin/pull/24/files
<references />
==Copyright==
This BIP is licensed under the [https://opensource.org/license/BSD-3-Clause BSD-3-Clause License].
==Acknowledgements==
Suhas Daftuar, AJ Towns, Sergio Demian Lerner, Greg Maxwell, Matt Corallo, Antoine Poinsot, Dave Harding and Eric Voskuil

Binary file not shown.

View File

@ -1,5 +0,0 @@
892f44a49de6f5b212cdbea514d09e692d9fed5d897f37bcef14bd0eedebf193
bbf71454857438c6dfd64c0d92a7c5360a8d8d57c9202f5806449e5b0d26b848
6713d61a83e3d095582211ea8d6db452ac7561e863decba7c4046fb9f6d88aa0
7f2efc6546011ad3227b2da678be0d30c7f4b08e2ce57b5edadd437f9e27a612
5302e01dc4b7e34314a34c7c3347107e612b9524be684d388cd4d2ca35ff1ec9

View File

@ -1,6 +0,0 @@
af32bb06f12f2ae5fdb7face7cd272be67c923e86b7a66a76ded02d954c2f94d:0
faf8989ed87c5a667a1ead813aea718727e01767c124193297eaf409ff4645e5:1
c4b46c5d88327d7af6254820562327c5f11b6ee5449da04b7cfd3710b48b6f55:0
702c36851ed202495c2bec1dd0cefb448b50fafd3a5cdd5058c18ca53fc2c3d1:0
6f8a70aac37786b1f619d40250b8bca1a1f6da487146a7e81091f611068a23ef:0
fb01987b540ec286973aac248fab643de82813af452d958056fee8de9f4535ab:0

View File

@ -1,266 +0,0 @@
```
BIP: 54
Layer: Consensus (soft fork)
Title: Consensus Cleanup
Authors: Antoine Poinsot <mail@antoinep.com>
Matt Corallo <bips@bluematt.me>
Status: Complete
Type: Specification
Assigned: 2025-04-11
License: CC0-1.0
```
## Abstract
This document proposes new consensus rules in order to fix the timewarp attack, reduce the worst
case block validation time, prevent Merkle tree weaknesses, and avoid duplicate transactions without
[bip-0030][BIP30] validation.
## Motivation
This proposal addresses a number of long-standing vulnerabilities and weaknesses in the Bitcoin
protocol. Bundling these fixes together amortizes the fixed cost of deploying a Bitcoin soft fork.
The [timewarp bug][SE timewarp] makes it possible for a majority-hashrate attacker to arbitrarily
lower mining difficulty, and therefore arbitrarily increase the block rate. In the worst case, an
attacker can bring down the difficulty to its minimum within 38 days of starting the attack. Besides
empowering a 51% attacker, the presence of this bug makes it harder to reason about miners'
incentives. Accelerating the block rate allows an attacker to steal block subsidy from future
miners and increases available block space. It may be in the interest of short-sighted users and
miners to exploit this vulnerability to materially increase the block rate without fatally hurting
the network.
Specially crafted blocks may be expensive to process, [taking up to][Delving worst block] several
minutes to validate even on high-end devices, and up to a few hours on lower-end devices. Long block
validation times are a nuisance to users, increasing the cost to independently fully validate the
consensus rules. In addition they can be used by miners to attack their competition, creating
perverse incentives, centralization pressures and leading to reduced network security.
In computing a block's Merkle root, a transaction with exactly 64 bytes of non-witness data can be
interpreted both as an intermediate node in the tree and as a leaf in the tree. This makes it
possible to trick an SPV verifier into accepting an inclusion proof for a transaction that is not
part of a block, by pretending a 64-byte block transaction is actually an inner node[^9]. Invalidating
64-byte transactions addresses this vulnerability without requiring users of SPV verifiers, or
any other user of Merkle proofs, to rely on one of the available workarounds[^13] or even to know one is
necessary in the first place.
Since [bip-0034][BIP34] activation, explicit [bip-0030][BIP30] validation is not necessary until
block height 1,983,702[^0]. Resuming [bip-0030][BIP30] validation would unnecessarily increase block
validation overhead and preclude alternative full node designs (such as [bip-0182][BIP182] Utreexo).
Enforcing that new coinbase transactions are different from the early [bip-0034][BIP34] violations
makes it possible to get rid of [bip-0030][BIP30] validation forever.
## Specification
For all blocks after activation the following new rules apply.
Given a block at height `N`:
- if `N % 2016` is equal to 0, the timestamp of the block must be set to a value higher than or
equal to the value of the timestamp of block at height `N-1` minus 7200 (T<sub>N</sub> &ge;
T<sub>N1</sub> 7200);
- if `N % 2016` is equal to 2015, the timestamp of the block must be set to a value higher than
or equal to the value of the timestamp of the block at height `N-2015` (T<sub>N</sub> &ge;
T<sub>N2015</sub>).
A limit is set on the number of signature operations present in the scripts used to validate a
transaction. It applies to all transactions in the block except the coinbase transaction[^1]. For
each input in the transaction, count the number of `CHECKSIG` and `CHECKMULTISIG` in the input
scriptSig and previous output's scriptPubKey, including the P2SH redeemScript. If the total summed
over all transaction inputs is strictly higher than 2500, the transaction is invalid. The accounting is the
same as for [bip-0016][BIP16 specs], evaluating the scriptSig, scriptPubKey, and P2SH redeemScript
separately:
1. `CHECKSIG` and `CHECKSIGVERIFY` count as 1 signature operation, whether or not they are evaluated.
2. `CHECKMULTISIG` and `CHECKMULTISIGVERIFY` immediately preceded by `OP_1` through `OP_16` are counted as 1 to 16 signature operations, whether or not they are evaluated.
3. All other `CHECKMULTISIG` and `CHECKMULTISIGVERIFY` are counted as 20 signature operations, whether or not they are evaluated.
Transactions whose witness-stripped serialized size is exactly 64 bytes are invalid.
The coinbase transaction's `nLockTime` field must be set to the height of the block minus 1[^2]
and its `nSequence` field must not be equal to 0xffffffff.
## Rationale
The restrictions on the timestamp of the first and last blocks of a difficulty adjustment period fix
the timewarp and MurchZawy vulnerabilities[^3]. The latter poses mostly theoretical concerns but is
extremely low risk to fix: the duration of an adjustment period has never been, and should never be,
negative. The former is fixed by preventing the timestamp of the first block of a difficulty period
from being lower than the previous block's, with a two-hour grace period. A [previous
proposal][BIP-XXXX] to fix the timewarp attack used a ten-minute grace period instead, and this
approach has been adopted for [testnet4][BIP94 timewarp]. Out of an abundance of caution and because it only trivially worsens the
block rate increase under attack, a two-hour grace period is used here[^4].
Disabling some Script operations and functionalities was [previously proposed][BIP-XXXX] to reduce
the worst case block validation time but was met with resistance due to confiscation concerns[^5]. A
delicate balance needs to be struck between minimizing the confiscation risks of a mitigation, even
if merely theoretical, and bounding the costs one could impose on all other users of the system. To
that end, limiting potentially executed signature operations targets the exact harmful behaviour while
preserving maximal flexibility in Script usage.
Such a limit reduces the worst case block validation time by a factor of 40 and drastically
increases the preparation cost of an attack, making it uneconomical for a miner[^6]. The maximum of
2500 was chosen as the tightest value that did not make any non-pathological standard transaction
invalid[^7].
64-byte transactions can only contain a scriptPubKey that lets anyone spend the funds, or one that
burns them. They have also been non-standard since 2019 and never been used since 2016. Several
alternatives to invalidating them were previously proposed. Some believe the improvements for users
of Merkle proofs are too marginal to be worth introducing a discontinuity in the set of valid
witness-stripped transaction sizes. Others have suggested instead committing to the Merkle
tree depth in the header's version field[^8], which would make one workaround for a known
vulnerability easier to deploy. The authors believe it is preferable to address the root cause by
invalidating 64-byte transactions, fixing the vulnerability without Merkle proof users having to
rely on any workaround or even know one is necessary in the first place. See [this post][64 bytes
debate] for an attempt at summarizing the arguments for both sides of this debate.
The `nLockTime` field of transactions is a natural place to store a block height and is currently
unused in coinbase transactions. Using it to enforce that new coinbase transactions differ from
early [bip-0034][BIP34] violations also allows applications to recover the block height without
having to parse Script. Leveraging the existing timelock mechanism makes the check self-contained:
the same coinbase transaction cannot have been valid in a previous block[^11]. This simplifies both
reasoning and client implementation, since the [bip-0030][BIP30] check can be skipped entirely past
Consensus Cleanup activation, regardless of the [bip-0034][BIP34] activation status[^12]. One person
[raised the concern][miningdev nLockTime] that the `nLockTime` field would be an ideal extranonce
for ASIC controllers if such controllers ever became a bottleneck in mining operations. Others
[replied][miningdev nLockTime] that the same benefits could be achieved by using a dummy output
instead, should that ever become necessary. The authors [believe][ML remaining concerns] the
benefits of using `nLockTime` to differentiate coinbase transactions outweigh the theoretical
cost of making it unavailable for extranonce rolling by ASIC controllers.
## Backward compatibility
This proposal only tightens the block validation rules: there is no block that is valid under the
rules proposed in this BIP but not under the existing Bitcoin consensus rules. As a consequence
these changes are backward-compatible with non-upgraded node software. That said, the authors
strongly encourage node operators to upgrade in order to fully validate all consensus rules.
## Miner forward compatibility
Bitcoin Core version [29.0][Core 29.0] and later will not generate a block template that violates
the timestamp restrictions introduced in this BIP. Although it would be extremely unlikely due to
the grace period used in this proposal, miners should use the `curtime` or `mintime` field from the
`getblocktemplate` result for their block's timestamp to make sure they always create blocks valid
according to this proposal. Note this is not a new requirement: using a timestamp lower than the
`mintime` field from the `getblocktemplate` result already leads to creating an invalid block.
Bitcoin Core version [30.0][Core 30.0] and later will not generate a block template including a
transaction that violates the signature operations limit introduced in this BIP.
Bitcoin Core version [0.16.1][Core 0.16.1] and later will neither relay nor create block templates
that include transactions whose witness-stripped serialized size is exactly 64 bytes.
The coinbase transaction is usually crafted by mining pool software. To the best of the authors'
knowledge, there does not exist an open source reference broadly in use today for such software.
We encourage mining pools to update their software to craft coinbase transactions that are
forward-compatible with the changes proposed in this BIP.
## Reference implementation
An implementation of BIP54 for Bitcoin Core is available [here][Core BIP 54 implem].
## Test vectors
Documented test vectors are available [here](./bip-0054/test_vectors/) for all mitigations
introduced in this BIP.
## Acknowledgements
This document builds upon an [earlier proposal][BIP-XXXX] by Matt Corallo.
The authors would like to thank everyone involved in researching the most appropriate mitigation for
each of these bugs. We would like to thank in particular Anthony Towns and Sjors Provoost for their
direct contributions to this proposal, as well as @0xb10c and Brian Groll for providing the authors
with data to analyze the proposed mitigations. Thanks to Chris Stewart for digging up historical
violations to the new transaction size rule, which are partially reused in this BIP's test vectors.
## Copyright
This document is licensed under the Creative Commons CC0 1.0 Universal license.
## Changelog
* __1.0.0__ (2026-05-22):
* Complete planned work on the BIP.
[^0]: Block 1,983,702 is the earliest future block which could contain a duplicate coinbase
transaction while still respecting [bip-0034][BIP34]. See [this post][Delving duplicable] for a list
of all such future blocks.
[^1]: Technically this limit *cannot* apply to a coinbase transaction as the size of its sole
input's scriptSig is limited.
[^2]: The locktime validation, which is also performed for coinbase transactions, enforces that the
nLockTime value is the last block at which a transaction is invalid, not the first one at which it
is valid.
[^3]: The timewarp attack is described [here][SE timewarp] and the MurchZawy attack [here][Delving
Murch-Zawy].
[^4]: The testnet4 difficulty exception pushed blocks' timestamps in the future when abused,
revealing how some broken pool software may produce blocks that don't respect a 10 minutes grace
period. Some [raised concerns][Sjors grace period] similarly broken software might be used on
mainnet. Using a grace period of 2 hours instead of 10 minutes only reduces the expected block
interval time under attack by ~2.2 seconds. See [this post][grace period debate summary] for more.
[^5]: The argument is about someone having a timelocked presigned transaction using some of those
features in its output script. The transaction cannot be mined before activation. Such outputs would
not be covered by an amnesty for old UTxOs. See for instance [here][O'Connor OP_CODESEPARATOR] and
[here][O'Connor sighash type] for discussions on this topic.
[^6]: It is important to reduce the worst case block validation time as well as the ratio of
validation time imposed over preparation cost. The former is to limit the damages an externally
motivated attacker can do. The latter is to disincentivize miners slowing down their competition by
mining expensive blocks. See [this thread][ML thread validation time] for more.
[^7]: A non-pathological transaction would have a public key per signature operation and at least
one signature per input. Per standardness a single P2SH input may not have more than 15 signature
operations. Even by using 1-of-15 `CHECKMULTISIG`s a transaction would bump against the maximum
standard transaction size before running into the newly introduced limit. To run against the newly
introduced limit but not the transaction size a transaction would need to spend P2SH inputs with a
redeem script similar to `CHECKSIG DROP CHECKSIG DROP ...`. This type of redeem script serves no
purpose beyond increasing its validation cost, which is exactly what this proposal aims to mitigate.
[^8]: By Sergio Demian Lerner in a [blog post][Sergio post].
[^9]: Conversely, pretending that the inner nodes on one level of the tree are the actual block
transactions is another source of complexity for full node implementations, which previously
resulted in consensus bugs. For instance, Bitcoin Core versions between 0.13.0 and 0.13.2
implemented caching that made it vulnerable to this attack. See [this writeup][Suhas Merkle] by
Suhas Daftuar for a detailed explanation. Invalidating 64-byte transactions may avoid this risk, but
the issue is largely orthogonal to this proposal: it is fundamentally about caching validation
status for malleable blocks.
[^11]: Technically it could be argued a duplicate could in principle always be possible before block
31,001 when `nLockTime` enforcement [was originally soft-forked][Harding nLockTime]. But treating
coinbase transactions as not having duplicate past Consensus Cleanup activation would be consistent
for any implementation which enforces `nLockTime` from the genesis block, which is the behaviour
notably of Bitcoin Core but also of all other implementations the authors are aware of.
[^12]: For instance Bitcoin Core only disables [bip-0030][BIP30] validation for a specific chain
where [bip-0034][BIP34] violations have been manually inspected (see [here][Core validation.cpp
BIP34]). Without the guarantee given by enforcing the timelock on coinbase transactions, this would
have to be perpetuated for the Consensus Cleanup.
[^13]: The authors are aware of three workarounds for SPV verifiers. The first is to request a
Merkle proof for the coinbase transaction in addition to the transaction of interest, to infer the
depth of the Merkle tree. The second is to reject Merkle proofs in which any inner node is also a
valid serialisation of a Bitcoin transaction. More details about these are available [here][Sergio
post]. A third workaround is to change the Merkle proof structure by requiring inner nodes to be
provided as the single-SHA256 of their preimage, instead of the double-SHA256. See [here][Sergio
MERKLEBLOCK] for a full description.
[Delving worst block]: https://delvingbitcoin.org/t/great-consensus-cleanup-revival/710/93
[BIP30]: https://github.com/bitcoin/bips/blob/master/bip-0030.mediawiki
[BIP182]: https://github.com/bitcoin/bips/pull/1923
[BIP-XXXX]: https://github.com/TheBlueMatt/bips/blob/7f9670b643b7c943a0cc6d2197d3eabe661050c2/bip-XXXX.mediawiki
[BIP34]: https://github.com/bitcoin/bips/blob/master/bip-0034.mediawiki
[BIP16 specs]: https://github.com/bitcoin/bips/blob/master/bip-0016.mediawiki#specification
[SE timewarp]: https://bitcoin.stackexchange.com/questions/75831/what-is-time-warp-attack-and-how-does-it-work-in-general/75834#75834
[Delving Murch-Zawy]: https://delvingbitcoin.org/t/zawy-s-alternating-timestamp-attack/1062#variant-on-zawys-attack-2
[BIP94 timewarp]: https://github.com/bitcoin/bips/blob/master/bip-0094.mediawiki#time-warp-fix
[Sjors grace period]: https://delvingbitcoin.org/t/timewarp-attack-600-second-grace-period/1326
[grace period debate summary]: https://delvingbitcoin.org/t/great-consensus-cleanup-revival/710/66
[O'Connor OP_CODESEPARATOR]: https://gnusha.org/pi/bitcoindev/CAMZUoKneArC+YZ36YFwxNTKsDtJhEz5P2cosXKxJS8Rf_3Nyuw@mail.gmail.com
[O'Connor sighash type]: https://gnusha.org/pi/bitcoindev/CAMZUoK=1kgZLR1YZ+cJgzwmEOwrABYFs=2Ri=xGX=BCr+w=VQw@mail.gmail.com
[ML thread validation time]: https://gnusha.org/pi/bitcoindev/VsltJ2PHqWfzG4BU9YETTXjL7fYBbJhjVXKZQyItemySIA1okvNee9kf0zAOyLMeJ4Nqv1VOrYbWns5nP4TANCWvPJYu1ew_yxQSaudizzk=@protonmail.com
[Suhas Merkle]: https://gnusha.org/pi/bitcoindev/CAFp6fsGtEm9p-ZQF_XqfqyQGzZK7BS2SNp2z680QBsJiFDraEA@mail.gmail.com
[Sergio post]: https://bitslog.com/2018/06/09/leaf-node-weakness-in-bitcoin-merkle-tree-design
[Sergio MERKLEBLOCK]: https://bitslog.com/2018/08/21/simple-change-to-the-bitcoin-merkleblock-command-to-protect-from-leaf-node-weakness-in-transaction-merkle-tree/
[64 bytes debate]: https://delvingbitcoin.org/t/great-consensus-cleanup-revival/710/41
[Harding nLockTime]: https://bitcoin.stackexchange.com/questions/90229/nlocktime-in-bitcoin-core
[Delving duplicable]: https://delvingbitcoin.org/t/great-consensus-cleanup-revival/710/4
[Core 0.16.1]: https://bitcoincore.org/en/releases/0.16.1
[Core 29.0]: https://bitcoincore.org/en/releases/29.0
[Core BIP 54 implem]: https://github.com/darosior/bitcoin/tree/bip54
[Core 30.0]: https://bitcoincore.org/en/releases/30.0
[Core validation.cpp BIP34]: https://github.com/bitcoin/bitcoin/blob/390e7d61bd531505bb3d13f38316c282b85ed1dd/src/validation.cpp#L2401-L2459
[miningdev nLockTime]: https://groups.google.com/g/bitcoinminingdev/c/jlqlNHHNSNk
[ML remaining concerns]: https://gnusha.org/pi/bitcoindev/UsKuvCXXhSAnNVx5a0K2UfP3srAr3slW9mcOjtYk9LnolaOXfWrW9jpqbxsQQPkyQuZogkhz2Hbfwii2VsTm79vRDpgKduxk35hpBu_t7Do=@protonmail.com/

View File

@ -1,102 +0,0 @@
## BIP54 test vectors
This folder contains a set of test vectors for each mitigation introduced in the BIP. This document
presents them in more detail.
The code used to generate half of the test vectors is included with the implementation and available
[here][other-vectors]. The other half requires mining mainnet blocks and is [published
separately][bip54-miner]. In both cases it is implemented as a regular Bitcoin Core unit test, and
the test vectors are persisted as a JSON file if the `UPDATE_JSON_TESTS` preprocessor directive is
set (off by default).
To compile the [header][header-miner] and [block][block-miner] miners you may have to link to
libatomic explicitly. This can be achieved like so:
```
cmake -B atomicbuild -DAPPEND_LDFLAGS="-latomic"
cmake --build atomicbuild/ -j $(nproc)
```
[Premined headers][premined-headers] are also provided along with the header miner to allow changing
some of the last headers without having to re-generate the whole chain.
### Difficulty adjustment exploits
The [`timestamps.json`](./timestamps.json) test vectors exercise the two constraints on block header
timestamps introduced by BIP54 to mitigate the Timewarp and Murch-Zawy attacks. Each test case
features a chain of mainnet headers starting from the genesis block, and whether this header chain
is valid by BIP54 rules. Each test case also contains a comment describing why this particular chain
is (in)valid according to BIP54. All test cases are valid according to current Bitcoin consensus
rules. It is intended to be used to test a BIP54 implementation by feeding the header chain to a
Bitcoin node implementation, enforcing the BIP54 rules on this chain from genesis.
The test vector file features a JSON array of JSON objects, each corresponding to a test case. Each
JSON object features the following entries:
- `header_chain`: a JSON array of strings. An ordered list of hex-encoded mainnet block headers.
- `valid`: a JSON boolean. Whether this chain of headers is valid according to BIP54.
- `comment`: a JSON string. Description of the test case.
For the purpose of testing a Timewarp fix, a Timewarp attack was included early on in the history of
testnet3. An implementer of BIP54 may want to ensure that syncing testnet3 by enforcing BIP54 since
genesis will treat block `00000000118da1e2165a19307b86f87eba814845e8a0f99734dce279ca3fb029` as
invalid.
### Long block validation time
The [`sigops.json`](sigops.json) file contains test vectors for the limit on the number of
potentially-executed legacy signature operations in a single transaction, introduced by BIP54 in
order to mitigate long block validation times. Each test case represents a transaction and whether a
block containing it would be valid according to BIP54. The test cases feature an extensive set of
combinations of inputs and output types, ways to run into the limit, historical violations and some
pathological transactions exhibiting the specific implementation details. All test cases but those
belonging to this last category feature transactions that are valid under current Bitcoin consensus
rules. Each test case also features a comment describing why the transaction is (in)valid according
to BIP54.
The test vector file features a JSON array of JSON objects, each corresponding to a test case. Each
JSON object features the following entries:
- `spent_outputs`: a JSON array of strings. An ordered list of hex-encoded Bitcoin-serialized
transaction outputs spent by each input of this test case's transaction.
- `tx`: a JSON string. A hex-encoded Bitcoin-serialized transaction to be evaluated.
- `valid`: a JSON boolean. Whether this transaction is valid according to current consensus rules
supplemented by BIP54.
- `comment`: a JSON string. Description of the test case.
### Merkle tree malleability with 64-byte transactions
The [`txsize.json`](./txsize.json) file contains test cases exercising the new constraint on
non-witness transaction size introduced in BIP54. Each test case contains a transaction and whether
it would be valid according to BIP54, as well as a comment describing why it is (in)valid. All test
cases are otherwise valid according to current Bitcoin consensus rules.
The test vector file features a JSON array of JSON objects, each corresponding to a test case. Each
JSON object features the following entries:
- `tx`: a JSON string. A hex-encoded Bitcoin-serialized transaction to be evaluated.
- `valid`: a JSON boolean. Whether this transaction is valid according to BIP54.
- `comment`: a JSON string. Description of the test case.
### Possibility of duplicate coinbase transactions
The [`coinbases.json`](./coinbases.json) file contains test cases exercising the new restrictions on
coinbase transactions introduced in BIP54 to prevent duplicate coinbase transactions without
resorting to BIP30 validation. Each test case contains a chain of mainnet blocks (including the
genesis block), and whether this block chain is valid according to BIP54. All test cases are valid
according to current Bitcoin's consensus rules, except one that features a block containing a
coinbase transaction timelocked to a future block height.
The test vector file features a JSON array of JSON objects, each corresponding to a test case. Each
JSON object features the following entries:
- `block_chain`: a JSON array of strings. An ordered list of hex-encoded mainnet blocks.
- `valid`: a JSON boolean. Whether this block chain is valid according to current Bitcoin consensus
rules supplemented by BIP54.
- `comment`: a JSON string. Description of the test case.
[bip54-miner]: https://github.com/darosior/bitcoin/commits/bip54_miner/
[header-miner]: https://github.com/darosior/bitcoin/blob/bip54_miner/src/test/bip54_header_miner.cpp
[block-miner]: https://github.com/darosior/bitcoin/blob/bip54_miner/src/test/bip54_block_miner.cpp
[other-vectors]: https://github.com/darosior/bitcoin/blob/2509_inquisition_consensus_cleanup/src/test/bip54_tests.cpp
[premined-headers]: https://github.com/darosior/bitcoin/blob/bip54_miner/src/test/bip54_premined_headers.h

View File

@ -1,80 +0,0 @@
[
{
"block_chain": [
"0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c0101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4d04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73ffffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000",
"010000006fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d619000000000068fcdbe419c7d12484fd7e1f7cc22c98e4afab982539e2333ca8ce9a317a592f81ad5f49ffff001d846f5e090101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff025100feffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000",
"01000000a58a17b4a4487b9c83ab80ed6a9ccbb9de25925193cc084f41872bd700000000462c6597dd11214ae6f20905dc3828c000a693c3e4b17df82469e528dd9eeab8d9af5f49ffff001dd6bbd40a0101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff05520360ae0afeffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac01000000",
"010000005702226e10bfe0b24a41a05f406c73046b9ad6fca09255968d3a954b00000000d72d147d9b46612e6adb7168821448e3eca3231ffce8c812a1503ab30001e3bd31b25f49ffff001d7b1408060101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff05530320d613feffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac02000000",
"01000000131cda7ce756b84bd95dd3ee07333f2224e286bb9a5e13ed99613746000000003e699c73b70d61674235d749cfcc240c91df1b658ab774fce2779679f6867d4189b45f49ffff001dc1adcf010101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff055403e0c810feffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac15000000"
],
"valid": false,
"comment": "Block at height 4 with coinbase's nLockTime set to 21 and non-final nSequence."
},
{
"block_chain": [
"0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c0101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4d04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73ffffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000",
"010000006fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d619000000000068fcdbe419c7d12484fd7e1f7cc22c98e4afab982539e2333ca8ce9a317a592f81ad5f49ffff001d846f5e090101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff025100feffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000",
"01000000a58a17b4a4487b9c83ab80ed6a9ccbb9de25925193cc084f41872bd700000000462c6597dd11214ae6f20905dc3828c000a693c3e4b17df82469e528dd9eeab8d9af5f49ffff001dd6bbd40a0101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff05520360ae0afeffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac01000000",
"010000005702226e10bfe0b24a41a05f406c73046b9ad6fca09255968d3a954b00000000d72d147d9b46612e6adb7168821448e3eca3231ffce8c812a1503ab30001e3bd31b25f49ffff001d7b1408060101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff05530320d613feffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac02000000",
"01000000131cda7ce756b84bd95dd3ee07333f2224e286bb9a5e13ed996137460000000082cf0907a8dfb0b461f9c3f4a807cff5fb85df8e54fcc5d8b5a6208b1144fac289b45f49ffff001d094390190101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff05540320d613921000000100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac04000000"
],
"valid": false,
"comment": "Block at height 4 with coinbase's nLockTime set to 4 and non-final nSequence."
},
{
"block_chain": [
"0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c0101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4d04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73ffffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000",
"010000006fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d619000000000068fcdbe419c7d12484fd7e1f7cc22c98e4afab982539e2333ca8ce9a317a592f81ad5f49ffff001d846f5e090101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff025100feffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000",
"01000000a58a17b4a4487b9c83ab80ed6a9ccbb9de25925193cc084f41872bd700000000462c6597dd11214ae6f20905dc3828c000a693c3e4b17df82469e528dd9eeab8d9af5f49ffff001dd6bbd40a0101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff05520360ae0afeffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac01000000",
"010000005702226e10bfe0b24a41a05f406c73046b9ad6fca09255968d3a954b00000000d72d147d9b46612e6adb7168821448e3eca3231ffce8c812a1503ab30001e3bd31b25f49ffff001d7b1408060101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff05530320d613feffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac02000000",
"01000000131cda7ce756b84bd95dd3ee07333f2224e286bb9a5e13ed9961374600000000da08acbf43b797bea5a20bb65f0a02871f6272cd0dbd5d192de0b8b241a285aa89b45f49ffff001d5077290a0101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff055403400d03feffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac02000000"
],
"valid": false,
"comment": "Block at height 4 with coinbase's nLockTime set to 2 and non-final nSequence."
},
{
"block_chain": [
"0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c0101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4d04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73ffffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000",
"010000006fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d619000000000068fcdbe419c7d12484fd7e1f7cc22c98e4afab982539e2333ca8ce9a317a592f81ad5f49ffff001d846f5e090101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff025100feffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000",
"01000000a58a17b4a4487b9c83ab80ed6a9ccbb9de25925193cc084f41872bd700000000462c6597dd11214ae6f20905dc3828c000a693c3e4b17df82469e528dd9eeab8d9af5f49ffff001dd6bbd40a0101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff05520360ae0afeffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac01000000",
"010000005702226e10bfe0b24a41a05f406c73046b9ad6fca09255968d3a954b00000000d72d147d9b46612e6adb7168821448e3eca3231ffce8c812a1503ab30001e3bd31b25f49ffff001d7b1408060101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff05530320d613feffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac02000000",
"01000000131cda7ce756b84bd95dd3ee07333f2224e286bb9a5e13ed99613746000000000035fba8f8f05b94463822ffd007213ff095c4b82e5bc166fd51c8ba01e0659189b45f49ffff001d394a4d070101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff025400fb4003000100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac03000000"
],
"valid": true,
"comment": "Block at height 4 with coinbase's nLockTime set to 3 and non-final nSequence."
},
{
"block_chain": [
"0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c0101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4d04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73ffffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000",
"010000006fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d619000000000068fcdbe419c7d12484fd7e1f7cc22c98e4afab982539e2333ca8ce9a317a592f81ad5f49ffff001d846f5e090101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff025100feffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000",
"01000000a58a17b4a4487b9c83ab80ed6a9ccbb9de25925193cc084f41872bd700000000462c6597dd11214ae6f20905dc3828c000a693c3e4b17df82469e528dd9eeab8d9af5f49ffff001dd6bbd40a0101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff05520360ae0afeffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac01000000",
"010000005702226e10bfe0b24a41a05f406c73046b9ad6fca09255968d3a954b00000000d72d147d9b46612e6adb7168821448e3eca3231ffce8c812a1503ab30001e3bd31b25f49ffff001d7b1408060101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff05530320d613feffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac02000000",
"01000000131cda7ce756b84bd95dd3ee07333f2224e286bb9a5e13ed9961374600000000e7822dba53b0868472211017555701e69bbd9c3e2ec5502347dce64e963cff0989b45f49ffff001dfb8e6e110101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff05540360ae0afeffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac03000000"
],
"valid": true,
"comment": "Block at height 4 with coinbase's nLockTime set to 3 and maximum non-final nSequence."
},
{
"block_chain": [
"0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c0101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4d04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73ffffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000",
"010000006fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d619000000000068fcdbe419c7d12484fd7e1f7cc22c98e4afab982539e2333ca8ce9a317a592f81ad5f49ffff001d846f5e090101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff025100feffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000",
"01000000a58a17b4a4487b9c83ab80ed6a9ccbb9de25925193cc084f41872bd700000000462c6597dd11214ae6f20905dc3828c000a693c3e4b17df82469e528dd9eeab8d9af5f49ffff001dd6bbd40a0101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff05520360ae0afeffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac01000000",
"010000005702226e10bfe0b24a41a05f406c73046b9ad6fca09255968d3a954b00000000d72d147d9b46612e6adb7168821448e3eca3231ffce8c812a1503ab30001e3bd31b25f49ffff001d7b1408060101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff05530320d613feffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac02000000",
"01000000131cda7ce756b84bd95dd3ee07333f2224e286bb9a5e13ed9961374600000000a392d0e70a32b369e2ec509ec0b5cdfad3db5f78d594f855588d6193d7e5bef889b45f49ffff001d5ec3630c0101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff05540320d613ffffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac03000000"
],
"valid": false,
"comment": "Block at height 4 with coinbase's nLockTime set to 3 and final nSequence."
},
{
"block_chain": [
"0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c0101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4d04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73ffffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000",
"010000006fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d619000000000068fcdbe419c7d12484fd7e1f7cc22c98e4afab982539e2333ca8ce9a317a592f81ad5f49ffff001d846f5e090101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff025100feffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000",
"01000000a58a17b4a4487b9c83ab80ed6a9ccbb9de25925193cc084f41872bd700000000462c6597dd11214ae6f20905dc3828c000a693c3e4b17df82469e528dd9eeab8d9af5f49ffff001dd6bbd40a0101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff05520360ae0afeffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac01000000",
"010000005702226e10bfe0b24a41a05f406c73046b9ad6fca09255968d3a954b00000000d72d147d9b46612e6adb7168821448e3eca3231ffce8c812a1503ab30001e3bd31b25f49ffff001d7b1408060101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff05530320d613feffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac02000000",
"01000000131cda7ce756b84bd95dd3ee07333f2224e286bb9a5e13ed99613746000000002be83903e9da68744e4da285d3641faf33694531e1717724d415265bc987bfbb89b45f49ffff001dbfe17c1f0101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff05540340420ffeffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac88b45f49"
],
"valid": false,
"comment": "Block at height 4 with coinbase's nLockTime set to block's nTime minus 1 and maximum non-final nSequence."
}
]

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@ -1,67 +0,0 @@
[
{
"comment": "A 63-byte legacy transaction.",
"tx": "0200000001827da3d85a6547d6b03662d2cb86982d655a6f390547285a3bf9ec9f28e0c8831500000000ffffffff0100000000000000000300515200000000",
"valid": true
},
{
"comment": "A 61-byte legacy transaction with a witness.",
"tx": "02000000000101827da3d85a6547d6b03662d2cb86982d655a6f390547285a3bf9ec9f28e0c8831500000000ffffffff01000000000000000000010000000000",
"valid": true
},
{
"comment": "A 64-byte legacy transaction (4 bytes in spk).",
"tx": "0200000001827da3d85a6547d6b03662d2cb86982d655a6f390547285a3bf9ec9f28e0c8831500000000ffffffff010000000000000000040051525400000000",
"valid": false
},
{
"comment": "A 64-byte legacy transaction (4 bytes in scriptsig).",
"tx": "0200000001827da3d85a6547d6b03662d2cb86982d655a6f390547285a3bf9ec9f28e0c883150000000403424242ffffffff010040075af07507000000000000",
"valid": false
},
{
"comment": "A 65-byte legacy transaction.",
"tx": "0200000001827da3d85a6547d6b03662d2cb86982d655a6f390547285a3bf9ec9f28e0c8831500000000ffffffff01000000000000000005005152545800000000",
"valid": true
},
{
"comment": "A 64-byte Segwit transaction.",
"tx": "02000000000101827da3d85a6547d6b03662d2cb86982d655a6f390547285a3bf9ec9f28e0c8831500000000ffffffff01000000000000000004005152540108213245576281941200000000",
"valid": false
},
{
"comment": "A 64-byte Segwit transaction (1 p2tr input, 1 p2a output).",
"tx": "02000000000101827da3d85a6547d6b03662d2cb86982d655a6f390547285a3bf9ec9f28e0c8831500000000ffffffff0100000000000000000451024e7301415a78b5a14a2527feb02c08b8124e74c3b9bcc1bd3dba1fbfa87f1c930f28a46fea2bf375105dfd835e212c9127aad4976c46ef86be02edbb681e6f38f9a9e06f0100000000",
"valid": false
},
{
"comment": "A 64-byte Segwit transaction (1 p2tr input with annex, 1 OP_RETURN output).",
"tx": "02000000000101827da3d85a6547d6b03662d2cb86982d655a6f390547285a3bf9ec9f28e0c8831500000000ffffffff010000000000000000046a02ab0102415a78b5a14a2527feb02c08b8124e74c3b9bcc1bd3dba1fbfa87f1c930f28a46fea2bf375105dfd835e212c9127aad4976c46ef86be02edbb681e6f38f9a9e06f01064242ffab212100000000",
"valid": false
},
{
"comment": "Historical 64-byte transaction 892f44a49de6f5b212cdbea514d09e692d9fed5d897f37bcef14bd0eedebf193",
"tx": "0200000001deb98691723fa71260ffca6ea0a7bc0a63b0a8a366e1b585caad47fb269a2ce401000000030251b201000000010000000000000000016a00000000",
"valid": false
},
{
"comment": "Historical 64-byte transaction bbf71454857438c6dfd64c0d92a7c5360a8d8d57c9202f5806449e5b0d26b848",
"tx": "01000000010d0afe3d74062ee60c0ec55579d691d8c8af5c04eb97b777157a21a8c5fb143d00000000035101b100000000010000000000000000016a01000000",
"valid": false
},
{
"comment": "Historical 64-byte transaction 6713d61a83e3d095582211ea8d6db452ac7561e863decba7c4046fb9f6d88aa0",
"tx": "02000000011658a33df410379bb512206659910c9fbd0e50bfb732f7be9936558ff036919401000000035101b201000000010000000000000000016a00000000",
"valid": false
},
{
"comment": "Historical 64-byte transaction 7f2efc6546011ad3227b2da678be0d30c7f4b08e2ce57b5edadd437f9e27a612",
"tx": "02000000011a7a4cf262fb7e53e2e6e0b2ef8b763f6ee97d8681ca968d1938418d56e6c38700000000035101b201000000010000000000000000016a00000000",
"valid": false
},
{
"comment": "Historical 64-byte transaction 5302e01dc4b7e34314a34c7c3347107e612b9524be684d388cd4d2ca35ff1ec9",
"tx": "01000000019222bbb054bb9f94571dfe769af5866835f2a97e883959fa757de4064bed8bca01000000035101b100000000010000000000000000016a01000000",
"valid": false
}
]

View File

@ -2,12 +2,12 @@
BIP: 60
Layer: Peer Services
Title: Fixed Length "version" Message (Relay-Transactions Field)
Authors: Amir Taaki <genjix@riseup.net>
Author: Amir Taaki <genjix@riseup.net>
Comments-Summary: Discouraged for implementation (one person)
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0060
Status: Closed
Type: Specification
Assigned: 2013-06-16
Status: Draft
Type: Standards Track
Created: 2013-06-16
License: PD
</pre>
@ -23,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 adherence 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 adherance 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 further 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 futher communication is possible until both peers have exchanged their version.
Payload:

View File

@ -2,12 +2,12 @@
BIP: 61
Layer: Peer Services
Title: Reject P2P message
Authors: Gavin Andresen <gavinandresen@gmail.com>
Author: Gavin Andresen <gavinandresen@gmail.com>
Comments-Summary: Controversial; some recommendation, and some discouragement
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0061
Status: Deployed
Type: Specification
Assigned: 2014-06-18
Status: Final
Type: Standards Track
Created: 2014-06-18
</pre>
==Abstract==
@ -57,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 anything besides diagnosing
use different strings. The string should not be shown to users or used for anthing besides diagnosing
interoperability problems.
The following reject code categories are used; in the descriptions below, "server" is the peer generating
@ -149,7 +149,7 @@ The reject message is backwards-compatible; older peers that do not recognize th
== Implementation notes ==
Implementers must consider what happens if an attacker either sends them
Implementors must consider what happens if an attacker either sends them
reject messages for valid transactions/blocks or sends them random
reject messages, and should beware of possible denial-of-service attacks.
For example, notifying the user of every reject message received

View File

@ -4,10 +4,12 @@
BIP: 62
Layer: Consensus (soft fork)
Title: Dealing with malleability
Authors: Pieter Wuille <pieter.wuille@gmail.com>
Status: Closed
Type: Specification
Assigned: 2014-03-12
Author: Pieter Wuille <pieter.wuille@gmail.com>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0062
Status: Withdrawn
Type: Standards Track
Created: 2014-03-12
License: BSD-2-Clause
</pre>
@ -32,7 +34,7 @@ Several sources of malleability are known:
# '''Non-DER encoded ECDSA signatures''' Right now, the Bitcoin reference client uses OpenSSL to validate signatures. As OpenSSL accepts more than serializations that strictly adhere to the DER standard, this is a source of malleability. Since v0.8.0, non-DER signatures are no longer relayed already.
# '''Non-push operations in scriptSig''' Any sequence of script operations in scriptSig that results in the intended data pushes, but is not just a push of that data, results in an alternative transaction with the same validity.
# '''Push operations in scriptSig of non-standard size type''' The Bitcoin scripting language has several push operators (OP_0, single-byte pushes, data pushes of up to 75 bytes, OP_PUSHDATA1, OP_PUSHDATA2, OP_PUSHDATA4). As the latter ones have the same result as the former ones, they result in additional possibilities.
# '''Push operations in scriptSig of non-standard size type''' The Bitcoin scripting language has several push operators (OP_0, single-byte pushes, data pushes of up to 75 bytes, OP_PUSHDATA1, OP_PUSHDATA2, OP_PUSHDATA4). As the later ones have the same result as the former ones, they result in additional possibilities.
# '''Zero-padded number pushes''' In cases where scriptPubKey opcodes use inputs that are interpreted as numbers, they can be zero padded.
# '''Inherent ECDSA signature malleability''' ECDSA signatures themselves are already malleable: taking the negative of the number S inside (modulo the curve order) does not invalidate it.
# '''Superfluous scriptSig operations''' Adding extra data pushes at the start of scripts, which are not consumed by the corresponding scriptPubKey, is also a source of malleability.

View File

@ -2,10 +2,12 @@
BIP: 64
Layer: Peer Services
Title: getutxo message
Authors: Mike Hearn <hearn@vinumeris.com>
Status: Closed
Type: Specification
Assigned: 2014-06-10
Author: Mike Hearn <hearn@vinumeris.com>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0064
Status: Obsolete
Type: Standards Track
Created: 2014-06-10
</pre>
==Abstract==
@ -84,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.

View File

@ -2,10 +2,12 @@
BIP: 65
Layer: Consensus (soft fork)
Title: OP_CHECKLOCKTIMEVERIFY
Authors: Peter Todd <pete@petertodd.org>
Status: Deployed
Type: Specification
Assigned: 2014-10-01
Author: Peter Todd <pete@petertodd.org>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0065
Status: Final
Type: Standards Track
Created: 2014-10-01
License: PD
</pre>
@ -168,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 technique - announce-commit sacrifices
non-trivial, and even the best existing technqiue - 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
@ -203,19 +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
@ -231,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.
@ -250,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
@ -268,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

View File

@ -2,10 +2,12 @@
BIP: 66
Layer: Consensus (soft fork)
Title: Strict DER signatures
Authors: Pieter Wuille <pieter.wuille@gmail.com>
Status: Deployed
Type: Specification
Assigned: 2015-01-10
Author: Pieter Wuille <pieter.wuille@gmail.com>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0066
Status: Final
Type: Standards Track
Created: 2015-01-10
License: BSD-2-Clause
</pre>
@ -73,7 +75,7 @@ bool static IsValidSignatureEncoding(const std::vector<unsigned char> &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;
@ -138,7 +140,7 @@ 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==

View File

@ -2,12 +2,14 @@
BIP: 67
Layer: Applications
Title: Deterministic Pay-to-script-hash multi-signature addresses through public key sorting
Authors: Thomas Kerin <me@thomaskerin.io>
Jean-Pierre Rupp <root@haskoin.com>
Ruben de Vries <ruben@rubensayshi.com>
Status: Complete
Type: Specification
Assigned: 2015-02-08
Author: Thomas Kerin <me@thomaskerin.io>
Jean-Pierre Rupp <root@haskoin.com>
Ruben de Vries <ruben@rubensayshi.com>
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
</pre>
@ -17,7 +19,7 @@ This BIP describes a method to deterministically generate multi-signature pay-to
==Motivation==
Pay-to-script-hash (BIP-0011<ref>[https://github.com/bitcoin/bips/blob/master/bip-0011.mediawiki BIP-0011]</ref>) 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<ref>[https://github.com/bitcoin/bips/blob/master/bip-0011.mediawiki BIP-0011]</ref>) 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<ref>[https://github.com/bitcoin/bips/blob/master/bip-0016.mediawiki BIP-0016]</ref>. 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.
@ -25,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:
..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 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.
* 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.
* 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 addresses.
* Implementations which do adopt this standard will be cross-compatible when choosing multisig addressses.
* 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==
@ -73,11 +75,11 @@ Vector 1
** 39bgKC7RFbpoCRbtD5KEdkYKtNyhpsNa3Z
Vector 2 (Already sorted, no action required)
* List:
* List:
** 02632b12f4ac5b1d1b72b2a3b508c19172de44f6f46bcee50ba33f3f9291e47ed0
** 027735a29bae7780a9755fae7a1c4374c656ac6a69ea9f3697fda61bb99a4f3e77
** 02e2cc6bd5f45edd43bebe7cb9b675f0ce9ed3efe613b177588290ad188d11b404
* Sorted:
* Sorted:
** 02632b12f4ac5b1d1b72b2a3b508c19172de44f6f46bcee50ba33f3f9291e47ed0
** 027735a29bae7780a9755fae7a1c4374c656ac6a69ea9f3697fda61bb99a4f3e77
** 02e2cc6bd5f45edd43bebe7cb9b675f0ce9ed3efe613b177588290ad188d11b404
@ -87,12 +89,12 @@ Vector 2 (Already sorted, no action required)
** 3CKHTjBKxCARLzwABMu9yD85kvtm7WnMfH
Vector 3:
* List:
* List:
** 030000000000000000000000000000000000004141414141414141414141414141
** 020000000000000000000000000000000000004141414141414141414141414141
** 020000000000000000000000000000000000004141414141414141414141414140
** 030000000000000000000000000000000000004141414141414141414141414140
* Sorted:
* Sorted:
** 020000000000000000000000000000000000004141414141414141414141414140
** 020000000000000000000000000000000000004141414141414141414141414141
** 030000000000000000000000000000000000004141414141414141414141414140
@ -103,11 +105,11 @@ Vector 3:
** 32V85igBri9zcfBRVupVvwK18NFtS37FuD
Vector 4: (from bitcore)
* List:
* List:
** 022df8750480ad5b26950b25c7ba79d3e37d75f640f8e5d9bcd5b150a0f85014da
** 03e3818b65bcc73a7d64064106a859cc1a5a728c4345ff0b641209fba0d90de6e9
** 03e3818b65bcc73a7d64064106a859cc1a5a728c4345ff0b641209fba0d90de6e9
** 021f2f6e1e50cb6a953935c3601284925decd3fd21bc445712576873fb8c6ebc18
* Sorted:
* Sorted:
** 021f2f6e1e50cb6a953935c3601284925decd3fd21bc445712576873fb8c6ebc18
** 022df8750480ad5b26950b25c7ba79d3e37d75f640f8e5d9bcd5b150a0f85014da
** 03e3818b65bcc73a7d64064106a859cc1a5a728c4345ff0b641209fba0d90de6e9
@ -117,14 +119,14 @@ 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]]
==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/f7ea0b92a619800c143b0142dc70306da33119a9/core/src/main/java/org/bitcoinj/script/ScriptBuilder.java#L331|BitcoinJ]]
* [[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 ==
<references>

View File

@ -2,13 +2,15 @@
BIP: 68
Layer: Consensus (soft fork)
Title: Relative lock-time using consensus-enforced sequence numbers
Authors: Mark Friedenbach <mark@friedenbach.org>
BtcDrak <btcdrak@gmail.com>
Nicolas Dorier <nicolas.dorier@gmail.com>
kinoshitajona <kinoshitajona@gmail.com>
Status: Deployed
Type: Specification
Assigned: 2015-05-28
Author: Mark Friedenbach <mark@friedenbach.org>
BtcDrak <btcdrak@gmail.com>
Nicolas Dorier <nicolas.dorier@gmail.com>
kinoshitajona <kinoshitajona@gmail.com>
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
</pre>
==Abstract==
@ -19,7 +21,7 @@ This BIP introduces relative lock-time (RLT) consensus-enforced semantics of the
Bitcoin transactions have a sequence number field for each input. The original idea appears to have been that a transaction in the mempool would be replaced by using the same input with a higher sequence value. Although this was not properly implemented, it assumes miners would prefer higher sequence numbers even if the lower ones were more profitable to mine. However, a miner acting on profit motives alone would break that assumption completely. The change described by this BIP repurposes the sequence number for new use cases without breaking existing functionality. It also leaves room for future expansion and other use cases.
The transaction nLockTime is used to prevent the mining of a transaction until a certain date. nSequence will be repurposed to prevent mining of a transaction until a certain age of the spent output in blocks or timespan. This, among other uses, allows bi-directional payment channels as used in [https://github.com/ElementsProject/lightning/raw/master/doc/miscellaneous/deployable-lightning.pdf Hashed Timelock Contracts (HTLCs)] and [https://github.com/bitcoin/bips/blob/master/bip-0112.mediawiki#Bidirectional_Payment_Channels BIP112].
The transaction nLockTime is used to prevent the mining of a transaction until a certain date. nSequence will be repurposed to prevent mining of a transaction until a certain age of the spent output in blocks or timespan. This, among other uses, allows bi-directional payment channels as used in [https://github.com/ElementsProject/lightning/raw/master/doc/deployable-lightning.pdf Hashed Timelock Contracts (HTLCs)] and [https://github.com/bitcoin/bips/blob/master/bip-0112.mediawiki#Bidirectional_Payment_Channels BIP112].
==Specification==
@ -31,7 +33,7 @@ If bit (1 << 31) of the sequence number is set, then no consensus meaning is app
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 of the outputs 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.
@ -63,7 +65,7 @@ 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;
@ -201,7 +203,7 @@ bool CheckSequenceLocks(const CTransaction &tx, int flags)
return error("%s: Missing input", __func__);
}
if (coins.nHeight == MEMPOOL_HEIGHT) {
// Assume all mempool transactions are confirmed in the next block
// Assume all mempool transaction confirm in the next block
prevheights[txinIndex] = tip->nHeight + 1;
} else {
prevheights[txinIndex] = coins.nHeight;
@ -240,10 +242,10 @@ Additionally, this BIP specifies only 16 bits to actually encode relative lock-t
The most efficient way to calculate sequence number from relative lock-time is with bit masks and shifts:
<pre>
// 0 <= nHeight <= 65,535 blocks (1.25 years)
// 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;
@ -259,5 +261,5 @@ BIP112: https://github.com/bitcoin/bips/blob/master/bip-0112.mediawiki
BIP113: https://github.com/bitcoin/bips/blob/master/bip-0113.mediawiki
Hashed Timelock Contracts (HTLCs): https://github.com/ElementsProject/lightning/raw/master/doc/miscellaneous/deployable-lightning.pdf
Hashed Timelock Contracts (HTLCs): https://github.com/ElementsProject/lightning/raw/master/doc/deployable-lightning.pdf

View File

@ -2,11 +2,13 @@
BIP: 69
Layer: Applications
Title: Lexicographical Indexing of Transaction Inputs and Outputs
Authors: Kristov Atlas <kristov@openbitcoinprivacyproject.org>
Author: Kristov Atlas <kristov@openbitcoinprivacyproject.org>
Editor: Daniel Cousens <bips@dcousens.com>
Status: Complete
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0069
Status: Proposed
Type: Informational
Assigned: 2015-06-12
Created: 2015-06-12
License: PD
</pre>
@ -160,7 +162,7 @@ Outputs:
* [[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/btcd/blob/master/btcutil/txsort/txsort.go|Btcsuite]]
* [[https://github.com/btcsuite/btcutil/blob/master/txsort/txsort.go|Btcsuite]]
==Acknowledgements==

22
bip-0069/bip-0069_examples.py Executable file → Normal file
View File

@ -1,6 +1,4 @@
#!/usr/bin/env python3
import binascii
from functools import cmp_to_key
#returns -1 if barr1 is less, 1 if barr1 is greater, and 0 if equal
def bytearr_cmp(barr1, barr2):
@ -31,13 +29,12 @@ def input_cmp(input_tuple1, input_tuple2):
elif (input_tuple1[1] > input_tuple2[1]):
return 1
else:
raise ValueError('Matching previous transaction hash and previous transaction output index for two distinct inputs. Invalid!')
raise ValueError('Matching previous transaction hash and previous transaction output index for two disinct inputs. Invalid!')
def sort_inputs(input_tuples):
return sorted(input_tuples, key=cmp_to_key(input_cmp))
return sorted(input_tuples, cmp=input_cmp)
def print_inputs(ordered_input_tuples):
print("inputs")
index = 0
for prev_tx_hash_byte_arr_little_endian, prev_tx_output_index in ordered_input_tuples:
prev_tx_hash_hex = binascii.hexlify(bytearray(prev_tx_hash_byte_arr_little_endian))
@ -52,13 +49,12 @@ def output_cmp(output_tuple1, output_tuple2):
elif (output_tuple1[0] > output_tuple2[0]):
return 1
#tie-breaker: scriptPubKey_byte_arr
return bytearr_cmp(output_tuple1[1], output_tuple2[1])
return bytearray_cmp(output_tuple1[1], output_tuple2[1])
def sort_outputs(output_tuples):
return sorted(output_tuples, key=cmp_to_key(output_cmp))
return sorted(output_tuples, cmp=output_cmp)
def print_outputs(ordered_output_tuples):
print("outputs")
index = 0
for amount, scriptPubKey_byte_arr in ordered_output_tuples:
scriptPubKey_hex = binascii.hexlify(bytearray(scriptPubKey_byte_arr))
@ -86,7 +82,6 @@ def main():
([0x7d, 0x03, 0x7c, 0xeb, 0x2e, 0xe0, 0xdc, 0x03, 0xe8, 0x2f, 0x17, 0xbe, 0x79, 0x35, 0xd2, 0x38, 0xb3, 0x5d, 0x1d, 0xea, 0xbf, 0x95, 0x3a, 0x89, 0x2a, 0x45, 0x07, 0xbf, 0xbe, 0xeb, 0x3b, 0xa4], 1),
([0x6c, 0x1d, 0x56, 0xf3, 0x1b, 0x2d, 0xe4, 0xbf, 0xc6, 0xaa, 0xea, 0x28, 0x39, 0x6b, 0x33, 0x31, 0x02, 0xb1, 0xf6, 0x00, 0xda, 0x9c, 0x6d, 0x61, 0x49, 0xe9, 0x6c, 0xa4, 0x3f, 0x11, 0x02, 0xb1], 1),
([0xb4, 0x11, 0x2b, 0x8f, 0x90, 0x0a, 0x7c, 0xa0, 0xc8, 0xb0, 0xe7, 0xc4, 0xdf, 0xad, 0x35, 0xc6, 0xbe, 0x5f, 0x6b, 0xe4, 0x6b, 0x34, 0x58, 0x97, 0x49, 0x88, 0xe1, 0xcd, 0xb2, 0xfa, 0x61, 0xb8], 0)]
print("\ntx 0a6a357e2f7796444e02638749d9611c008b253fb55f5dc88b739b230ed0c4c3")
tx_0a6a_sorted_input_tuples = sort_inputs(tx_0a6a_input_tuples)
print_inputs(tx_0a6a_sorted_input_tuples)
@ -99,11 +94,10 @@ def main():
#reference data: https://blockchain.info/rawtx/28204cad1d7fc1d199e8ef4fa22f182de6258a3eaafe1bbe56ebdcacd3069a5f thanks @quantabytes!
tx_2820_input_tuples = [
# (prev_tx_hash_byte_arr_little_endian, prev_tx_output_index)
([0x55, 0x60, 0x5d, 0xc6, 0x5f, 0x3c, 0xcc, 0x4d, 0xb1, 0xd8, 0x56, 0x4a, 0x28, 0x04, 0x2b, 0xdb, 0x2c, 0x2b, 0xe3, 0x85, 0xea, 0xb2, 0xeb, 0xea, 0x41, 0x19, 0xee, 0x9c, 0x26, 0x8d, 0x28, 0x35], 0),
([0x55, 0x60, 0x5d, 0xc6, 0x5f, 0x3c, 0xcc, 0x4d, 0xb1, 0xd8, 0x56, 0x4a, 0x28, 0x04, 0x2b, 0xdb, 0x2c, 0x2b, 0xe3, 0x85, 0xea, 0xb2, 0xeb, 0xea, 0x41, 0x19, 0xee, 0x9c, 0x26, 0x8d, 0x28, 0x35], 1)] #duplicate prev_tx_hash
# (prev_tx_hash, prev_tx_output_index)
("35288d269cee1941eaebb2ea85e32b42cdb2b04284a56d8b14dcc3f5c65d6055", 0),
("35288d269cee1941eaebb2ea85e32b42cdb2b04284a56d8b14dcc3f5c65d6055", 1)] #duplicate prev_tx_hash
print("\ntx 28204cad1d7fc1d199e8ef4fa22f182de6258a3eaafe1bbe56ebdcacd3069a5f")
tx_2820_sorted_input_tuples = sort_inputs(tx_2820_input_tuples)
print_inputs(tx_2820_sorted_input_tuples)
@ -112,7 +106,7 @@ def main():
(100000000, [0x41, 0x04, 0x6a, 0x07, 0x65, 0xb5, 0x86, 0x56, 0x41, 0xce, 0x08, 0xdd, 0x39, 0x69, 0x0a, 0xad, 0xe2, 0x6d, 0xfb, 0xf5, 0x51, 0x14, 0x30, 0xca, 0x42, 0x8a, 0x30, 0x89, 0x26, 0x13, 0x61, 0xce, 0xf1, 0x70, 0xe3, 0x92, 0x9a, 0x68, 0xae, 0xe3, 0xd8, 0xd4, 0x84, 0x8b, 0x0c, 0x51, 0x11, 0xb0, 0xa3, 0x7b, 0x82, 0xb8, 0x6a, 0xd5, 0x59, 0xfd, 0x2a, 0x74, 0x5b, 0x44, 0xd8, 0xe8, 0xd9, 0xdf, 0xdc, 0x0c, 0xac]),
(2400000000, [0x41, 0x04, 0x4a, 0x65, 0x6f, 0x06, 0x58, 0x71, 0xa3, 0x53, 0xf2, 0x16, 0xca, 0x26, 0xce, 0xf8, 0xdd, 0xe2, 0xf0, 0x3e, 0x8c, 0x16, 0x20, 0x2d, 0x2e, 0x8a, 0xd7, 0x69, 0xf0, 0x20, 0x32, 0xcb, 0x86, 0xa5, 0xeb, 0x5e, 0x56, 0x84, 0x2e, 0x92, 0xe1, 0x91, 0x41, 0xd6, 0x0a, 0x01, 0x92, 0x8f, 0x8d, 0xd2, 0xc8, 0x75, 0xa3, 0x90, 0xf6, 0x7c, 0x1f, 0x6c, 0x94, 0xcf, 0xc6, 0x17, 0xc0, 0xea, 0x45, 0xaf, 0xac])]
tx_2820_sorted_output_tuples = sort_outputs(tx_2820_output_tuples)
print_outputs(tx_2820_sorted_output_tuples)
print_outputs(tx_2820_output_tuples)
if __name__ == "__main__":
main()

View File

@ -2,11 +2,13 @@
BIP: 70
Layer: Applications
Title: Payment Protocol
Authors: Gavin Andresen <gavinandresen@gmail.com>
Mike Hearn <mhearn@bitcoinfoundation.org>
Status: Deployed
Type: Specification
Assigned: 2013-07-29
Author: Gavin Andresen <gavinandresen@gmail.com>
Mike Hearn <mhearn@bitcoinfoundation.org>
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
</pre>
==Abstract==
@ -260,7 +262,7 @@ occurs.
Trusted root certificates may be obtained from the operating system;
if validation is done on a device without an operating system, the
[https://www.mozilla.org/about/governance/policies/security-group/certs/policy/ Mozilla root store] is recommended.
[http://www.mozilla.org/projects/security/certs/included/index.html Mozilla root store] is recommended.
==Extensibility==
@ -300,7 +302,7 @@ Protocol Buffers : https://developers.google.com/protocol-buffers/
==Reference implementation==
Create Payment Request generator : https://developer.bitcoin.org/examples/payment_processing.html ([[https://github.com/gavinandresen/paymentrequest|source]])
Create Payment Request generator : https://bitcoincore.org/~gavin/createpaymentrequest.php ([[https://github.com/gavinandresen/paymentrequest|source]])
BitcoinJ : https://bitcoinj.github.io/payment-protocol#introduction

View File

@ -2,10 +2,12 @@
BIP: 71
Layer: Applications
Title: Payment Protocol MIME types
Authors: Gavin Andresen <gavinandresen@gmail.com>
Status: Deployed
Type: Specification
Assigned: 2013-07-29
Author: Gavin Andresen <gavinandresen@gmail.com>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0071
Status: Final
Type: Standards Track
Created: 2013-07-29
</pre>
==Abstract==

View File

@ -2,10 +2,12 @@
BIP: 72
Layer: Applications
Title: bitcoin: uri extensions for Payment Protocol
Authors: Gavin Andresen <gavinandresen@gmail.com>
Status: Deployed
Type: Specification
Assigned: 2013-07-29
Author: Gavin Andresen <gavinandresen@gmail.com>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0072
Status: Final
Type: Standards Track
Created: 2013-07-29
</pre>
==Abstract==
@ -67,4 +69,4 @@ bitcoin:?r=https://merchant.com/pay.php?h%3D2a8628fc2fbe
==References==
[[http://www.w3.org/Protocols/rfc2616/rfc2616.html|RFC 2616]] : Hypertext Transfer Protocol -- HTTP/1.1
[[http://www.w3.org/Protocols/rfc2616/rfc2616.html|RFC 2616]] : Hypertext Transfer Protocol -- HTTP/1.1

View File

@ -2,10 +2,12 @@
BIP: 73
Layer: Applications
Title: Use "Accept" header for response type negotiation with Payment Request URLs
Authors: Stephen Pair <stephen@bitpay.com>
Status: Deployed
Type: Specification
Assigned: 2013-08-27
Author: Stephen Pair <stephen@bitpay.com>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0073
Status: Final
Type: Standards Track
Created: 2013-08-27
</pre>
==Abstract==

View File

@ -2,12 +2,12 @@
BIP: 74
Layer: Applications
Title: Allow zero value OP_RETURN in Payment Protocol
Authors: Toby Padilla <tobypadilla@gmail.com>
Author: Toby Padilla <tobypadilla@gmail.com>
Comments-Summary: Unanimously Discourage for implementation
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0074
Status: Closed
Type: Specification
Assigned: 2016-01-29
Status: Rejected
Type: Standards Track
Created: 2016-01-29
License: PD
</pre>

View File

@ -2,15 +2,15 @@
BIP: 75
Layer: Applications
Title: Out of Band Address Exchange using Payment Protocol Encryption
Authors: Justin Newton <justin@netki.com>
Matt David <mgd@mgddev.com>
Aaron Voisine <voisine@gmail.com>
James MacWhyte <macwhyte@gmail.com>
Author: Justin Newton <justin@netki.com>
Matt David <mgd@mgddev.com>
Aaron Voisine <voisine@gmail.com>
James MacWhyte <macwhyte@gmail.com>
Comments-Summary: Recommended for implementation (one person)
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0075
Status: Deployed
Type: Specification
Assigned: 2015-11-20
Status: Final
Type: Standards Track
Created: 2015-11-20
License: CC-BY-4.0
</pre>
@ -18,11 +18,11 @@
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 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
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==
@ -125,13 +125,13 @@ message InvoiceRequest {
|-
| 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
| 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.
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.
<pre>
enum ProtocolMessageType {
UNKNOWN_MESSAGE_TYPE = 0;
@ -177,7 +177,7 @@ This BIP introduces version 1 of this protocol. All messages sent using these ba
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 encapsulating 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.
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.
<pre>
message EncryptedProtocolMessage {
required uint64 version = 1 [default = 1];
@ -217,14 +217,14 @@ message EncryptedProtocolMessage {
|}
==Payment Protocol Process with InvoiceRequests==
The full process overview for using '''InvoiceRequests''' in the Payment Protocol is defined below.
The full process overview for using '''InvoiceRequests''' in the Payment Protocol is defined below.
<br/><br/>
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 MUST be encapsulated in either a [[#ProtocolMessage|ProtocolMessage]] or [[#EncryptedProcotolMessage|EncryptedProtocolMessage]]. Once the process begins using [[#EncryptedProtocolMessage|EncryptedProtocolMessage]] messages, all subsequent communications MUST use [[#EncryptedProtocolMessage|EncryptedProtocolMessages]].
<br/><br/>
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.
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.
<br/><br/>
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]].
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:
@ -238,7 +238,7 @@ A standard exchange from start to finish would look like the following:
# 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.
'''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.
<img src="bip-0075/encrypted-invoice-request-process.png" alt="Flow diagram of Encrypted InvoiceRequest">
@ -257,14 +257,14 @@ When communicated via '''HTTP''', the listed messages MUST be transmitted via TL
===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.
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.
<br/><br/>
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
@ -301,7 +301,7 @@ The status_message value SHOULD be set with a human readable explanation of the
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 facilities. 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]).
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]].
@ -311,27 +311,27 @@ For the following we assume the Sender already knows the Receiver's public key,
'''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
* 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.
* '''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
* 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
** 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 '''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
* 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
* 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
@ -339,14 +339,14 @@ For the following we assume the Sender already knows the Receiver's public key,
* '''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
* 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.
'''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]]
* 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===
@ -366,10 +366,10 @@ For the following we assume the Sender already knows the Receiver's public key,
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.
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:
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]
@ -387,7 +387,7 @@ Clients SHOULD keep in mind Receivers can broadcast a transaction without return
==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 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.
@ -408,12 +408,12 @@ The following flowchart is borrowed from [[bip-0070.mediawiki|BIP70]] and expand
==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.
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.
<img src="bip-0075/mobile-sf-ir-with-payment.png" alt="Payment Required flow diagram">
===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.
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.
<img src="bip-0075/mobile-sf-encrypted-ir-without-payment.png" alt="Encrypted InvoiceRequest without payment">

View File

@ -2,8 +2,8 @@
// Simple Bitcoin Payment Protocol messages
//
// Use fields 1000+ for extensions;
// to avoid conflicts, register extensions via pull request to update
// https://github.com/bitcoin/bips/blob/master/bip-0070/extensions.mediawiki
// to avoid conflicts, register extensions via pull-req at
// https://github.com/bitcoin/bips/bip-0070/extensions.mediawiki
//
package payments;

View File

@ -1,783 +0,0 @@
```
BIP: 77
Layer: Applications
Title: Async Payjoin
Authors: Dan Gould <d@ngould.dev>
Yuval Kogman <nothingmuch@woobling.org>
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0077
Status: Draft
Type: Specification
Assigned: 2023-08-08
License: BSD-2-Clause
Discussion: https://github.com/bitcoin/bips/pull/1483
https://gnusha.org/pi/bitcoindev/7B11AE34-27A7-46ED-95BF-66CA13BA26F3@ngould.dev/#t
https://gnusha.org/pi/bitcoindev/3C0A6E4C-444E-4E75-829C-1A21D8EE40E0@ngould.dev/#t
Version: 0.2.0
Requires: 21, 78, 173, 174
```
## Copyright
This BIP is licensed under the 2-clause BSD license.
## Abstract
Payjoin lets Bitcoin senders and receivers interact to make batched
transactions.
This document proposes a second, backwards-compatible, asynchronous version of
the Payjoin protocol ("Version 2") relative to and described in [BIP 78](bip-0078.mediawiki) ("Version 1"). An untrusted
third-party "directory server" replaces the requirement
for a receiver to host a secure public endpoint for interactions. HTTP clients
access the directory server using an asynchronous protocol and authenticated,
encrypted payloads. The design preserves complete Payjoin receiver
functionality, including payment
output substitution. Authenticated encryption depends only on cryptographic
primitives available in Bitcoin Core. Requests use [Oblivious
HTTP](https://www.ietf.org/rfc/rfc9458.html) (OHTTP) to
prevent the directory and other Payjoin clients from linking requests to client
IP addresses.
## Motivation
Satoshi Nakamoto pointed out one specific privacy risk in the
[whitepaper](https://bitcoin.org/en/bitcoin-paper),
that transactions with multiple inputs "necessarily reveal that
their inputs were owned by the same owner."
Payjoin addresses that risk, the _common-input-ownership heuristic_,
by making it practical to spend inputs owned by multiple parties
in one transaction.
While addressing Bitcoin's primal privacy risk, Payjoin *input* batching
also improves on the widespread non-interactive *output* batching practice
deployed by exchanges. When combined, the same movement of funds can use
less block weight and save fees.
A natural application of Payjoin would be to combine
getting paid with consolidating UTXOs into one transaction. But Payjoin
can also secure [transaction
cut-through](https://bitcointalk.org/index.php?topic=281848.0),
allowing a sender to transfer funds to a receiver who also transfers
funds to a third party in the same transaction. For example, deposits to an
exchange may "cut through" in a single transaction that also satisfies
withdrawals instead of with a second transaction that spends the deposited
funds. Payjoin enables more blockspace-efficient transactions that
reduce fees while addressing privacy risks.
However, BIP 78's requirements for Payjoin Version 1 have proven to be an
obstacle to adoption. Version 1 receivers must host a secured
public-facing HTTP server. Mobile and web environments limit the ability
to fulfil such a requirement. Version 1 also requires synchronous
communication. Both sender and receiver must be online simultaneously.
Wallet developers [
regard](https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2021-January/018358.html)
these requirements as barriers to Payjoin adoption.
To address these limitations, our goal is to specify a practical
coordination mechanism suitable for widespread implementation. This proposal
leverages mature solutions to common problems, building on established web
standards and proven Bitcoin primitives.
## Overview
A Payjoin *sender* and *receiver* interact so that they may both contribute to a
transaction. In this proposal, they exchange asynchronous end-to-end
encrypted messages by relaying them to a store-and-forward *directory* server
using OHTTP.
Before initiating the protocol, the receiver must secure communications with
the directory by [bootstrapping](#ohttp-bootstrapping).
- The receiver [initiates a Payjoin Session](#session-initiation)
by sharing a [Payjoin URI](#payjoin-uri) that includes the URL of an
ephemeral mailbox hosted on the directory, where it can receive a message
from the sender.
- The sender [posts a message](#sender-original-psbt-messaging)
containing a fully signed fallback transaction, known as the *Original PSBT*,
to the mailbox.
- The receiver gets this message and
[posts a message containing a *Proposal
PSBT*](#receiver-proposal-psbt-messaging)
to the sender's ephemeral mailbox, by updating the Original PSBT with
appropriate inputs and/or outputs.
- The sender gets the Proposal PSBT, [checks it, signs, and
broadcasts](#sender-signing-and-broadcast) the final transaction.
At any point, either party may choose to broadcast the
fallback transaction described by the Original PSBT instead of proceeding.
Because the Original PSBT and Proposal PSBT spend the same input(s) they are
mutually exclusive and only one can be confirmed.
Messages are buffered in the directory, allowing both parties to tolerate
temporary disconnections and resume communication by polling.
### Async Payjoin Directory Mediated Sequence Diagram
```text
+----------+ +------------+ +----------+ +----------+
| Receiver | | Directory | | Sender | | Network |
+----+-----+ +-----+------+ +----+-----+ +----+-----+
| | | |
| Payjoin URI (BIP21), out-of-band | |
+------------------------------------------------>| |
| | | |
| Poll GET: original PSBT (repeat until available) |
+- - - - - - - - - - - ->+ | |
| # POST: original PSBT | |
| #<-----------------------+ |
| 200 OK: original PSBT # | |
|<-----------------------+ | |
| | | |
| | Poll GET: proposal PSBT (repeat until available)
| +<- - - - - - - - - - - -+ |
| POST: proposal PSBT # | |
+-----------------------># | |
| # 200 OK: proposal PSBT | |
| +----------------------->| |
| | | |
| | | Broadcast payjoin |
| | +---------------------->|
| | | |
```
## Specification
### OHTTP Bootstrapping
Before initiating a Payjoin Session a receiver must first discover the
directory's
[OHTTP Key Configuration](https://www.ietf.org/rfc/rfc9458.html#section-3.1),
via an authenticated
bootstrap mechanism. The key configuration contains information to establish
[Hybrid Public Key Encryption](#secp256k1-hybrid-public-key-encryption) (HPKE) in order to secure communications between the client and the directory in
lieu of TLS.
The bootstrap mechanism may vary by implementation but must
follow [OHTTP Consistency
Requirements](https://datatracker.ietf.org/doc/html/draft-ietf-privacypass-key-consistency-01)
and should not reveal a receiver IP address to the directory. Some
examples of suitable mechanisms include getting a key configuration
from a Payjoin URI, a trusted application binary, or fetching using https-in-http
CONNECT method, https-in-WebSocket, Tor, or a VPN.
Directory OHTTP Gateways MUST support [RFC 9540 Key Configuration
Fetching](https://www.rfc-editor.org/rfc/rfc9540.html#name-key-configuration-fetching)
via GET request. RFC 9540 defines the
gateway location as `/.well-known/ohttp-gateway`.
### Session Initiation
A receiver initiates a session by sharing a Payjoin URI. Because a URI
contains sensitive information, such as a receiver address, it should be shared
over a confidential channel.
#### Payjoin URI
Bitcoin URIs ([BIP
21](https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki)
or [BIP
321](https://github.com/bitcoin/bips/blob/master/bip-0321.mediawiki))
are a standard way to request bitcoin.
A Payjoin URI is a Bitcoin URI that contains a `pj` parameter. The `pj`
parameter value is a URL in both BIP 78 and BIP 77.
Senders that understand Bitcoin URI but don't support Payjoin will just
ignore the `pj` parameter and proceed to typical address-based
transaction flows.
A `req-pj` parameter may be used as a [BIP 21 forwards compatibility `reqparam`](https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki#forward-compatibility) instead of
`pj` to signal that Payjoin is required.
The parameter value must be [uppercased and the parameter should be placed last in the URI](#uppercase-url).
Since BIP 78 payloads are neither encrypted nor authenticated,
a directory used for backwards-compatible payloads is known
as an ["unsecured payjoin server" in BIP 78
parlance](https://github.com/bitcoin/bips/blob/master/bip-0078.mediawiki#unsecured-payjoin-server).
Backwards-compatible receivers MUST disable output substitution
by setting `pjos=0` to prevent modification by a malicious directory.
##### Mailbox endpoint
In this proposal the URL in the `pj` parameter value is the mailbox
endpoint URL. Mailboxes are shared HTTP resources hosted by the
directory and serve as OHTTP Target Resources. Clients use these endpoints
to relay encrypted messages. They `POST` messages to and `GET` messages from
mailbox endpoints via OHTTP.
Senders that support BIP 78 but not this proposal may POST messages directly to
mailbox endpoints for [backwards compatibility](#backwards-compatibility).
###### Short ID
A Short ID identifies a mailbox based on its associated public key. The Short
ID is the path component of the mailbox endpoint. One is derived by hashing the
33-byte compressed public key encoding with SHA-256, truncating it to
[8 bytes (64 bits)](#64-bit-short-id-length), and encoding it in
[uppercase](#uppercase-url) using the bech32 character set (like a bech32 string without the HRP, separator and checksum).
##### Receiver fragment parameters
This proposal introduces session-specific parameters which the
receiver shares encoded in the URI.
Instead of defining new Bitcoin URI parameters, the session-specific
parameters are encoded in the [
fragment](https://datatracker.ietf.org/doc/html/rfc3986#section-3.5)
of the mailbox endpoint URL.
The `#` fragment separator character must be [RFC 3986
percent-encoded](https://datatracker.ietf.org/doc/html/rfc3986#section-2.1)
as `%23`, because it separates the
fragment of the mailbox endpoint URL included in the `pj` parameter, not the
fragment of the Bitcoin URI.
These session-specific parameters use a bech32-inspired encoding.
The HRP is used as the parameter key, followed by the '1' separator,
followed by the parameter value encoded using the bech32 character set in
[uppercase](#uppercase-url). No checksum is used. Parameters are separated
by a `-` character.
The following parameters are defined, and must be provided in lexicographical
order:
- `EX`: specifies a [session
expiration](#session-expiration) in [unix
time](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16).
- `OH`: encodes an alternate format of the OHTTP Key Configuration of
the directory. It consists of a 33-byte compressed public key of the
directory's OHTTP Gateway, prefixed by the 2-byte Key Identifier. A [
RFC 9458 Key
Configuration](https://www.ietf.org/rfc/rfc9458.html#section-3.1)
is reconstructed by assuming the HPKE KEM ID and Symmetric Algorithms
are [fixed](#secp256k1-hybrid-public-key-encryption).
- `RK`: encodes the *receiver key* as a 33-byte compressed public key.
Senders will initiate HPKE with the receiver using this key.
For example, a properly encoded endpoint Bitcoin URI looks like this
`bitcoin:tb1q6q6de88mj8qkg0q5lupmpfexwnqjsr4d2gvx2p?amount=0.00666666&pjos=0&pj=HTTPS://PAYJO.IN/TXJCGKTKXLUUZ%23EX1WKV8CEC-OH1QYPM59NK2LXXS4890SUAXXYT25Z2VAPHP0X7YEYCJXGWAG6UG9ZU6NQ-RK1Q0DJS3VVDXWQQTLQ8022QGXSX7ML9PHZ6EDSF6AKEWQG758JPS2EV`
Until 2026 implementations SHOULD also accept `+` as a fragment parameter
separator and not enforce parameter ordering requirements, for compatibility
with the [previous version of this document](#changelog).
### Sender Original PSBT Messaging
The sender constructs the fallback transaction, a typical transaction
spending funds to the receiver's address specified in the Payjoin URI.
This transaction is serialized as a BIP 174 PSBTv0, satisfying
[the receiver checklist](#receivers-original-psbt-checklist).
The Original PSBT MUST:
- Include complete UTXO data.
- Be fully signed.
- Exclude unnecessary fields such as global xpubs or keypath
information.
- Be broadcastable.
The Original PSBT MAY:
- Include outputs unrelated to the sender-receiver transfer for batching
purposes.
This *Original PSBT* is encoded as base64, followed by the query
parameter string on a new line containing [optional sender
parameters](#optional-sender-parameters).
The sender generates an ephemeral mailbox key. The corresponding public key is
known as the *reply key*, and it is prepended to the base64 plaintext string,
serialized in compressed form as 33 bytes.
This plaintext string is encrypted to the receiver key according to [HPKE Base
mode](https://www.rfc-editor.org/rfc/rfc9180.html#name-encryption-to-a-public-key).
The HPKE `info` string, used for domain separation, is `PjV2MsgA`. The
ciphertext ensures message secrecy and integrity when passed to the receiver
using the mailbox endpoint. The 16-byte authentication tag is appended to the
ciphertext.
RFC 9180 [does not
specify](https://www.rfc-editor.org/rfc/rfc9180.html#section-10) the wire format
encoding of HPKE messages. To construct an HPKE payload, the secp256k1 public
key from the DHKEM is encoded using ElligatorSwift in 64 bytes. Note that
ElligatorSwift is only the wire format; when deriving shared secrets, the curve
point is re-serialized in uncompressed form.
```
PjV2MsgA Byte Representation (7168 bytes total)
+---------------------------------------------------------------------------------------+
| ElligatorSwift | Ciphertext |
| (64 bytes) | (7104 bytes) |
| +-----------------------+---------------------------------+------------+
| | Reply Key | Padded Plaintext | AEAD Tag |
| | (33 bytes) | (7055 bytes = 7168-64-33-16) | (16 bytes) |
+---------------------------------------------------------------------------------------+
```
The resulting HPKE payload is the body of a POST request to the
receiver's mailbox. This request is then [
encapsulated](#clientdirectory-interactions) according to
Oblivious HTTP to the directory's OHTTP Gateway. OHTTP serializes the
inner request as BHTTP, and provides another layer of HPKE encryption,
between the client and directory.
Upon receipt, the directory's OHTTP Gateway decapsulates the OHTTP
request and handles the inner POST request at the receiver's mailbox
endpoint, which stores the HPKE encrypted payload to be forwarded to the
receiver.
The sender then polls OHTTP encapsulated GET requests to the sender's
mailbox endpoint until it receives a response from the directory
containing the receiver's *Proposal PSBT*, and proceeds to
[sign and broadcast](#sender-signing-and-broadcast).
It stops polling after expiration.
#### Optional sender parameters
[BIP 78's optional sender parameters](https://github.com/bitcoin/bips/blob/master/bip-0078.mediawiki#optional-parameters)
may be used in this proposal, but must be included in
the body as part of the ciphertext rather than as a query string.
HPKE binds ciphertexts to application-specific `info` strings. Because
of this domain separation, BIP 78's `v` parameter is redundant and
should be omitted for this proposal.
### Receiver Proposal PSBT Messaging
After sharing the Payjoin URI with the sender, the receiver polls via
OHTTP encapsulated GET requests to the receiver's mailbox endpoint. So
long as the mailbox contains no message, the directory responds with
status 202 ACCEPTED. Once a mailbox contains a message, the directory
returns it in the response body with status 200 OK.
Upon receiving an encapsulated 200 OK response, the receiver decrypts
the payload and checks the *Original PSBT* therein according to the
[receiver checklist](#receivers-original-psbt-checklist).
The receiver then updates the *Original PSBT* to include new signed
inputs and outputs, invalidating the sender's signature(s). The receiver
may also adjust the transaction fee. The result, called the *Proposal
PSBT*, must satisfy the [sender checklist](#senders-proposal-psbt-checklist)
The Proposal PSBT MUST:
- Include complete UTXO data.
- Include all inputs from the Original PSBT.
- Include all outputs which do not belong to the receiver from the
Original PSBT.
- Use a random index if additional inputs or outputs are added.
The Proposal PSBT sender MAY:
- Add inputs at random indices.
- Add outputs at random indices.
- Remove or modify Original PSBT outputs under the control of the
receiver (i.e. not sender change).
The Proposal PSBT MUST NOT:
- Shuffle the order of inputs or outputs contained in the Original PSBT.
- Decrease the absolute fee of the Original PSBT.
The receiver encrypts the *Proposal PSBT* to the sender's reply key according to
[HPKE Auth
mode](https://www.rfc-editor.org/rfc/rfc9180.html#name-authentication-using-an-asy),
using the receiver's key for authentication. The HPKE `info` string is
`PjV2MsgB`. The HPKE wire format is the same as in the [sender's
message](#sender-original-psbt-messaging).
```
PjV2MsgB Byte Representation (7168 bytes total)
+---------------------------------------------------------------------------------------+
| ElligatorSwift | Ciphertext |
| (64 bytes) | (7104 bytes) |
| +---------------------------------------------------------+------------+
| | Padded Plaintext | AEAD Tag |
| | (7088 bytes = 7168-64-16) | (16 bytes) |
+---------------------------------------------------------------------------------------+
```
The receiver makes the resulting HPKE payload the body of a POST request to the
sender's mailbox whose Short ID is derived from the sender's reply key. This request is then [
encapsulated](#clientdirectory-interactions) according to
Oblivious HTTP to the directory's OHTTP Gateway. OHTTP serializes the
inner request as BHTTP, and provides another layer of HPKE encryption,
between the client and directory.
The above describes the receiver's reply path when the sender used
Version 2. When the sender used the BIP 78 backwards-compatible path
(the Original PSBT was a BIP 78 cleartext payload rather than an
HPKE-encrypted v2 message), the receiver's response MUST instead follow
[Backwards compatibility](#backwards-compatibility): the *Proposal PSBT*
is not HPKE-encrypted and the request method is `PUT`.
Once the receiver makes this request, they wait for either transaction from the
Original PSBT or Proposal PSBT to be broadcast to the Bitcoin network.
#### Receiver's Original PSBT checklist
The receiver checklist is the same as [the BIP 78 receiver
checklist](https://github.com/bitcoin/bips/blob/master/bip-0078.mediawiki#receivers-original-psbt-checklist).
### Sender signing and broadcast
The sender validates the *Proposal PSBT* it receives against a
checklist. If the checks pass, it may sign and broadcast the resulting
Payjoin transaction.
#### Sender's Proposal PSBT checklist
This proposal's sender checklist is the same as [the BIP 78 sender
checklist](https://github.com/bitcoin/bips/blob/master/bip-0078.mediawiki#senders-payjoin-proposal-checklist).
### Client/Directory interactions
The Payjoin Directory provides a rendezvous point for senders and
receivers to exchange messages. The directory stores Payjoin payloads to
support asynchronous communication. Async Payjoin requests must be
submitted as encapsulated messages to the directory's OHTTP Gateway.
The wire format OHTTP request is specified in [RFC
9458](https://www.ietf.org/rfc/rfc9458.html#name-hpke-encapsulation). HPKE
requires the directory's OHTTP key configuration. The plaintext is a binary
encoded HTTP request ([RFC 9292](https://www.rfc-editor.org/rfc/rfc9292.html))
intended for the OHTTP target resource, usually a mailbox endpoint, padded to
8104 bytes with [random data](#random-padding).
```
OHTTP Encapsulated Request Byte Representation (8192 bytes total)
+--------------+-------------------------+------------------------------------------+
| OHTTP Header | HPKE KEM | Ciphertext |
| (7 bytes) | Uncompressed Public Key | (8120 bytes = 8192-65-7) +
| | (65 bytes) +-----------------------------+------------+
| | | Padded BHTTP Request | AEAD Tag |
| | | (8104 bytes = 8192-65-16-7) | (16 bytes) |
+--------------+-------------------------+------------------------------------------+
```
Response encryption uses the Export functionality of the request HPKE context to
establish a shared secret, and therefore consists of a 32 byte nonce followed by
the AEAD ciphertext and tag.
```
OHTTP Encapsulated Response Byte Representation (8192 bytes total)
+---------------------+------------------------------------------+
| Nonce | Ciphertext |
| (32 bytes) | (8160 bytes = 8192-32) +
| +-----------------------------+------------+
| | Padded BHTTP Response | AEAD Tag |
| | (8144 bytes = 8192-32-16) | (16 bytes) |
+---------------------+------------------------------------------+
```
GET requests on an empty mailbox should block until a message is posted
or a timeout occurs. The timeout should be 30 seconds because that will
not exceed the default timeout for most HTTP clients.
The directory may optionally accept HTTP/1.1 POST requests without OHTTP
to mailbox endpoint URLs for backwards compatibility with BIP 78 senders.
#### OHTTP Sequence Diagram
```text
.-------------------------------------------.
| Payjoin Directory |
+--------+ +-----------+ | +-------------+ +--------------+ |
| Client | | OHTTP | | | OHTTP | | HTTP | |
| | | Relay | | | Gateway | | Resource | |
+---+----+ +------+----+ | +-----+-------+ +------+-------+ |
| | `--------|-----------------------|----------'
| Relay Request | | |
| [ + Encapsulated | | |
| Request ] | | |
+------------------->| Gateway Request | |
| | [ + Encapsulated | |
| | Request ] | |
| +------------------->| Request |
| | +---------------------->|
| | | |
| | | Response |
| | Gateway |<----------------------+
| | Response | |
| | [ + Encapsulated | |
| | Response ] | |
| Relay |<-------------------+ |
| Response | | |
| [ + Encapsulated | | |
| Response ] | | |
|<-------------------+ | |
| | | |
```
### Relay/Directory interactions
RFC 9458 requires each OHTTP Relay to be configured to forward requests
to exactly one OHTTP Gateway. This requirement prevents receivers from
being able to choose any directory, and senders from choosing relays
independently. Without addressing this limitation, senders would have to
know which relays are appropriate to use for each directory, creating a
tendency for one directory and its affiliated relays to monopolize the
protocol.
In order to allow OHTTP Relays to be used with any directory, a
directory's OHTTP Gateway may advertise this allowed purpose. This
advertisement prevents OHTTP Relays from acting as open internet proxies,
which would otherwise allow anonymized access to arbitrary resources and
expose them to denial-of-service attacks, as well as other forms of abuse.
When the directory receives a GET request to the `/.well-known/ohttp-gateway`
path with an `allowed_purposes` query parameter, its response body
should contain a magic string in the same format as a TLS ALPN protocol
list (a U16BE length encoded list of U8 length encoded strings). The
magic string is `BIP77 454403bb-9f7b-4385-b31f-acd2dae20b7e`, offering
an unambiguous signal to relays that this OHTTP Gateway will accept
requests associated with this purpose from any relay.
By supporting this `allowed_purposes` parameter, the directory signals
to OHTTP Relays that it is willing to handle requests related to BIP 77,
removing the RFC 9458's requirement that relays and
Gateways be configured in a one-to-one relationship.
## Rationale
### Uppercase URL
In order to simplify parsing and allow QR encoders to use [Alphanumeric
QR
mode](https://www.rfc-editor.org/rfc/rfc9285.html#name-the-alphabet-used-in-base45),
which is more compact than Byte mode, the mailbox endpoint URL,
including the fragment parameters, is encoded in uppercase.
Unlike Bitcoin URI parameters, which require switching back to Byte
mode, the use of the URL fragment for session-specific parameters makes
it possible to stay in Alphanumeric mode.
### Parameter Ordering
The order of fragment parameters, Bitcoin URI parameters, as well as in the
sender's optional parameters have no defined meaning.
In the BIP 21 URI, the `pj` parameter mailbox endpoint URL SHOULD be the last
parameter to avoid QR mode switching.
Since variations might create a fingerprint for particular wallet software,
this document requires that fragment parameters MUST appear in reverse
lexicographical order.
### Session Expiration
The directory may hold a message for an offline Payjoin client until that
client comes online. However, the BIP 78 spec [
recommends](https://github.com/bitcoin/bips/blob/master/bip-0078.mediawiki#receiver-does-not-need-to-be-a-full-node)
broadcasting Original PSBTs in the case of an offline counterparty.
Doing so exposes a naïve, surveillance-vulnerable transaction, which
Payjoin intends to avoid.
Because BIP 78 is a synchronous protocol without a standard expiration
mechanism, and automated receivers are vulnerable to probing attacks,
BIP 78 encourages receivers to broadcast the Original PSBT after some
undefined expiration time.
Because BIP 77 is an asynchronous protocol, it requires an explicit [
session-specific fragment
parameter](#receiver-fragment-parameters), `EX`, to
communicate this expiration time to the sender.
There is no way for a sender to prevent a receiver from broadcasting the
fallback transaction extracted from the Original PSBT before the
receiver-specified expiration time.
### 64-bit Short ID Length
64 bits are sufficient to make the probability of experiencing a random
collision negligible. As of writing, the UTXO set has ~2^28 elements.
This is a very loose upper bound for the number of concurrent (non-spam)
sessions, for which the probability of a random collision will be less
than 1%. The actual number of sessions will of course be (orders of
magnitudes) lower given that sessions are short-lived. With ~2^21
sessions (a loose bound on number of transactions that can be confirmed
in 24 hours) the probability is less than 1e-6. These figures bound the
probability of a collision existing anywhere in the entire set, whereas
the probability for an individual session to experience a collision is
\<\< 1e-10 in either case.
### Complete UTXO Data
Complete UTXO data is required because this information is required for
signing and calculating fees for some input types.
### HTTP
HTTP is ubiquitous. Using simple HTTP polling allows even Bitcoin Core
to consider an implementation. Unlike a WebSockets protocol, plain HTTP
can benefit from metadata protection by using Oblivious HTTP.
### Oblivious HTTP
OHTTP protects sender and receiver IP addresses both from one another
and from the directory. This makes it more difficult for a directory to
correlate many Payjoin transactions with specific IP addresses.
OHTTP relays can be run as basic HTTP proxies from wallet providers or
third parties.
### Uniform Payloads
Encapsulated OHTTP payloads seen by the relay and directory, and
encrypted messages seen by the directory, are constructed to be uniform
so that these third-party services are unable to distinguish between
them.
Encapsulated OHTTP messages are 8192 bytes long, and begin with a
cleartext OHTTP header and an uncompressed key which is distinguishable
from random bytes but uniform across different encapsulated requests.
End-to-end encrypted messages are 7168 bytes long, and should be
indistinguishable from uniformly random bytes.
[ElligatorSwift as defined in BIP 324](https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki#elligatorswift-encoding-of-curve-x-coordinates)
is used to encode encapsulated HPKE public keys prepended to the HPKE ciphertext
so that the directory can't distinguish between key material, the
ciphertext, and randomness. This ensures the two different protocol
messages are indistinguishable from each other as well as any protocol
extensions.
These padded sizes are sufficient for most PSBTs without exceeding the [
8KB
limit](https://www.geekersdigest.com/max-http-request-header-size-server-comparison/)
of many HTTP/1.1 web servers. 8KB is also too small for image sharing,
making misuse of the directory impractical.
#### Random Padding
The typical [zero padding recommended by the BHTTP
specification](https://www.rfc-editor.org/rfc/rfc9292.html#name-padding-and-truncation)
would make future use of [multi-hop OHTTP inspired by the Sphinx mix
format](https://github.com/orgs/payjoin/discussions/582) detectable from the
point of view of the directory. Random padding is allowed so long as the BHTTP
encoded request is not truncated.
By randomly padding OHTTP messages, any future use of such techniques would be
indistinguishable from clients that only implement standardized OHTTP. Since
this would limit a malicious directory's ability to censor any such requests in
the future, and such requests significantly bolster the privacy threat model
against malicious OHTTP relays or traffic analysis by a global passive
adversary, it is desirable to do so for standard OHTTP requests as well.
### Secp256k1 Hybrid Public Key Encryption
[RFC 9180 Hybrid Public Key
Encryption](https://www.rfc-editor.org/rfc/rfc9180.html)
(HPKE) is a modern IETF standard for secure
message exchange without TLS, since TLS is not available in Bitcoin Core.
This proposal uses `DHKEM(Secp256k1, HKDF-SHA256)` and
`ChaCha20Poly1305` AEAD for both OHTTP encapsulation and for end-to-end
encryption between the sender and receiver.
The receiver transmits its receiver key in [receiver fragment
parameters](#receiver-fragment-parameters). The sender shares
its reply key along with the Original PSBT. These keys are ephemeral and
must only be used for a single Payjoin Session.
#### Secp256k1-based DHKEM
[Secp256k1-based DHKEM for
HPKE](https://www.ietf.org/archive/id/draft-wahby-cfrg-hpke-kem-secp256k1-01.html)
is most appropriate because of secp256k1's availability in bitcoin
contexts.
#### ChaCha20Poly1305 AEAD
This authenticated encryption with additional data [
algorithm](https://en.wikipedia.org/wiki/ChaCha20-Poly1305)
is standardized in [RFC
8439](https://www.rfc-editor.org/rfc/rfc8439) and has high
performance. ChaCha20Poly1305 AEAD has been implemented [in Bitcoin
Core](https://github.com/bitcoin/bitcoin/pull/15649) for [
BIP 324 Encrypted
Transport](https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki)
as well. This has widespread support in browsers and common
cryptographic libraries. AES-GCM is more widespread but slower without
hardware support and not typically already a dependency in bitcoin software.
#### HKDF-SHA256
SHA-256 is necessarily available in bitcoin contexts.
## Attack vectors
In addition to the attack vectors and mitigations in
[BIP 78](https://github.com/bitcoin/bips/blob/master/bip-0078.mediawiki#attack-vectors),
this proposal has the following attack vectors.
### Directory Denial of Service
Since each mailbox stores arbitrary encrypted payloads, directories are
vulnerable to flooding. To mitigate such denial of service attacks,
directory operators may respond with `401` unauthorized unless an
authorization token is provided. Authorization tokens must be unlinkable
to preserve client privacy. A specific unlinkable authorization token
mechanism is out of the scope of this proposal.
### Network privacy
Oblivious HTTP must be used to protect the IP addresses of both sender
and receiver from the directory. This requires an OHTTP Key
Configuration to be shared in the Payjoin URI and for the directory to
support Oblivious HTTP.
Unlike BIP 78 implementations, sender and receiver clients will only see
the IP address of the directory and not that of the client they are
interacting with.
Senders that submit requests directly to the directory, without using
an OHTTP Relay, may reveal their IP address to the receiver since that
receiver also specifies the directory.
## Backwards compatibility
Senders not supporting Payjoin will just ignore the `pj` parameter and
proceed to typical address-based transaction flows.
All Payjoin versions use [Bitcoin URIs](#payjoin-uri).
Receivers may choose to accept BIP 78 payloads at their discretion.
A BIP 78 sender posts their request to the directory, which stores
and forwards it to the BIP 77 receiver. A backwards-compatible
receiver proceeds with the BIP 78 checks if the encapsulated response
body is UTF-8 plaintext, signifying BIP 78. In order to service the
request, a BIP 78 response must be returned to the sender within 30
seconds or else the directory should respond with an `unavailable` JSON
error code as [defined in BIP
78](https://github.com/bitcoin/bips/blob/master/bip-0078.mediawiki#receivers-well-known-errors).
When responding to a BIP 78 sender, the receiver MUST NOT HPKE-encrypt
the *Proposal PSBT*. The receiver MUST send the *Proposal PSBT* as the
body of a PUT request, with the body being the base64-encoded PSBT,
encoded as ASCII bytes. The target mailbox endpoint MUST be the
receiver's own mailbox (the same mailbox at which the sender posted the
*Original PSBT*), because a BIP 78 sender provides no reply key from which
a sender-side reply mailbox could be derived. The PUT request is then
OHTTP-encapsulated to the directory's OHTTP Gateway as for any other
Payjoin Directory interaction.
## Reference implementation
A production reference implementation client can be found at
<https://crates.io/crates/payjoin-cli>. Source code for the clients, the
directory, and development kit may be found here:
<https://github.com/payjoin/rust-payjoin>. Source code for an Oblivious
HTTP relay implementation may be found here:
<https://github.com/payjoin/ohttp-relay>.
## Changelog
- 0.2.0 2025-07-08
- Change fragment parameter delimiter from `+` to `-` to improve
compatibility with generic URI parsing libraries, and order them
lexicographically. `+` can cause issues due to a common convention (not
specified in RFC 3986, but in RFC 1866, in relation to HTML form
submission and query parameters) of interpreting `+` as ` ` when decoding
URIs.
- 0.1.0 2025-05-28
- First merged Draft version of BIP 77

View File

@ -2,12 +2,14 @@
BIP: 78
Layer: Applications
Title: A Simple Payjoin Proposal
Authors: Nicolas Dorier <nicolas.dorier@gmail.com>
Status: Deployed
Type: Specification
Assigned: 2019-05-01
License: BSD-2-Clause
Author: Nicolas Dorier <nicolas.dorier@gmail.com>
Replaces: 79
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0078
Status: Draft
Type: Standards Track
Created: 2019-05-01
License: BSD-2-Clause
</pre>
==Introduction==
@ -93,7 +95,7 @@ The payjoin proposal PSBT is sent in the HTTP response body, base64 serialized w
To ensure compatibility with web-wallets and browser-based-tools, all responses (including errors) must contain the HTTP header <code>Access-Control-Allow-Origin: *</code>.
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 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 <code>witnessUTXO</code> or <code>nonWitnessUTXO</code> information filled in.
@ -104,20 +106,14 @@ The original PSBT MUST:
The original PSBT MAY:
* Have outputs unrelated to the payment for batching purpose.
The original PSBT SHOULD NOT:
* Include mixed input types until September 2024. Mixed inputs were previously completely disallowed so this gives some grace period for receivers to update.
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.
* Use all the outputs which do not belongs to the receiver from the original PSBT.
* Only finalize the inputs added by the receiver. (Referred later as <code>additional inputs</code>)
* Only fill the <code>witnessUTXO</code> or <code>nonWitnessUTXO</code> for the additional inputs.
The payjoin proposal MAY:
* Add, or replace the outputs belonging to the receiver unless output substitution is disabled.
The payjoin proposal SHOULD NOT:
* Include mixed input types until September 2024. Mixed inputs were previously completely disallowed so this gives some grace period for senders to update.
* 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.
@ -129,8 +125,6 @@ This proposal is defining the following new [[bip-0021.mediawiki|BIP 21 URI]] pa
* <code>pj=</code>: Represents an http(s) endpoint which the sender can POST the original PSBT.
* <code>pjos=0</code>: Signal to the sender that they MUST disallow [[#output-substitution|payment output substitution]]. (See [[#unsecured-payjoin|Unsecured payjoin server]])
Note: the <code>amount</code> parameter is *not* required.
===<span id="optional-params"></span>Optional parameters===
When the payjoin sender posts the original PSBT to the receiver, he can optionally specify the following HTTP query string parameters:
@ -149,7 +143,7 @@ If the receiver does not support the version of the sender, they should send an
}
</pre>
* <code>additionalfeeoutputindex=</code>, if the sender is willing to pay for increased fee, this indicate output can have its value subtracted to pay for it.
* <code>additionalfeeoutputindex=</code>, if the sender is willing to pay for increased fee, this indicate output can have its value substracted to pay for it.
If the <code>additionalfeeoutputindex</code> 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.
@ -193,10 +187,10 @@ The well-known error codes are:
|The receiver rejected the original PSBT.
|}
The receiver is allowed to return implementation-specific errors which may assist the sender to diagnose any issue.
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.
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.
@ -204,9 +198,9 @@ It is advised to hard code the description of the well known error codes into th
===<span id="fee-output"></span>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]] <code>additionalfeeoutputindex=</code> and <code>maxadditionalfeecontribution=</code> to indicate which output and how much the receiver can subtract fee.
If such is the case, the sender must use both [[#optional-params|optional parameters]] <code>additionalfeeoutputindex=</code> and <code>maxadditionalfeecontribution=</code> to indicate which output and how much the receiver can substract fee.
There are several cases where a fee output is useful:
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 <code>minimum relay transaction fee rate</code>, which is typically 1 satoshi per vbyte.
@ -219,9 +213,28 @@ To prevent this, the sender can agree to pay more fee so the receiver make sure
* 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.
When a sender pick 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 <code>maxadditionalfeecontribution=</code> is <code>originalPSBTFeeRate * vsize(sender_input_type)</code>.
{| class="wikitable"
!sender_input_type
!vsize(sender_input_type)
|-
|P2WPKH
|68
|-
|P2PKH
|148
|-
|P2SH-P2WPKH
|91
|-
|P2TR
|58
|}
Our recommendation for <code>maxadditionalfeecontribution=</code> is <code>originalPSBTFeeRate * 110</code>.
===Receiver's original PSBT checklist===
@ -229,9 +242,10 @@ 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. <code>*</code>
* If the sender included inputs in the original PSBT owned by the receiver, the receiver must either return error <code>original-psbt-rejected</code> 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 <code>unavailable</code>.
* 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.
** This prevent [[#probing-attack|probing attacks]].
** This prevent reentrant payjoin, where a sender attempts to use payjoin transaction as a new original transaction for a new payjoin.
<code>*</code>: Interactive receivers are not required to validate the original PSBT because they are not exposed to [[#probing-attack|probing attacks]].
@ -243,24 +257,26 @@ The sender should check the payjoin proposal before signing it to prevent a mali
* If the receiver's BIP21 signalled <code>pjos=0</code>, 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
* For each inputs in the proposal:
** Verify that no keypaths is in the PSBT input
** Verify that no partial signature has been filled
** If it is one of the sender's inputs:
** If it is one of the sender's input
*** Verify that input's sequence is unchanged.
*** Verify the PSBT input is not finalized
** If it is one of the receiver's inputs:
*** Verify that <code>non_witness_utxo</code> and <code>witness_utxo</code> are not specified.
** If it is one of the receiver's input
*** Verify the PSBT input is finalized
*** Verify that <code>non_witness_utxo</code> or <code>witness_utxo</code> are filled in.
** Verify that the payjoin proposal inputs all specify the same sequence value.
** Verify that the payjoin proposal did not introduced mixed input's sequence.
** Verify that the payjoin proposal did not introduced 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
* For each outputs in the proposal:
** Verify that no keypaths is 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 <code>maxadditionalfeecontribution</code>. Let's call this amount <code>actual contribution</code>.
*** Make sure the actual contribution is only going towards fees: The <code>actual contribution</code> 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: <code>actual contribution</code> is less than or equal to <code>originalPSBTFeeRate * vsize(sender_input_type) * (count(payjoin_proposal_inputs) - count(original_psbt_inputs))</code>. (see [[#fee-output|Fee output]] section)
** If the output is the payment output and payment output substitution is allowed,
*** The amount that was substracted from the output's value is less than or equal to <code>maxadditionalfeecontribution</code>. Let's call this amount <code>actual contribution</code>.
*** Make sure the actual contribution is only paying fee: The <code>actual contribution</code> 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 fee incurred by additional inputs: <code>actual contribution</code> is less than or equals to <code>originalPSBTFeeRate * vsize(sender_input_type) * (count(payjoin_proposal_inputs) - count(original_psbt_inputs))</code>. (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.
@ -271,15 +287,15 @@ The sender must be careful to only sign the inputs that were present in the orig
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.
* The sender should allow the receiver to not add any inputs. This is useful for the receiver to change the paymout output scriptPubKey type.
* If no input have been added, 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 are several consequences of our proposal:
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.
@ -328,8 +344,8 @@ On top of this the receiver can poison analysis by randomly faking a round amoun
===<span id="output-substitution"></span>Payment output substitution===
Unless disallowed by the sender explicitly via <code>disableoutputsubstitution=true</code> or by the BIP21 URL via the query parameter <code>pjos=0</code>, the receiver is free to decrease the amount or change the scriptPubKey output paying to himself.
Note that if payment output substitution is disallowed, the receiver can still increase the amount of the output. (See [[#reference-impl|the reference implementation]])
Unless disallowed by sender explicitely via `disableoutputsubstitution=true` or by the BIP21 url via query parameter the `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.
@ -342,7 +358,7 @@ A compromised payjoin server could steal the hot wallet outputs of the receiver,
===Impacted heuristics===
Our proposal of payjoin breaks the following blockchain heuristics:
Our proposal of payjoin is breaking the following blockchain heuristics:
* Common inputs heuristics.
@ -392,12 +408,12 @@ With payjoin, the maximum amount of money that can be lost is equal to two payme
==<span id="reference-impl"></span>Reference sender's implementation==
Here is pseudo code of a sender implementation.
<code>RequestPayjoin</code> takes the BIP21 URI of the payment, the wallet and the <code>signedPSBT</code>.
<code>RequestPayjoin</code> takes the bip21 URI of the payment, the wallet and the <code>signedPSBT</code>.
The <code>signedPSBT</code> represents a PSBT which has been fully signed, but not yet finalized.
We then prepare <code>originalPSBT</code> from the <code>signedPSBT</code> via the <code>CreateOriginalPSBT</code> function and get back the <code>proposal</code>.
While we verify the <code>proposal</code>, we also import into it information about our own inputs and outputs from the <code>signedPSBT</code>.
While we verify the <code>proposal</code>, we also import into it informations about our own inputs and outputs from the <code>signedPSBT</code>.
At the end of this <code>RequestPayjoin</code>, 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]].
@ -413,6 +429,7 @@ public async Task<PSBT> RequestPayjoin(
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;
@ -480,6 +497,9 @@ public async Task<PSBT> RequestPayjoin(
// Verify the PSBT input is not finalized
if (proposedPSBTInput.IsFinalized())
throw new PayjoinSenderException("The receiver finalized one of our inputs");
// Verify that <code>non_witness_utxo</code> and <code>witness_utxo</code> 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.
@ -500,6 +520,9 @@ public async Task<PSBT> RequestPayjoin(
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");
}
}
@ -531,19 +554,18 @@ public async Task<PSBT> RequestPayjoin(
if (isOriginalOutput || substitutedOutput)
{
originalOutputs.Dequeue();
if (originalOutput.OriginalTxOut == feeOutput)
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
// The amount that was substracted 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
// This assumes an additional input can be up to 110 bytes.
int additionalInputsCount = proposalGlobalTx.Inputs.Count - originalGlobalTx.Inputs.Count;
if (actualContribution > originalFeeRate * 110 * additionalInputsCount)
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)
@ -578,6 +600,21 @@ public async Task<PSBT> RequestPayjoin(
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)
{
@ -605,7 +642,7 @@ A successful exchange with:
{| class="wikitable"
!InputScriptType
!Original PSBT Fee rate
!Orginal PSBT Fee rate
!maxadditionalfeecontribution
!additionalfeeoutputindex
|-
@ -622,7 +659,7 @@ A successful exchange with:
<pre>cHNidP8BAHMCAAAAAY8nutGgJdyYGXWiBEb45Hoe9lWGbkxh/6bNiOJdCDuDAAAAAAD+////AtyVuAUAAAAAF6kUHehJ8GnSdBUOOv6ujXLrWmsJRDCHgIQeAAAAAAAXqRR3QJbbz0hnQ8IvQ0fptGn+votneofTAAAAAAEBIKgb1wUAAAAAF6kU3k4ekGHKWRNbA1rV5tR5kEVDVNCHAQcXFgAUx4pFclNVgo1WWAdN1SYNX8tphTABCGsCRzBEAiB8Q+A6dep+Rz92vhy26lT0AjZn4PRLi8Bf9qoB/CMk0wIgP/Rj2PWZ3gEjUkTlhDRNAQ0gXwTO7t9n+V14pZ6oljUBIQMVmsAaoNWHVMS02LfTSe0e388LNitPa1UQZyOihY+FFgABABYAFEb2Giu6c4KO5YW0pfw3lGp9jMUUAAA=</pre>
<code>payjoin proposal</code>
<pre>cHNidP8BAJwCAAAAAo8nutGgJdyYGXWiBEb45Hoe9lWGbkxh/6bNiOJdCDuDAAAAAAD+////jye60aAl3JgZdaIERvjkeh72VYZuTGH/ps2I4l0IO4MBAAAAAP7///8CJpW4BQAAAAAXqRQd6EnwadJ0FQ46/q6NcutaawlEMIcACT0AAAAAABepFHdAltvPSGdDwi9DR+m0af6+i2d6h9MAAAAAAQEgqBvXBQAAAAAXqRTeTh6QYcpZE1sDWtXm1HmQRUNU0IcAAQEggIQeAAAAAAAXqRTI8sv5ymFHLIjkZNRrNXSEXZHY1YcBBxcWABRfgGZV5ZJMkgTC1RvlOU9L+e2iEAEIawJHMEQCIGe7e0DfJaVPRYEKWxddL2Pr0G37BoKz0lyNa02O2/tWAiB7ZVgBoF4s8MHocYWWmo4Q1cyV2wl7MX0azlqa8NBENAEhAmXWPPW0G3yE3HajBOb7gO7iKzHSmZ0o0w0iONowcV+tAAAA</pre>
<pre>cHNidP8BAJwCAAAAAo8nutGgJdyYGXWiBEb45Hoe9lWGbkxh/6bNiOJdCDuDAAAAAAD+////jye60aAl3JgZdaIERvjkeh72VYZuTGH/ps2I4l0IO4MBAAAAAP7///8CJpW4BQAAAAAXqRQd6EnwadJ0FQ46/q6NcutaawlEMIcACT0AAAAAABepFHdAltvPSGdDwi9DR+m0af6+i2d6h9MAAAAAAAEBIICEHgAAAAAAF6kUyPLL+cphRyyI5GTUazV0hF2R2NWHAQcXFgAUX4BmVeWSTJIEwtUb5TlPS/ntohABCGsCRzBEAiBnu3tA3yWlT0WBClsXXS9j69Bt+waCs9JcjWtNjtv7VgIge2VYAaBeLPDB6HGFlpqOENXMldsJezF9Gs5amvDQRDQBIQJl1jz1tBt8hNx2owTm+4Du4isx0pmdKNMNIjjaMHFfrQAAAA==</pre>
<code>payjoin proposal filled with sender's information</code>
<pre>cHNidP8BAJwCAAAAAo8nutGgJdyYGXWiBEb45Hoe9lWGbkxh/6bNiOJdCDuDAAAAAAD+////jye60aAl3JgZdaIERvjkeh72VYZuTGH/ps2I4l0IO4MBAAAAAP7///8CJpW4BQAAAAAXqRQd6EnwadJ0FQ46/q6NcutaawlEMIcACT0AAAAAABepFHdAltvPSGdDwi9DR+m0af6+i2d6h9MAAAAAAQEgqBvXBQAAAAAXqRTeTh6QYcpZE1sDWtXm1HmQRUNU0IcBBBYAFMeKRXJTVYKNVlgHTdUmDV/LaYUwIgYDFZrAGqDVh1TEtNi300ntHt/PCzYrT2tVEGcjooWPhRYYSFzWUDEAAIABAACAAAAAgAEAAAAAAAAAAAEBIICEHgAAAAAAF6kUyPLL+cphRyyI5GTUazV0hF2R2NWHAQcXFgAUX4BmVeWSTJIEwtUb5TlPS/ntohABCGsCRzBEAiBnu3tA3yWlT0WBClsXXS9j69Bt+waCs9JcjWtNjtv7VgIge2VYAaBeLPDB6HGFlpqOENXMldsJezF9Gs5amvDQRDQBIQJl1jz1tBt8hNx2owTm+4Du4isx0pmdKNMNIjjaMHFfrQABABYAFEb2Giu6c4KO5YW0pfw3lGp9jMUUIgICygvBWB5prpfx61y1HDAwo37kYP3YRJBvAjtunBAur3wYSFzWUDEAAIABAACAAAAAgAEAAAABAAAAAAA=</pre>
@ -637,7 +674,7 @@ A successful exchange with:
==Backward compatibility==
The receivers advertise payjoin capabilities through [[bip-0021.mediawiki|BIP21's URI Scheme]].
The receivers are advertising payjoin capabilities through [[bip-0021.mediawiki|BIP21's URI Scheme]].
Senders not supporting payjoin will just ignore the <code>pj</code> variable and thus, will proceed to normal payment.

View File

@ -2,12 +2,14 @@
BIP: 79
Layer: Applications
Title: Bustapay :: a practical coinjoin protocol
Authors: Ryan Havar <rhavar@protonmail.com>
Status: Closed
Author: Ryan Havar <rhavar@protonmail.com>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0079
Status: Replaced
Type: Informational
Assigned: 2018-10-05
Created: 2018-10-05
License: CC0-1.0
Proposed-Replacement: 78
Superseded-By: 78
</pre>
@ -72,7 +74,7 @@ Should the receiver reject a transaction, it should not attempt to propagate it
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 receiver's utxo set, it is essential that the receiver always returns the same contributed inputs when it's seen the same inputs.
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.
@ -82,7 +84,7 @@ After adding inputs to the transaction, the receiver generally will want to adju
=== 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: *"
The receiver must sign all contributed inputs in the partial transaction. The partial transaction should also remove all witnesses from the 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 ===
@ -95,7 +97,7 @@ The sender *must* do important validation on the partial transaction. They *must
=== 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 by the sender, with the hope the sender blindly signs everything.
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 ===

View File

@ -1,11 +1,13 @@
<pre>
BIP: 80
Title: Hierarchy for Non-Colored Voting Pool Deterministic Multisig Wallets
Authors: Justus Ranvier <justus@opentransactions.org>
Jimmy Song <jimmy@monetas.net>
Status: Closed
Author: Justus Ranvier <justus@opentransactions.org>
Jimmy Song <jimmy@monetas.net>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0080
Status: Deferred
Type: Informational
Assigned: 2014-08-11
Created: 2014-08-11
License: PD
</pre>
@ -33,7 +35,7 @@ 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.
Purpose is a constant set following the BIP43 recommendation to: the ASCII value of "80" with the most signifigant 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.

View File

@ -1,11 +1,13 @@
<pre>
BIP: 81
Title: Hierarchy for Colored Voting Pool Deterministic Multisig Wallets
Authors: Justus Ranvier <justus@opentransactions.org>
Jimmy Song <jimmy@monetas.net>
Status: Closed
Author: Justus Ranvier <justus@opentransactions.org>
Jimmy Song <jimmy@monetas.net>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0081
Status: Deferred
Type: Informational
Assigned: 2014-08-11
Created: 2014-08-11
License: PD
</pre>
@ -33,7 +35,7 @@ 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.
Purpose is a constant set following the BIP43 recommendation to: the ASCII value of "81" with the most signifigant 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.

View File

@ -2,10 +2,12 @@
BIP: 83
Layer: Applications
Title: Dynamic Hierarchical Deterministic Key Trees
Authors: Eric Lombrozo <eric@ciphrex.com>
Status: Closed
Type: Specification
Assigned: 2015-11-16
Author: Eric Lombrozo <eric@ciphrex.com>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0083
Status: Rejected
Type: Standards Track
Created: 2015-11-16
License: PD
</pre>
@ -51,7 +53,7 @@ p //' n instead of p / 0' / n
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 (2<sup>31</sup> - 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.
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 (2<sup>31</sup> - 1) for this purpose. However, we believe doing so introduces more ideosyncracies 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==
@ -81,7 +83,7 @@ We can continue creating subaccounts indefinitely using this scheme.
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.
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==

View File

@ -2,12 +2,12 @@
BIP: 84
Layer: Applications
Title: Derivation scheme for P2WPKH based accounts
Authors: Pavol Rusnak <stick@satoshilabs.com>
Author: Pavol Rusnak <stick@satoshilabs.com>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0084
Status: Deployed
Type: Specification
Assigned: 2017-12-28
Status: Final
Type: Informational
Created: 2017-12-28
License: CC0-1.0
</pre>
@ -61,7 +61,7 @@ Additional registered version bytes are listed in [[https://github.com/satoshila
==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.
This BIP is not backwards compatible by design as described under [#considerations]. An incompatible wallet will not discover accounts at all and the user will notice that something is wrong.
==Test vectors==

View File

@ -2,30 +2,27 @@
BIP: 85
Layer: Applications
Title: Deterministic Entropy From BIP32 Keychains
Authors: Ethan Kosakovsky <ethankosakovsky@protonmail.com>
Aneesh Karve <dowsing.seaport0d@icloud.com>
Status: Deployed
Author: Ethan Kosakovsky <ethankosakovsky@protonmail.com>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0085
Status: Draft
Type: Informational
Assigned: 2020-03-20
License: BSD-2-Clause OR OPUBL-1.0
Version: 2.0.0
Created: 2020-03-20
License: BSD-2-Clause
OPL
</pre>
==Abstract==
''"One Seed to rule them all,''<br>
''One Key to find them,''<br>
''One Path to bring them all,''<br>
''"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.
@ -36,16 +33,13 @@ The terminology related to keychains used in the wild varies widely, for example
# '''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 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.
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 scenarios are particularly satisfactory for security reasons. For example, some wallets may be inherently less secure like hot wallets on smartphones, Join Market 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 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.
There is added complication with wallets that implement other standards, or no standards at all. 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 also 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.
@ -53,13 +47,9 @@ Ultimately, all of the mnemonic/seed schemes start with some "initial entropy" t
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: <code>HMAC-SHA512(key="bip-entropy-from-k", msg=k)</code>
<ref name="hmac-sha512">
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 hardened 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.
</ref>.
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.
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: <code>HMAC-SHA512(key="bip-entropy-from-k", msg=k)</code>. The result produces 512 bits of entropy. Each application SHOULD use up to the required number of bits necessary for their operation truncating the rest.
The HMAC-SHA512 function is specified in [https://tools.ietf.org/html/rfc4231 RFC 4231].
The HMAC-SHA512 function is specified in [http://tools.ietf.org/html/rfc4231 RFC 4231].
===Test vectors===
@ -88,7 +78,7 @@ BIP85-DRNG-SHAKE256 is a deterministic random number generator for cryptographic
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)
rsa_key = RSA.generate_key(4096, drng_reader.read())
===Test Vectors===
INPUT:
@ -101,13 +91,28 @@ OUTPUT
* DRNG(80 bytes)=b78b1ee6b345eae6836c2d53d33c64cdaf9a696487be81b03e822dc84b3f1cd883d7559e53d175f243e4c349e822a957bbff9224bc5dde9492ef54e8a439f6bc8c7355b87a925a37ee405a7502991111
==Reference Implementation==
* Python library implementation: [https://github.com/ethankosakovsky/bip85]
* JavaScript library implementation: [https://github.com/hoganri/bip85-js]
===Other Implementations===
* JavaScript library implementation: [https://github.com/hoganri/bip85-js]
* Coldcard Firmware: [https://github.com/Coldcard/firmware/pull/39]
* Ian Coleman's Mnemonic Code Converter: [https://github.com/iancoleman/bip39] and [https://iancoleman.io/bip39/]
* AirGap Vault: [https://github.com/airgap-it/airgap-vault/commit/d64332fc2f332be622a1229acb27f621e23774d6]
* btc_hd_wallet: [https://github.com/scgbckbone/btc-hd-wallet]
==Applications==
The Application number defines how entropy will be used post processing. Some basic examples follow:
Derivation paths follow the format <code>m/83696968'/{app_no}'/{index}'</code>, 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.
Derivation path uses the format <code>m/83696968'/{app_no}'/{index}'</code> where ''{app_no}'' is the path for the application, and ''{index}'' is the index.
===BIP39===
Application number: 39'
@ -150,10 +155,6 @@ Language Table
|-
| Czech
| 8'
|-
| Portuguese
| 9'
|-
|}
Words Table
@ -167,18 +168,10 @@ Words Table
| 128 bits
| 12'
|-
| 15 words
| 160 bits
| 15'
|-
| 18 words
| 192 bits
| 18'
|-
| 21 words
| 224 bits
| 21'
|-
| 24 words
| 256 bits
| 24'
@ -200,7 +193,7 @@ OUTPUT:
====18 English words====
BIP39 English 18 word mnemonic seed
192 bits of entropy as input to BIP39 to derive 18 word mnemonic
196 bits of entropy as input to BIP39 to derive 18 word mnemonic
INPUT:
* MASTER BIP32 ROOT KEY: xprv9s21ZrQH143K2LBWUUQRFXhucrQqBpKdRRxNVq2zBqsx8HVqFk2uYo8kmbaLLHRdqtQpUm98uKfu3vca1LqdGhUtyoFnCNkfmXRyPXLjbKb
@ -226,16 +219,7 @@ OUTPUT:
===HD-Seed WIF===
Application number: 2'
Uses the most significant 256 bits<ref name="curve-order">
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:
<blockquote>
In case parse<sub>256</sub>(I<sub>L</sub>) ≥ n or k<sub>i</sub> = 0, the resulting key is invalid, and one should proceed with the next value for i. (Note: this has probability lower than 1 in 2<sup>127</sup>.)
</blockquote>
</ref>
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.
Uses 256 bits[1] of entropy as the secret exponent to derive a private key and encode as a compressed WIF which will be used as the hdseed for Bitcoin Core wallets.
Path format is <code>m/83696968'/2'/{index}'</code>
@ -250,11 +234,7 @@ OUTPUT
===XPRV===
Application number: 32'
Taking 64 bytes of the HMAC digest, the first 32 bytes are the chain code, and the second 32 bytes<ref name="curve-order" /> 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.
Taking 64 bytes of the HMAC digest, the first 32 bytes are the chain code, and second 32 bytes[1] are the private key for BIP32 XPRV value. Child number, depth, and parent fingerprint are forced to zero.
Path format is <code>m/83696968'/32'/{index}'</code>
@ -289,12 +269,12 @@ The derivation path format is: <code>m/83696968'/707764'/{pwd_len}'/{index}'</co
`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
[https://datatracker.ietf.org/doc/html/rfc4648 Base64] encode the 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:<br>
R = 64 (Base64 - do not count padding)<br>
R = 64 (base64 - do not count padding)<br>
L = pwd_len<br>
Entropy = log2(R ** L)<br>
@ -317,7 +297,7 @@ INPUT:
* PATH: m/83696968'/707764'/21'/0'
OUTPUT
* DERIVED ENTROPY=74a2e87a9ba0cdd549bdd2f9ea880d554c6c355b08ed25088cfa88f3f1c4f74632b652fd4a8f5fda43074c6f6964a3753b08bb5210c8f5e75c07a4c2a20bf6e9
* DERIVED ENTROPY=d7ad61d4a76575c5bad773feeb40299490b224e8e5df6c8ad8fe3d0a6eed7b85ead9fef7bcca8160f0ee48dc6e92b311fc71f2146623cc6952c03ce82c7b63fe
* DERIVED PWD=dKLoepugzdVJvdL56ogNV
===PWD BASE85===
@ -327,8 +307,8 @@ The derivation path format is: <code>m/83696968'/707785'/{pwd_len}'/{index}'</co
`10 <= pwd_len <= 80`
Base85 encode all 64 bytes of entropy.
Remove any spaces or new lines inserted by Base85 encoding process. Slice Base85 result string
Base85 encode the 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:<br>
@ -347,7 +327,7 @@ Entropy = log2(R ** L)<br>
|-
| 30 || 192.0
|-
| 80 || 512.0
| 20 || 512.0
|}
INPUT:
@ -380,104 +360,39 @@ Keys allocated for RSA-GPG purposes use the following scheme:
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 <code>'2009-01-03 18:15:05'</code> UTC)<ref>The human-readable datetime string was incorrectly noted as '2009-01-03 18:05:05' prior to v2.0.0 of this BIP, so implementations that relied on it rather than UNIX Epoch timestamp 1231006505 will produce different key fingerprints.</ref> 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 <code>faketime</code>).
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 <code>'2009-01-03 18:05:05'</code> 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 <code>faketime</code>).
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.
GPG capable smart-cards SHOULD be 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: <code>m/83696968'/89101'/{sides}'/{rolls}'/{index}'</code>
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
<code>[0, N-1]</code>, 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 <code>bytes_per_roll</code> bytes from the DRNG.
Trim any bits in excess of <code>bits_per_roll</code> (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==
==Discussion==
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==
===2.0.0 (2025-09-19)===
====Fixed====
* Fixed the human-readable datetime string for BIP85 GPG Keys that was incorrectly stated as '2009-01-03 18:05:05' rather than '2009-01-03 18:15:05'. Implementations that relied on the previously incorrect datetime string instead of UNIX Epoch timestamp 1231006505 will produce different key fingerprints.
===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==
<references />
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 compromized. 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.
==Acknowledgements==
Many thanks to Peter Gray and Christopher Allen for their input, and to Peter for suggesting extra application use cases.
==References==
BIP32, BIP39
==Footnotes==
[1] There is a very small chance that you'll make an invalid key that is zero or bigger 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 parse<sub>256</sub>(I<sub>L</sub>) is 0 or ≥ n, the resulting key is invalid, and one should proceed with the next value for i. (Note: this has probability lower than 1 in 2<sup>127</sup>.)
==Copyright==
This BIP is dual-licensed under the Open Publication License and BSD 2-clause license.

View File

@ -2,10 +2,12 @@
BIP: 86
Layer: Applications
Title: Key Derivation for Single Key P2TR Outputs
Authors: Ava Chow <me@achow101.com>
Status: Deployed
Type: Specification
Assigned: 2021-06-22
Author: Ava Chow <me@achow101.com>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0086
Status: Draft
Type: Standards Track
Created: 2021-06-22
License: BSD-2-Clause
</pre>

View File

@ -2,10 +2,12 @@
BIP: 87
Layer: Applications
Title: Hierarchy for Deterministic Multisig Wallets
Authors: Robert Spigler <RobertSpigler@ProtonMail.ch>
Status: Complete
Type: Specification
Assigned: 2020-03-11
Author: Robert Spigler <RobertSpigler@ProtonMail.ch>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0087
Status: Proposed
Type: Standards Track
Created: 2020-03-11
License: BSD-2-Clause
</pre>
@ -38,7 +40,7 @@ A modern standardization is needed for multisig derivation paths. There are som
m / purpose' / cosigner_index / change / address_index
</pre>
BIP45 unnecessarily demands a single script type (here, P2SH). In addition, BIP45 sets <code>cosigner_index</code> in order to sort the <code>purpose'</code> public keys of each cosigner. This too is redundant, as descriptors can set the order of the public keys with <code>multi</code> or have them sorted lexicographically (as described in [https://github.com/bitcoin/bips/blob/master/bip-0067.mediawiki BIP67]) with <code>sortedmulti</code>. 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.
BIP45 unecessarily demands a single script type (here, P2SH). In addition, BIP45 sets <code>cosigner_index</code> in order to sort the <code>purpose'</code> public keys of each cosigner. This too is redundant, as descriptors can set the order of the public keys with <code>multi</code> or have them sorted lexicographically (as described in [https://github.com/bitcoin/bips/blob/master/bip-0067.mediawiki BIP67]) with <code>sortedmulti</code>. 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:
@ -46,7 +48,7 @@ The second multisignature "standard" in use is m/48', which specifies:
m / purpose' / coin_type' / account' / script_type' / change / address_index
</pre>
Rather than following in BIP 44/49/84's path and having a separate BIP per script after P2SH (BIP45), vendors decided to insert <code>script_type'</code> 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, <code>script_type</code> list.
Rather than following in BIP 44/49/84's path and having a separate BIP per script after P2SH (BIP45), vendors decided to insert <code>script_type'</code> 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 maintainence work by getting rid of new BIPs-per-script, it still requires maintaining an updated, redundant, <code>script_type</code> 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 <ref>'''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.</ref>.
@ -103,7 +105,7 @@ 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 <code>account'</code> level.
This prevents key reuse - across ECDSA and Schnorr signatures, across different script types, and in between the same wallet types.
This prevents key reuse - across ECDSA and Schnorr signatures, across different script types, and inbetween the same wallet types.
===Change===

View File

@ -2,10 +2,12 @@
BIP: 88
Layer: Applications
Title: Hierarchical Deterministic Path Templates
Authors: Dmitry Petukhov <dp@simplexum.com>
Status: Complete
Author: Dmitry Petukhov <dp@simplexum.com>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0088
Status: Proposed
Type: Informational
Assigned: 2020-06-23
Created: 2020-06-23
License: BSD-2-Clause
</pre>
@ -25,7 +27,7 @@ This BIP is licensed under the 2-clause BSD license.
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,
industry participants to implement custom derivation shemes 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
@ -39,18 +41,18 @@ addresses differently than the one they used before.
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
At the time of writing, this website has used their own format to succintly describe multiple
derivation paths. As far as author knows, it was the only publicitly 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 <code>|</code> to denote alternative derivation indexes
(example: <code>m/|44'|49'|84'/0'/0'</code>) or whole alternative paths (<code>m/44'/0'/0'|m/44'/1'/0'</code>).
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
described in this BIP is intended for unambigouos 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 <code>|</code> in the template could allow. Wider range of paths can be defined in a single template more
succinctly and unambiguously.
succintly and unambiguously.
===Intended use and advantages===
@ -69,7 +71,7 @@ into using well-known paths, or convince other vendors to support their custom p
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.
that succintly 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.
@ -87,7 +89,7 @@ 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.
The format for the template was choosen to make it easy to read, convenient and visually unambigous.
Template starts with optional prefix <code>m/</code>, and then one or more sections delimited by the slash character (<code>/</code>).
@ -125,13 +127,13 @@ Constraints:
# To avoid ambiguity, an index range that matches a single value MUST be specified as Unit range.
# To avoid ambiguity, an index range <code>0-2147483647</code> 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.
# 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 preceeding range.
# To avoid ambiguity, all representations of integer values larger than 0 MUST NOT start with character <code>0</code> (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 <code>h</code> or <code>'</code>).
# To avoid ambiguity, trailing slashes (for example, <code>1/2/</code>) and duplicate slashes (for example, <code>0//1</code>) 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.
It may be desireable 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:
@ -210,7 +212,7 @@ There is a discussion on path templating for bitcoin script descriptors at https
<code>m/{44,49,84}'/0'/0'/{0-1}/{0-50000}</code> 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)],
[[(2147483692, 2147483692), (2147483697, 2147483697), (2147483732, 2147483732)),
[(2147483648, 2147483648)],
[(2147483648, 2147483648)],
[(0, 1)],

View File

@ -1,405 +0,0 @@
<pre>
BIP: 89
Layer: Applications
Title: Chain Code Delegation
Authors: Jesse Posner <jesse@vora.io>
Jurvis Tan <jurvis@block.xyz>
Comments-Summary: No comments yet.
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0089
Status: Draft
Type: Specification
Assigned: 2025-12-03
License: BSD-3-Clause
Discussion: https://delvingbitcoin.org/t/chain-code-delegation-private-access-control-for-bitcoin-keys/1837
Requires: 32, 340, 341
</pre>
== Abstract ==
Chain Code Delegation (CCD) is a method for multi-signature wallets in which a privileged participant withholds BIP32 chain codes from one or more non-privileged participants, and supplies per-input scalar tweaks at signing time. This allows non-privileged participants to co-sign transactions without learning wallet-wide derivations, balances, or signing activity from other spending combinations. CCD defines the tweak exchange needed for verification and signing behavior when the signer does not possess a chain code.
== Motivation ==
In multisig deployments, sharing extended public keys (xpubs) or descriptors enables all participants to scan the chain and infer counterparties' activity. CCD limits that visibility by ensuring non-privileged participants only ever hold a non-extended keypair and only receive the minimum per-spend data needed to sign. The procedure keeps policy enforcement feasible for the non-privileged signer while preserving balance privacy, which is particularly useful in collaborative custody arrangements where the wallet owner wants balance privacy from their custodian.
== Terminology ==
In CCD, the chain code is the object of delegation—not signing authority. A participant who gives up their chain code delegates it to another.
* A "Delegator" is a participant who delegates their chain code to another party. They hold only a non-extended keypair and receive scalar tweaks from the delegatee when asked to sign.
* A "Delegatee" is a participant who receives and retains a delegated chain code for another participant's public key, and computes derivation tweaks for that participant.
* A "Participant" is any key holder that can co-sign for UTXOs in the wallet (including delegators and delegatees).
* A "Non-hardened derivation" is a BIP32 child derivation where index &lt; 2^31.
== Overview ==
CCD operates by having Delegatees deprive Delegators of BIP32 chain codes during setup and later conveying the aggregated scalar tweak computed as the sum of non-hardened derivation tweaks along the remaining path to the child key used by a given input or change output. A Delegator uses the tweak to compute the child keys for verification and signing without being able to derive or recognize keys for other paths.
== Specification ==
=== Key material and setup ===
* '''Delegator key:''' Each delegator generates a standard (non-extended) secp256k1 keypair and provides the public key to the counterparties. A delegator MUST NOT retain or be provided a chain code for this key.
* '''Delegated chain code:''' A designated delegatee computes and retains a BIP32 chain code bound to the delegator's public key, forming an xpub that MUST NOT be disclosed to the delegator. The delegatee MAY share this xpub with other delegatees.
* '''Other participants:''' Non-delegator participants use conventional extended keys and share the public half as appropriate for the wallet descriptor.
* '''Derivation constraints:''' The delegatee holds an extended public key for the delegator. All derivation from this extended key MUST be non-hardened, as hardened derivation requires the private key, which the delegatee does not possess.
=== 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 ''y<sup>2</sup> = x<sup>3</sup> + 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 &ge; 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 ''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..2<sup>256</sup>-1'', returns the point ''P'' for which ''x(P) = x''<ref>
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 = x<sup>3</sup> + 7 mod p'' and they can be computed as ''y = &plusmn;c<sup>(p+1)/4</sup> 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''.</ref> 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 &gt; p-1''.
*** Let ''c = x<sup>3</sup> + 7 mod p''.
*** Let ''y' = c<sup>(p+1)/4</sup> mod p''.
*** Fail if ''c &ne; y'<sup>2</sup> 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 ''hash256<sub>tag</sub>(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)''.
** The function ''hash512<sub>tag</sub>(x)'' where ''tag'' is a UTF-8 encoded tag name and ''x'' is a byte array returns the 64-byte hash ''SHA512(SHA512(tag) || SHA512(tag) || x)''.
* Other:
** Tuples are written by listing the elements within parentheses and separated by commas. For example, ''(2, 3, 1)'' is a tuple.
=== Tweak Calculation ===
To produce CCD tweak data, a delegatee computes a per-participant scalar that aggregates the non-hardened derivation tweaks along the remaining path. Let the extended key retained by the delegatee be P at depth d, and let the target index vector be I = (i<sub>d+1</sub>, …, i<sub>n</sub>) with each i<sub>k</sub> < 2<sup>31</sup>.
<div>
Algorithm ''ComputeBIP32Tweak(P, I)'':
* Inputs:
** ''P'': base public key at depth ''d''
** ''I = (i<sub>d+1</sub>, …, i<sub>n</sub>)'': ordered sequence of non-hardened child indices
* Let ''t = 0'' and ''E = P''.
* For each index ''i'' in ''I'' (from left to right):
** Run the BIP32 non-hardened derivation ''CKDpub'' on ''E'' with child index ''i'', yielding the child extended key ''P<sub>child</sub>'' and its scalar tweak ''δ'' (the parse<sub>256</sub>(''I<sub>L</sub>'') term from BIP32).
** Let ''t = (t + δ) mod n''.
** Let ''E = P<sub>child</sub>''.
* If ''I'' is empty, let ''P = P''; otherwise let ''P = P<sub>child</sub>'' from the final iteration.
* Return ''(t, P)''.
</div>
Any attempt to apply a hardened derivation (index ≥ 2<sup>31</sup>) MUST fail. Delegatees MAY discard P after extracting t if it is not otherwise required.
=== Delegation Bundle ===
CCD requires the delegatee to provide per-participant tweaks for inputs and (optionally) change outputs. Tweaks for change outputs are only required if a delegator wants to be able to compute the amount of bitcoin they are spending.
A delegatee MUST provide each delegator with, for every signing context, a collection of tuples (P<sub>i</sub>, t<sub>i</sub>) where P<sub>i</sub> is the participant's base public key disclosed to the delegator and t<sub>i</sub> is the aggregated tweak returned by ''ComputeBIP32Tweak''. The scalar t<sub>i</sub> MUST be encoded as a 32-byte big-endian integer.
The transport that carries this bundle is out of scope for this proposal; implementers MAY use PSBT proprietary keys, RPC payloads, or bespoke messages as long as the delegator can authenticate the origin of the data. Delegatees SHOULD attach the witness script (or sufficient script template information) built with the tweaked keys when the delegator is expected to verify the input or enforce spending policy on change outputs.
Delegators use the supplied CCD tweak bundle during verification (see ''Delegator input and change verification'') and signature generation (see ''DelegatorSign''). The message to be signed is provided separately as part of the standard signing protocol and is not part of the CCD-specific bundle.
=== Signing Modes ===
This BIP supports two modes:
* '''Nonblinded.''' The delegator receives the tweak for the child public key and the message. The delegator learns only about the specific child keys and transactions it signs for; it does not learn the wider address space.
* '''Blinded.''' The delegator receives only a blinded challenge and parity bits. The delegator learns nothing about the message or child key for which it produces a signature.
Both modes produce valid BIP340 signatures.
====Non-Blinded Signing====
For non-blinded signing, the delegator can produce signatures as usual using the tweaked key.
=====Delegator input and change verification (Optional)=====
A delegator MAY validate the data it receives before producing signatures.
For example, input verification reassures the delegator that every tweaked key they are asked to sign for corresponds to a wallet input they recognise. Change verification lets them establish the net outflow and enforce spending policy.
Both checks rely on the same delegated tweak bundle described above.
=====Input verification=====
For each input, the delegatee SHOULD disclose the descriptor template, the untweaked participant keys, the input witness script, and the per-participant tweaks. The delegator then applies the following procedure.
<div>
Algorithm ''InputVerification(D, W, T)'':
* Inputs:
** ''D'': wallet policy or descriptor template expressed in terms of the untweaked participant keys ''P<sub>i</sub>''
** ''W'': witness script disclosed for the input under review
** ''T'': mapping from each ''P<sub>i</sub>'' to a 32-byte big-endian tweak scalar ''t<sub>i</sub>''
* For each participant key ''P<sub>i</sub>'' referenced in ''D'':
** Retrieve ''t<sub>i</sub>'' from ''T''; fail if the entry is missing or malformed.
** If the verifier controls the corresponding private key ''d<sub>i</sub>'', let ''d<sub>i</sub> = (d<sub>i</sub> + t<sub>i</sub>) mod n'' and ''P<sub>i</sub> = d<sub>i</sub> · G''; otherwise let ''P<sub>i</sub> = P<sub>i</sub> + t<sub>i</sub> · G''.
* Let ''D'' be the descriptor formed by substituting every occurrence of ''P<sub>i</sub>'' in ''D'' with ''P<sub>i</sub>''.
* Derive the witness script ''W'' from ''D''.
* Return <code>true</code> if ''W = W'', otherwise <code>false</code>.
</div>
Successful verification of an input confirms that the delegator is signing for a script that belongs to the wallet and that the aggregate tweak values align with the expected policy.
=====Change-output verification=====
When change outputs are disclosed, the delegator can perform an analogous check to ensure the destination script matches their policy template and to calculate outflows. Let D be the descriptor expressed in untweaked keys, W the provided witness script, and T the tweak mapping:
<div>
Algorithm ''ChangeOutputVerification(D, W, T)'':
* Inputs:
** ''D'': wallet policy or descriptor template expressed in terms of the untweaked participant keys ''P<sub>i</sub>''
** ''W'': witness script disclosed for the change output
** ''T'': mapping from each ''P<sub>i</sub>'' to a 32-byte big-endian tweak scalar ''t<sub>i</sub>''
* For each participant key ''P<sub>i</sub>'' referenced in ''T'':
** Retrieve ''t<sub>i</sub>'' from ''T''; fail if the entry is missing or malformed.
** If the verifier controls the corresponding private key ''d<sub>i</sub>'', let ''d<sub>i</sub> = (d<sub>i</sub> + t<sub>i</sub>) mod n'' and ''P<sub>i</sub> = d<sub>i</sub> · G''; otherwise let ''P<sub>i</sub> = P<sub>i</sub> + t<sub>i</sub> · G''.
* Let ''D'' be the descriptor formed by substituting every occurrence of ''P<sub>i</sub>'' in ''D'' with ''P<sub>i</sub>''.
* Derive the witness script ''W'' from ''D''.
* Return <code>true</code> if ''W = W'', otherwise <code>false</code>.
</div>
Successful verification ensures the change output commits to the tweaked participant keys implied by the CCD tweaks, preserving the intended policy.
The delegator may perform additional application-specific verification on the transaction (e.g., recipient addresses, amounts, compliance checks) using the message ''m''. In the concurrently secure blinded mode, such policies can be enforced via zero-knowledge proofs that encode predicates about ''m''. Specification of such policies is outside the scope of this BIP.
=====Delegator Signing=====
A delegator that holds only its base secret key <code>x</code> and public key <code>P</code> uses the delegated tweak bundle to derive per-input signing keys. The delegator MAY first call ''InputVerification'' and ''ChangeOutputVerification'' on any input and change output that provides a tweak in order to confirm outflow or policy requirements before signing.
<div>
Algorithm ''DelegatorSign(t, x, m)'':
* Inputs:
** ''t'': aggregated tweak for the signing context (scalar mod ''n'')
** ''x'': delegator base secret key
** ''m'': message to be signed (for example, a transaction digest under the desired SIGHASH policy)
* Let ''x = (x + t) mod n''.
* Use secret key ''x'' to produce the required signature ''σ'' under the indicated policy.
* Return ''σ''.
</div>
The delegatee is responsible for inserting ''σ'' into the surrounding protocol (e.g., a PSBT, transaction witness, or adaptor signature exchange).
====Blinded Signing====
The delegator learns neither the message, the challenge, or the public key used in the BIP340 signature, only a blinded challenge e'.
This blindsigning protocol specifies how a delegator can produce a blind partial Schnorr signature that a delegatee can unblind into a standard [https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki BIP340] signature under a possibly tweaked Xonly public key. The notation, algorithmic patterns, and testvector style are adapted from [BIP327 (MuSig2)] and from the [https://github.com/siv2r/bip-frost-signing FROST Signing BIP]. The design follows the “plain” blind Schnorr flow described in Concurrently Secure Blind Schnorr Signatures ([https://eprint.iacr.org/2022/1676 ePrint 2022/1676]), but without the concurrency hardening from that work.
The output signature is a BIP340 Schnorr signature valid under an Xonly key obtained by applying a sequence of plain (e.g. BIP32) and Xonly (e.g. Tapscript) tweaks to the signers plain public key. Consequently the protocol is compatible with [https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki BIP341]. The delegator learns neither the message, the challenge, or the public key used in the BIP340 signature, only a blinded challenge e'.
The plain protocol here is '''not''' concurrently secure. A signer '''MUST NOT''' run multiple blind signing sessions in parallel or interleave state across sessions. A signer '''MUST''' refuse any new blindnonce requests while a previous blindsignature request is outstanding, or '''MUST''' irrevocably discard (and never reuse) any inflight blind nonce commitments that have not resulted in a signature, before accepting new ones.
To obtain concurrency security as in ([https://eprint.iacr.org/2022/1676 ePrint 2022/1676]), the delegatee first sends an encryption of (m, a, b) before the signer commits to the blind nonce; later, the delegatee includes a zeroknowledge proof binding the produced challenge to that encrypted tuple. That proof can additionally encode policy predicates about m (spend limits, velocity controls, etc.). A complete specification of this variant is outside the scope of this BIP.
The following sections fully specify the non-concurrent blind signing protocol.
===== Overview =====
* '''Round 1 (blind nonce).''' The delegator runs ''BlindNonceGen'' to produce ''blindsecnonce'' and ''blindpubnonce'' and sends ''blindpubnonce'' to the delegatee.
* '''Round 2 (challenge).''' The delegatee runs ''BlindChallengeGen'' using the message ''m'', ''blindpubnonce'', the base public key ''pk'', and a list of ordinary and X-only tweaks, to produce a ''session context'' (kept locally for unblinding), a ''blindchallenge'', and two booleans ''pk_parity'' and ''nonce_parity''. The delegatee sends ''blindchallenge'', ''pk_parity'', and ''nonce_parity'' to the signer.
* '''Round 3 (blind signature).''' The delegator runs ''BlindSign'' with ''sk'', ''blindchallenge'', ''blindsecnonce'', ''pk_parity'', and ''nonce_parity'' and returns ''blindsignature''. The delegatee completes by calling ''UnblindSignature'' with the stored session context and ''blindsignature'' to obtain the final BIP340 signature ''sig''.
''BlindSign'' '''MUST NOT''' be executed twice with the same ''blindsecnonce''. As a defense, implementations '''SHOULD''' overwrite the first 64 bytes of ''blindsecnonce'' with zeros after they have been read by ''BlindSign''.
=====Key Tweaking=====
======Tweak Context======
The Tweak Context is a data structure consisting of the following elements:
* The point ''Q'' representing the potentially tweaked public key: an elliptic curve point
* The accumulated tweak ''tacc'': an integer with ''0 &le; tacc < n''
* The value ''gacc'' : 1 or -1 mod n
We write "Let ''(Q, gacc, tacc) = tweak_ctx''" to assign names to the elements of a Tweak Context.
<div>
Algorithm ''TweakCtxInit(pk)'':
* Input:
** The base public key pk: a 33-byte array
* Let ''Q = cpoint(pk)''
* Fail if ''is_infinite(Q)''
* Let ''gacc = 1''
* Let ''tacc = 0''
* Return ''tweak_ctx = (Q, gacc, tacc)''
</div>
<div>
Algorithm ''ApplyTweak(tweak_ctx, tweak, is_xonly_t)'':
* Inputs:
** The ''tweak_ctx'': a [[#tweak-context|Tweak Context]] data structure
** The ''tweak'': a 32-byte array
** The tweak mode ''is_xonly_t'': a boolean
* Let ''(Q, gacc, tacc) = tweak_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 &ge; 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 ''tweak_ctx' = (Q', gacc', tacc')''
</div>
=====Blind Nonce Generation=====
<div>
Algorithm ''BlindNonceGen(sk, pk, aggpk, m, extra_in)'':
* Inputs:
** The base secret signing key ''sk'': a 32-byte array (optional argument)
** The base public key ''pk'': a 33-byte array (optional argument)
** The auxiliary input ''extra_in'': a byte array with ''0 &le; len(extra_in) &le; 2<sup>32</sup>-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 ''hash256<sub>CCD/aux</sub>(rand')''<ref>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.</ref>
* Else:
** Let ''rand = rand' ''
* If the optional argument ''extra_in'' is not present:
** Let ''extra_in = empty_bytestring''
* Let ''k' = int(hash256<sub>CCD/blindnonce</sub>(rand || bytes(1, len(pk)) || pk || bytes(4, len(extra_in)) || extra_in )) mod n''
* Fail if ''k' = 0''
* Let ''R' = k'⋅G''
* Let ''blindpubnonce = cbytes(R')''
* Let ''blindsecnonce = bytes(32, k' || pk)''<ref name="blindsecnonce">The algorithms as specified here assume that the ''blindsecnonce'' is stored as a 65-byte array using the serialization ''blindsecnonce = bytes(32, k') || pk''. The same format is used in the reference implementation and in the test vectors. However, since the ''blindsecnonce'' is not meant to be sent over the wire, compatibility between implementations is not a concern, and this method of storing the ''blindsecnonce'' is merely a suggestion.<br />
The ''blindsecnonce'' is effectively a local data structure of the signer which comprises the value double ''(k', pk)'', and implementations may choose any suitable method to carry it from ''BlindNonceGen'' (first communication round) to ''BlindSign'' (third communication round). In particular, implementations may choose to hide the ''blindsecnonce'' in internal state without exposing it in an API explicitly, e.g., in an effort to prevent callers from reusing a ''blindsecnonce'' accidentally.</ref>
* Return ''(secnonce, pubnonce)''
</div>
=====Session Context=====
The Session Context is a data structure consisting of the following elements:
* The base public key ''pk'': a 33-byte array
* The blind factor ''blindfactor'': a 32-byte array
* The challenge hash ''challenge'': a 32-byte array
* The public nonce ''pubnonce'': a 33-byte array
* The number ''v'' of tweaks with ''0 &le; v < 2^32''
* The tweaks ''tweak<sub>1..v</sub>'': ''v'' 32-byte arrays
* The tweak modes ''is_xonly_t<sub>1..v</sub>'' : ''v'' booleans
We write "Let ''(pk, blindfactor, challenge, pubnonce, v, tweak<sub>1..v</sub>, is_xonly_t<sub>1..v</sub>) = session_ctx''" to assign names to the elements of a Session Context.
<div>
Algorithm ''GetSessionValues(session_ctx)'':
* Let ''(pk, blindfactor, challenge, pubnonce, v, tweak<sub>1..v</sub>, is_xonly_t<sub>1..v</sub>) = session_ctx''
* Let ''tweak_ctx<sub>0</sub> = TweakCtxInit(pk)''; fail if that fails
* For ''i = 1 .. v'':
** Let ''tweak_ctx<sub>i</sub> = ApplyTweak(tweak_ctx<sub>i-1</sub>, tweak<sub>i</sub>, is_xonly_t<sub>i</sub>)''; fail if that fails
* Let ''(Q, gacc, tacc) = tweak_ctx<sub>v</sub>''
* Let ''a = int(blindfactor)''; fail if ''a ≥ n''
* Let ''b = int(blindfactor)''; fail if ''b ≥ n''
* Let ''e = int(challenge)''; fail if ''e ≥ n''
* Let ''R = cpoint(pubnonce)''; fail if that fails
* Return ''(Q, gacc, tacc, a, e, R)''
</div>
=====Blind Challenge Generation=====
<div>
Algorithm ''BlindChallengeGen(m, blindpubnonce, pk, tweak<sub>1..v</sub>, is_xonly<sub>1..v</sub>, extra_in)'':
* Inputs:
** The message ''m'': a byte array
** The blind public nonce ''blindpubnonce'': a 33-byte array
** The base public key ''pk'': a 33-byte array
** The tweaks ''tweak<sub>1..v</sub>'': ''v'' 32-byte arrays
** The tweak modes ''is_xonly<sub>1..v</sub>'': ''v'' booleans
** The auxiliary input ''extra_in'': a byte array with ''0 &le; len(extra_in) &le; 2<sup>32</sup>-1'' (optional argument)
* If ''extra_in'' is not present:
** Let ''extra_in = empty_bytestring''
* Let ''(Q, gacc, tacc) = TweakCtxInit(pk)''
* For ''i = 1 .. v'':
** Let ''(Q, gacc, tacc) = ApplyTweak((Q, gacc, tacc), tweak<sub>i</sub>, is_xonly<sub>i</sub>)''; fail if that fails
* Let ''cpk = cbytes(Q)''
* Draw 32 random bytes ''rand''
* Let ''z = hash512<sub>CCD/blindfactor</sub>(rand || bytes(1, len(cpk)) || cpk || bytes(1, len(blindpubnonce)) || blindpubnonce || bytes(8, len(m)) || m || bytes(4, len(extra_in)) || extra_in)''
* Let ''a' = int(z[0:32]) mod n''; fail if ''a' = 0''
* Let ''b' = int(z[32:64]) mod n''; fail if ''b' = 0''
* Let ''g = 1'' if ''has_even_y(Q)'', else ''g = 1 mod n''
* Let ''pk_parity = (g⋅gacc mod n == 1)''
* Let ''X' = cpoint(pk)''; let ''X = X' '' if ''pk_parity'' else ''X' ''
* Let ''R' = cpoint(blindpubnonce)''
* Let ''R = R' + a'⋅G + b'⋅X''; fail if ''is_infinite(R)''
* Let ''nonce_parity = has_even_y(R)''
* If ''nonce_parity'':
** Let ''a = a' '', ''b = b' ''
* Else:
** Let ''a = n a' '', ''b = n b' ''
* Let ''e = int(hash<sub>BIP0340/challenge</sub>(xbytes(R) || xbytes(Q) || m)) mod n''
* Let ''e' = (e + b) mod n''
* Let ''session_ctx = (pk, bytes(32, a), bytes(32, e), cbytes(R), tweak<sub>1..v</sub>, is_xonly<sub>1..v</sub>)''
* Return ''(session_ctx, bytes(32, e'), pk_parity, nonce_parity)''
</div>
=====Blind Signing=====
<div>
Algorithm ''BlindSign(sk, blindchallenge, blindsecnonce, pk_parity, nonce_parity)'':
* Inputs:
** The secret key ''sk'': a 32-byte array
** The blind challenge ''blindchallenge'': a 32-byte array ''e' ''
** The secret nonce ''blindsecnonce'': a byte array whose first 32 bytes are ''k'' (remaining bytes are implementation-defined)
** ''pk_parity'': boolean (from ''BlindChallengeGen'')
** ''nonce_parity'': boolean (from ''BlindChallengeGen'')
* Let ''d' = int(sk)''; fail if ''d' = 0'' or ''d' ≥ n''
* Let ''P = d'⋅G''; fail if ''is_infinite(P)''
* Let ''d = d' '' if ''pk_parity'' else ''n d' ''
* Let ''e' = int(blindchallenge)''; fail if ''e' ≥ n''
* Let ''k' = int(blindsecnonce[0:32])''; fail if ''k' = 0'' or ''k' ≥ n''
* Let ''k = k' '' if ''nonce_parity'' else ''n k' ''
* Overwrite ''blindsecnonce[0:64]'' with 64 zero bytes<ref> This helps prevent accidental nonce reuse. A zeroed ''blindsecnonce'' MUST cause subsequent ''BlindSign'' calls to fail.</ref>
* Let ''R' = k'⋅G''; fail if ''is_infinite(R')''<ref> This check holds except with negligible probability.</ref>
* Let ''s' = (k + e'⋅d) mod n''
* If ''VerifyBlindSignature(cbytes(P), cbytes(R'), blindchallenge, bytes(32, s'), pk_parity, nonce_parity)'' returns failure, abort
* Return ''blindsignature = bytes(32, s')''
</div>
<div>
Algorithm ''VerifyBlindSignature(pk, blindpubnonce, blindchallenge, blindsignature, pk_parity, nonce_parity)'':
* Inputs:
** ''pk'': a 33-byte compressed public key
** ''blindpubnonce'': the signers 33-byte ''R' = k'⋅G''
** ''blindchallenge'': 32-byte ''e' ''
** ''blindsignature'': 32-byte ''s' ''
** ''pk_parity, nonce_parity'': booleans
* Let ''P' ' = cpoint(pk)''; let ''P = P' '' if ''pk_parity'' else ''P' '' ; fail if ''is_infinite(P)''
* Let ''R' ' = cpoint(blindpubnonce)''; let ''R = R' '' if ''nonce_parity'' else ''R' ''
* Let ''e' = int(blindchallenge)'', ''s' = int(blindsignature)''
* Return success iff ''s'⋅G == R + e'⋅P''
</div>
=====Unblinding=====
<div>
Algorithm ''UnblindSignature(session_ctx, blindsignature)'':
* Inputs:
** ''session_ctx'': as defined above
** ''blindsignature'': the 32-byte ''s' '' returned by the signer
* Let ''(Q, gacc, tacc, a, e, R) = GetSessionValues(session_ctx)''; fail if that fails
* Let ''g = 1'' if ''has_even_y(Q)'', else ''g = 1 mod n''
* Let ''s' = int(blindsignature)''; fail if ''s' ≥ n''
* Let ''s = (s' + a + e⋅g⋅tacc) mod n''
* Return the BIP340 signature ''sig = xbytes(R) || bytes(32, s)''
</div>
== Security Considerations ==
* Exposure of any delegated tweak scalar <code>t</code> enables signing only for the specific child key(s) that scalar was derived for, and is typically short-lived if disclosed immediately before spending.
* Delegatees MUST ensure every delegated path remains non-hardened and that ''ComputeBIP32Tweak'' yields the correct tweak <code>t</code>; incorrect scalars could render the delegator incapable of producing a signature.
* Delegators MUST verify change outputs when tweak data is provided (for example via ''ChangeOutputVerification'') to avoid authorizing unexpected scripts.
* Reusing the same k' (first 32 bytes in blindsecnonce) across two BlindSign calls allows recovery of the base secret key.
* When using blinded signing, opening multiple sessions concurrently against the same signer can allow an attacker to learn the base secret key. If concurrency is required, use the concurrently secure variant (encryption + ZK) instead (not specified in this BIP).
== Test Vectors ==
A [[bip-0089/vectors|collection of JSON test vectors]] are provided, along with a [[bip-0089/reference.py|python reference implementation]].
It uses a vendored copy of the [https://github.com/secp256k1lab/secp256k1lab/ secp256k1lab] library
(commit [https://github.com/secp256k1lab/secp256k1lab/commit/a265da139aea27386085a2a8760f8698e1bda64e
a265da139aea27386085a2a8760f8698e1bda64e]).
You may also find example code of CCD in action [https://github.com/jurvis/chaincode-delegation here].
== Changelog ==
* '''0.1.3''' (2026-02-02): Upgrade secp256k1lab and add license file; fix type checker and linter issues; clarify Delegator/Delegatee terminology, derivation constraints, signing modes, and verification scope.
* '''0.1.2''' (2025-12-03): Updated to reflect BIP number assignment.
* '''0.1.1''' (2025-11-30): Fix acknowledgments spelling, BIP3 formatting, and use "Chain Code" with a space throughout.
* '''0.1.0''' (2025-10-14): Publication of draft BIP
== Acknowledgements ==
* Arik Sosman and Wilmer Paulino for the initial discussions and validation of this idea.
* Sanket Kajalkar, Jordan Mecom, Gregory Sanders, ZmnSCPxj, Yuval Kogman, and John Cantrell for code and design review.
== Copyright ==
This BIP is licensed under the BSD 3-Clause license.

View File

@ -1,170 +0,0 @@
"""BIP32 helpers for the CCD reference implementation."""
from __future__ import annotations
from dataclasses import dataclass
import hmac
from hashlib import new as hashlib_new, sha256, sha512
from typing import List, Tuple, Mapping, Sequence
from secp256k1lab.secp256k1 import G, GE, Scalar
CURVE_N = Scalar.SIZE
def int_to_bytes(value: int, length: int) -> bytes:
return value.to_bytes(length, "big")
def bytes_to_int(data: bytes) -> int:
return int.from_bytes(data, "big")
def compress_point(point: GE) -> bytes:
if point.infinity:
raise ValueError("Cannot compress point at infinity")
return point.to_bytes_compressed()
def decompress_point(data: bytes) -> GE:
return GE.from_bytes_compressed(data)
def apply_tweak_to_public(base_public: bytes, tweak: int) -> bytes:
base_point = GE.from_bytes_compressed(base_public)
tweaked_point = base_point + (tweak % CURVE_N) * G
if tweaked_point.infinity:
raise ValueError("Tweaked key is at infinity")
return tweaked_point.to_bytes_compressed()
def apply_tweak_to_secret(base_secret: int, tweak: int) -> int:
if not (0 < base_secret < CURVE_N):
raise ValueError("Invalid base secret scalar")
return (base_secret + tweak) % CURVE_N
def decode_path(path_elements: Sequence[object]) -> List[int]:
result: List[int] = []
for element in path_elements:
if isinstance(element, int):
index = element
else:
element_str = str(element)
hardened = element_str.endswith("'") or element_str.endswith("h")
suffix = element_str[:-1] if hardened else element_str
if not suffix:
raise AssertionError("invalid derivation index")
index = int(suffix)
if hardened:
index |= HARDENED_INDEX
result.append(index)
return result
HARDENED_INDEX = 0x80000000
def _hash160(data: bytes) -> bytes:
return hashlib_new("ripemd160", sha256(data).digest()).digest()
@dataclass
class ExtendedPublicKey:
point: GE
chain_code: bytes
depth: int = 0
parent_fingerprint: bytes = b"\x00\x00\x00\x00"
child_number: int = 0
def fingerprint(self) -> bytes:
return _hash160(compress_point(self.point))[:4]
def derive_child(self, index: int) -> Tuple[int, "ExtendedPublicKey"]:
tweak, child_point, child_chain = derive_public_child(self.point, self.chain_code, index)
child = ExtendedPublicKey(
point=child_point,
chain_code=child_chain,
depth=self.depth + 1,
parent_fingerprint=self.fingerprint(),
child_number=index,
)
return tweak, child
def derive_public_child(parent_point: GE, chain_code: bytes, index: int) -> Tuple[int, GE, bytes]:
if index >= HARDENED_INDEX:
raise ValueError("Hardened derivations are not supported for delegates")
data = compress_point(parent_point) + int_to_bytes(index, 4)
il_ir = hmac.new(chain_code, data, sha512).digest()
il, ir = il_ir[:32], il_ir[32:]
tweak = bytes_to_int(il)
if tweak >= CURVE_N:
raise ValueError("Invalid tweak derived (>= curve order)")
child_point_bytes = apply_tweak_to_public(compress_point(parent_point), tweak)
child_point = decompress_point(child_point_bytes)
return tweak, child_point, ir
def parse_path(path: str) -> List[int]:
if not path or path in {"m", "M"}:
return []
if path.startswith(("m/", "M/")):
path = path[2:]
components: List[int] = []
for element in path.split("/"):
if element.endswith("'") or element.endswith("h"):
raise ValueError("Hardened steps are not allowed in CCD derivations")
index = int(element)
if index < 0 or index >= HARDENED_INDEX:
raise ValueError("Derivation index out of range")
components.append(index)
return components
def parse_extended_public_key(data: Mapping[str, object]) -> ExtendedPublicKey:
compressed_hex = data.get("compressed")
if not isinstance(compressed_hex, str):
raise ValueError("Compressed must be a string")
chain_code_hex = data.get("chain_code")
if not isinstance(chain_code_hex, str):
raise ValueError("Chain code must be a string")
depth = data.get("depth")
if not isinstance(depth, int):
raise ValueError("Depth must be an integer")
child_number = data.get("child_number", 0)
if not isinstance(child_number, int):
raise ValueError("Child number must be an integer")
parent_fp_hex = data.get("parent_fingerprint", "00000000")
compressed = bytes.fromhex(compressed_hex)
chain_code = bytes.fromhex(chain_code_hex)
parent_fp = bytes.fromhex(str(parent_fp_hex))
return build_extended_public_key(
compressed,
chain_code,
depth=depth,
parent_fingerprint=parent_fp,
child_number=child_number,
)
def build_extended_public_key(
compressed: bytes,
chain_code: bytes,
*,
depth: int = 0,
parent_fingerprint: bytes = b"\x00\x00\x00\x00",
child_number: int = 0,
) -> ExtendedPublicKey:
if len(chain_code) != 32:
raise ValueError("Chain code must be 32 bytes")
point = decompress_point(compressed)
return ExtendedPublicKey(
point=point,
chain_code=chain_code,
depth=depth,
parent_fingerprint=parent_fingerprint,
child_number=child_number,
)

View File

@ -1,42 +0,0 @@
"""Helpers for working with minimal SortedMulti descriptor templates."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Sequence
@dataclass(frozen=True)
class SortedMultiDescriptorTemplate:
"""Minimal representation of a ``wsh(sortedmulti(m, ...))`` descriptor."""
threshold: int
def witness_script(self, tweaked_keys: Sequence[bytes]) -> bytes:
"""Return the witness script for ``wsh(sortedmulti(threshold, tweaked_keys))``."""
if not tweaked_keys:
raise ValueError("sortedmulti requires at least one key")
if not 1 <= self.threshold <= len(tweaked_keys):
raise ValueError("threshold must satisfy 1 <= m <= n")
for key in tweaked_keys:
if len(key) != 33:
raise ValueError("sortedmulti keys must be 33-byte compressed pubkeys")
sorted_keys = sorted(tweaked_keys)
script = bytearray()
script.append(_op_n(self.threshold))
for key in sorted_keys:
script.append(len(key))
script.extend(key)
script.append(_op_n(len(sorted_keys)))
script.append(0xAE) # OP_CHECKMULTISIG
return bytes(script)
def _op_n(value: int) -> int:
if not 0 <= value <= 16:
raise ValueError("OP_N value out of range")
if value == 0:
return 0x00
return 0x50 + value

View File

@ -1,784 +0,0 @@
# BIPXXX reference implementation
#
# WARNING: This implementation is for demonstration purposes only and _not_ to
# be used in production environments. The code is vulnerable to timing attacks,
# for example.
from typing import Dict, Mapping, Optional, Sequence, Tuple, NewType, NamedTuple, List, Callable, Any, cast
import hashlib
import json
import os
import secrets
import sys
from bip32 import (
CURVE_N,
ExtendedPublicKey,
apply_tweak_to_public,
apply_tweak_to_secret,
int_to_bytes,
parse_extended_public_key,
compress_point,
decode_path,
)
from descriptor import SortedMultiDescriptorTemplate
from secp256k1lab.bip340 import schnorr_sign, schnorr_verify
from secp256k1lab.keys import pubkey_gen_plain
from secp256k1lab.secp256k1 import G, GE, Scalar
HashFunc = Callable[[bytes], Any]
PlainPk = NewType('PlainPk', bytes)
XonlyPk = NewType('XonlyPk', bytes)
def xbytes(P: GE) -> bytes:
return P.to_bytes_xonly()
def cbytes(P: GE) -> bytes:
return P.to_bytes_compressed()
def cpoint(x: bytes) -> GE:
return GE.from_bytes_compressed(x)
TweakContext = NamedTuple('TweakContext', [('Q', GE),
('gacc', Scalar),
('tacc', Scalar)])
def tweak_ctx_init(pk: PlainPk) -> TweakContext:
Q = cpoint(pk)
if Q.infinity:
raise ValueError('The public key cannot be infinity.')
gacc = Scalar(1)
tacc = Scalar(0)
return TweakContext(Q, gacc, tacc)
def apply_tweak(tweak_ctx: TweakContext, tweak: bytes, is_xonly: bool) -> TweakContext:
if len(tweak) != 32:
raise ValueError('The tweak must be a 32-byte array.')
Q, gacc, tacc = tweak_ctx
if is_xonly and not Q.has_even_y():
g = Scalar(-1)
else:
g = Scalar(1)
try:
t = Scalar.from_bytes_checked(tweak)
except ValueError:
raise ValueError('The tweak must be less than n.')
Q_ = g * Q + t * G
if Q_.infinity:
raise ValueError('The result of tweaking cannot be infinity.')
gacc_ = g * gacc
tacc_ = t + g * tacc
return TweakContext(Q_, gacc_, tacc_)
# Return the plain public key corresponding to a given secret key
def individual_pk(seckey: bytes) -> PlainPk:
return PlainPk(pubkey_gen_plain(seckey))
def bytes_xor(a: bytes, b: bytes) -> bytes:
return bytes(x ^ y for x, y in zip(a, b))
# 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, hash_func: HashFunc = hashlib.sha256) -> bytes:
tag_hash = hash_func(tag.encode()).digest()
return hash_func(tag_hash + tag_hash + msg).digest()
def nonce_hash(rand: bytes, pk: PlainPk, extra_in: bytes) -> bytes:
buf = b''
buf += rand
buf += len(pk).to_bytes(1, 'big')
buf += pk
buf += len(extra_in).to_bytes(4, 'big')
buf += extra_in
return tagged_hash('CCD/blindnonce', buf)
def blind_nonce_gen_internal(rand_: bytes, sk: Optional[bytes], pk: Optional[PlainPk], extra_in: Optional[bytes]) -> Tuple[bytearray, bytes]:
if sk is not None:
rand = bytes_xor(sk, tagged_hash('CCD/aux', rand_))
else:
rand = rand_
if pk is None:
pk = PlainPk(b'')
if extra_in is None:
extra_in = b''
k = Scalar.from_bytes_wrapping(nonce_hash(rand, pk, extra_in))
# k == 0 cannot occur except with negligible probability.
assert k != 0
R = k * G
assert R is not None
blindpubnonce = cbytes(R)
blindsecnonce = bytearray(k.to_bytes() + pk)
return blindsecnonce, blindpubnonce
def blind_nonce_gen(sk: Optional[bytes], pk: Optional[PlainPk], extra_in: Optional[bytes]) -> Tuple[bytearray, bytes]:
if sk is not None and len(sk) != 32:
raise ValueError('The optional byte array sk must have length 32.')
rand_ = secrets.token_bytes(32)
return blind_nonce_gen_internal(rand_, sk, pk, extra_in)
SessionContext = NamedTuple('SessionContext', [('pk', PlainPk),
('blindfactor', bytes),
('challenge', bytes),
('pubnonce', bytes),
('tweaks', List[bytes]),
('is_xonly', List[bool])])
def blind_factor_hash(rand: bytes, cpk: PlainPk, blindpubnonce: bytes, msg: bytes, extra_in: bytes) -> bytes:
buf = b''
buf += rand
buf += len(cpk).to_bytes(1, 'big')
buf += cpk
buf += len(blindpubnonce).to_bytes(1, 'big')
buf += blindpubnonce
buf += len(msg).to_bytes(8, 'big')
buf += msg
buf += len(extra_in).to_bytes(4, 'big')
buf += extra_in
return tagged_hash('CCD/blindfactor', buf, hashlib.sha512)
def blind_challenge_gen_internal(rand: bytes, msg: bytes, blindpubnonce: bytes, pk: PlainPk, tweaks: List[bytes], is_xonly: List[bool], extra_in: Optional[bytes]) -> Tuple[SessionContext, bytes, bool, bool]:
if extra_in is None:
extra_in = b''
Q, gacc, tacc = pubkey_and_tweak(pk, tweaks, is_xonly)
cpk = PlainPk(cbytes(Q))
k = blind_factor_hash(rand, cpk, blindpubnonce, msg, extra_in)
a_ = Scalar.from_bytes_wrapping(k[0:32])
assert a_ != 0
b_ = Scalar.from_bytes_wrapping(k[32:64])
assert b_ != 0
g = Scalar(1) if Q.has_even_y() else Scalar(-1)
pk_parity = g * gacc == 1
X_ = cpoint(pk)
X = X_ if pk_parity else -X_
R_ = cpoint(blindpubnonce)
R = R_ + (a_ * G) + (b_ * X)
if R is None:
raise ValueError('The result of nonce blinding cannot be infinity.')
nonce_parity = R.has_even_y()
if not nonce_parity:
a = -a_
b = -b_
else:
a = a_
b = b_
e = Scalar.from_bytes_wrapping(tagged_hash("BIP0340/challenge", xbytes(R) + xbytes(Q) + msg))
e_ = e + b
session_ctx = SessionContext(pk, a.to_bytes(), e.to_bytes(), cbytes(R), tweaks, is_xonly)
return session_ctx, e_.to_bytes(), pk_parity, nonce_parity
def blind_challenge_gen(msg: bytes, blindpubnonce: bytes, pk: PlainPk, tweaks: List[bytes], is_xonly: List[bool], extra_in: Optional[bytes]) -> Tuple[SessionContext, bytes, bool, bool]:
rand = secrets.token_bytes(32)
return blind_challenge_gen_internal(rand, msg, blindpubnonce, pk, tweaks, is_xonly, extra_in)
def blind_sign(sk: bytes, blindchallenge: bytes, blindsecnonce: bytearray, pk_parity: bool, nonce_parity: bool) -> bytes:
try:
d_ = Scalar.from_bytes_checked(sk)
if d_ == 0:
raise ValueError('The secret key cannot be zero.')
except ValueError:
raise ValueError('The secret key is out of range.')
P = d_ * G
if P.infinity:
raise ValueError('The public key cannot be infinity.')
d = d_ if pk_parity else -d_
e_ = Scalar.from_bytes_checked(blindchallenge)
k_ = Scalar.from_bytes_checked(bytes(blindsecnonce[0:32]))
k = k_ if nonce_parity else -k_
# Overwrite the secnonce argument with zeros such that subsequent calls of
# sign with the same secnonce raise a ValueError.
blindsecnonce[:64] = bytearray(b'\x00'*64)
R_ = k_ * G
if R_.infinity:
raise ValueError('The blindpubnonce cannot be infinity.')
s_ = k + (e_ * d)
pk = PlainPk(cbytes(P))
blindsignature = s_.to_bytes()
assert verify_blind_signature(pk, cbytes(R_), blindchallenge, blindsignature, pk_parity, nonce_parity)
return blindsignature
def verify_blind_signature(pk: PlainPk, blindpubnonce: bytes, blindchallenge: bytes, blindsignature: bytes, pk_parity: bool, nonce_parity: bool) -> bool:
P_ = cpoint(pk)
P = P_ if pk_parity else -P_
if P.infinity:
raise ValueError('The public key cannot be infinity.')
R_ = cpoint(blindpubnonce)
R = R_ if nonce_parity else -R_
e_ = Scalar.from_bytes_checked(blindchallenge)
s_ = Scalar.from_bytes_checked(blindsignature)
R_calc = (s_ * G) + (-e_ * P)
if R_calc.infinity:
return False
return R == R_calc
def pubkey_and_tweak(pk: PlainPk, tweaks: List[bytes], is_xonly: List[bool]) -> TweakContext:
if len(tweaks) != len(is_xonly):
raise ValueError('The tweaks and is_xonly arrays must have the same length.')
tweak_ctx = tweak_ctx_init(pk)
v = len(tweaks)
for i in range(v):
tweak_ctx = apply_tweak(tweak_ctx, tweaks[i], is_xonly[i])
return tweak_ctx
def get_session_values(session_ctx: SessionContext) -> Tuple[GE, Scalar, Scalar, GE, Scalar, Scalar]:
(pk, blindfactor, challenge, pubnonce, tweaks, is_xonly) = session_ctx
Q, gacc, tacc = pubkey_and_tweak(pk, tweaks, is_xonly)
a = Scalar.from_bytes_checked(blindfactor)
e = Scalar.from_bytes_checked(challenge)
R = cpoint(pubnonce)
return Q, a, e, R, gacc, tacc
def unblind_signature(session_ctx: SessionContext, blindsignature: bytes) -> bytes:
Q, a, e, R, gacc, tacc = get_session_values(session_ctx)
s_ = Scalar.from_bytes_checked(blindsignature)
g = Scalar(1) if Q.has_even_y() else Scalar(-1)
s = s_ + a + (e * g * tacc)
return xbytes(R) + s.to_bytes()
#
# The following code is only used for testing.
#
def hx(s: str) -> bytes:
return bytes.fromhex(s)
def fromhex_all(l): # noqa: E741
return [hx(l_i) for l_i in l]
def get_error_details(tc):
et = tc["error"]["type"]
# Resolve to real class from name
exc_cls = getattr(__builtins__, et, None) or getattr(__import__("builtins"), et)
# Optional message predicate
msg = tc["error"].get("message")
if msg is None:
return exc_cls, (lambda e: True)
return exc_cls, (lambda e: msg in str(e))
def assert_raises(exc_cls, fn, pred):
try:
fn()
except Exception as e:
assert isinstance(e, exc_cls), f"Raised {type(e).__name__}, expected {exc_cls.__name__}"
assert pred(e), f"Exception message predicate failed: {e}"
return
assert False, f"Expected {exc_cls.__name__} but no exception was raised"
def build_session_ctx(obj):
pk = PlainPk(bytes.fromhex(obj["pk"]))
a = bytes.fromhex(obj["blindfactor"])
e = bytes.fromhex(obj["challenge"])
R = bytes.fromhex(obj["pubnonce"])
tweaks = fromhex_all(obj["tweaks"])
is_xonly = obj["is_xonly"]
return (pk, a, e, R, tweaks, is_xonly)
def test_blind_nonce_gen_vectors():
with open(os.path.join(sys.path[0], 'vectors', 'blind_nonce_gen_vectors.json')) as f:
tv = json.load(f)
for tc in tv["test_cases"]:
def get_bytes(key) -> bytes:
return bytes.fromhex(tc[key])
def get_bytes_maybe(key) -> Optional[bytes]:
v = tc.get(key)
return None if v is None else bytes.fromhex(v)
rand_ = get_bytes("rand_")
sk = get_bytes_maybe("sk")
pk = get_bytes_maybe("pk")
if pk is not None:
pk = PlainPk(pk)
extra_in = get_bytes_maybe("extra_in")
expected_blindsecnonce = get_bytes("expected_blindsecnonce")
expected_blindpubnonce = get_bytes("expected_blindpubnonce")
blindsecnonce, blindpubnonce = blind_nonce_gen_internal(rand_, sk, pk, extra_in)
assert bytes(blindsecnonce) == expected_blindsecnonce
assert blindpubnonce == expected_blindpubnonce
pk_len = 0 if tc["pk"] is None else 33
assert len(expected_blindsecnonce) == 32 + pk_len
assert len(expected_blindpubnonce) == 33
def test_blind_challenge_gen_vectors():
with open(os.path.join(sys.path[0], 'vectors', 'blind_challenge_gen_vectors.json')) as f:
tv = json.load(f)
# ---------- Valid cases ----------
for tc in tv["test_cases"]:
rand = bytes.fromhex(tc["rand"])
msg = bytes.fromhex(tc["msg"]) if tc["msg"] != "" else b""
blindpubnonce = bytes.fromhex(tc["blindpubnonce"])
pk = PlainPk(bytes.fromhex(tc["pk"]))
tweaks = fromhex_all(tc["tweaks"])
is_xonly = tc["is_xonly"]
extra_in = None if tc["extra_in"] is None else bytes.fromhex(tc["extra_in"])
expected_a = bytes.fromhex(tc["expected_blindfactor"])
expected_e = bytes.fromhex(tc["expected_challenge"])
expected_R = bytes.fromhex(tc["expected_pubnonce"])
expected_e_prime = bytes.fromhex(tc["expected_blindchallenge"])
expected_pk_parity = bool(tc["expected_pk_parity"])
expected_nonce_parity = bool(tc["expected_nonce_parity"])
session_ctx, blindchallenge, pk_parity, nonce_parity = blind_challenge_gen_internal(
rand, msg, blindpubnonce, pk, tweaks, is_xonly, extra_in
)
# Check tuple outputs
assert blindchallenge == expected_e_prime
assert pk_parity == expected_pk_parity
assert nonce_parity == expected_nonce_parity
# Check session_ctx fields
pk_sc, blindfactor_sc, challenge_sc, pubnonce_sc, tweaks_sc, is_xonly_sc = session_ctx
assert pk_sc == pk
assert blindfactor_sc == expected_a
assert challenge_sc == expected_e
assert pubnonce_sc == expected_R
assert tweaks_sc == tweaks
assert is_xonly_sc == is_xonly
# Extra sanity: recompute Q and e and compare
Q, gacc, tacc = pubkey_and_tweak(pk, tweaks, is_xonly)
R = cpoint(expected_R)
e_check = tagged_hash("BIP0340/challenge", xbytes(R) + xbytes(Q) + msg)
assert e_check == expected_e
# Length sanity
assert len(expected_a) == 32
assert len(expected_e) == 32
assert len(expected_R) == 33
assert len(expected_e_prime) == 32
# ---------- Error cases ----------
for tc in tv.get("error_test_cases", []):
rand = bytes.fromhex(tc["rand"])
msg = bytes.fromhex(tc["msg"]) if tc["msg"] != "" else b""
blindpubnonce = bytes.fromhex(tc["blindpubnonce"])
pk = PlainPk(bytes.fromhex(tc["pk"]))
tweaks = fromhex_all(tc["tweaks"])
is_xonly = tc["is_xonly"]
extra_in = None if tc["extra_in"] is None else bytes.fromhex(tc["extra_in"])
err = tc["error"]
err_type = err["type"]
err_message = err.get("message")
raised = False
try:
_ = blind_challenge_gen_internal(rand, msg, blindpubnonce, pk, tweaks, is_xonly, extra_in)
except Exception as e:
raised = True
# Type check
assert e.__class__.__name__ == err_type
# Optional substring match on message, if provided
if err_message is not None:
assert err_message in str(e)
assert raised, "Expected an exception but none was raised"
def test_blind_sign_and_verify_vectors():
with open(os.path.join(sys.path[0], 'vectors', 'blind_sign_and_verify_vectors.json')) as f:
tv = json.load(f)
# ------------------ Valid ------------------
for test_case in tv["valid_test_cases"]:
sk = hx(test_case["sk"])
pk = PlainPk(hx(test_case["pk"]))
blindsecnonce_all = hx(test_case["blindsecnonce"])
blindpubnonce = hx(test_case["blindpubnonce"])
blindchallenge = hx(test_case["blindchallenge"])
pk_parity = bool(test_case["pk_parity"])
nonce_parity = bool(test_case["nonce_parity"])
# R' consistency check: cbytes(k'*G) == blindpubnonce
k_ = Scalar.from_bytes_checked(blindsecnonce_all[0:32])
R_prime = k_ * G
assert cbytes(R_prime) == blindpubnonce
expected_sprime = hx(test_case["expected"]["blindsignature"])
# Copy because blind_sign zeroizes the first 64 bytes of the buffer
secnonce_buf = bytearray(blindsecnonce_all)
s_prime = blind_sign(sk, blindchallenge, secnonce_buf, pk_parity, nonce_parity)
assert s_prime == expected_sprime
checks = test_case.get("checks", {})
if checks.get("secnonce_prefix_zeroed_after_sign", False):
assert all(b == 0 for b in secnonce_buf[:64])
if checks.get("verify_returns_true", True):
ok = verify_blind_signature(pk, blindpubnonce, blindchallenge, s_prime, pk_parity, nonce_parity)
assert ok is True
if checks.get("second_call_raises_valueerror", False):
# Reuse the same (now zeroized) buffer; must raise
def try_again():
blind_sign(sk, blindchallenge, secnonce_buf, pk_parity, nonce_parity)
raised = False
try:
try_again()
except ValueError:
raised = True
assert raised, "Expected ValueError on nonce reuse"
# ------------------ Sign errors (exceptions) ------------------
for test_case in tv.get("sign_error_test_cases", []):
exception, except_fn = get_error_details(test_case)
sk = hx(test_case["sk"])
blindsecnonce_all = hx(test_case["blindsecnonce"])
blindchallenge = hx(test_case["blindchallenge"])
pk_parity = bool(test_case["pk_parity"])
nonce_parity = bool(test_case["nonce_parity"])
repeat = int(test_case.get("repeat", 1))
if repeat == 1:
# Single-call error (e.g., out-of-range e')
assert_raises(exception, lambda: blind_sign(sk, blindchallenge, bytearray(blindsecnonce_all), pk_parity, nonce_parity), except_fn)
else:
# Two-call error (nonce reuse)
buf = bytearray(blindsecnonce_all)
# First call should succeed
_ = blind_sign(sk, blindchallenge, buf, pk_parity, nonce_parity)
# Second call must raise
assert_raises(exception, lambda: blind_sign(sk, blindchallenge, buf, pk_parity, nonce_parity), except_fn)
# ------------------ Verify returns False (no exception) ------------------
for test_case in tv.get("verify_fail_test_cases", []):
pk = PlainPk(hx(test_case["pk"]))
blindpubnonce = hx(test_case["blindpubnonce"])
blindchallenge = hx(test_case["blindchallenge"])
blindsignature = hx(test_case["blindsignature"])
pk_parity = bool(test_case["pk_parity"])
nonce_parity = bool(test_case["nonce_parity"])
assert verify_blind_signature(pk, blindpubnonce, blindchallenge, blindsignature, pk_parity, nonce_parity) is False
# ------------------ Verify errors (exceptions) ------------------
for test_case in tv.get("verify_error_test_cases", []):
exception, except_fn = get_error_details(test_case)
pk = PlainPk(hx(test_case["pk"]))
blindpubnonce = hx(test_case["blindpubnonce"])
blindchallenge = hx(test_case["blindchallenge"])
blindsignature = hx(test_case["blindsignature"])
pk_parity = bool(test_case["pk_parity"])
nonce_parity = bool(test_case["nonce_parity"])
assert_raises(exception, lambda: verify_blind_signature(pk, blindpubnonce, blindchallenge, blindsignature, pk_parity, nonce_parity), except_fn)
def test_unblind_signature_vectors():
with open(os.path.join(sys.path[0], 'vectors', 'unblind_signature_vectors.json')) as f:
tv = json.load(f)
# ---------- Valid ----------
for tc in tv["valid_test_cases"]:
session_ctx = build_session_ctx(tc["session_ctx"])
msg = bytes.fromhex(tc["msg"]) if tc["msg"] != "" else b""
blindsignature = bytes.fromhex(tc["blindsignature"])
expected_sig = bytes.fromhex(tc["expected_bip340_sig"])
sig = unblind_signature(session_ctx, blindsignature)
assert sig == expected_sig
# Verify BIP340 with tweaked Q
pk, _, _, _, tweaks, is_xonly = session_ctx
Q, _, _ = pubkey_and_tweak(pk, tweaks, is_xonly)
assert schnorr_verify(msg, xbytes(Q), sig)
# ---------- Errors ----------
for tc in tv.get("error_test_cases", []):
session_ctx = build_session_ctx(tc["session_ctx"])
msg = bytes.fromhex(tc["msg"]) if tc["msg"] != "" else b""
blindsignature = bytes.fromhex(tc["blindsignature"])
err = tc["error"]
err_type = err["type"]
err_msg = err.get("message")
raised = False
try:
_ = unblind_signature(session_ctx, blindsignature)
except Exception as e:
raised = True
assert e.__class__.__name__ == err_type
if err_msg is not None:
assert err_msg in str(e)
assert raised, "Expected an exception but none was raised"
def test_sign_and_verify_random(iters: int) -> None:
for _ in range(iters):
sk = Scalar.from_bytes_wrapping(secrets.token_bytes(32))
pk = individual_pk(sk.to_bytes())
msg = Scalar.from_bytes_wrapping(secrets.token_bytes(32))
v = secrets.randbelow(4)
tweaks = [secrets.token_bytes(32) for _ in range(v)]
tweak_modes = [secrets.choice([False, True]) for _ in range(v)]
Q, _, _ = pubkey_and_tweak(pk, tweaks, tweak_modes)
assert not Q.infinity
# Round 1
# Signer
extra_in_1 = secrets.token_bytes(32)
blindsecnonce, blindpubnonce = blind_nonce_gen(sk.to_bytes(), pk, extra_in_1)
# User
extra_in_2 = secrets.token_bytes(32)
session_ctx, blindchallenge, pk_parity, nonce_parity = blind_challenge_gen(msg.to_bytes(), blindpubnonce, pk, tweaks, tweak_modes, extra_in_2)
# Round 2
# Signer
blindsignature = blind_sign(sk.to_bytes(), blindchallenge, blindsecnonce, pk_parity, nonce_parity)
# User
sig = unblind_signature(session_ctx, blindsignature)
assert schnorr_verify(msg.to_bytes(), xbytes(Q), sig)
def compute_bip32_tweak(xpub: ExtendedPublicKey, path: Sequence[int]) -> Tuple[int, ExtendedPublicKey]:
"""Compute the CCD tweak scalar for a non-hardened derivation path."""
aggregate = 0
current = xpub
for index in path:
tweak, child = current.derive_child(index)
aggregate = (aggregate + tweak) % CURVE_N
current = child
return aggregate, current
def input_verification(
descriptor_template: SortedMultiDescriptorTemplate,
witness_script: Optional[bytes],
tweaks: Mapping[bytes, int],
) -> bool:
"""Check that an input script matches the tweaked policy from CCD data."""
return _verify_tweaked_descriptor(
descriptor_template,
witness_script,
tweaks,
)
def change_output_verification(
descriptor_template: SortedMultiDescriptorTemplate,
witness_script: Optional[bytes],
tweaks: Mapping[bytes, int],
) -> bool:
"""Validate a change output script using delegated CCD tweak data."""
return _verify_tweaked_descriptor(
descriptor_template,
witness_script,
tweaks,
)
def _verify_tweaked_descriptor(
descriptor_template: SortedMultiDescriptorTemplate,
witness_script: Optional[bytes],
tweaks: Mapping[bytes, int],
) -> bool:
if witness_script is None or not tweaks:
return False
if descriptor_template.threshold > len(tweaks):
return False
tweaked_keys: List[bytes] = []
for base_key, tweak in sorted(tweaks.items(), key=lambda item: item[0]):
if len(base_key) != 33:
return False
tweaked_key = apply_tweak_to_public(base_key, tweak % CURVE_N)
tweaked_keys.append(tweaked_key)
try:
expected_witness_script = descriptor_template.witness_script(tweaked_keys)
except ValueError:
return False
return witness_script == expected_witness_script
def delegator_sign(
tweak: int,
base_secret: int,
message: bytes,
) -> bytes:
"""Derive the delegated key, sign ``message``, and return signature."""
child_secret = int_to_bytes(apply_tweak_to_secret(base_secret, tweak), 32)
message_digest = hashlib.sha256(message).digest()
signature = schnorr_sign(message_digest, child_secret, bytes(32))
return signature
def test_compute_tweak_vectors() -> None:
with open(os.path.join(sys.path[0], 'vectors', 'compute_bip32_tweak_vectors.json')) as f:
data = json.load(f)
default_xpub_data = data.get("xpub")
if default_xpub_data is None:
raise AssertionError("compute_bip32_tweak_vectors.json missing top-level 'xpub'")
for case in data.get("valid_test_cases", []):
xpub_data = case.get("xpub", default_xpub_data)
xpub = parse_extended_public_key(xpub_data)
path = decode_path(case.get("path", []))
expected = case.get("expected")
if not isinstance(expected, Mapping):
raise AssertionError("valid compute_tweak case missing 'expected'")
tweak_hex = expected.get("tweak")
if not isinstance(tweak_hex, str):
raise AssertionError("expected 'tweak' must be a string")
derived = expected.get("derived_xpub", {})
derived_compressed = derived.get("compressed")
if not isinstance(derived_compressed, str):
raise AssertionError("expected 'derived_xpub.compressed' must be a string")
derived_chain_code = derived.get("chain_code")
if not isinstance(derived_chain_code, str):
raise AssertionError("expected 'derived_xpub.chain_code' must be a string")
tweak, child = compute_bip32_tweak(xpub, path)
actual_tweak_hex = f"{tweak:064x}"
if actual_tweak_hex != tweak_hex.lower():
raise AssertionError(f"tweak mismatch: expected {tweak_hex}, got {actual_tweak_hex}")
actual_compressed = compress_point(child.point).hex()
actual_chain_code = child.chain_code.hex()
if actual_compressed != derived_compressed.lower():
raise AssertionError("derived public key mismatch")
if actual_chain_code != derived_chain_code.lower():
raise AssertionError("derived chain code mismatch")
for case in data.get("error_test_cases", []):
xpub_data = case.get("xpub", default_xpub_data)
xpub = parse_extended_public_key(xpub_data)
path = decode_path(case.get("path", []))
error_spec = case.get("error", {})
exc_type, message = resolve_error_spec(error_spec)
try:
compute_bip32_tweak(xpub, path)
except exc_type as exc:
if message and message.lower() not in str(exc).lower():
raise AssertionError(f"expected error containing '{message}' but got '{exc}'")
else:
raise AssertionError("expected failure but case succeeded")
def test_delegator_sign_vectors() -> None:
with open(os.path.join(sys.path[0], 'vectors', 'delegator_sign_vectors.json')) as f:
data = json.load(f)
for case in data.get("test_cases", []):
base_secret_hex = case.get("base_secret")
tweak_hex = case.get("tweak")
message_hex = case.get("message")
base_secret = int(base_secret_hex, 16)
tweak = int(tweak_hex, 16)
message = message_hex.encode('utf-8')
expected = case.get("expected")
if not isinstance(expected, Mapping):
raise AssertionError("delegator_sign case missing 'expected'")
expected_signature_hex = expected.get("signature")
if not isinstance(expected_signature_hex, str):
raise AssertionError("expected 'signature' must be a string")
expected_signature = bytes.fromhex(expected_signature_hex)
signature = delegator_sign(
tweak,
base_secret,
message,
)
if signature != expected_signature:
raise AssertionError("signature mismatch")
def test_input_verification_vectors() -> None:
with open(os.path.join(sys.path[0], 'vectors', 'input_verification_vectors.json')) as f:
data = json.load(f)
for case in data.get("test_cases", []):
descriptor = SortedMultiDescriptorTemplate(threshold=2)
witness_hex = case.get("witness_script")
# Get the tweak map of the bare public keys to the BIP 32 tweak
tweaks_raw = case.get("tweak_map", {})
tweaks = parse_tweak_map(tweaks_raw)
expected_bool = bool(case.get("expected", False))
result = input_verification(
descriptor,
bytes.fromhex(witness_hex),
tweaks,
)
if result != expected_bool:
raise AssertionError(
f"input_verification result {result} did not match expected {expected_bool}"
)
def test_change_output_verification_vectors() -> None:
with open(os.path.join(sys.path[0], 'vectors', 'change_output_verification_vectors.json')) as f:
data = json.load(f)
for case in data.get("test_cases", []):
descriptor = SortedMultiDescriptorTemplate(threshold=2)
witness_hex = case.get("witness_script")
# Get the tweak map of the bare public keys to the BIP 32 tweak
tweaks_raw = case.get("tweak_map", {})
tweaks = parse_tweak_map(tweaks_raw)
expected_bool = bool(case.get("expected", False))
result = change_output_verification(
descriptor,
bytes.fromhex(witness_hex),
tweaks,
)
if result != expected_bool:
raise AssertionError(
f"change_output_verification result {result} did not match expected {expected_bool}"
)
def parse_tweak_map(raw: Mapping[str, object]) -> Dict[bytes, int]:
tweaks: Dict[bytes, int] = {}
for key_hex, tweak_hex in raw.items():
base_key = bytes.fromhex(key_hex)
if not isinstance(tweak_hex, str):
raise ValueError(f"tweak value for key {key_hex} must be a string")
tweak_value = int(tweak_hex, 16)
tweaks[base_key] = tweak_value % CURVE_N
return tweaks
def resolve_error_spec(raw: object) -> Tuple[type[Exception], Optional[str]]:
mapping: Dict[str, type[Exception]] = {"value": ValueError, "assertion": AssertionError, "runtime": RuntimeError}
if not isinstance(raw, dict):
return ValueError, None
raw_dict = cast(Dict[str, Any], raw)
name = str(raw_dict.get("type", "value")).lower()
message = raw_dict.get("message")
exc_type = mapping.get(name, ValueError)
return exc_type, None if message is None else str(message)
if __name__ == '__main__':
test_blind_nonce_gen_vectors()
test_blind_challenge_gen_vectors()
test_blind_sign_and_verify_vectors()
test_unblind_signature_vectors()
test_sign_and_verify_random(6)
test_compute_tweak_vectors()
test_delegator_sign_vectors()
test_input_verification_vectors()
test_change_output_verification_vectors()
print("All tests passed")

View File

@ -1,23 +0,0 @@
The MIT License (MIT)
Copyright (c) 2009-2024 The Bitcoin Core developers
Copyright (c) 2009-2024 Bitcoin Developers
Copyright (c) 2025- The secp256k1lab Developers
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.

View File

@ -1,73 +0,0 @@
# The following functions are based on the BIP 340 reference implementation:
# https://github.com/bitcoin/bips/blob/master/bip-0340/reference.py
from .secp256k1 import FE, GE, G
from .util import int_from_bytes, bytes_from_int, xor_bytes, tagged_hash
def pubkey_gen(seckey: bytes) -> bytes:
d0 = int_from_bytes(seckey)
if not (1 <= d0 <= GE.ORDER - 1):
raise ValueError("The secret key must be an integer in the range 1..n-1.")
P = d0 * G
assert not P.infinity
return P.to_bytes_xonly()
def schnorr_sign(
msg: bytes, seckey: bytes, aux_rand: bytes, tag_prefix: str = "BIP0340"
) -> bytes:
d0 = int_from_bytes(seckey)
if not (1 <= d0 <= GE.ORDER - 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 = d0 * G
assert not P.infinity
d = d0 if P.has_even_y() else GE.ORDER - d0
t = xor_bytes(bytes_from_int(d), tagged_hash(tag_prefix + "/aux", aux_rand))
k0 = (
int_from_bytes(tagged_hash(tag_prefix + "/nonce", t + P.to_bytes_xonly() + msg))
% GE.ORDER
)
if k0 == 0:
raise RuntimeError("Failure. This happens only with negligible probability.")
R = k0 * G
assert not R.infinity
k = k0 if R.has_even_y() else GE.ORDER - k0
e = (
int_from_bytes(
tagged_hash(
tag_prefix + "/challenge", R.to_bytes_xonly() + P.to_bytes_xonly() + msg
)
)
% GE.ORDER
)
sig = R.to_bytes_xonly() + bytes_from_int((k + e * d) % GE.ORDER)
assert schnorr_verify(msg, P.to_bytes_xonly(), sig, tag_prefix=tag_prefix)
return sig
def schnorr_verify(
msg: bytes, pubkey: bytes, sig: bytes, tag_prefix: str = "BIP0340"
) -> 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.")
try:
P = GE.from_bytes_xonly(pubkey)
except ValueError:
return False
r = int_from_bytes(sig[0:32])
s = int_from_bytes(sig[32:64])
if (r >= FE.SIZE) or (s >= GE.ORDER):
return False
e = (
int_from_bytes(tagged_hash(tag_prefix + "/challenge", sig[0:32] + pubkey + msg))
% GE.ORDER
)
R = s * G - e * P
if R.infinity or (not R.has_even_y()) or (R.x != r):
return False
return True

View File

@ -1,16 +0,0 @@
import hashlib
from .secp256k1 import GE, Scalar
def ecdh_compressed_in_raw_out(seckey: bytes, pubkey: bytes) -> GE:
"""TODO"""
shared_secret = Scalar.from_bytes_checked(seckey) * GE.from_bytes_compressed(pubkey)
assert not shared_secret.infinity # prime-order group
return shared_secret
def ecdh_libsecp256k1(seckey: bytes, pubkey: bytes) -> bytes:
"""TODO"""
shared_secret = ecdh_compressed_in_raw_out(seckey, pubkey)
return hashlib.sha256(shared_secret.to_bytes_compressed()).digest()

View File

@ -1,15 +0,0 @@
from .secp256k1 import GE, G
from .util import int_from_bytes
# The following function is based on the BIP 327 reference implementation
# https://github.com/bitcoin/bips/blob/master/bip-0327/reference.py
# Return the plain public key corresponding to a given secret key
def pubkey_gen_plain(seckey: bytes) -> bytes:
d0 = int_from_bytes(seckey)
if not (1 <= d0 <= GE.ORDER - 1):
raise ValueError("The secret key must be an integer in the range 1..n-1.")
P = d0 * G
assert not P.infinity
return P.to_bytes_compressed()

View File

@ -1,483 +0,0 @@
# 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
"""
from __future__ import annotations
from typing import Self
# TODO Docstrings of methods still say "field element"
class APrimeFE:
"""Objects of this class represent elements of a prime field.
They are represented internally in numerator / denominator form, in order to delay inversions.
"""
# The size of the field (also its modulus and characteristic).
SIZE: int
def __init__(self, a: int | Self = 0, b: int | Self = 1) -> None:
"""Initialize a field element a/b; both a and b can be ints or field elements."""
if isinstance(a, type(self)):
num = a._num
den = a._den
else:
assert isinstance(a, int)
num = a % self.SIZE
den = 1
if isinstance(b, type(self)):
den = (den * b._num) % self.SIZE
num = (num * b._den) % self.SIZE
else:
assert isinstance(b, int)
den = (den * b) % self.SIZE
assert den != 0
if num == 0:
den = 1
self._num: int = num
self._den: int = den
def __add__(self, a: int | Self) -> Self:
"""Compute the sum of two field elements (second may be int)."""
if isinstance(a, type(self)):
return type(self)(self._num * a._den + self._den * a._num, self._den * a._den)
if isinstance(a, int):
return type(self)(self._num + self._den * a, self._den)
return NotImplemented
def __radd__(self, a: int) -> Self:
"""Compute the sum of an integer and a field element."""
return type(self)(a) + self
@classmethod
def sum(cls, *es: Self) -> Self:
"""Compute the sum of field elements.
sum(a, b, c, ...) is identical to (0 + a + b + c + ...)."""
return sum(es, start=cls(0))
def __sub__(self, a: int | Self) -> Self:
"""Compute the difference of two field elements (second may be int)."""
if isinstance(a, type(self)):
return type(self)(self._num * a._den - self._den * a._num, self._den * a._den)
if isinstance(a, int):
return type(self)(self._num - self._den * a, self._den)
return NotImplemented
def __rsub__(self, a: int) -> Self:
"""Compute the difference of an integer and a field element."""
return type(self)(a) - self
def __mul__(self, a: int | Self) -> Self:
"""Compute the product of two field elements (second may be int)."""
if isinstance(a, type(self)):
return type(self)(self._num * a._num, self._den * a._den)
if isinstance(a, int):
return type(self)(self._num * a, self._den)
return NotImplemented
def __rmul__(self, a: int) -> Self:
"""Compute the product of an integer with a field element."""
return type(self)(a) * self
def __truediv__(self, a: int | Self) -> Self:
"""Compute the ratio of two field elements (second may be int)."""
if isinstance(a, type(self)) or isinstance(a, int):
return type(self)(self, a)
return NotImplemented
def __pow__(self, a: int) -> Self:
"""Raise a field element to an integer power."""
return type(self)(pow(self._num, a, self.SIZE), pow(self._den, a, self.SIZE))
def __neg__(self) -> Self:
"""Negate a field element."""
return type(self)(-self._num, self._den)
def __int__(self) -> int:
"""Convert a field element to an integer in range 0..SIZE-1. The result is cached."""
if self._den != 1:
self._num = (self._num * pow(self._den, -1, self.SIZE)) % self.SIZE
self._den = 1
return self._num
def sqrt(self) -> Self | None:
"""Compute the square root of a field element if it exists (None otherwise)."""
raise NotImplementedError
def is_square(self) -> bool:
"""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) -> bool:
"""Determine whether this field element, represented as integer in 0..SIZE-1, is even."""
return int(self) & 1 == 0
def __eq__(self, a: object) -> bool:
"""Check whether two field elements are equal (second may be an int)."""
if isinstance(a, type(self)):
return (self._num * a._den - self._den * a._num) % self.SIZE == 0
elif isinstance(a, int):
return (self._num - self._den * a) % self.SIZE == 0
return False # for other types
def to_bytes(self) -> bytes:
"""Convert a field element to a 32-byte array (BE byte order)."""
return int(self).to_bytes(32, 'big')
@classmethod
def from_int_checked(cls, v: int) -> Self:
"""Convert an integer to a field element (no overflow allowed)."""
if v >= cls.SIZE:
raise ValueError
return cls(v)
@classmethod
def from_int_wrapping(cls, v: int) -> Self:
"""Convert an integer to a field element (reduced modulo SIZE)."""
return cls(v % cls.SIZE)
@classmethod
def from_bytes_checked(cls, b: bytes) -> Self:
"""Convert a 32-byte array to a field element (BE byte order, no overflow allowed)."""
v = int.from_bytes(b, 'big')
return cls.from_int_checked(v)
@classmethod
def from_bytes_wrapping(cls, b: bytes) -> Self:
"""Convert a 32-byte array to a field element (BE byte order, reduced modulo SIZE)."""
v = int.from_bytes(b, 'big')
return cls.from_int_wrapping(v)
def __str__(self) -> str:
"""Convert this field element to a 64 character hex string."""
return f"{int(self):064x}"
def __repr__(self) -> str:
"""Get a string representation of this field element."""
return f"{type(self).__qualname__}(0x{int(self):x})"
class FE(APrimeFE):
SIZE = 2**256 - 2**32 - 977
def sqrt(self) -> Self | None:
# Due to the fact that our modulus p 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, (self.SIZE + 1) // 4, self.SIZE)
if s**2 % self.SIZE == v:
return type(self)(s)
return None
class Scalar(APrimeFE):
"""TODO Docstring"""
SIZE = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
@classmethod
def from_int_nonzero_checked(cls, v: int) -> Self:
"""Convert an integer to a scalar (no zero or overflow allowed)."""
if not (0 < v < cls.SIZE):
raise ValueError
return cls(v)
@classmethod
def from_bytes_nonzero_checked(cls, b: bytes) -> Self:
"""Convert a 32-byte array to a scalar (BE byte order, no zero or overflow allowed)."""
v = int.from_bytes(b, 'big')
return cls.from_int_nonzero_checked(v)
class GE:
"""Objects of this class represent secp256k1 group elements (curve points or infinity)
GE objects are immutable.
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
"""
# TODO The following two class attributes should probably be just getters as
# classmethods to enforce immutability. Unfortunately Python makes it hard
# to create "classproperties". `G` could then also be just a classmethod.
# Order of the group (number of points on the curve, plus 1 for infinity)
ORDER = Scalar.SIZE
# Number of valid distinct x coordinates on the curve.
ORDER_HALF = ORDER // 2
@property
def infinity(self) -> bool:
"""Whether the group element is the point at infinity."""
return self._infinity
@property
def x(self) -> FE:
"""The x coordinate (a field element) of a non-infinite group element."""
assert not self.infinity
return self._x
@property
def y(self) -> FE:
"""The y coordinate (a field element) of a non-infinite group element."""
assert not self.infinity
return self._y
def __init__(self, x: int | FE | None = None, y: int | FE | None = None) -> 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).
assert x is not None
assert y is not None
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: GE) -> GE:
"""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 sum(*ps: GE) -> GE:
"""Compute the sum of group elements.
GE.sum(a, b, c, ...) is identical to (GE() + a + b + c + ...)."""
return sum(ps, start=GE())
@staticmethod
def batch_mul(*aps: tuple[Scalar, GE]) -> GE:
"""Compute a (batch) scalar group element multiplication.
GE.batch_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 = [(int(a), 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: int | Scalar) -> GE:
"""Multiply an integer or scalar with a group element."""
if self == G:
return FAST_G.mul(Scalar(a))
return GE.batch_mul((Scalar(a), self))
def __neg__(self) -> GE:
"""Compute the negation of a group element."""
if self.infinity:
return self
return GE(self.x, -self.y)
def __sub__(self, a: GE) -> GE:
"""Subtract a group element from another."""
return self + (-a)
def __eq__(self, a: object) -> bool:
"""Check if two group elements are equal."""
if not isinstance(a, type(self)):
return False
return (self - a).infinity
def has_even_y(self) -> bool:
"""Determine whether a non-infinity group element has an even y coordinate."""
assert not self.infinity
return self.y.is_even()
def to_bytes_compressed(self) -> bytes:
"""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_compressed_with_infinity(self) -> bytes:
"""Convert a group element to 33-byte compressed encoding, mapping infinity to zeros."""
if self.infinity:
return 33 * b"\x00"
return self.to_bytes_compressed()
def to_bytes_uncompressed(self) -> bytes:
"""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) -> bytes:
"""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: int | FE) -> GE:
"""Return group element with specified field element as x coordinate (and even y)."""
y = (FE(x)**3 + 7).sqrt()
if y is None:
raise ValueError
if not y.is_even():
y = -y
return GE(x, y)
@staticmethod
def from_bytes_compressed(b: bytes) -> GE:
"""Convert a compressed to a group element."""
assert len(b) == 33
if b[0] != 2 and b[0] != 3:
raise ValueError
x = FE.from_bytes_checked(b[1:])
r = GE.lift_x(x)
if b[0] == 3:
r = -r
return r
@staticmethod
def from_bytes_compressed_with_infinity(b: bytes) -> GE:
"""Convert a compressed to a group element, mapping zeros to infinity."""
if b == 33 * b"\x00":
return GE()
else:
return GE.from_bytes_compressed(b)
@staticmethod
def from_bytes_uncompressed(b: bytes) -> GE:
"""Convert an uncompressed to a group element."""
assert len(b) == 65
if b[0] != 4:
raise ValueError
x = FE.from_bytes_checked(b[1:33])
y = FE.from_bytes_checked(b[33:])
if y**2 != x**3 + 7:
raise ValueError
return GE(x, y)
@staticmethod
def from_bytes(b: bytes) -> GE:
"""Convert a compressed or uncompressed encoding to a group element."""
assert len(b) in (33, 65)
if len(b) == 33:
return GE.from_bytes_compressed(b)
else:
return GE.from_bytes_uncompressed(b)
@staticmethod
def from_bytes_xonly(b: bytes) -> GE:
"""Convert a point given in xonly encoding to a group element."""
assert len(b) == 32
x = FE.from_bytes_checked(b)
r = GE.lift_x(x)
return r
@staticmethod
def is_valid_x(x: int | FE) -> bool:
"""Determine whether the provided field element is a valid X coordinate."""
return (FE(x)**3 + 7).is_square()
def __str__(self) -> str:
"""Convert this group element to a string."""
if self.infinity:
return "(inf)"
return f"({self.x},{self.y})"
def __repr__(self) -> str:
"""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})"
def __hash__(self) -> int:
"""Compute a non-cryptographic hash of the group element."""
if self.infinity:
return 0 # 0 is not a valid x coordinate
return int(self.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: GE) -> None:
self.table: list[GE] = [p] # table[i] = (2^i) * p
for _ in range(255):
p = p + p
self.table.append(p)
def mul(self, a: Scalar | int) -> GE:
result = GE()
a_ = int(a)
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)

View File

@ -1,24 +0,0 @@
import hashlib
# 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 bytes_from_int(x: int) -> bytes:
return x.to_bytes(32, byteorder="big")
def xor_bytes(b0: bytes, b1: bytes) -> bytes:
return bytes(x ^ y for (x, y) in zip(b0, b1))
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()

View File

@ -1,51 +0,0 @@
{
"test_cases": [
{
"rand": "92950940B9C21B956D2950EA4C2CBD966D5DCF32517D2419636C3B434E7E7243",
"msg": "33DF4B220B36836C25198D4AFCFD25D1EE2E7B237C3021D7A0EDBA137E70958C",
"blindpubnonce": "02866A953BB982D4755FC9DCF0E09CC8EA56E2F75040DCAFE0C17A2A6FB5D4AC6E",
"pk": "0232D9E2657C0AA02A6E5AFF67175757832D1B3260A915970EA1CD95E2C9838B52",
"tweaks": ["7F91E8EA5D4FD39AAEB0FCDE90ABAAA8681D2610AF0FDDF132DEFBD5E1183580", "8F4ECAB71A22CDB15945BD2898DF005A8623B8DC50013F12700E678E92837406", "FD890EE6226ECA9EFB889DC1EC77B5D59FE0AF1D876C35F2CBE9F25F6B8FB760"],
"is_xonly": [true, true, false],
"extra_in": "FD8AA0C64B66C38EA627FABB0CFCCE5BB905D130470101ED88771E0A62331AC9",
"expected_blindfactor": "545AB2AAB17406BE3270D0DFB7B13568F9ED5FAD5ABC5E9ACBAFC8D17131CC37",
"expected_challenge": "AC03DF1F1DA05BFD6E01E11BD7B95E3A6A0752BBB0E31EA26251675CECCE3A15",
"expected_pubnonce": "0367E34DAB4F1377CD8F3E7C5CD3E1E4A4D3B27BEAB9C0C0DC6717C9C52275D03B",
"expected_blindchallenge": "B5B3A3D63771818E930E55D3F91EBF11ED16BCDB11E0F1B5DF06F636F870DFB5",
"expected_pk_parity": true,
"expected_nonce_parity": false
}
],
"error_test_cases": [
{
"rand": "2B01EE16681AE0C2D8845C5F1D3F05F92453E95E7AC053DD5CABC736322B6CA3",
"msg": "6C22FC98FEEB69347A04BDE44B99FA50428689608E63B307D9F5904F86FE0B28",
"blindpubnonce": "02D9F53C5816BD205B8208A11491530CD6BD1EC35FFA31F026AD3444EFEA329440",
"pk": "03E9EBFEEAF165FBA6CD394EB1DBD514AE45CE8EA0AE56D54C8B5D7931D79FFBAF",
"tweaks": ["E3DD85653AAFDF2D94312FB8133D6B7E12DFC94B1B82A4E98D85E69D6F2F179A"],
"is_xonly": [true, false],
"extra_in": "C8BB4B046334864F71173C39BDE2A305289AA1AB5C0E0C624EC2D30A0A182310",
"error": {
"type": "ValueError",
"message": "The tweaks and is_xonly arrays must have the same length."
},
"comment": "mismatched arrays"
},
{
"rand": "A8F932BD0BAC6F31824002482A42493B7AA1CAC2814D80D470A716D47ADCDF86",
"msg": "1776037E19AA1A2BF2C9DB770CA12A5AB683E2D7B436090BAC8CE48CB22582E0",
"blindpubnonce": "04411898DF38979F1DA000CEFF9166EE258AB6B0F696B8537F90E551751AA3C6F2",
"pk": "0333438C1C269BD73BADE95C62EDA258F74B093DA359DEDBF990E923CEC95BD6A4",
"tweaks": [],
"is_xonly": [],
"extra_in": null,
"error": {
"type": "ValueError"
},
"comment": "invalid blindpubnonce encoding"
}
]
}

View File

@ -1,22 +0,0 @@
{
"test_cases": [
{
"rand_": "0F6166D1645791EAD551572348A43CA9293E02CF0ED32B17EA5E1AEC6BC41931",
"sk": "F22F1B584D8B5CE15ED8F561DAD077B3FB743E6AABB97DBA758AFD88852DB490",
"pk": "0204B445C4EF4E822DA5842965BC03CBDC865EF846774FD27ACDE063F40CD7812C",
"extra_in": "887BEFE686260D09F471715719B7CB2D48E4116BD346319D9C002A4FC9D82857",
"expected_blindsecnonce": "A4B954BBCB05059CF0ACE8BC2C82BEA5ABD0D2C39B03D7A7205DB41E9BE9CA610204B445C4EF4E822DA5842965BC03CBDC865EF846774FD27ACDE063F40CD7812C",
"expected_blindpubnonce": "0355A32C1B472EE1874924CD9A1BF2536D6A2B214413684FBDFC5B84870EFDCEF8",
"comment": "All params present"
},
{
"rand_": "D4B20323E12CEC7E21B41A4FD2395844F93D4B3E9F3FED13CF3234C32702A242",
"sk": null,
"pk": null,
"extra_in": null,
"expected_blindsecnonce": "78ACDD864846BB5C18017A421E792CC771D63EDA6B63A6CDC3825F298CAC7788",
"expected_blindpubnonce": "025CA329F7676AECEAC10C29566D9C7883A661DB2574454AE491476EADEE3CD430",
"comment": "Every optional parameter is absent"
}
]
}

Some files were not shown because too many files have changed in this diff Show More