mirror of
https://github.com/bitcoin/bips.git
synced 2026-11-09 19:47:16 +00:00
Merge pull request #2212 from fjahr/cisa
BIP460: CISA for Taproot Key Path Spends
This commit is contained in:
26 files changed
+4758
No files matched your search
@@ -1549,6 +1549,13 @@ users (see also: [https://en.bitcoin.it/wiki/Economic_majority economic majority
|
||||
| Specification
|
||||
| Draft
|
||||
|-
|
||||
| [[bip-0460.mediawiki|460]]
|
||||
| Consensus (soft fork)
|
||||
| CISA for Taproot Key Path Spends in SegWit v2
|
||||
| Fabian Jahr
|
||||
| Specification
|
||||
| Draft
|
||||
|-
|
||||
| [[bip-0461.md|461]]
|
||||
| Applications
|
||||
| Deterministic ECDSA Signatures
|
||||
|
||||
@@ -0,0 +1,576 @@
|
||||
<pre>
|
||||
BIP: 460
|
||||
Layer: Consensus (soft fork)
|
||||
Title: CISA for Taproot Key Path Spends in SegWit v2
|
||||
Authors: Fabian Jahr <fjahr@protonmail.com>
|
||||
Status: Draft
|
||||
Type: Specification
|
||||
Assigned: 2026-07-28
|
||||
License: CC0-1.0 OR MIT
|
||||
Discussion: 2026-07-18: https://groups.google.com/g/bitcoindev/c/1XH6sBLWZuA
|
||||
Requires: 340, 341, 458, 459
|
||||
</pre>
|
||||
|
||||
== Introduction ==
|
||||
|
||||
=== Abstract ===
|
||||
|
||||
This document proposes cross-input signature aggregation (CISA) for Bitcoin transactions.
|
||||
A new witness version (v2) enables Taproot-style key path spending with two Schnorr signature aggregation schemes: half-aggregation and full-aggregation.
|
||||
Half-aggregation non-interactively reduces ''n'' signatures from ''64*n'' bytes to ''(n+1)*32'' bytes, while full-aggregation reduces them to a constant 64 bytes but requires interactive signing.
|
||||
Aggregated inputs carry their share of the aggregate signature data and optionally a sighash type, with a marker byte indicating the aggregation mode (half-agg or full-agg) on the last input of each group, while opted-out inputs carry a plain BIP 341 signature.
|
||||
The opt-out mode exists for protocols that depend on a specific signature appearing on chain, such as some adaptor signature protocols.
|
||||
|
||||
=== Copyright ===
|
||||
|
||||
This document, along with the [[bip-0460/test-vectors.py|test vector generator]] and test vectors, is licensed under CC0-1.0 or the MIT License, at your option.
|
||||
The vendored copy of the secp256k1lab library in [[bip-0460/secp256k1lab/|bip-0460/secp256k1lab]] is licensed under the MIT License only, as stated in its [[bip-0460/secp256k1lab/COPYING|COPYING]] file.
|
||||
|
||||
=== Motivation ===
|
||||
|
||||
Signature data makes up a large share of Bitcoin transaction sizes.
|
||||
Each Taproot key path spend requires a 64-byte [[bip-0340.mediawiki|BIP 340]] Schnorr signature, so transactions with many inputs spend much of their weight on signatures.
|
||||
|
||||
The linearity of Schnorr signatures allows combining multiple signatures into a more compact form.
|
||||
Cross-input signature aggregation applies this to the signatures of different inputs within one transaction.
|
||||
|
||||
This provides:
|
||||
|
||||
* '''Lower fees and smaller transactions''': Signature data shrinks with the number of aggregated inputs, reducing transaction weight and fees and freeing up block space
|
||||
* '''Reduced cost of privacy''': Aggregation reduces the signature cost of any batched transaction, and collaborative transactions such as CoinJoin and PayJoin benefit the most per participant because they batch the inputs of many users
|
||||
* '''Flexible usage''': Two aggregation schemes serve different use cases and individual inputs can opt out
|
||||
* '''Protocol compatibility''': The opt-out protects protocols that depend on a specific signature appearing on chain
|
||||
* '''Low initial adoption cost''': Opted-out spends are plain BIP 341 key path spends, so wallets that do not aggregate can adopt witness v2 outputs without new signing logic
|
||||
|
||||
Use cases include:
|
||||
|
||||
* '''CoinJoin/PayJoin transactions''': With CISA, the per-participant cost of CoinJoin and PayJoin transactions decreases as the number of participants increases, making privacy-enhancing usage cheaper
|
||||
* '''Consolidation and batching''': Businesses and users combining many small UTXOs into a single output or multiple payment outputs benefit from reduced transaction costs
|
||||
* '''Lightning channel opens and splices''': Dual funding and splicing combine inputs from both peers in a collaborative transaction, and the existing interactive negotiation between the peers can accommodate the signing rounds of full-aggregation
|
||||
|
||||
Aside from these use cases, any transaction spending more than one witness v2 input benefits from CISA through fee savings.
|
||||
|
||||
== Design ==
|
||||
|
||||
This BIP introduces a new witness version (v2) that enables signature aggregation for Taproot-style key path spends.
|
||||
The design reuses the existing Taproot and tapscript machinery wherever possible and makes aggregation opt-in on a per-input basis, so witness v2 outputs can be adopted independently of whether aggregation is used.
|
||||
Both aggregation schemes are supported, inputs can opt out, and aggregation is limited to key path spends.
|
||||
The reasoning behind these decisions is covered in the [[#rationale|Rationale]] section.
|
||||
|
||||
The main design decision is that every aggregated witness v2 key path input carries only its share of the aggregate signature data plus an optional sighash byte, while opted-out inputs carry a plain BIP 341 signature.
|
||||
The last input in each aggregation group completes the aggregate signature and tags it with a marker byte identifying the scheme.
|
||||
This design:
|
||||
|
||||
* Shows which inputs participate in aggregation
|
||||
* Lets each input specify its own sighash type
|
||||
* Allows mixing aggregated, opted-out, and non-aggregated inputs in the same transaction
|
||||
* Commits to the aggregation mode in the signature message, protecting opted-out inputs from non-consensual aggregation by third parties
|
||||
* Supports half-aggregation and full-aggregation within the same transaction (as separate groups, one per scheme)
|
||||
|
||||
== Specification ==
|
||||
|
||||
=== Witness version 2 ===
|
||||
|
||||
Witness version 2 outputs are created with a scriptPubKey of <code>OP_2 <32-byte witness program></code> (or <code>0x5220{32-byte witness program}</code>).
|
||||
|
||||
Validation of witness v2 spends is identical to the witness version 1 rules of [[bip-0341.mediawiki|BIP 341]], with the following modifications for key path spends:
|
||||
|
||||
* The single witness stack element remaining after removal of the optional annex is only interpreted as a signature if it is 64 bytes long, or 65 bytes long with a last byte that is not a marker byte. Otherwise its interpretation follows the aggregation forms defined below.
|
||||
* For inputs that participate in aggregation, the key path signature message and signature verification are replaced by the rules defined below.
|
||||
|
||||
All other rules apply unchanged.
|
||||
In particular script path spending and its upgrade mechanisms, annex handling, and the treatment of witness programs that are not exactly 32 bytes long or are wrapped in P2SH follow BIP 341.
|
||||
Signatures inside script path spends are not aggregated under this BIP.
|
||||
|
||||
=== Marker definitions ===
|
||||
|
||||
This BIP defines two marker bytes for the final inputs of the aggregation groups:
|
||||
|
||||
* <code>0xbc</code>: '''Half-aggregation marker'''. The input completes the half-aggregation group.
|
||||
* <code>0xbd</code>: '''Full-aggregation marker'''. The input completes the full-aggregation group.
|
||||
|
||||
The marker is the last byte of the final input's witness element.
|
||||
The marker byte is not an opcode, since a key path witness element is not script.
|
||||
The only structural constraint is that markers must be disjoint from the valid sighash types, so that a 65-byte witness element ending in a marker can never be a valid BIP 341 signature.
|
||||
A 64-byte element is always an opted-out signature, since no marked form has that length.
|
||||
The chosen values fall into the range <code>0xbb</code> to <code>0xfe</code>, which is unassigned in legacy script and corresponds to <code>OP_SUCCESS</code> opcodes in tapscript, so they do not collide with opcodes commonly seen in scripts.
|
||||
|
||||
Opted-out inputs and aggregation group members carry no marker.
|
||||
An opted-out witness element is a 64-byte or 65-byte BIP 341 signature, and member elements are identified by their length.
|
||||
A key path spend whose witness element is neither such a signature nor one of the aggregation forms defined below is invalid.
|
||||
Undefined marker values cannot serve as an upgrade hook because witness data is not committed to by the output.
|
||||
A marker value that validated unconditionally would make every witness v2 output spendable by anyone.
|
||||
Future aggregation modes are therefore expected to be introduced through new witness versions or new leaf versions instead of new marker values.
|
||||
|
||||
=== Witness structure ===
|
||||
|
||||
Aggregation changes only the content of the witness.
|
||||
The transaction format is unchanged.
|
||||
A transaction may contain at most two aggregation groups: one half-aggregation group and one full-aggregation group.
|
||||
Aggregated and non-aggregated inputs can be mixed in any order, with the constraint that all members of a group must appear before the input carrying the group's marker.
|
||||
The input carrying a group's marker is called the ''final input'' of the group, all other aggregated inputs are called ''members''.
|
||||
Only witness v2 key path spends can participate in aggregation groups.
|
||||
Inputs spending other output types, as well as witness v2 script path spends and opted-out key path spends, are validated independently under their own rules and can be combined freely with aggregated inputs in the same transaction.
|
||||
|
||||
Each witness v2 key path spend uses a single witness element (plus optional annex).
|
||||
For opted-out inputs this element is a 64-byte or 65-byte BIP 341 signature.
|
||||
For aggregated inputs it consists of the input's share of the aggregate signature data, an optional sighash byte, and the marker on the final input:
|
||||
|
||||
* '''Signature data''': The 32-byte nonce share for half-aggregation members, nothing for full-aggregation members, and the completion of the aggregate signature for final inputs
|
||||
* '''Sighash type''': Optional byte following the signature data. If absent, <code>SIGHASH_DEFAULT</code> (<code>0x00</code>) is used<ref>'''Why does the marker follow the sighash byte and the signature data?''' Traditionally the sighash byte is appended to the signature, as in the 65-byte signatures of BIP 341, and this BIP keeps that order. Placing the marker last, in the position of the sighash byte, is what allows opted-out inputs to use unchanged BIP 341 signatures. A 65-byte element ending in a valid sighash byte is an opted-out signature and one ending in a marker is an aggregation group final, and no marked form is 64 bytes long. With the marker in front, a 65-byte element could be either an opted-out signature with a sighash byte or a full-aggregation final without one.</ref>
|
||||
* '''Marker''': Last byte of the final input's element (<code>0xbc</code> or <code>0xbd</code>)
|
||||
|
||||
The marker and the length of the witness element together determine its interpretation:
|
||||
|
||||
{| class="wikitable"
|
||||
|+ Valid witness element forms by marker and length
|
||||
|-
|
||||
! Marker !! Length !! Content !! Interpretation
|
||||
|-
|
||||
| none || 64 bytes || 64-byte signature || Opted-out, <code>SIGHASH_DEFAULT</code>
|
||||
|-
|
||||
| none || 65 bytes || 64-byte signature and sighash || Opted-out, explicit sighash
|
||||
|-
|
||||
| none || 0 bytes || none || Full-aggregation member, <code>SIGHASH_DEFAULT</code>
|
||||
|-
|
||||
| none || 1 byte || sighash || Full-aggregation member, explicit sighash
|
||||
|-
|
||||
| none || 32 bytes || nonce share || Half-aggregation member, <code>SIGHASH_DEFAULT</code>
|
||||
|-
|
||||
| none || 33 bytes || nonce share and sighash || Half-aggregation member, explicit sighash
|
||||
|-
|
||||
| <code>0xbc</code> || 65 bytes || nonce share and 32-byte ''s'' value || Half-aggregation final, <code>SIGHASH_DEFAULT</code>
|
||||
|-
|
||||
| <code>0xbc</code> || 66 bytes || nonce share, ''s'' value, and sighash || Half-aggregation final, explicit sighash
|
||||
|-
|
||||
| <code>0xbd</code> || 65 bytes || 64-byte signature || Full-aggregation final, <code>SIGHASH_DEFAULT</code>
|
||||
|-
|
||||
| <code>0xbd</code> || 66 bytes || 64-byte signature and sighash || Full-aggregation final, explicit sighash
|
||||
|}
|
||||
|
||||
All forms have a fixed length.
|
||||
A witness element whose marker and length combination matches no row of this table is invalid.
|
||||
Opted-out elements have no marker, so a 64-byte element is an opted-out signature even if its last byte equals a marker value, and a 65-byte element is an opted-out signature unless its last byte is a marker.
|
||||
Only 65-byte and 66-byte elements are interpreted against the marker.
|
||||
In the 1-byte and 33-byte member forms the last byte is a sighash byte, so an element of those lengths ending in a marker value is a member with an invalid sighash type.
|
||||
|
||||
In all forms with an explicit sighash byte the byte must not be <code>0x00</code>.
|
||||
<code>SIGHASH_DEFAULT</code> can only be expressed by omitting the sighash byte.
|
||||
This mirrors the rule for 65-byte signatures in BIP 341 and ensures that every signature message has exactly one witness encoding, preventing third parties from malleating the wtxid by switching between equivalent encodings.
|
||||
|
||||
=== Signature message ===
|
||||
|
||||
The signature message of an aggregated input commits to the input's aggregation mode in addition to the transaction data.
|
||||
Let ''SigMsg(hash_type, ext_flag)'' be the common signature message function defined in BIP 341, including all of its failure conditions.
|
||||
For an aggregated witness v2 key path spend with sighash type ''hash_type'', the message is computed as:
|
||||
|
||||
<source>
|
||||
m = hash_TapSighash(0x01 || agg_mode || SigMsg(hash_type, 0))
|
||||
</source>
|
||||
|
||||
The first byte is the sighash epoch.
|
||||
BIP 341 messages use epoch <code>0x00</code> and reserve other values for signature algorithms that make invasive changes to how hashing is performed, such as this one.
|
||||
The ''agg_mode'' byte is the marker byte of the input's group (<code>0xbc</code> for half-aggregation, <code>0xbd</code> for full-aggregation).
|
||||
Opted-out inputs use the unchanged BIP 341 message ''hash_TapSighash(0x00 || SigMsg(hash_type, 0))''.<ref>'''Why do opted-out inputs keep sighash epoch 0x00?''' The epoch identifies the message computation, not the witness version, and other values are reserved for algorithms that change how hashing is performed. Opted-out spends leave the computation unchanged, so a different epoch would force wallets that do not aggregate to implement a second signing code path without a security benefit. Replaying the resulting signatures across witness versions is not possible because SigMsg commits to the scriptPubKey of the output being spent. Keeping epoch 0x00 also means that a hypothetical witness v2 output type following the BIP 341 rules unchanged would produce the exact same key path spends as the opt-out mode of this BIP.</ref>
|
||||
|
||||
Committing to the aggregation mode makes aggregation consensual.
|
||||
A signature created for an opted-out input is not valid as a member of an aggregation group and vice versa.
|
||||
Without this commitment any third party could fold an opted-out signature into the half-aggregation group unchanged, because half-aggregation of existing signatures is a public operation.
|
||||
See [[#why-no-opt-out-marker|Why no opt-out marker]] for details.
|
||||
|
||||
Valid sighash types are:
|
||||
|
||||
* <code>0x00</code>: <code>SIGHASH_DEFAULT</code> (only expressible by omitting the sighash byte)
|
||||
* <code>0x01</code>: <code>SIGHASH_ALL</code>
|
||||
* <code>0x02</code>: <code>SIGHASH_NONE</code>
|
||||
* <code>0x03</code>: <code>SIGHASH_SINGLE</code>
|
||||
* <code>0x81</code>: <code>SIGHASH_ALL | SIGHASH_ANYONECANPAY</code>
|
||||
* <code>0x82</code>: <code>SIGHASH_NONE | SIGHASH_ANYONECANPAY</code>
|
||||
* <code>0x83</code>: <code>SIGHASH_SINGLE | SIGHASH_ANYONECANPAY</code>
|
||||
|
||||
Note: <code>SIGHASH_ANYONECANPAY</code> composes with aggregation only partially, see [[#usage-of-anyonecanpay|Usage of ANYONECANPAY]].
|
||||
|
||||
=== Opted-out key path spends ===
|
||||
|
||||
An opted-out witness v2 key path spend has a witness stack containing:
|
||||
|
||||
* '''Without annex''': <code>[signature]</code> (64 bytes) or <code>[signature || sighash]</code> (65 bytes)
|
||||
* '''With annex''': <code>[signature] [0x50...]</code> or <code>[signature || sighash] [0x50...]</code>
|
||||
|
||||
Validation proceeds exactly as for a BIP 341 key path spend, using the BIP 341 signature message and BIP 340 signature verification against the output key.
|
||||
|
||||
=== Aggregated key path spends ===
|
||||
|
||||
The aggregate signature data of a group is split across the witness elements of its inputs.
|
||||
|
||||
'''Half-aggregation members:'''
|
||||
|
||||
* '''Without annex''': <code>[nonce share]</code> (32 bytes) or <code>[nonce share || sighash]</code> (33 bytes)
|
||||
* '''With annex''': <code>[nonce share] [0x50...]</code> or <code>[nonce share || sighash] [0x50...]</code>
|
||||
|
||||
The nonce share of an input is the first 32 bytes of its individual BIP 340 signature, see [[#signing|Signing]].
|
||||
|
||||
'''Half-aggregation final input:'''
|
||||
|
||||
* '''Without annex''': <code>[nonce share || s || 0xbc]</code> (65 bytes) or <code>[nonce share || s || sighash || 0xbc]</code> (66 bytes)
|
||||
* '''With annex''': <code>[nonce share || s || 0xbc] [0x50...]</code> or <code>[nonce share || s || sighash || 0xbc] [0x50...]</code>
|
||||
|
||||
The nonce shares of all group inputs in input order, followed by the ''s'' value from the final input, form the ''(n+1)*32''-byte aggregate signature of [[bip-0458.mediawiki|BIP 458]].
|
||||
|
||||
'''Full-aggregation members:'''
|
||||
|
||||
* '''Without annex''': <code>[]</code> (empty element) or <code>[sighash]</code> (1 byte)
|
||||
* '''With annex''': <code>[] [0x50...]</code> or <code>[sighash] [0x50...]</code>
|
||||
|
||||
The empty element is a single witness stack item of length zero.
|
||||
A witness stack without any items remains invalid, see BIP 341.
|
||||
|
||||
'''Full-aggregation final input:'''
|
||||
|
||||
* '''Without annex''': <code>[signature || 0xbd]</code> (65 bytes) or <code>[signature || sighash || 0xbd]</code> (66 bytes)
|
||||
* '''With annex''': <code>[signature || 0xbd] [0x50...]</code> or <code>[signature || sighash || 0xbd] [0x50...]</code>
|
||||
|
||||
The signature is the 64-byte aggregate signature of [[bip-0459.mediawiki|BIP 459]].
|
||||
|
||||
An aggregation group may consist of a single input.
|
||||
In that case the group's only input is its final input.
|
||||
|
||||
=== Validation rules ===
|
||||
|
||||
Witness v2 key path spends are validated in three passes:
|
||||
|
||||
'''Pass 1: Parse and collect aggregation information'''
|
||||
|
||||
For each witness v2 key path spend:
|
||||
|
||||
1. '''Extract annex if present''':
|
||||
* If the witness stack has at least two elements, and the first byte of the last element is <code>0x50</code>, this last element is the annex and is removed from the witness stack
|
||||
|
||||
2. '''Parse the witness element''':
|
||||
* If the element is 64 bytes long, or 65 bytes long and its last byte is not <code>0xbc</code> or <code>0xbd</code>, it is an opted-out signature and is parsed per BIP 341
|
||||
* Otherwise the length determines the structure per the table above, where 65-byte and 66-byte elements must end in a marker byte. Fail if the combination matches no defined structure
|
||||
* Extract ''hash_type'' and signature data if present
|
||||
* Verify ''hash_type'' is valid (<code>0x01</code>-<code>0x03</code>, <code>0x81</code>-<code>0x83</code> in explicit form). Fail on an explicit <code>0x00</code>
|
||||
|
||||
3. '''Classify input''':
|
||||
* '''64-byte or 65-byte signature''': Opted-out input
|
||||
* '''Empty, 1-byte, 32-byte, or 33-byte element''': Aggregation member
|
||||
* '''65-byte or 66-byte element ending in <code>0xbc</code> or <code>0xbd</code>''': Final input of that marker's group
|
||||
|
||||
The structure table is exhaustive, so every witness element that parses successfully falls into exactly one class.
|
||||
|
||||
'''Pass 2: Validate aggregation group structure'''
|
||||
|
||||
Group formation rules:
|
||||
* The half-aggregation group consists of the 32-byte and 33-byte members and the <code>0xbc</code> final input
|
||||
* The full-aggregation group consists of the empty and 1-byte members and the <code>0xbd</code> final input
|
||||
* Fail if a group has members but no final input, or more than one final input
|
||||
* Fail if a member of a group appears after that group's final input
|
||||
* Opted-out inputs do not form groups
|
||||
|
||||
'''Pass 3: Verify signatures'''
|
||||
|
||||
1. '''For each opted-out input''':
|
||||
* Compute the message ''m = hash_TapSighash(0x00 || SigMsg(hash_type, 0))'' as in BIP 341
|
||||
* Verify the 64-byte signature using BIP 340 against the output key (the 32-byte witness program of the spent output)
|
||||
|
||||
2. '''For each aggregation group''':
|
||||
* Collect the group's inputs, consisting of its members and its final input
|
||||
* Order the group's (pubkey, message) pairs by input index, where the pubkey of each pair is the 32-byte witness program of the spent output
|
||||
* For each aggregated input ''i'': compute ''m<sub>i</sub> = hash_TapSighash(0x01 || marker || SigMsg(hash_type<sub>i</sub>, 0))''
|
||||
* For half-agg: assemble the aggregate signature as the concatenation of the group's nonce shares in input order followed by the ''s'' value of the final input
|
||||
* For half-agg: verify the assembled aggregate signature with ''VerifyAggregate(aggsig, pm_aggd)'' as defined in [[bip-0458.mediawiki|BIP 458]], where ''pm_aggd'' is the ordered list of pairs
|
||||
* For full-agg: verify the final input's 64-byte signature with ''Verify'' as defined in [[bip-0459.mediawiki|BIP 459]] over the ordered pubkey and message lists
|
||||
|
||||
=== Signing ===
|
||||
|
||||
Signers of aggregated inputs compute the signature message defined above with the marker byte of their group as ''agg_mode''.
|
||||
The secret key is the Taproot tweaked private key corresponding to the 32-byte witness program, derived as in BIP 341.
|
||||
|
||||
'''Opted-out inputs''':
|
||||
The signer creates a BIP 341 key path signature exactly as for a Taproot output.
|
||||
|
||||
'''Half-aggregated inputs''':
|
||||
Each signer creates an ordinary BIP 340 signature over its message in a single stateless pass.
|
||||
The first 32 bytes of the signature are the input's nonce share, which can be placed in the member's witness element as soon as the signature exists.
|
||||
The ''s'' parts of the individual signatures do not appear on chain.
|
||||
Once all signatures of the group are available, any party can combine them with ''Aggregate'' or ''IncAggregate'' as defined in [[bip-0458.mediawiki|BIP 458]], over the group's pairs ordered by input index, and place the last 32 bytes of the result as the ''s'' value in the final input's witness element.
|
||||
The aggregating party should verify the individual signatures first.
|
||||
This identifies a disruptive signer and is necessary because ''Aggregate'' does not validate its inputs, see BIP 458.
|
||||
|
||||
'''Full-aggregated inputs''':
|
||||
The group's signers run the interactive signing protocol of [[bip-0459.mediawiki|BIP 459]].
|
||||
The public key list of the session is the ordered list of the group's 32-byte witness programs and the message list contains the corresponding signature messages in the same order.
|
||||
Each signer uses its tweaked secret key, see the [[bip-0459.mediawiki#key-tweaking|Key Tweaking]] section of BIP 459.
|
||||
The 64-byte signature returned by ''SigAgg'' is placed in the final input's witness element.
|
||||
Any change that affects a group member's signature message or the group's ordered member list invalidates the session and requires a new one.
|
||||
Secret nonces must never be reused across signing sessions, see BIP 459.
|
||||
|
||||
== Examples ==
|
||||
|
||||
The final input of each aggregation group carries the marker and the completion of the aggregate signature and therefore more witness weight than the other group members.
|
||||
How this weight difference is accounted for between the participants of a collaborative transaction is a protocol level concern outside the scope of this BIP.
|
||||
|
||||
'''Example 1: Three inputs, all half-aggregated with SIGHASH_DEFAULT'''
|
||||
<source>
|
||||
Input 0 witness: [32-byte nonce share] # 32 bytes: half-agg member
|
||||
Input 1 witness: [32-byte nonce share] # 32 bytes: half-agg member
|
||||
Input 2 witness: [nonce share || s || 0xbc] # 65 bytes: half-agg final
|
||||
|
||||
Total overhead: 1 marker byte
|
||||
Signature size reduction: 192 bytes → 129 bytes
|
||||
</source>
|
||||
|
||||
'''Example 2: Three inputs full-aggregated with SIGHASH_ALL'''
|
||||
<source>
|
||||
Input 0 witness: [0x01] # 1 byte: full-agg member, SIGHASH_ALL
|
||||
Input 1 witness: [0x01] # 1 byte: full-agg member, SIGHASH_ALL
|
||||
Input 2 witness: [64-byte sig || 0x01 || 0xbd] # 66 bytes: full-agg final, SIGHASH_ALL
|
||||
|
||||
Total overhead: 1 marker byte
|
||||
Signature size reduction: 195 bytes → 68 bytes
|
||||
</source>
|
||||
|
||||
'''Example 3: Witness v1 input alongside a witness v2 aggregation group'''
|
||||
<source>
|
||||
Input 0 witness: [64-byte sig] # witness v1 (Taproot) key path spend
|
||||
Input 1 witness: [32-byte nonce share] # 32 bytes: half-agg member
|
||||
Input 2 witness: [nonce share || s || 0xbc] # 65 bytes: half-agg final
|
||||
|
||||
Input 0 spends a Taproot output and does not participate in aggregation.
|
||||
Inputs 1 and 2 form the half-aggregation group.
|
||||
|
||||
Total overhead: 1 marker byte
|
||||
Signature size reduction (v2 inputs): 128 bytes → 97 bytes
|
||||
</source>
|
||||
|
||||
'''Example 4: Mixed transaction'''
|
||||
<source>
|
||||
Input 0 witness: [64-byte sig] # 64 bytes: opted-out, SIGHASH_DEFAULT
|
||||
Input 1 witness: [nonce share || 0x03] # 33 bytes: half-agg member, SIGHASH_SINGLE
|
||||
Input 2 witness: [] # empty: full-agg member
|
||||
Input 3 witness: [] # empty: full-agg member
|
||||
Input 4 witness: [nonce share || s || 0xbc] # 65 bytes: half-agg final
|
||||
Input 5 witness: [64-byte sig || 0x82] # 65 bytes: opted-out, SIGHASH_NONE|SIGHASH_ANYONECANPAY
|
||||
Input 6 witness: [64-byte sig || 0xbd] # 65 bytes: full-agg final
|
||||
|
||||
This transaction has:
|
||||
- Two opted-out inputs (0, 5) with different sighash types
|
||||
- One half-aggregation group (inputs 1, 4)
|
||||
- One full-aggregation group (inputs 2, 3, 6)
|
||||
|
||||
Total overhead: 2 marker bytes
|
||||
Signature size reduction: 450 bytes → 292 bytes
|
||||
</source>
|
||||
|
||||
== Security ==
|
||||
|
||||
'''Non-consensual aggregation''':
|
||||
The signature message of aggregated inputs commits to the aggregation mode, so third parties cannot move signatures between opted-out witnesses and aggregation groups, see [[#why-no-opt-out-marker|Why no opt-out marker]].
|
||||
Signatures also cannot be replayed between witness versions because the signature message always commits to the scriptPubKey of the output being spent.
|
||||
|
||||
'''Adaptor signature incompatibility''':
|
||||
Aggregation is incompatible with protocols that extract a secret from a specific signature appearing on chain, most notably some adaptor signature protocols.
|
||||
Adaptor protocols in which the final signature is delivered directly between the parties are not affected.
|
||||
Protocols that rely on on-chain extraction should use opted-out signatures for those inputs.
|
||||
|
||||
'''Shared security of the three modes''':
|
||||
Every witness v2 output can be spent through any of the three key path modes, chosen by whoever produces the witness.
|
||||
The security of v2 outputs therefore rests on all three verification algorithms together, and a soundness failure in BIP 340, BIP 458, or BIP 459 would affect all v2 outputs regardless of the mode their owners intended to use.
|
||||
Both aggregation schemes come with security proofs that reduce to established assumptions in the same discrete logarithm setting as BIP 340, see the security discussions in BIP 458 and BIP 459.
|
||||
|
||||
'''Witness malleability''':
|
||||
For key path spends every witness element size is fixed by consensus and the annex is committed by the signature message, so third parties cannot change the weight of a fully signed input.
|
||||
Given the nonce shares of a group, only one value of ''s'' satisfies the verification equation, and replacing a nonce share requires knowledge of the individual signatures.
|
||||
Third parties therefore cannot malleate witness v2 key path witness data.
|
||||
Opted-out inputs carry plain BIP 340 signatures, which are non-malleable.
|
||||
|
||||
'''Transaction level verification''':
|
||||
Aggregated inputs add one transaction level verification step per aggregation group, while parsing, structure checks, opted-out inputs, and script path spends remain per-input operations.
|
||||
Implementations that parallelize script validation per input can schedule the group verification as one additional check.
|
||||
Existing wtxid based validation caches remain correct since any witness change alters the wtxid.
|
||||
Aggregate verification can also join verification batches together with individual BIP 340 signatures, so aggregation does not preclude batch validation.
|
||||
|
||||
'''Computation limits''':
|
||||
Aggregation does not increase the worst-case signature verification cost of a block.
|
||||
Full-aggregation requires about half the elliptic curve multiplications per input of individual BIP 340 verification, while half-aggregation requires about the same number in a single batchable equation.
|
||||
The densest packing of signature verification work per weight unit remains tapscript under the BIP 342 validation weight budget, which this BIP does not change.<ref>A minimal Taproot key path input weighs 230 weight units, 164 for the input base data plus 66 for the witness element, and BIP 340 verification costs two elliptic curve multiplications per signature.
|
||||
Per member of a large group, full-aggregation accounts for 166 weight units and half-aggregation for 198 weight units including the member's 32-byte nonce share, ignoring small per-group constants.
|
||||
The BIP 459 verification equation costs ''n+1'' multiplications for a group of ''n'' inputs, while the BIP 458 equation costs about ''2n'' since the randomizers multiply both the nonce point and the challenge term of each member.
|
||||
Ignoring transaction overhead, a block filled with minimal full-aggregation members needs about 4,000,000 / 166 ≈ 24,100 multiplications and one filled with minimal half-aggregation members about 2 * 4,000,000 / 198 ≈ 40,400, compared to 2 * 4,000,000 / 230 ≈ 34,800 for minimal Taproot key path spends.
|
||||
The half-aggregation count is about 16 percent higher, but its per-input cost matches batch verified BIP 340 signatures and the whole group is verified as one multi-scalar multiplication, which is faster in practice than the same number of independent verifications.
|
||||
All of these remain far below the BIP 342 validation weight budget, which admits one tapscript signature verification per 50 weight units, or 80,000 verifications with about 160,000 multiplications per block.
|
||||
Aggregation also does not increase the maximum number of inputs per block, since an input spending an output that requires no signature, such as a bare OP_TRUE script, weighs only 164 weight units today.</ref>
|
||||
|
||||
'''Mode fingerprinting''':
|
||||
The aggregation mode of every input is visible on chain from its witness element, so distinctive mode combinations can fingerprint the wallets or protocols that created a transaction.
|
||||
Participants of collaborative transactions should prefer one mode for all participating inputs if they want to avoid this.
|
||||
|
||||
== Test vectors ==
|
||||
|
||||
Wallet operation vectors covering scriptPubKey and address computation, signature message computation, and witness construction for both key path and script path spending can be found in [[bip-0460/wallet-test-vectors.json|wallet-test-vectors.json]].
|
||||
|
||||
Transaction level validity cases, including marker parsing failures, group structure failures, annex handling, script path spending, and the aggregation mode commitment, can be found in [[bip-0460/consensus-test-vectors.json|consensus-test-vectors.json]].
|
||||
|
||||
Both files are generated by [[bip-0460/test-vectors.py|test-vectors.py]], which builds on the reference code of BIP 458 and BIP 459.
|
||||
All vectors use deterministic test-only keys and nonces, and BIP 340 signatures are created with an all-zero auxiliary randomness array, except one vector that deterministically searches auxiliary randomness values to produce a signature ending in a marker byte.
|
||||
|
||||
== Reference implementation ==
|
||||
|
||||
A work in progress implementation for Bitcoin Core is available at https://github.com/fjahr/bitcoin/tree/bip460.
|
||||
It implements the validation rules of this BIP and validates all consensus test vectors.
|
||||
|
||||
== Rationale ==
|
||||
|
||||
=== Why a new witness version? ===
|
||||
|
||||
A new witness version is necessary because BIP 341 completely specifies the validation rules for witness v1, fixing key path witnesses to 64-byte or 65-byte signatures.
|
||||
The aggregation witness forms used by this BIP are invalid under those rules, and a soft fork can only turn valid transactions into invalid ones, not the reverse.
|
||||
Aggregation therefore cannot be retrofitted onto existing Taproot outputs.
|
||||
|
||||
=== Why the marker-based design? ===
|
||||
|
||||
The primary alternative to markers is a design without them, where aggregated inputs carry only a 1-byte sighash placeholder and aggregation applies to all witness v2 inputs of a transaction or to none of them.
|
||||
Compared to that alternative the markers cost one byte per aggregation group.
|
||||
In exchange the marker provides three properties:
|
||||
|
||||
'''Per-input consent''':
|
||||
An all-or-nothing design couples the choices of unrelated parties.
|
||||
In a CoinJoin a single participant that requires a plain on-chain signature, for example for an adaptor signature based protocol, would force every other participant to forgo aggregation.
|
||||
With markers this choice is local to the input, which matters most in exactly the multi-party transactions that CISA is designed to make cheaper.
|
||||
|
||||
'''Self-describing witnesses''':
|
||||
Every input is classified locally by the length and last byte of its witness element instead of inferring a transaction-wide mode from the shape of all witnesses.
|
||||
This avoids inference edge cases.
|
||||
For example, in the placeholder design the final aggregated input's witness consists of a sighash byte followed by the aggregate signature as a separate element, and an aggregate signature whose first byte happens to be <code>0x50</code> is misparsed as an annex under the BIP 341 annex rule.
|
||||
Roughly one in 256 honestly generated aggregate signatures would hit this case and force the signers to start over.
|
||||
In this design the signature data of every input is part of its single witness element, which the annex rule never inspects, so no signature data can be misparsed as an annex.
|
||||
|
||||
'''Two coexisting groups''':
|
||||
A transaction can contain one half-aggregation group and one full-aggregation group at the same time.
|
||||
This allows a tightly coordinated subset of signers, for example the inputs of a single wallet, to use full-aggregation while the remaining inputs of a collaborative transaction use half-aggregation.
|
||||
|
||||
Group members carry no marker, since the member element lengths are disjoint from all other forms and the length alone classifies them.
|
||||
Half-aggregation members carry their nonce share directly instead of contributing to a growing aggregate signature on the final input.
|
||||
This makes every witness element form fixed-size and distributes the witness weight of the aggregate evenly across the group's inputs.
|
||||
Only the final inputs need a marker, because the completion of an aggregate signature is indistinguishable from a BIP 341 signature by content.
|
||||
|
||||
A more flexible alternative with multiple aggregation groups per scheme, similar to the bucket concept from early aggregation discussions, was rejected.
|
||||
Multiple groups would only benefit full-aggregation, since half-aggregation groups can be merged by anyone after signing.
|
||||
They would allow several smaller signing sessions instead of one session spanning all aggregated inputs, for example through a group number encoded in the marker byte.
|
||||
However, with <code>SIGHASH_DEFAULT</code> the signers of every group still have to agree on the complete output list of the transaction before signing, making coordination across groups necessary.
|
||||
Decoupling the groups through <code>SIGHASH_SINGLE</code> with <code>SIGHASH_ANYONECANPAY</code> is limited to groups of signers with a single input and output each, reveals which input pays which output, and lets anyone split the merged transaction apart again.
|
||||
Half-aggregation already provides this flexibility without any joint signing session at a cost of 32 weight units per input, and a separate transaction per group provides it at the cost of repeating the transaction overhead.
|
||||
Group numbers would also reveal which inputs belong together, which has negative privacy implications.
|
||||
|
||||
=== Why no opt-out marker? ===
|
||||
|
||||
The main motivation for the unmarked opt-out is compatibility with BIP 341.
|
||||
Opted-out spends are byte-identical to BIP 341 key path spends, so wallets that do not aggregate can adopt the new output type without new signing logic.
|
||||
Leaving out the marker also saves one byte per opted-out input.
|
||||
|
||||
Opted-out inputs still need protection from non-consensual aggregation.
|
||||
Half-aggregation of existing signatures is a public operation.
|
||||
Any third party in possession of valid BIP 340 signatures, such as a miner or a relaying node, can aggregate them without the signers' involvement.
|
||||
Some protocols depend on a specific signature appearing on chain.
|
||||
Most notably, some adaptor signature protocols extract a secret from the difference between an on-chain signature and a previously shared adaptor signature, and this extraction becomes impossible once the signature has been folded into an aggregate.
|
||||
|
||||
For this protection the separation of the signature messages is sufficient.
|
||||
An opted-out signature is created over the BIP 341 message and is therefore useless as an aggregation group member, and vice versa.
|
||||
Aggregation is consensual for every input.
|
||||
|
||||
An explicit opt-out marker would serve parsing rather than protection, distinguishing a 65-byte opted-out signature with a sighash byte from an aggregation group final without one.
|
||||
Markers in the position of the sighash byte resolve this ambiguity without marking opted-out inputs, since marker values are disjoint from valid sighash values.
|
||||
A small caveat is that a future witness version that keeps the witness v2 rules cannot use the marker values as sighash types.
|
||||
|
||||
A consequence of the mode commitment is that the aggregation mode is chosen at signing time.
|
||||
A signature created for aggregation cannot later be used as a standalone opted-out signature either, so signers that want to keep both options open must produce two signatures.
|
||||
Planning for aggregation costs one weight unit if the group ends up with a single member, since the single-member group signature carries the marker.
|
||||
|
||||
=== Why two aggregation schemes? ===
|
||||
|
||||
Half-aggregation and full-aggregation serve different use cases:
|
||||
|
||||
{| class="wikitable"
|
||||
|+ Comparison of aggregation schemes
|
||||
|-
|
||||
! Property !! Half-Aggregation !! Full-Aggregation
|
||||
|-
|
||||
| '''Signature size''' || ''(n+1)*32'' bytes || 64 bytes (constant)
|
||||
|-
|
||||
| '''Interactivity''' || Non-interactive || Interactive (2 rounds)
|
||||
|-
|
||||
| '''Use case''' || All transaction types || Interactive protocols such as CoinJoins, wallet consolidation
|
||||
|-
|
||||
| '''Incremental''' || Yes || No
|
||||
|}
|
||||
|
||||
Full-aggregation offers roughly twice the savings of half-aggregation but requires all signers to run a stateful two-round protocol within one signing session.
|
||||
Mishandling the secret nonce state between the rounds can lead to key extraction, which makes supporting it on hardware signers and air-gapped devices demanding.
|
||||
The slow adoption of MuSig2 by signing devices illustrates this cost.
|
||||
|
||||
Half-aggregation signers produce plain BIP 340 signatures in a single stateless pass, and the aggregation happens downstream of all signing.
|
||||
This fits existing asynchronous multi-party workflows, for example PSBT based signing ceremonies where cosigners are available at different times, or [[bip-0077.md|BIP 77]] Async Payjoin where sender and receiver are not required to be online at the same time.
|
||||
It also avoids giving every participant of a large collaborative transaction a second opportunity to stall the protocol between signing rounds.
|
||||
Finally, half-aggregation composes with workflows where the input set is still growing after signing has started, such as ANYONECANPAY based fee bumping, because aggregation can happen once the set is final.
|
||||
|
||||
=== Why key path only? ===
|
||||
|
||||
Key path spends have one signature per input that is visible from the witness structure alone, which makes their aggregation rules simple.
|
||||
The use cases motivating this BIP, collaborative transactions and consolidations, also typically use simple key path spends.
|
||||
Aggregating signatures from within scripts, in contrast, conflicts with the tapscript upgrade mechanisms.
|
||||
Whether a signature operation contributes to the transaction level aggregate depends on script execution, but a script containing an <code>OP_SUCCESS</code> opcode succeeds without being executed.
|
||||
A later soft fork redefining such an opcode would change which signatures the aggregate has to cover, so transactions valid under the new rules would be invalid for older nodes, turning the redefinition into a hard fork.
|
||||
This is a variant of the problem described in [https://gnusha.org/pi/bitcoindev/20180321040618.GA4494@erisian.com.au/ the 2018 aggregation discussion by Anthony Towns], whose mitigations rely on execution order, which the parse time <code>OP_SUCCESS</code> semantics of tapscript do not provide.
|
||||
Script execution raises further design questions, for example the BIP 342 sigops budget assumes 50 witness weight units per signature check and would be exhausted by short placeholder signatures, and the aggregate signature must be located before execution while group membership only becomes known during it.
|
||||
Solving these questions is left for a separate BIP with its own upgrade semantics.
|
||||
|
||||
=== Usage of ANYONECANPAY ===
|
||||
|
||||
This BIP permits all standard sighash types at the consensus level, including <code>SIGHASH_ANYONECANPAY</code> (<code>0x80</code> flag).
|
||||
Whether to aggregate is an application level decision, not a consensus concern, so the consensus rules stay permissive.
|
||||
|
||||
'''Full-aggregation''':
|
||||
The signing session of BIP 459 fixes the group's public key and message lists, so the membership of a full-aggregation group cannot grow after signing has started.
|
||||
ANYONECANPAY still composes with full-aggregation in one direction.
|
||||
Once the group members have signed with ANYONECANPAY, additional opted-out, half-aggregated, or non-v2 inputs can be appended to the transaction without invalidating the group, because the group's messages do not commit to those inputs.
|
||||
Only extending the full-aggregation group itself with later inputs is impossible.
|
||||
|
||||
'''Half-aggregation''':
|
||||
Half-aggregation composes with ANYONECANPAY directly.
|
||||
Signers create their signatures over the half-aggregation flavored message at signing time, further inputs are added later, and once the input set is final anyone can aggregate the collected signatures without further involvement of the signers.
|
||||
|
||||
=== Future considerations ===
|
||||
|
||||
'''Block-wide aggregation''':
|
||||
Block-wide aggregation remains a potential future optimization and is not precluded by this design.
|
||||
Opted-out inputs do not necessarily signal that the signer needs the signature on chain unaggregated, since there may be other motivations such as simple adoption, so such a design would probably need its own explicit opt-out.
|
||||
|
||||
'''Script path aggregation''':
|
||||
Script path aggregation can be specified in a separate BIP and added in the same or a future soft fork.
|
||||
|
||||
== Deployment ==
|
||||
|
||||
This BIP is to be deployed by a soft fork activation mechanism.
|
||||
The activation parameters are to be determined and will be specified in a future update of this document.
|
||||
Since other proposals also target witness version 2, the witness version is subject to coordination and may change in a future update as well.
|
||||
|
||||
== Backward compatibility ==
|
||||
|
||||
=== Non-upgraded nodes ===
|
||||
|
||||
Nodes that have not upgraded to support witness v2 treat witness v2 outputs as anyone-can-spend, per the [[bip-0141.mediawiki|BIP 141]] unknown witness version rule.
|
||||
Depending on their policy settings, such nodes might not relay witness v2 transactions or include them in blocks.
|
||||
|
||||
=== Non-upgraded wallets ===
|
||||
|
||||
Wallets without witness v2 support cannot create or spend witness v2 outputs but can send to witness v2 addresses if they support Bech32m.
|
||||
|
||||
== Acknowledgements ==
|
||||
|
||||
Thanks to Vojtěch Strnad for feedback on early versions of this BIP, in particular for prompting a precise description of the script path aggregation obstacles and for streamlining the specification.
|
||||
Thanks to conduition for suggesting the distribution of the half-aggregation signature data across the group's witness elements.
|
||||
|
||||
== Footnotes ==
|
||||
|
||||
<references />
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,211 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Reference implementation of BIP 459 DahLIAS fully aggregated signatures
|
||||
for secp256k1.
|
||||
|
||||
WARNING: This implementation is for demonstration purposes only and is not
|
||||
optimized for production use.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
from typing import List, Tuple, Optional
|
||||
import secrets
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent / "secp256k1lab/src"))
|
||||
from secp256k1lab.secp256k1 import G, GE, Scalar
|
||||
from secp256k1lab.util import tagged_hash, xor_bytes
|
||||
|
||||
n = GE.ORDER
|
||||
|
||||
FULLAGG_TAG_AUX = "BIP0459/aux"
|
||||
FULLAGG_TAG_NONCE = "BIP0459/nonce"
|
||||
FULLAGG_TAG_NONCECOEF = "BIP0459/noncecoef"
|
||||
FULLAGG_TAG_SIG = "BIP0459/sig"
|
||||
|
||||
|
||||
#
|
||||
# Helpers
|
||||
#
|
||||
|
||||
def has_even_y(P: GE) -> bool:
|
||||
return P.has_even_y()
|
||||
|
||||
|
||||
def cbytes(P: GE) -> bytes:
|
||||
return P.to_bytes_compressed()
|
||||
|
||||
|
||||
def xbytes(P: GE) -> bytes:
|
||||
return P.to_bytes_xonly()
|
||||
|
||||
|
||||
#
|
||||
# Key Tweaking
|
||||
#
|
||||
|
||||
def TweakSK(sk: Scalar, t: Scalar, is_xonly: bool) -> Scalar:
|
||||
d = sk if (not is_xonly or has_even_y(sk * G)) else -sk
|
||||
sk_out = d + t
|
||||
if sk_out == 0:
|
||||
raise ValueError("tweaked secret key is zero")
|
||||
return sk_out
|
||||
|
||||
|
||||
def TweakPK(pk: GE, t: Scalar, is_xonly: bool) -> GE:
|
||||
P = pk if (not is_xonly or has_even_y(pk)) else -pk
|
||||
Q = P + t * G
|
||||
if Q.infinity:
|
||||
raise ValueError("tweaked public key is the point at infinity")
|
||||
return Q
|
||||
|
||||
|
||||
#
|
||||
# Nonce Generation and Aggregation
|
||||
#
|
||||
|
||||
def NonceGenInternal(rand_prime: bytes, sk: Optional[Scalar] = None,
|
||||
extra_in: bytes = b'') -> Tuple[Tuple[Scalar, Scalar], Tuple[GE, GE]]:
|
||||
if sk is not None:
|
||||
rand = xor_bytes(sk.to_bytes(), tagged_hash(FULLAGG_TAG_AUX, rand_prime))
|
||||
else:
|
||||
rand = rand_prime
|
||||
r1 = Scalar.from_bytes_wrapping(tagged_hash(FULLAGG_TAG_NONCE, rand + extra_in + b'\x00'))
|
||||
r2 = Scalar.from_bytes_wrapping(tagged_hash(FULLAGG_TAG_NONCE, rand + extra_in + b'\x01'))
|
||||
assert r1 != 0 and r2 != 0
|
||||
R1, R2 = r1 * G, r2 * G
|
||||
return (r1, r2), (R1, R2)
|
||||
|
||||
|
||||
def NonceGen(sk: Optional[Scalar] = None,
|
||||
extra_in: bytes = b'') -> Tuple[Tuple[Scalar, Scalar], Tuple[GE, GE]]:
|
||||
rand_prime = secrets.token_bytes(32)
|
||||
return NonceGenInternal(rand_prime, sk, extra_in)
|
||||
|
||||
|
||||
def NonceAgg(pubnonces: List[Tuple[GE, GE]]) -> Tuple[GE, GE]:
|
||||
u = len(pubnonces)
|
||||
R1, R2 = pubnonces[0]
|
||||
for i in range(1, u):
|
||||
R1 = R1 + pubnonces[i][0]
|
||||
R2 = R2 + pubnonces[i][1]
|
||||
if R1.infinity or R2.infinity:
|
||||
raise ValueError("aggregate nonce is the point at infinity")
|
||||
return R1, R2
|
||||
|
||||
|
||||
#
|
||||
# Session Values
|
||||
#
|
||||
|
||||
def GetSessionValues(aggnonce: Tuple[GE, GE], pks: List[GE], msgs: List[bytes],
|
||||
pubnonces: List[Tuple[GE, GE]]) -> Tuple[GE, Scalar]:
|
||||
R1, R2 = aggnonce
|
||||
u = len(pks)
|
||||
nonce_data = cbytes(R1) + cbytes(R2)
|
||||
for i in range(u):
|
||||
nonce_data += xbytes(pks[i]) + msgs[i] + cbytes(pubnonces[i][1])
|
||||
b = Scalar.from_bytes_wrapping(tagged_hash(FULLAGG_TAG_NONCECOEF, nonce_data))
|
||||
R = R1 + b * R2
|
||||
assert not R.infinity
|
||||
return R, b
|
||||
|
||||
|
||||
#
|
||||
# Signing
|
||||
#
|
||||
|
||||
def Sign(secnonce: Tuple[Scalar, Scalar], sk: Scalar, m: bytes,
|
||||
aggnonce: Tuple[GE, GE], pks: List[GE], msgs: List[bytes],
|
||||
pubnonces: List[Tuple[GE, GE]]) -> Scalar:
|
||||
if not (len(pks) == len(msgs) == len(pubnonces) >= 1):
|
||||
raise ValueError("list lengths must match and be nonzero")
|
||||
if len(m) != 32 or any(len(mi) != 32 for mi in msgs):
|
||||
raise ValueError("messages must be 32 bytes")
|
||||
r1, r2 = secnonce
|
||||
if r1 == 0 or r2 == 0:
|
||||
raise ValueError("secnonce value is zero")
|
||||
if sk == 0:
|
||||
raise ValueError("secret key is zero")
|
||||
P = sk * G
|
||||
R2_local = r2 * G
|
||||
|
||||
# Index lookup and uniqueness check
|
||||
matches = [j for j in range(len(pubnonces)) if pubnonces[j][1] == R2_local]
|
||||
if len(matches) != 1:
|
||||
raise ValueError("signer's R2 must appear exactly once")
|
||||
j = matches[0]
|
||||
if xbytes(pks[j]) != xbytes(P) or msgs[j] != m:
|
||||
raise ValueError("public key or message at signer's index does not match")
|
||||
|
||||
R, b = GetSessionValues(aggnonce, pks, msgs, pubnonces)
|
||||
e = Scalar(1) if has_even_y(R) else -Scalar(1)
|
||||
d_prime = sk if has_even_y(P) else -sk
|
||||
|
||||
L = b''
|
||||
for i in range(len(pks)):
|
||||
L += xbytes(pks[i]) + msgs[i]
|
||||
c_j = Scalar.from_bytes_wrapping(tagged_hash(FULLAGG_TAG_SIG, L + xbytes(R) + xbytes(pks[j]) + msgs[j]))
|
||||
s_j = e * (r1 + b * r2) + c_j * d_prime
|
||||
return s_j
|
||||
|
||||
|
||||
#
|
||||
# Aggregation
|
||||
#
|
||||
|
||||
def SigAgg(aggnonce: Tuple[GE, GE], pks: List[GE], msgs: List[bytes],
|
||||
pubnonces: List[Tuple[GE, GE]], psigs: List[Scalar]) -> Tuple[GE, Scalar]:
|
||||
if not (len(pks) == len(msgs) == len(pubnonces) == len(psigs) >= 1):
|
||||
raise ValueError("list lengths must match and be nonzero")
|
||||
if any(len(mi) != 32 for mi in msgs):
|
||||
raise ValueError("messages must be 32 bytes")
|
||||
R, _ = GetSessionValues(aggnonce, pks, msgs, pubnonces)
|
||||
s = Scalar.sum(*psigs)
|
||||
return R, s
|
||||
|
||||
|
||||
#
|
||||
# Partial Signature Verification
|
||||
#
|
||||
|
||||
def PartialSigVerify(psig: Scalar, pks: List[GE], msgs: List[bytes],
|
||||
pubnonces: List[Tuple[GE, GE]], signer_index: int) -> bool:
|
||||
if not (len(pks) == len(msgs) == len(pubnonces) >= 1) or any(len(mi) != 32 for mi in msgs):
|
||||
return False
|
||||
if not (0 <= signer_index < len(pks)):
|
||||
return False
|
||||
i = signer_index
|
||||
R1_i, R2_i = pubnonces[i]
|
||||
P_i = GE.from_bytes_xonly(xbytes(pks[i]))
|
||||
R, b = GetSessionValues(NonceAgg(pubnonces), pks, msgs, pubnonces)
|
||||
e = Scalar(1) if has_even_y(R) else -Scalar(1)
|
||||
|
||||
L = b''
|
||||
for k in range(len(pks)):
|
||||
L += xbytes(pks[k]) + msgs[k]
|
||||
c_i = Scalar.from_bytes_wrapping(tagged_hash(FULLAGG_TAG_SIG, L + xbytes(R) + xbytes(pks[i]) + msgs[i]))
|
||||
R_eff_i = R1_i + b * R2_i
|
||||
return psig * G == e * R_eff_i + c_i * P_i
|
||||
|
||||
|
||||
#
|
||||
# Aggregate Signature Verification
|
||||
#
|
||||
|
||||
def Verify(pks: List[GE], msgs: List[bytes], sig: Tuple[GE, Scalar]) -> bool:
|
||||
R_point, s = sig
|
||||
if not (len(pks) == len(msgs) >= 1) or any(len(mi) != 32 for mi in msgs):
|
||||
return False
|
||||
u = len(pks)
|
||||
R = GE.from_bytes_xonly(xbytes(R_point))
|
||||
Ps = [GE.from_bytes_xonly(xbytes(pks[i])) for i in range(u)]
|
||||
|
||||
L = b''
|
||||
for i in range(u):
|
||||
L += xbytes(pks[i]) + msgs[i]
|
||||
rhs = R
|
||||
for i in range(u):
|
||||
c_i = Scalar.from_bytes_wrapping(tagged_hash(FULLAGG_TAG_SIG, L + xbytes(R) + xbytes(pks[i]) + msgs[i]))
|
||||
rhs = rhs + c_i * Ps[i]
|
||||
return s * G == rhs
|
||||
@@ -0,0 +1,197 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Schnorr signature half-aggregation reference implementation
|
||||
|
||||
WARNING: This implementation is for demonstration purposes only and _not_ to
|
||||
be used in production environments.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent / "secp256k1lab/src"))
|
||||
from secp256k1lab.secp256k1 import (
|
||||
G,
|
||||
GE,
|
||||
Scalar,
|
||||
)
|
||||
from secp256k1lab.util import (
|
||||
tagged_hash,
|
||||
)
|
||||
|
||||
|
||||
def Aggregate(pms):
|
||||
"""
|
||||
Aggregates an array of triples (public key, message, signature) into a single aggregate signature.
|
||||
|
||||
:param pms: An array of triples (public key, message, signature).
|
||||
:return: The aggregate signature.
|
||||
"""
|
||||
|
||||
# Let aggsig = bytes(0)
|
||||
aggsig = bytes([0] * 32)
|
||||
|
||||
pm_aggd = []
|
||||
|
||||
# Return IncAggregate(aggsig, pms0..u-1); fail if that fails.
|
||||
return IncAggregate(aggsig, pm_aggd, pms)
|
||||
|
||||
|
||||
# IncAggregate(aggsig, pm_aggd0..v-1, pms_to_agg0..u-1)
|
||||
def IncAggregate(aggsig, pm_aggd, pms_to_agg):
|
||||
"""
|
||||
Incrementally aggregates an additional array of triples (public key, message, signature)
|
||||
into an existing aggregate signature.
|
||||
|
||||
:param aggsig: A byte array representing the aggregate signature.
|
||||
:param pm_aggd: An array of tuples (public key, message).
|
||||
:param pms_to_agg: An array of triples (public key, message, signature).
|
||||
:return: The new aggregate signature.
|
||||
"""
|
||||
|
||||
v = len(pm_aggd)
|
||||
u = len(pms_to_agg)
|
||||
|
||||
# Fail if len(aggsig) ≠ 32 * (v + 1)
|
||||
if len(aggsig) != 32 * (v + 1):
|
||||
raise ValueError("Length of aggsig must be 32 * (v + 1)")
|
||||
|
||||
r_values = []
|
||||
pmr_to_agg = []
|
||||
|
||||
# For i = 0 .. v-1:
|
||||
for i in range(v):
|
||||
# Let (pki, mi) = pm_aggdi
|
||||
(pki, mi) = pm_aggd[i]
|
||||
if len(pki) != 32 or len(mi) != 32:
|
||||
raise ValueError("Public key and message must be 32 bytes")
|
||||
|
||||
# Let ri = aggsig[i⋅32:(i+1)⋅32]
|
||||
ri = aggsig[i * 32:(i + 1) * 32]
|
||||
r_values.append(ri)
|
||||
|
||||
pmr_to_agg.append((pki, mi, ri))
|
||||
|
||||
z_values = []
|
||||
s_values = []
|
||||
|
||||
# For i = v .. v+u-1:
|
||||
for i in range(v, v + u):
|
||||
# Let (pki, mi, sigi) = pms_to_aggi-v
|
||||
(pki, mi, sigi) = pms_to_agg[i - v]
|
||||
if len(pki) != 32 or len(mi) != 32 or len(sigi) != 64:
|
||||
raise ValueError("Public key and message must be 32 bytes and signature 64 bytes")
|
||||
|
||||
# Let ri = sigi[0:32]
|
||||
ri = sigi[0:32]
|
||||
r_values.append(ri)
|
||||
|
||||
# Let si = int(sigi[32:64]); fail if si ≥ n
|
||||
si = Scalar.from_bytes_checked(sigi[32:64])
|
||||
s_values.append(si)
|
||||
|
||||
# If i = 0:
|
||||
# Let zi = 1
|
||||
# Else:
|
||||
# Let zi = int(hashBIP0458/randomizer(r0 || pk0 || m0 || ... || ri || pki || mi)) mod n
|
||||
pmr_to_agg.append((pki, mi, ri))
|
||||
z_values.append(hashHalfAgg_randomizer(pmr_to_agg))
|
||||
|
||||
# Let sagg = int(aggsig[v⋅32:(v+1)⋅32]); fail if sagg ≥ n
|
||||
s = Scalar.from_bytes_checked(aggsig[v * 32:(v + 1) * 32])
|
||||
|
||||
# Let s = sagg + zv⋅sv + ... + zv+u-1⋅sv+u-1 mod n
|
||||
for i in range(u):
|
||||
s = s + z_values[i] * s_values[i]
|
||||
|
||||
# Return r0 || ... || rv+u-1 || bytes(s)
|
||||
return b''.join(r_values) + s.to_bytes()
|
||||
|
||||
|
||||
# VerifyAggregate(aggsig, pm_aggd0..u-1)
|
||||
def VerifyAggregate(aggsig, pm_aggd):
|
||||
"""
|
||||
Verifies an aggregate signature against an array of public key and message tuples.
|
||||
|
||||
:param aggsig: A byte array representing the aggregate signature.
|
||||
:param pm_aggd: An array of tuples (public key, message).
|
||||
:return: Boolean indicating whether the verification is successful.
|
||||
"""
|
||||
|
||||
u = len(pm_aggd)
|
||||
|
||||
# Fail if len(aggsig) ≠ 32 * (u + 1)
|
||||
if len(aggsig) != 32 * (u + 1):
|
||||
raise ValueError("Length of aggsig must be 32 * (u + 1)")
|
||||
|
||||
z_values = []
|
||||
R_values = []
|
||||
P_values = []
|
||||
e_values = []
|
||||
r_values = []
|
||||
|
||||
# For i = 0 .. u-1:
|
||||
for i in range(u):
|
||||
# Let (pki, mi) = pm_aggdi
|
||||
(pki, mi) = pm_aggd[i]
|
||||
if len(pki) != 32 or len(mi) != 32:
|
||||
raise ValueError("Public key and message must be 32 bytes")
|
||||
|
||||
# Let Pi = lift_x(int(pki)); fail if that fails
|
||||
try:
|
||||
Pi = GE.from_bytes_xonly(pki)
|
||||
except ValueError:
|
||||
return False
|
||||
P_values.append(Pi)
|
||||
|
||||
# Let ri = aggsig[i⋅32:(i+1)⋅32]
|
||||
ri = aggsig[i * 32:(i + 1) * 32]
|
||||
# Let Ri = lift_x(int(ri)); fail if that fails
|
||||
try:
|
||||
Ri = GE.from_bytes_xonly(ri)
|
||||
except ValueError:
|
||||
return False
|
||||
R_values.append(Ri)
|
||||
r_values.append(ri)
|
||||
|
||||
# Let ei = int(hashBIP0340/challenge(ri || pki || mi)) mod n
|
||||
ei = Scalar.from_bytes_wrapping(hashBIP0340_challenge(ri, pki, mi))
|
||||
e_values.append(ei)
|
||||
|
||||
# If i = 0:
|
||||
# Let zi = 1
|
||||
# Else:
|
||||
# Let zi = int(hashBIP0458/randomizer(r0 || pk0 || m0 || ... || ri || pki || mi)) mod n
|
||||
pmr = [(pki, mi, ri) for (pki, mi), ri in zip(pm_aggd, r_values)]
|
||||
z_values.append(hashHalfAgg_randomizer(pmr))
|
||||
|
||||
# Let s = int(aggsig[u⋅32:(u+1)⋅32]); fail if s ≥ n
|
||||
try:
|
||||
s = Scalar.from_bytes_checked(aggsig[u * 32:(u + 1) * 32])
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
# Fail if s⋅G ≠ z0⋅(R0 + e0⋅P0) + ... + zu-1⋅(Ru-1 + eu-1⋅Pu-1)
|
||||
lhs = s * G
|
||||
rhs = GE()
|
||||
for i in range(u):
|
||||
rhs += z_values[i] * (R_values[i] + e_values[i] * P_values[i])
|
||||
|
||||
return lhs == rhs
|
||||
|
||||
|
||||
def hashBIP0340_challenge(sig, pubkey, msg):
|
||||
return tagged_hash("BIP0340/challenge", sig + pubkey + msg)
|
||||
|
||||
|
||||
def hashHalfAgg_randomizer(pmr):
|
||||
if len(pmr) == 1:
|
||||
return Scalar(1)
|
||||
|
||||
random_input = bytes()
|
||||
for (pki, mi, ri) in pmr:
|
||||
random_input += ri
|
||||
random_input += pki
|
||||
random_input += mi
|
||||
|
||||
return Scalar.from_bytes_wrapping(tagged_hash("BIP0458/randomizer", random_input))
|
||||
@@ -0,0 +1,34 @@
|
||||
name: Tests
|
||||
on: [push, pull_request]
|
||||
jobs:
|
||||
ruff:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install the latest version of uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
- run: uvx ruff check .
|
||||
mypy:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
python-version: ["3.11", "3.12", "3.13", "3.14"]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install the latest version of uv, setup Python ${{ matrix.python-version }}
|
||||
uses: astral-sh/setup-uv@v5
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
- run: uvx mypy .
|
||||
unittest:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
python-version: ["3.11", "3.12", "3.13", "3.14"]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Setup Python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
- run: python3 -m unittest
|
||||
@@ -0,0 +1,10 @@
|
||||
# Python-generated files
|
||||
__pycache__/
|
||||
*.py[oc]
|
||||
build/
|
||||
dist/
|
||||
wheels/
|
||||
*.egg-info
|
||||
|
||||
# Virtual environments
|
||||
.venv
|
||||
@@ -0,0 +1 @@
|
||||
3.11
|
||||
@@ -0,0 +1,25 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
#### Added
|
||||
- Added new methods `Scalar.from_int_nonzero_checked` and `Scalar.from_bytes_nonzero_checked`
|
||||
that ensure a constructed scalar is in the range `0 < s < N` (i.e. is non-zero and within the
|
||||
group order) and throw a `ValueError` otherwise. This is e.g. useful for ensuring that newly
|
||||
generated secret keys or nonces are valid without having to do the non-zero check manually.
|
||||
The already existing methods `Scalar.from_int_checked` and `Scalar.from_bytes_checked` error
|
||||
on overflow, but not on zero, i.e. they only ensure `0 <= s < N`.
|
||||
|
||||
- Added a new method `GE.from_bytes_compressed_with_infinity` to parse a compressed
|
||||
public key (33 bytes) to a group element, where the all-zeros bytestring maps to the
|
||||
point at infinity. This is the counterpart to the already existing serialization
|
||||
method `GE.to_bytes_compressed_with_infinity`.
|
||||
|
||||
## [1.0.0] - 2025-03-31
|
||||
|
||||
Initial release.
|
||||
@@ -0,0 +1,23 @@
|
||||
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.
|
||||
@@ -0,0 +1,13 @@
|
||||
secp256k1lab
|
||||
============
|
||||
|
||||

|
||||
|
||||
An INSECURE implementation of the secp256k1 elliptic curve and related cryptographic schemes written in Python, intended for prototyping, experimentation and education.
|
||||
|
||||
Features:
|
||||
* Low-level secp256k1 field and group arithmetic.
|
||||
* Schnorr signing/verification and key generation according to [BIP-340](https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki).
|
||||
* ECDH key exchange.
|
||||
|
||||
WARNING: The code in this library is slow and trivially vulnerable to side channel attacks.
|
||||
@@ -0,0 +1,34 @@
|
||||
[project]
|
||||
name = "secp256k1lab"
|
||||
version = "1.0.0"
|
||||
description = "An INSECURE implementation of the secp256k1 elliptic curve and related cryptographic schemes, intended for prototyping, experimentation and education"
|
||||
readme = "README.md"
|
||||
authors = [
|
||||
{ name = "Pieter Wuille", email = "pieter@wuille.net" },
|
||||
{ name = "Tim Ruffing", email = "me@real-or-random.org" },
|
||||
{ name = "Jonas Nick", email = "jonasd.nick@gmail.com" },
|
||||
{ name = "Sebastian Falbesoner", email = "sebastian.falbesoner@gmail.com" }
|
||||
]
|
||||
maintainers = [
|
||||
{ name = "Tim Ruffing", email = "me@real-or-random.org" },
|
||||
{ name = "Jonas Nick", email = "jonasd.nick@gmail.com" },
|
||||
{ name = "Sebastian Falbesoner", email = "sebastian.falbesoner@gmail.com" }
|
||||
]
|
||||
requires-python = ">=3.11"
|
||||
license = "MIT"
|
||||
license-files = ["COPYING"]
|
||||
keywords = ["secp256k1", "elliptic curves", "cryptography", "Bitcoin"]
|
||||
classifiers = [
|
||||
"Development Status :: 5 - Production/Stable",
|
||||
"Intended Audience :: Developers",
|
||||
"Intended Audience :: Education",
|
||||
"Intended Audience :: Science/Research",
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Programming Language :: Python",
|
||||
"Topic :: Security :: Cryptography",
|
||||
]
|
||||
dependencies = []
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
Whitespace-only changes.
@@ -0,0 +1,73 @@
|
||||
# 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
|
||||
@@ -0,0 +1,16 @@
|
||||
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()
|
||||
@@ -0,0 +1,15 @@
|
||||
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()
|
||||
Whitespace-only changes.
@@ -0,0 +1,483 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,24 @@
|
||||
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()
|
||||
@@ -0,0 +1,5 @@
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
# Ensure secp256k1lab is found and can be imported directly
|
||||
sys.path.insert(0, str(Path(__file__).parent / "../src/"))
|
||||
@@ -0,0 +1,51 @@
|
||||
import csv
|
||||
from pathlib import Path
|
||||
from random import randbytes
|
||||
import unittest
|
||||
|
||||
from secp256k1lab.bip340 import pubkey_gen, schnorr_sign, schnorr_verify
|
||||
|
||||
|
||||
class BIP340Tests(unittest.TestCase):
|
||||
"""Test schnorr signatures (BIP 340)."""
|
||||
|
||||
def test_correctness(self):
|
||||
seckey = randbytes(32)
|
||||
pubkey_xonly = pubkey_gen(seckey)
|
||||
aux_rand = randbytes(32)
|
||||
message = b'this is some arbitrary message'
|
||||
signature = schnorr_sign(message, seckey, aux_rand)
|
||||
success = schnorr_verify(message, pubkey_xonly, signature)
|
||||
self.assertTrue(success)
|
||||
|
||||
def test_vectors(self):
|
||||
# Test against vectors from the BIPs repository
|
||||
# [https://github.com/bitcoin/bips/blob/master/bip-0340/test-vectors.csv]
|
||||
vectors_file = Path(__file__).parent / "vectors" / "bip340.csv"
|
||||
with open(vectors_file, encoding='utf8') as csvfile:
|
||||
reader = csv.DictReader(csvfile)
|
||||
for row in reader:
|
||||
with self.subTest(i=int(row['index'])):
|
||||
self.subtest_vectors_case(row)
|
||||
|
||||
def subtest_vectors_case(self, row):
|
||||
seckey = bytes.fromhex(row['secret key'])
|
||||
pubkey_xonly = bytes.fromhex(row['public key'])
|
||||
aux_rand = bytes.fromhex(row['aux_rand'])
|
||||
msg = bytes.fromhex(row['message'])
|
||||
sig = bytes.fromhex(row['signature'])
|
||||
result_str = row['verification result']
|
||||
comment = row['comment']
|
||||
|
||||
result = result_str == 'TRUE'
|
||||
assert result or result_str == 'FALSE'
|
||||
if seckey != b'':
|
||||
pubkey_xonly_actual = pubkey_gen(seckey)
|
||||
self.assertEqual(pubkey_xonly.hex(), pubkey_xonly_actual.hex(), f"BIP340 test vector ({comment}): pubkey mismatch")
|
||||
sig_actual = schnorr_sign(msg, seckey, aux_rand)
|
||||
self.assertEqual(sig.hex(), sig_actual.hex(), f"BIP340 test vector ({comment}): sig mismatch")
|
||||
result_actual = schnorr_verify(msg, pubkey_xonly, sig)
|
||||
if result:
|
||||
self.assertEqual(result, result_actual, f"BIP340 test vector ({comment}): verification failed unexpectedly")
|
||||
else:
|
||||
self.assertEqual(result, result_actual, f"BIP340 test vector ({comment}): verification succeeded unexpectedly")
|
||||
@@ -0,0 +1,18 @@
|
||||
from random import randbytes
|
||||
import unittest
|
||||
|
||||
from secp256k1lab.ecdh import ecdh_libsecp256k1
|
||||
from secp256k1lab.keys import pubkey_gen_plain
|
||||
|
||||
|
||||
class ECDHTests(unittest.TestCase):
|
||||
"""Test ECDH module."""
|
||||
|
||||
def test_correctness(self):
|
||||
seckey_alice = randbytes(32)
|
||||
pubkey_alice = pubkey_gen_plain(seckey_alice)
|
||||
seckey_bob = randbytes(32)
|
||||
pubkey_bob = pubkey_gen_plain(seckey_bob)
|
||||
shared_secret1 = ecdh_libsecp256k1(seckey_alice, pubkey_bob)
|
||||
shared_secret2 = ecdh_libsecp256k1(seckey_bob, pubkey_alice)
|
||||
self.assertEqual(shared_secret1, shared_secret2)
|
||||
@@ -0,0 +1,180 @@
|
||||
"""Test low-level secp256k1 field and group arithmetic classes."""
|
||||
from random import randint
|
||||
import unittest
|
||||
|
||||
from secp256k1lab.secp256k1 import FE, G, GE, Scalar
|
||||
|
||||
|
||||
class PrimeFieldTests(unittest.TestCase):
|
||||
def test_fe_constructors(self):
|
||||
P = FE.SIZE
|
||||
random_fe_valid = randint(0, P-1)
|
||||
random_fe_overflowing = randint(P, 2**256-1)
|
||||
|
||||
# wrapping constructors
|
||||
for init_value in [0, P-1, P, P+1, random_fe_valid, random_fe_overflowing]:
|
||||
fe1 = FE(init_value)
|
||||
fe2 = FE.from_int_wrapping(init_value)
|
||||
fe3 = FE.from_bytes_wrapping(init_value.to_bytes(32, 'big'))
|
||||
reduced_value = init_value % P
|
||||
self.assertEqual(int(fe1), reduced_value)
|
||||
self.assertEqual(int(fe1), int(fe2))
|
||||
self.assertEqual(int(fe2), int(fe3))
|
||||
|
||||
# checking constructors (should throw on overflow)
|
||||
for valid_value in [0, P-1, random_fe_valid]:
|
||||
fe1 = FE.from_int_checked(valid_value)
|
||||
fe2 = FE.from_bytes_checked(valid_value.to_bytes(32, 'big'))
|
||||
self.assertEqual(int(fe1), valid_value)
|
||||
self.assertEqual(int(fe1), int(fe2))
|
||||
|
||||
for overflow_value in [P, P+1, random_fe_overflowing]:
|
||||
with self.assertRaises(ValueError):
|
||||
_ = FE.from_int_checked(overflow_value)
|
||||
with self.assertRaises(ValueError):
|
||||
_ = FE.from_bytes_checked(overflow_value.to_bytes(32, 'big'))
|
||||
|
||||
def test_scalar_constructors(self):
|
||||
N = Scalar.SIZE
|
||||
random_scalar_valid = randint(0, N-1)
|
||||
random_scalar_overflowing = randint(N, 2**256-1)
|
||||
|
||||
# wrapping constructors
|
||||
for init_value in [0, N-1, N, N+1, random_scalar_valid, random_scalar_overflowing]:
|
||||
s1 = Scalar(init_value)
|
||||
s2 = Scalar.from_int_wrapping(init_value)
|
||||
s3 = Scalar.from_bytes_wrapping(init_value.to_bytes(32, 'big'))
|
||||
reduced_value = init_value % N
|
||||
self.assertEqual(int(s1), reduced_value)
|
||||
self.assertEqual(int(s1), int(s2))
|
||||
self.assertEqual(int(s2), int(s3))
|
||||
|
||||
# checking constructors (should throw on overflow)
|
||||
for valid_value in [0, N-1, random_scalar_valid]:
|
||||
s1 = Scalar.from_int_checked(valid_value)
|
||||
s2 = Scalar.from_bytes_checked(valid_value.to_bytes(32, 'big'))
|
||||
self.assertEqual(int(s1), valid_value)
|
||||
self.assertEqual(int(s1), int(s2))
|
||||
|
||||
for overflow_value in [N, N+1, random_scalar_overflowing]:
|
||||
with self.assertRaises(ValueError):
|
||||
_ = Scalar.from_int_checked(overflow_value)
|
||||
with self.assertRaises(ValueError):
|
||||
_ = Scalar.from_bytes_checked(overflow_value.to_bytes(32, 'big'))
|
||||
|
||||
# non-zero checking constructors (should throw on zero or overflow, only for Scalar)
|
||||
random_nonzero_scalar_valid = randint(1, N-1)
|
||||
for valid_value in [1, N-1, random_nonzero_scalar_valid]:
|
||||
s1 = Scalar.from_int_nonzero_checked(valid_value)
|
||||
s2 = Scalar.from_bytes_nonzero_checked(valid_value.to_bytes(32, 'big'))
|
||||
self.assertEqual(int(s1), valid_value)
|
||||
self.assertEqual(int(s1), int(s2))
|
||||
|
||||
for invalid_value in [0, N, random_scalar_overflowing]:
|
||||
with self.assertRaises(ValueError):
|
||||
_ = Scalar.from_int_nonzero_checked(invalid_value)
|
||||
with self.assertRaises(ValueError):
|
||||
_ = Scalar.from_bytes_nonzero_checked(invalid_value.to_bytes(32, 'big'))
|
||||
|
||||
|
||||
class GeSerializationTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.point_at_infinity = GE()
|
||||
cls.group_elements_on_curve = [
|
||||
# generator point
|
||||
G,
|
||||
# Bitcoin genesis block public key
|
||||
GE(0x678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb6,
|
||||
0x49f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f),
|
||||
]
|
||||
# generate a few random points, to likely cover both even/odd y polarity
|
||||
cls.group_elements_on_curve.extend([randint(1, Scalar.SIZE-1) * G for _ in range(8)])
|
||||
# generate x coordinates that don't have a valid point on the curve
|
||||
# (note that ~50% of all x coordinates are valid, so finding one needs two loop iterations on average)
|
||||
cls.x_coords_not_on_curve = []
|
||||
while len(cls.x_coords_not_on_curve) < 8:
|
||||
x = randint(0, FE.SIZE-1)
|
||||
if not GE.is_valid_x(x):
|
||||
cls.x_coords_not_on_curve.append(x)
|
||||
|
||||
cls.group_elements = [cls.point_at_infinity] + cls.group_elements_on_curve
|
||||
|
||||
def test_infinity_raises(self):
|
||||
with self.assertRaises(AssertionError):
|
||||
_ = self.point_at_infinity.to_bytes_uncompressed()
|
||||
with self.assertRaises(AssertionError):
|
||||
_ = self.point_at_infinity.to_bytes_compressed()
|
||||
with self.assertRaises(AssertionError):
|
||||
_ = self.point_at_infinity.to_bytes_xonly()
|
||||
|
||||
def test_not_on_curve_raises(self):
|
||||
# for compressed and x-only GE deserialization, test with invalid x coordinate
|
||||
for x in self.x_coords_not_on_curve:
|
||||
x_bytes = x.to_bytes(32, 'big')
|
||||
with self.assertRaises(ValueError):
|
||||
_ = GE.from_bytes_compressed(b'\x02' + x_bytes)
|
||||
with self.assertRaises(ValueError):
|
||||
_ = GE.from_bytes_compressed(b'\x03' + x_bytes)
|
||||
with self.assertRaises(ValueError):
|
||||
_ = GE.from_bytes_compressed_with_infinity(b'\x02' + x_bytes)
|
||||
with self.assertRaises(ValueError):
|
||||
_ = GE.from_bytes_compressed_with_infinity(b'\x03' + x_bytes)
|
||||
with self.assertRaises(ValueError):
|
||||
_ = GE.from_bytes_xonly(x_bytes)
|
||||
|
||||
# for uncompressed GE serialization, test by invalidating either coordinate
|
||||
for ge in self.group_elements_on_curve:
|
||||
valid_x = ge.x
|
||||
valid_y = ge.y
|
||||
invalid_x = ge.x + 1
|
||||
invalid_y = ge.y + 1
|
||||
|
||||
# valid cases (if point (x,y) is on the curve, then point(x,-y) is on the curve as well)
|
||||
_ = GE.from_bytes_uncompressed(b'\x04' + valid_x.to_bytes() + valid_y.to_bytes())
|
||||
_ = GE.from_bytes_uncompressed(b'\x04' + valid_x.to_bytes() + (-valid_y).to_bytes())
|
||||
# invalid cases (curve equation y**2 = x**3 + 7 doesn't hold)
|
||||
self.assertNotEqual(invalid_y**2, valid_x**3 + 7)
|
||||
with self.assertRaises(ValueError):
|
||||
_ = GE.from_bytes_uncompressed(b'\x04' + valid_x.to_bytes() + invalid_y.to_bytes())
|
||||
self.assertNotEqual(valid_y**2, invalid_x**3 + 7)
|
||||
with self.assertRaises(ValueError):
|
||||
_ = GE.from_bytes_uncompressed(b'\x04' + invalid_x.to_bytes() + valid_y.to_bytes())
|
||||
|
||||
def test_affine(self):
|
||||
# GE serialization and parsing round-trip (variants that only support serializing points on the curve)
|
||||
for ge_orig in self.group_elements_on_curve:
|
||||
# uncompressed serialization: 65 bytes, starts with 0x04
|
||||
ge_ser = ge_orig.to_bytes_uncompressed()
|
||||
self.assertEqual(len(ge_ser), 65)
|
||||
self.assertEqual(ge_ser[0], 0x04)
|
||||
ge_deser = GE.from_bytes_uncompressed(ge_ser)
|
||||
self.assertEqual(ge_deser, ge_orig)
|
||||
|
||||
# compressed serialization: 33 bytes, starts with 0x02 (if y is even) or 0x03 (if y is odd)
|
||||
ge_ser = ge_orig.to_bytes_compressed()
|
||||
self.assertEqual(len(ge_ser), 33)
|
||||
self.assertEqual(ge_ser[0], 0x02 if ge_orig.has_even_y() else 0x03)
|
||||
ge_deser = GE.from_bytes_compressed(ge_ser)
|
||||
self.assertEqual(ge_deser, ge_orig)
|
||||
|
||||
# x-only serialization: 32 bytes
|
||||
ge_ser = ge_orig.to_bytes_xonly()
|
||||
self.assertEqual(len(ge_ser), 32)
|
||||
ge_deser = GE.from_bytes_xonly(ge_ser)
|
||||
if not ge_orig.has_even_y(): # x-only implies even y, so flip if necessary
|
||||
ge_deser = -ge_deser
|
||||
self.assertEqual(ge_deser, ge_orig)
|
||||
|
||||
def test_affine_with_infinity(self):
|
||||
# GE serialization and parsing round-trip (variants that also support serializing the point at infinity)
|
||||
for ge_orig in self.group_elements:
|
||||
# compressed serialization: 33 bytes, all-zeros for point at infinity
|
||||
ge_ser = ge_orig.to_bytes_compressed_with_infinity()
|
||||
self.assertEqual(len(ge_ser), 33)
|
||||
if ge_orig.infinity:
|
||||
self.assertEqual(ge_ser, b'\x00'*33)
|
||||
else:
|
||||
self.assertEqual(ge_ser[0], 0x02 if ge_orig.has_even_y() else 0x03)
|
||||
ge_deser = GE.from_bytes_compressed_with_infinity(ge_ser)
|
||||
self.assertEqual(ge_deser, ge_orig)
|
||||
@@ -0,0 +1,20 @@
|
||||
index,secret key,public key,aux_rand,message,signature,verification result,comment
|
||||
0,0000000000000000000000000000000000000000000000000000000000000003,F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9,0000000000000000000000000000000000000000000000000000000000000000,0000000000000000000000000000000000000000000000000000000000000000,E907831F80848D1069A5371B402410364BDF1C5F8307B0084C55F1CE2DCA821525F66A4A85EA8B71E482A74F382D2CE5EBEEE8FDB2172F477DF4900D310536C0,TRUE,
|
||||
1,B7E151628AED2A6ABF7158809CF4F3C762E7160F38B4DA56A784D9045190CFEF,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,0000000000000000000000000000000000000000000000000000000000000001,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,6896BD60EEAE296DB48A229FF71DFE071BDE413E6D43F917DC8DCF8C78DE33418906D11AC976ABCCB20B091292BFF4EA897EFCB639EA871CFA95F6DE339E4B0A,TRUE,
|
||||
2,C90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B14E5C9,DD308AFEC5777E13121FA72B9CC1B7CC0139715309B086C960E18FD969774EB8,C87AA53824B4D7AE2EB035A2B5BBBCCC080E76CDC6D1692C4B0B62D798E6D906,7E2D58D8B3BCDF1ABADEC7829054F90DDA9805AAB56C77333024B9D0A508B75C,5831AAEED7B44BB74E5EAB94BA9D4294C49BCF2A60728D8B4C200F50DD313C1BAB745879A5AD954A72C45A91C3A51D3C7ADEA98D82F8481E0E1E03674A6F3FB7,TRUE,
|
||||
3,0B432B2677937381AEF05BB02A66ECD012773062CF3FA2549E44F58ED2401710,25D1DFF95105F5253C4022F628A996AD3A0D95FBF21D468A1B33F8C160D8F517,FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF,FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF,7EB0509757E246F19449885651611CB965ECC1A187DD51B64FDA1EDC9637D5EC97582B9CB13DB3933705B32BA982AF5AF25FD78881EBB32771FC5922EFC66EA3,TRUE,test fails if msg is reduced modulo p or n
|
||||
4,,D69C3509BB99E412E68B0FE8544E72837DFA30746D8BE2AA65975F29D22DC7B9,,4DF3C3F68FCC83B27E9D42C90431A72499F17875C81A599B566C9889B9696703,00000000000000000000003B78CE563F89A0ED9414F5AA28AD0D96D6795F9C6376AFB1548AF603B3EB45C9F8207DEE1060CB71C04E80F593060B07D28308D7F4,TRUE,
|
||||
5,,EEFDEA4CDB677750A420FEE807EACF21EB9898AE79B9768766E4FAA04A2D4A34,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,6CFF5C3BA86C69EA4B7376F31A9BCB4F74C1976089B2D9963DA2E5543E17776969E89B4C5564D00349106B8497785DD7D1D713A8AE82B32FA79D5F7FC407D39B,FALSE,public key not on the curve
|
||||
6,,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,FFF97BD5755EEEA420453A14355235D382F6472F8568A18B2F057A14602975563CC27944640AC607CD107AE10923D9EF7A73C643E166BE5EBEAFA34B1AC553E2,FALSE,has_even_y(R) is false
|
||||
7,,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,1FA62E331EDBC21C394792D2AB1100A7B432B013DF3F6FF4F99FCB33E0E1515F28890B3EDB6E7189B630448B515CE4F8622A954CFE545735AAEA5134FCCDB2BD,FALSE,negated message
|
||||
8,,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,6CFF5C3BA86C69EA4B7376F31A9BCB4F74C1976089B2D9963DA2E5543E177769961764B3AA9B2FFCB6EF947B6887A226E8D7C93E00C5ED0C1834FF0D0C2E6DA6,FALSE,negated s value
|
||||
9,,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,0000000000000000000000000000000000000000000000000000000000000000123DDA8328AF9C23A94C1FEECFD123BA4FB73476F0D594DCB65C6425BD186051,FALSE,sG - eP is infinite. Test fails in single verification if has_even_y(inf) is defined as true and x(inf) as 0
|
||||
10,,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,00000000000000000000000000000000000000000000000000000000000000017615FBAF5AE28864013C099742DEADB4DBA87F11AC6754F93780D5A1837CF197,FALSE,sG - eP is infinite. Test fails in single verification if has_even_y(inf) is defined as true and x(inf) as 1
|
||||
11,,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,4A298DACAE57395A15D0795DDBFD1DCB564DA82B0F269BC70A74F8220429BA1D69E89B4C5564D00349106B8497785DD7D1D713A8AE82B32FA79D5F7FC407D39B,FALSE,sig[0:32] is not an X coordinate on the curve
|
||||
12,,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F69E89B4C5564D00349106B8497785DD7D1D713A8AE82B32FA79D5F7FC407D39B,FALSE,sig[0:32] is equal to field size
|
||||
13,,DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,6CFF5C3BA86C69EA4B7376F31A9BCB4F74C1976089B2D9963DA2E5543E177769FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141,FALSE,sig[32:64] is equal to curve order
|
||||
14,,FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC30,,243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89,6CFF5C3BA86C69EA4B7376F31A9BCB4F74C1976089B2D9963DA2E5543E17776969E89B4C5564D00349106B8497785DD7D1D713A8AE82B32FA79D5F7FC407D39B,FALSE,public key is not a valid X coordinate because it exceeds the field size
|
||||
15,0340034003400340034003400340034003400340034003400340034003400340,778CAA53B4393AC467774D09497A87224BF9FAB6F6E68B23086497324D6FD117,0000000000000000000000000000000000000000000000000000000000000000,,71535DB165ECD9FBBC046E5FFAEA61186BB6AD436732FCCC25291A55895464CF6069CE26BF03466228F19A3A62DB8A649F2D560FAC652827D1AF0574E427AB63,TRUE,message of size 0 (added 2022-12)
|
||||
16,0340034003400340034003400340034003400340034003400340034003400340,778CAA53B4393AC467774D09497A87224BF9FAB6F6E68B23086497324D6FD117,0000000000000000000000000000000000000000000000000000000000000000,11,08A20A0AFEF64124649232E0693C583AB1B9934AE63B4C3511F3AE1134C6A303EA3173BFEA6683BD101FA5AA5DBC1996FE7CACFC5A577D33EC14564CEC2BACBF,TRUE,message of size 1 (added 2022-12)
|
||||
17,0340034003400340034003400340034003400340034003400340034003400340,778CAA53B4393AC467774D09497A87224BF9FAB6F6E68B23086497324D6FD117,0000000000000000000000000000000000000000000000000000000000000000,0102030405060708090A0B0C0D0E0F1011,5130F39A4059B43BC7CAC09A19ECE52B5D8699D1A71E3C52DA9AFDB6B50AC370C4A482B77BF960F8681540E25B6771ECE1E5A37FD80E5A51897C5566A97EA5A5,TRUE,message of size 17 (added 2022-12)
|
||||
18,0340034003400340034003400340034003400340034003400340034003400340,778CAA53B4393AC467774D09497A87224BF9FAB6F6E68B23086497324D6FD117,0000000000000000000000000000000000000000000000000000000000000000,99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999,403B12B0D8555A344175EA7EC746566303321E5DBFA8BE6F091635163ECA79A8585ED3E3170807E7C03B720FC54C7B23897FCBA0E9D0B4A06894CFD249F22367,TRUE,message of size 100 (added 2022-12)
|
||||
|
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,222 @@
|
||||
{
|
||||
"scriptPubKey": [
|
||||
{
|
||||
"given": {
|
||||
"internalPubkey": "34b703e82bfdedfbab012da7a34767456c3f85524171663df7c0aaf227276901"
|
||||
},
|
||||
"intermediary": {
|
||||
"tweak": "4821522480fda0d8eeab11f09a642cae24605302c3ccda3f590e323f81d6fc0b",
|
||||
"tweakedPubkey": "4049ce224d4b6407e9c7864e88d8020996beb04663cd1596bf4ff8ab335bc57b"
|
||||
},
|
||||
"expected": {
|
||||
"scriptPubKey": "52204049ce224d4b6407e9c7864e88d8020996beb04663cd1596bf4ff8ab335bc57b",
|
||||
"address": "bc1zgpyuugjdfdjq06w8se8g3kqzpxttavzxv0x3t94lflu2kv6mc4as88u8yc"
|
||||
}
|
||||
},
|
||||
{
|
||||
"given": {
|
||||
"internalPubkey": "cca0578cd53156e37b6e87c90b2d03cb38b046587a7c4a9a2986e24d0c85c120"
|
||||
},
|
||||
"intermediary": {
|
||||
"tweak": "d18eb46c3f1105be40607ff7c064a3af23cb7cce36938f7cf73dbfd2e694a950",
|
||||
"tweakedPubkey": "cc93415eadd2ed34dc668b345ef49dd492eaaf5c0562482d393917966a6dbfd5"
|
||||
},
|
||||
"expected": {
|
||||
"scriptPubKey": "5220cc93415eadd2ed34dc668b345ef49dd492eaaf5c0562482d393917966a6dbfd5",
|
||||
"address": "bc1zejf5zh4d6tknfhrx3v69aaya6jfw4t6uq43ystfe8ytev6ndhl2sx2w44g"
|
||||
}
|
||||
}
|
||||
],
|
||||
"keyPathSpending": [
|
||||
{
|
||||
"description": "Opted-out input with SIGHASH_ALL alongside a two-member half-aggregation group with SIGHASH_DEFAULT",
|
||||
"given": {
|
||||
"rawUnsignedTx": "0200000003375412079d92555f10368dc54e08189023c8a6bfe0318933dda280bb8c96e76a0000000000ffffffff2dea8db84ee1bcea688026b1bda8fea0667b8f3b24d914e2afe0f5dffae5086d0000000000ffffffff8e89080fe122cee9ffa6c0b2128cc14be4ca148c2629d0040f6037cfd0f816190000000000ffffffff01c060d211000000002252204049ce224d4b6407e9c7864e88d8020996beb04663cd1596bf4ff8ab335bc57b00000000",
|
||||
"utxosSpent": [
|
||||
{
|
||||
"scriptPubKey": "52204049ce224d4b6407e9c7864e88d8020996beb04663cd1596bf4ff8ab335bc57b",
|
||||
"amountSats": 100000000
|
||||
},
|
||||
{
|
||||
"scriptPubKey": "5220cc93415eadd2ed34dc668b345ef49dd492eaaf5c0562482d393917966a6dbfd5",
|
||||
"amountSats": 101000000
|
||||
},
|
||||
{
|
||||
"scriptPubKey": "52208877c408836c8fac26214cd6ce52200ef5c44f8466b08d889cc671b7fa7dbcbd",
|
||||
"amountSats": 102000000
|
||||
}
|
||||
]
|
||||
},
|
||||
"inputSpending": [
|
||||
{
|
||||
"given": {
|
||||
"txinIndex": 0,
|
||||
"internalPrivkey": "50dbc446357ea19a9f032c65541a3d69d7fce0f909c67671ab92f0fdf75bc75b",
|
||||
"aggMode": null,
|
||||
"hashType": 1
|
||||
},
|
||||
"intermediary": {
|
||||
"internalPubkey": "34b703e82bfdedfbab012da7a34767456c3f85524171663df7c0aaf227276901",
|
||||
"tweak": "4821522480fda0d8eeab11f09a642cae24605302c3ccda3f590e323f81d6fc0b",
|
||||
"tweakedPrivkey": "98fd166ab67c42738dae3e55ee7e6a17fc5d33fbcd9350b104a1233d7932c366",
|
||||
"sigHash": "d69ac779928b23970adb2b5db967f32353d9f8025b721b146f063a65015e0809"
|
||||
},
|
||||
"expected": {
|
||||
"witness": [
|
||||
"86a207d61052859ed25d045739ff69f6c94e246c7e95c0bd2dbf951cb75f0ee55e890397180835f8d5aeb8eabef4c9e234b13aa87fe38c96f25001f3b1a0631d01"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"given": {
|
||||
"txinIndex": 1,
|
||||
"internalPrivkey": "26cc4c0d15b25be1e2137c638a99c9dbce9cfe8b74d2f1612731d9e620648870",
|
||||
"aggMode": "0xbc",
|
||||
"hashType": 0
|
||||
},
|
||||
"intermediary": {
|
||||
"internalPubkey": "cca0578cd53156e37b6e87c90b2d03cb38b046587a7c4a9a2986e24d0c85c120",
|
||||
"tweak": "d18eb46c3f1105be40607ff7c064a3af23cb7cce36938f7cf73dbfd2e694a950",
|
||||
"tweakedPrivkey": "f85b007954c361a02273fc5b4afe6d8af2687b59ab6680de1e6f99b906f931c0",
|
||||
"sigHash": "b4790a58d8405ea70b8758143fd245301d725b23af4a60a2d2393686b79122af"
|
||||
},
|
||||
"expected": {
|
||||
"witness": [
|
||||
"5dc80989a7bcfb1fce2602935d5b70052b7eb030c50f4a9f08b49c08cb20ef3f"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"given": {
|
||||
"txinIndex": 2,
|
||||
"internalPrivkey": "213ac0b0d8b50089762f10ee2851872255c673e87da343375d89060cbec74e4a",
|
||||
"aggMode": "0xbc",
|
||||
"hashType": 0
|
||||
},
|
||||
"intermediary": {
|
||||
"internalPubkey": "49d40eb515a74c614f7b231d3b2957b5dd4267f34b0c99f3da86116d1974670c",
|
||||
"tweak": "88e8cdaa41ee11c3a85fcb9b1321fcd82d4c79ba143265d6df49ed76127071ca",
|
||||
"tweakedPrivkey": "67ae0cf96939113a3230baacead075b5d78605d1968f229f81c0e76953a92380",
|
||||
"sigHash": "d8562e8cf18da05da50f2bc3f00fc8b93585bcc3c07e398b85a68b068c15247c"
|
||||
},
|
||||
"expected": {
|
||||
"witness": [
|
||||
"9e0f4cac3b04d5360ca75e857091040adbc8e35d7e72d6ba1e4d4d5f407018ebe603d806099e372dd2a69aa2a10d23361cf711fcdd5a7ca1b79456cf318c95adbc"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"auxiliary": {
|
||||
"aggregateSignature": "5dc80989a7bcfb1fce2602935d5b70052b7eb030c50f4a9f08b49c08cb20ef3f9e0f4cac3b04d5360ca75e857091040adbc8e35d7e72d6ba1e4d4d5f407018ebe603d806099e372dd2a69aa2a10d23361cf711fcdd5a7ca1b79456cf318c95ad"
|
||||
},
|
||||
"expected": {
|
||||
"rawSignedTx": "02000000000103375412079d92555f10368dc54e08189023c8a6bfe0318933dda280bb8c96e76a0000000000ffffffff2dea8db84ee1bcea688026b1bda8fea0667b8f3b24d914e2afe0f5dffae5086d0000000000ffffffff8e89080fe122cee9ffa6c0b2128cc14be4ca148c2629d0040f6037cfd0f816190000000000ffffffff01c060d211000000002252204049ce224d4b6407e9c7864e88d8020996beb04663cd1596bf4ff8ab335bc57b014186a207d61052859ed25d045739ff69f6c94e246c7e95c0bd2dbf951cb75f0ee55e890397180835f8d5aeb8eabef4c9e234b13aa87fe38c96f25001f3b1a0631d0101205dc80989a7bcfb1fce2602935d5b70052b7eb030c50f4a9f08b49c08cb20ef3f01419e0f4cac3b04d5360ca75e857091040adbc8e35d7e72d6ba1e4d4d5f407018ebe603d806099e372dd2a69aa2a10d23361cf711fcdd5a7ca1b79456cf318c95adbc00000000"
|
||||
}
|
||||
},
|
||||
{
|
||||
"description": "Two-member full-aggregation group with SIGHASH_ALL (using deterministic nonces)",
|
||||
"given": {
|
||||
"rawUnsignedTx": "020000000254d36a0897340110cc34b526d73b206175ae4f5db4d25fe7bdeef3a8a5e89afd0100000000ffffffff835a02826d69e61b563ec713020bd2b7c3bc3848223cda2b3c52bbdcd3e6267a0100000000ffffffff01c0cb1707000000002252208640c68f13b51a1e63dfc5cc41202cca21c18f1f9d7037c2cbec3f03f63e52e400000000",
|
||||
"utxosSpent": [
|
||||
{
|
||||
"scriptPubKey": "52208640c68f13b51a1e63dfc5cc41202cca21c18f1f9d7037c2cbec3f03f63e52e4",
|
||||
"amountSats": 50000000
|
||||
},
|
||||
{
|
||||
"scriptPubKey": "522018b6491469cc78b764b01669b0a5a4e892f57e8c1b20b89bc1ca6dce3e881b51",
|
||||
"amountSats": 70000000
|
||||
}
|
||||
]
|
||||
},
|
||||
"inputSpending": [
|
||||
{
|
||||
"given": {
|
||||
"txinIndex": 0,
|
||||
"internalPrivkey": "edc07892ebcc0812db6aea0fbc967eed825fedecf70db83d4c69fbe574b97361",
|
||||
"aggMode": "0xbd",
|
||||
"hashType": 1
|
||||
},
|
||||
"intermediary": {
|
||||
"internalPubkey": "020be368e697e135d54cd88e86b42c0b5e3e72d4b0c77632a8a4d0441203ded5",
|
||||
"tweak": "22b1442d7532c6cdbe4d9854a90b8f7a5820c559af2ca6f7d375e6fc3bfd8a09",
|
||||
"tweakedPrivkey": "1071bcc060fecee099b8826465a20e691fd1d65ff6f1bef9600d8454e080bc29",
|
||||
"sigHash": "9339267f5f6715d1b7e1b26bd69e13689b3872be5fa0c50a9d90daf9f2ae46cc"
|
||||
},
|
||||
"expected": {
|
||||
"witness": [
|
||||
"01"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"given": {
|
||||
"txinIndex": 1,
|
||||
"internalPrivkey": "80f4d8f499868a546ca66497352d4df0aa1c7e99cd83faeba3eeb11ecafec708",
|
||||
"aggMode": "0xbd",
|
||||
"hashType": 1
|
||||
},
|
||||
"intermediary": {
|
||||
"internalPubkey": "0fef9c578d084fb5f7c8fe48a570dc644609cc012a356fdd0c056f674f9455c0",
|
||||
"tweak": "85fb96a1a8a6c3a93ebfaf308aecc9837eceb6cfda6eb735cf8586e989a87563",
|
||||
"tweakedPrivkey": "0506bdad0f203954d2194a9955bf7b92d4b238360ceabc4a2b96d5cabea9ae5b",
|
||||
"sigHash": "d2982e6665e1e964ecefa2a747b19f17ad46d6765e284d639c293647c9349857"
|
||||
},
|
||||
"expected": {
|
||||
"witness": [
|
||||
"4be941b64750c3c7746300107ddcb53de5a1a4e106938eed846bad8493d1e95272717f49232d9639b988cf0a135df878463dd5680bfc71c407d11cc09a42677e01bd"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"auxiliary": {
|
||||
"secnonces": [
|
||||
"87c33dcedc7db5994d68278a81a4693ee961d08ef7e3fdeab611ab8061e92dd4517ac39af981926ed1124224dfe721c6dc0769a8ea24d2e2fc2636c3b1e9ca15",
|
||||
"3c4b7832dd37bbdb955ebf900769d133d55161e5c6ad9e09c2efa4ace1ba2e153d007745e9f74e6b8a47651a672111b07589261401674263a40e286340bcefea"
|
||||
],
|
||||
"pubnonces": [
|
||||
"021be5111aa027a4b7368d88cb0f5419f7b530e17e41af6fe7a611a03abc9bab63020e72955a3c53f163a1373ac5233ad30ff8bb4ef69dad424d91529c0ef6329ac6",
|
||||
"0367b7d091e6b58f7e94e9228393bc6b777e9fbe0186e9fce56248c9177c96f65e03592137dea3431dbb0fbe1287c35f8e44a30d68e62486969d21e90d2b4c68f05e"
|
||||
],
|
||||
"aggregateSignature": "4be941b64750c3c7746300107ddcb53de5a1a4e106938eed846bad8493d1e95272717f49232d9639b988cf0a135df878463dd5680bfc71c407d11cc09a42677e"
|
||||
},
|
||||
"expected": {
|
||||
"rawSignedTx": "0200000000010254d36a0897340110cc34b526d73b206175ae4f5db4d25fe7bdeef3a8a5e89afd0100000000ffffffff835a02826d69e61b563ec713020bd2b7c3bc3848223cda2b3c52bbdcd3e6267a0100000000ffffffff01c0cb1707000000002252208640c68f13b51a1e63dfc5cc41202cca21c18f1f9d7037c2cbec3f03f63e52e401010101424be941b64750c3c7746300107ddcb53de5a1a4e106938eed846bad8493d1e95272717f49232d9639b988cf0a135df878463dd5680bfc71c407d11cc09a42677e01bd00000000"
|
||||
}
|
||||
}
|
||||
],
|
||||
"scriptPathSpending": [
|
||||
{
|
||||
"description": "Script path spend of a witness v2 output with a single CHECKSIG leaf, following BIP 341/342 unchanged",
|
||||
"given": {
|
||||
"rawUnsignedTx": "02000000019d159d40bef848f021458aee62eecb1006f6e987d41b8af985dcb13cf97b47d60000000000ffffffff01c09ee605000000002252204049ce224d4b6407e9c7864e88d8020996beb04663cd1596bf4ff8ab335bc57b00000000",
|
||||
"utxosSpent": [
|
||||
{
|
||||
"scriptPubKey": "5220e8605ff15e754192a9d6c053969ae935932c82ceaeea0fed9a152f0c6b4b424b",
|
||||
"amountSats": 100000000
|
||||
}
|
||||
],
|
||||
"internalPubkey": "39920c3a54000624c1923187eebbbd3fcdc409302757139c1a1b003bc9276da4",
|
||||
"script": "2038c01dda6433ce79606dda3f70ee5dd525104bbbba5b0fd96f56d6d634e92f71ac",
|
||||
"leafVersion": "0xc0",
|
||||
"hashType": 0
|
||||
},
|
||||
"intermediary": {
|
||||
"leafHash": "d888fa5463776e32e8b0fddf14df8b3862673078395cbc592c10912056af7c52",
|
||||
"tweak": "543da6eae6544c2af0aa1c684f67bf908059153e077714caa4af34da3bd72ae6",
|
||||
"tweakedPubkey": "e8605ff15e754192a9d6c053969ae935932c82ceaeea0fed9a152f0c6b4b424b",
|
||||
"controlBlock": "c139920c3a54000624c1923187eebbbd3fcdc409302757139c1a1b003bc9276da4",
|
||||
"sigHash": "ea23ae9afeeb7f6e5e6aa6ca278eee5071aa9f20ca843a590b28f0faf9df058c"
|
||||
},
|
||||
"expected": {
|
||||
"scriptPubKey": "5220e8605ff15e754192a9d6c053969ae935932c82ceaeea0fed9a152f0c6b4b424b",
|
||||
"address": "bc1zaps9lu27w4qe92wkcpfedxhfxkfjeqkw4m4qlmv6z5hsc66tgf9sg52494",
|
||||
"witness": [
|
||||
"3f748f6e85b7064aa161a2e35ed5d17f540a2de4975c690739a04af70adf372b6daa1b3a27d553c38e12547289803aeb2d726187cdf6faec419e5cd864391460",
|
||||
"2038c01dda6433ce79606dda3f70ee5dd525104bbbba5b0fd96f56d6d634e92f71ac",
|
||||
"c139920c3a54000624c1923187eebbbd3fcdc409302757139c1a1b003bc9276da4"
|
||||
],
|
||||
"rawSignedTx": "020000000001019d159d40bef848f021458aee62eecb1006f6e987d41b8af985dcb13cf97b47d60000000000ffffffff01c09ee605000000002252204049ce224d4b6407e9c7864e88d8020996beb04663cd1596bf4ff8ab335bc57b03403f748f6e85b7064aa161a2e35ed5d17f540a2de4975c690739a04af70adf372b6daa1b3a27d553c38e12547289803aeb2d726187cdf6faec419e5cd864391460222038c01dda6433ce79606dda3f70ee5dd525104bbbba5b0fd96f56d6d634e92f71ac21c139920c3a54000624c1923187eebbbd3fcdc409302757139c1a1b003bc9276da400000000"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user