# List of specifications

LNP/BP stands for "Bitcoin Protocol / Lightning Network Protocol".\
This repository covers standards & best practices for Layer 2+ in cases when they do\
not require soft- or hard-forks of the Bitcoin blockchain level and are not\
directly related to issues covered in Lightning Network RFCs (BOLTs).

LNPBP sstandards cover client-side validation protocols,\
which can be anchored or build on top of to Bitcoin.\
It includes primitives for L2+ solution design and describes complex\
use cases which can be built from some primitives. This allows such solutions as\
financial assets, storage, messaging, computing and different forms of secondary\
markets leveraging Bitcoin security model and Bitcoin as a method of\
payment/medium of exchange.

Criteria for a LNP/BP specification proposal:

* Should not be covered by existing or proposed BIPs
* Should not cause soft- or hard-fork in Bitcoin blockchain (but may depend on\
  soft-forks from an existing BIP proposals)
* Should not distort Bitcoin miner's economic incentives
* Should not pollute Bitcoin blockchain with unnecessary non-transaction related\
  data or have to maintain such pollution as low as possible
* Must not require a utility or security tokens to function (but may enable\
  creation of digital assets or tokenized physical goods)
* Must not depend on non-bitcoin blockchains (but may be applicable to other\
  blockchains)

## Verticals for LNP/BP proposals:

| Name            | Description                   | Examples                                        |
| --------------- | ----------------------------- | ----------------------------------------------- |
| Cryptography    | Cryptographic primitives      | Cryptography, zero knowledge                    |
| Wallet          | Standards for wallet and apps | Derivation paths, APIs, RGB asset schemata      |
| Networking      | P2P network communications    | Network encryption, framing, connectivity etc   |
| Smart contracts | Distributed smart contracts   | Scriptless scripts, RGB, lightning channels etc |

## List of LNP/BP standards and proposals

|                                                                                                      No | Vertical        | Title                                                                                     | Type          | Status   |
| ------------------------------------------------------------------------------------------------------: | --------------- | ----------------------------------------------------------------------------------------- | ------------- | -------- |
|                                                                     [1](/commitment-schemes/lnpbp-0001) | Cryptography    | Key tweaking: collision-resistant elliptic curve-based commitments                        | Standard      | Proposal |
|                                                                     [2](/commitment-schemes/lnpbp-0002) | Cryptography    | Script tweaking: deterministic embedding of cryptographic commitments into script pubkeys | Standard      | Proposal |
|                                                                     [3](/commitment-schemes/lnpbp-0003) | Cryptography    | Deterministic definition of transaction output containing cryptographic commitment        | Standard      | Proposal |
|                                                                     [4](/commitment-schemes/lnpbp-0004) | Cryptography    | Multi-protocol commitment scheme with zero-knowledge provable uniqueness                  | Standard      | Proposal |
|                                                                       [5](/bitcoin-protocol/lnpbp-0005) | Wallet          | Universal short Bitcoin identifiers for blocks, transactions and their inputs & outputs   | Standard      | Proposal |
|                                                                     [6](/commitment-schemes/lnpbp-0006) | Cryptography    | Deterministic bitcoin commitments                                                         | Standard      | Proposal |
|                                                                                                       7 | Cryptography    | Commitments for structural and hierarchical data                                          | Standard      | Proposal |
|                                                                     [8](/commitment-schemes/lnpbp-0008) | Cryptography    | Single-use-seals                                                                          | Informational | Draft    |
|                    [9](https://diyhpl.us/wiki/transcripts/scalingbitcoin/milan/client-side-validation/) | Cryptography    | Client-side-validation                                                                    | Informational | Draft    |
|                                                                    [10](/commitment-schemes/lnpbp-0010) | Cryptography    | Bitcoin transaction output-based single-use-seals                                         | Standard      | Proposal |
|                                                                                                      11 | Cryptography    | Anchoring multiple deterministic bitcoin commitments in the same transaction output       | Standard      | Final    |
|                                                                    [12](/commitment-schemes/lnpbp-0012) | Cryptography    | TapRet: Taproot script tree-based OP\_RETURN deterministic bitcoin commitments            | Standard      | Final    |
|                                                                                                   13-18 | *Reserved*      | *For the future use*                                                                      |               |          |
|                                                                                                      19 | Cryptography    | *Reserved for sign-to-contract deterministic bitcoin commitments*                         |               |          |
|                                                                                                   20-31 | *Reserved*      | *For the future use*                                                                      |               |          |
|                                                                                                      32 | Wallet          | BIP-32 derivation path extension for read-only wallets                                    | Standard      | Draft    |
|                                                        [33](https://github.com/LNP-BP/LNPBPs/issues/24) | Smart contracts | Lightspeed: micro-payments for Lightning Network                                          | Draft         |          |
|                                                           [34](https://github.com/storm-org/storm-spec) | Smart contracts | Zero-knowledge arguments for data persistence using probabilistic checkable proofs        | Standard      | Draft    |
|                                                          [35](https://github.com/LNP-BP/LNPBPs/pull/97) | Smart contracts | Bifrost: LN message extensions for RGB data propagation                                   | Standard      | Planned  |
|                                                                                                   36-37 | *Reserved*      | *For future use by bitcoin protocol extensions*                                           |               |          |
| [38](https://github.com/LNP-BP/FAQ/blob/master/Presentation%20slides/Universal%20LNP-BP%20invoices.pdf) | Wallet          | Universal LNP/BP invoices                                                                 | Standard      | Draft    |
|                                                                                                      39 | *Reserved*      | *For future use by bitcoin protocol extensions*                                           |               |          |
|                                                           [40](https://github.com/storm-org/storm-spec) | Smart contracts | Storm: trustless storage with escrow contracts                                            | Standard      | Draft    |
|                                                                                                      41 | Smart contracts | Lightning network message extensions for Storm                                            | Standard      | Planned  |
|                                                                                                      42 | *Reserved*      | *For future use*                                                                          |               |          |
|                                                                                                      43 | *Reserved*      | *For future use by bitcoin protocol extensions*                                           |               |          |
|                                                                                                      44 | Wallet          | Script templating: key derivations within Bitcoin scripts                                 | Standard      | Planned  |
|                                                                                                      45 | Smart contracts | Lightning network message extensions for decentralized exchange functionality             | Standard      | Planned  |
|                                                                                                      46 | Wallet          | Deterministic derivation paths for LNP                                                    | Draft         |          |
|                                                                                                   47,48 | *Reserved*      | *For future use by bitcoin protocol extensions*                                           |               |          |
|                                                                                                      49 | Smart contracts | Synchronized multi-hop state updates via delegation in Lightning network                  | Standard      | Planned  |
|                                                            [50](/lightning-network-protocol/lnpbp-0050) | Smart contracts | Bifrost: generalized Lightning network protocol core                                      | Standard      | Planned  |
|                                                            [51](/lightning-network-protocol/lnpbp-0051) | Smart contracts | Bifrost: channel management protocol                                                      | Standard      | Draft    |
|                                                                                                      52 | Smart contracts | Bifrost routed messaging system based on Sphinx protocol                                  | Standard      | Draft    |
|                                                            [53](/lightning-network-protocol/lnpbp-0053) | Smart contracts | Milti-peer payment channels for Bifrost                                                   | Standard      | Draft    |
|                                                                                                      54 | Smart contracts | Channel factories based on Bifrost protocol                                               | Standard      | Draft    |
|                                                            [55](/lightning-network-protocol/lnpbp-0055) | Smart contracts | HTLC channel synchronization in Bifrost                                                   | Standard      | Draft    |
|                                                                                                      56 | Smart contracts | PTLC channel synchronization in Bifrost                                                   | Standard      | Draft    |
|                                                                                                      57 | Smart contracts | Decentralized naming & name resolution system                                             | Standard      | Planned  |
|                                                        [58](https://github.com/pandoracore/typhon-spec) | Cryptography    | Apophis: distributed elliptic curve-based key creation with shared secrets                | Standard      | Draft    |
|                                                        [59](https://github.com/pandoracore/typhon-spec) | Smart contracts | Typhon: trustless Bitcoin sidechains                                                      | Standard      | Draft    |
|                                                         [60](https://github.com/pandoracore/ibiss-spec) | Smart contracts | Ibiss: reputation-based interactive computation integrity arguments                       | Informational | Draft    |
|                                                         [61](https://github.com/pandoracore/ibiss-spec) | Smart contracts | Toth: reputation-based interactive settlement for computation integrity arguments         | Informational | Draft    |
|                                                    [62](https://github.com/pandoracore/prometheus-spec) | Smart contracts | Prometheus: trustless multiparty computing with escrow & arbitration on bitcoin           | Standard      | Draft    |
|                                                                                                      63 | Smart contracts | Prometheus+: prometheus over LN with tokenized RGB reputation                             | Standard      | Planned  |
|                                                                                                   64-79 | *Reserved*      | *For the future use by lightning network protocol extensions*                             |               |          |
|  [80](https://github.com/opentimestamps/opentimestamps-server/blob/master/doc/merkle-mountain-range.md) | Cryptography    | Merkle mountain ranges                                                                    | Standard      | Final    |
|                                                                    [81](/commitment-schemes/lnpbp-0081) | Cryptography    | Tagged merkle trees for client-side-validation                                            | Standard      | Draft    |
|                                                                                                      82 | Cryptography    | OpenTimestamps bitcoin transaction commitments                                            | Standard      | Final    |
|                                                                                                      83 | Cryptography    | OpenTimestamps proof construction & verification                                          | Standard      | Final    |
|                                                                                                      83 | Cryptography    | OpenTimestamps proof serialization                                                        | Standard      | Final    |
|                                                                                                      84 | Cryptography    | OpenTimestamps calendar and attestation services                                          | Standard      | Final    |
|                                                                                                   85-99 | *Reserved*      |                                                                                           |               |          |
|                                                                                                     100 | *Reserved*      | *For future use by a scalable & confidential single-use-seal commitment layer 1*          |               |          |

### Invited or planned proposals to join LNP/BP standards family

1. Discreet log contracts:
   * [Specification effort](https://github.com/discreetlogcontracts/dlcspecs)
   * [Lightning Discreet Log Contract Channels](https://hackmd.io/@lpQxZaCeTG6OJZI3awxQPQ/LN-DLC)
2. Different [pre-Schnorr schemes for scriptless scripts](https://lists.linuxfoundation.org/pipermail/lightning-dev/2019-November/002316.html)
3. Other lightning network extensions:
   * [eltoo](https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-April/015907.html)
   * [PTLC](https://suredbits.com/payment-points-part-2-stuckless-payments/)


# LNPBP-1: Public keys

```
LNPBP: 0001
Vertical: Cryptographic primitives
Title: Key tweaking: collision-resistant elliptic curve-based commitments
Authors: Dr Maxim Orlovsky <orlovsky@protonmail.ch>,
         Dr Rene Pickhardt,
         Federico Tenga,
         Martino Salvetti,
         Giacomo Zucco,
         Max Hillebrand,
         Christophe Diederichs,
         Yojoe <https://github.com/yojoe>
Comments-URI: <https://github.com/LNP-BP/lnpbps/issues/3>
Status: Proposal
Type: Standards Track
Created: 2019-09-23
Finalized: not yet
License: CC0-1.0
```

* [Abstract](#abstract)
* [Background](#background)
* [Motivation](#motivation)
* [Specification](#specification)
  * [Commitment procedure](#commitment-procedure)
  * [Verification procedure](#verification-procedure)
  * [Reveal procedure](#reveal-procedure)
* [Compatibility](#compatibility)
* [Rationale](#rationale)
  * [Commitments with a set of public keys, not a single key](#commitments-with-a-set-of-public-keys-not-a-single-key)
  * [Use of HMAC insead of simple hash](#use-of-hmac-insead-of-simple-hash)
  * [Public key serialization to 64 byte uncompressed form](#public-key-serialization-to-64-byte-uncompressed-form)
  * [Use of protocol tags](#use-of-protocol-tags)
  * [Protocol failures](#protocol-failures)
  * [Choice of elliptic curve generator point order `n` over field order `p`](#choice-of-elliptic-curve-generator-point-order-n-over-field-order-p)
  * [No nonce](#no-nonce)
* [Reference implementation](#reference-implementation)
* [Acknowledgements](#acknowledgements)
* [References](#references)
* [License](#license)
* [Appendix A. Test vectors](#appendix-a-test-vectors)
  * [1. Correct test vectors](#1-correct-test-vectors)
    * [1.1. Zero-length message](#11-zero-length-message)
    * [1.2. Message consisting of a single zero byte](#12-message-consisting-of-a-single-zero-byte)
    * [1.3. Message of text string `test`](#13-message-of-text-string-test)
    * [1.4. Binary messsage, hex encoding (little-endian byte order)](#14-binary-messsage-hex-encoding-little-endian-byte-order)
    * [1.5. Keyset changes](#15-keyset-changes)
  * [2. Invalid test vectors](#2-invalid-test-vectors)
  * [3. Edge cases: protocol failures](#3-edge-cases-protocol-failures)

### Abstract

Cryptographic commitments embedded into bitcoin transactions is a widely-used practice. It's application include timestamping \[1], single-use seals \[2], pay-to-contract settlement schemes \[3], sidechains \[4], blockchain anchoring \[5], Taproot, Graftroot proposals \[6, 7, 8], Scriptless scripts \[9] and many others. Nevertheless, existing ways of creating commitments have never been standardized with best practices and do not commit to the exact protocol or commitment scheme used. They are also inapplicable to situations where multiple public keys are present in some output: how to deterministically detect which key is holding the commitment.

This work proposes a standardization for cryptographic commitments that utilize the homomorphic properties of the `Secp256k1` elliptic curve (EC) and allows to commit to arbitrary data using an EC public key or a set of EC public keys from the `Secp256k1` curve in a deterministic and safe way.

### Background

Cryptographic commitments represent a way to commit to some message without revealing it. The procedure consists of two phases, **commit** and **reveal**. In the *commit* phase, a party (**committer**), willing to prove its knowledge of some message, computes a *cryptographic hash function* over that message producing a message **digest**, which can be provided to other party(ies). In the *reveal* phase, the *committer* reveals the actual message and each party accessing it may check that its hash is equal to the originally provided *digest*.

Key tweaking is a procedure for creation of a cryptographic commitment to some **message** using elliptic curve properties. The procedure uses the discrete log problem (DLP) as a proof of existence & knowledge of certain information about the message by some party (Alice) without exposing the original message. This is done by adding to a public key, for which Alice knows the corresponding private key, a hash of the message multiplied on the generator point `G` of the elliptic curve. This produces a **tweaked** public key, containing the commitment. At a later time Alice may prove her past knowledge of the original message (at the time when the commitment was created) by providing a signature corresponding to the original public key and the message itself.

The main advantage of the public key tweak procedure is the fact that a tweaked key, or a corresponding signature, can't be distinguished from any other public keys or signatures; this property allows to hide the actual commitment in such a way that it can only be known to those parties which have knowledge of the secrets: the original public and/or key pair **and** a message.

This type of commitment was originally proposed as a part of the *pay to contract* concept by Ilja Gerhardt and Timo Hanke in \[1] and later used by Eternity Wall \[2] for the same purpose. However, these proposals were arguably vulnerable to length-extension attacks and, more importantly, were not applicable to scenarios when multiple public keys are used (for instance, multi-signature bitcoin transaction outputs). These problems were fixed as a part of the sidechain-design efforts by Blockstream \[3], which proposed to utilize a HMAC function and also introduced a nonce in the concept.

Here we propose a standardization of the algorithm based on the original Eternity Wall and Blockstream work, enhanced with Pieter Wuille's Tagged Hashes procedure, coming from a specification on Schnorr signatures in Bitcoin \[4], also used in the Taproot proposal \[5]. This procedure prevents cross-protocol collisions, such that the original message's byte sequence can't be reinterpreted under another protocol.

### Motivation

Publication of cryptographic commitments to the Bitcoin blockchain is a widely used mechanism, allowing timestamping of the commitment: it can be used to prove the fact that some information was known before a certain period in time without revealing the actual information. Use of elliptic curve homomorphic properties allows to perform such commitments without increasing the size of the transaction, by leveraging existing transaction outputs and not polluting blockchain space with excessive OP\_RETURNs. However, as of today, there is no single standard for such commitments. While different practices for that purpose exist (see \[1, 2, 3]), they contain multiple collision risks, such as the possibility of length-extension attacks and cross-protocol replay attacks. Or they can't be applied in situations where multiple public keys are used ( multi-signature or custom bitcoin scripts). This standard combines existing best practices into a single algorithm, that avoids all of those issues.

### Specification

#### Commitment procedure

For a given message `msg`, a list of public keys from the `Secp256k1` curve `P* := {P1, P2, ..., Pn}`, `n > 0`, with a selected original public key `Po` from this list (`Po ∈ P*`), and a protocol-specific `tag` known to both parties, the **commit procedure** runs as follows:

1. Reduce list `P*` to a set of unique public keys `P`, by removing all duplicate public keys from the list.
2. Compute sum `S` of all unique public keys in set `P`; fail the protocol if an overflow over elliptic curve generator point order happens during the procedure.
3. Construct a byte string `lnpbp1_msg`, composed of the original message prefixed with a single SHA256 hash of `LNPBP1` string and a single SHA256 hash of the protocol-specific `tag`:\
   `lnpbp1_msg = SHA256("LNPBP1") || SHA256(tag) || msg`
4. Serialize the aggregated public key `S` into a 64 byte array `S*` of uncompressed coordinates x and y in big-endian order and use `S*` to authenticate `lnbp1_msg` via HMAC-SHA256. The resulting value is named the **tweaking factor** `f`:\
   `f = HMAC-SHA256(lnpbp1_msg, S*)`
5. Make sure that the tweaking factor is less than the order `n` of a generator point of the used elliptic curve, such that no overflow can happen when it is added to the original public key. If the order is exceeded, fail the protocol indicating the reason of failure.
6. Multiply the tweaking factor `f` on the used elliptic curve generator point `G`: `F = G * f`
7. Check that the result of step 6 is not equal to the point-at-infinity; otherwise fail the protocol, indicating the reason of failure, such that the protocol may be run with another initial public key set `P'`.
8. Add the two elliptic curve points: the original public key `Po` and the point `F`, derived from the tweaking-factor. This will result in a tweaked public key `T`: `T = Po + F`. Check that the result is not equal to the point-at-infinity of the elliptic curve or fail the protocol otherwise, indicating the reason of failure, such that the protocol may be run with another initial public key list `P*'`.

The final formula for the commitment is:\
`T = Po + G * HMAC-SHA256(SHA256("LNPBP1") || SHA256(tag) || msg, S*)`

#### Verification procedure

**Verification procedure** for the commitment (i.e. tweaked public key `T`) can be performed with the provision of the list of public keys `P*`, the original public key `Po` and the message `msg` (assuming that the verifying party is aware of the protocol-specific `tag` and `LNPBP1` tag) and runs as follows:

1. Make sure that the provided tweaked public key `T` lies on the elliptic curve and is not equal to the point at infinity.
2. Compute `T' = Po + G * HMAC-SHA256(SHA256("LNPBP1") || SHA256(tag) || msg, S*)` repeating the *commitment procedure* according to the rules above.
3. Make sure that `T' = T` and report verification success; otherwise report verification failure.

#### Reveal procedure

Thus, **reveal data** required for the commitment verification constists of:

1. Original message `msg`
2. Tweaked public key value `T`
3. Original set of public keys `P` and a key `Po` from that set.

The used protocol tag `tag` must be known to all parties participating in the protocol.

### Compatibility

The proposed procedure should be compatible with previously-created pay-to-contract-style commitments based on SHA256 hashes under the assumption of SHA256 collision resistance. Utilization of a double tagged hash protocol prefix guarantees randomness in the first 64 bytes of the resulting tweaking string `lnpbp1_msg`, reducing probability for these bytes to be interpreted as a correct message under any of the previous standards.

The procedure is well compliant with Taproot SegWit v1, since it operates with a sum of the original public keys, and the Taproot intermediate key is a sum of all used public keys, so it can represent a correct input for the protocol.

The tweaked procedure may result in a public key that may, or may not have its *y* coordinate being a quadratic residue (in terms of BIP-340 \[4]). This may present a compatibility issue for using this scheme in Taproot/Schnorr-enabled outputs and protocols. Nevertheless, this issue may be mitigated by running the procedure a second time and replacing the original public key with its own negation, if the resulting tweaked version was not square.

The proposal relies on a tagged hash prefix similar to the one used in BIP-340, \[4], which helps to prevent protocol collisions.

### Rationale

#### Commitments with a set of public keys, not a single key

The protocol was designed to support commitments to multiple public keys in order to be usable with non-P2(W)PK outputs. For instance, with Lightning network all outputs in the commitment transaction are non-P2WPK, so all existing key tweaking schemes are not usable within LN structure.

#### Use of HMAC insead of simple hash

Reason: prevention of length-extension attacks

As this protocol aims to be a generic scheme, the message `msg` can be of any length. If we would just use a simple hash (e.g. SHA256), users of `LNPBP-1` could **potentially** be vulnerable to length-extension attacks, if they are not careful. To be on the safe side, we use HMAC-SHA256, which is resistant to length-extension attacks, but computationally more expensive. However, this protocol aims to be used in client-side validation applications primarily and should therefore run many orders of magnitude less often then complete validatation of all public blockchain data. The computational overhead of HMAC on a client node is therefore considered negligible, for the targeted use cases.

#### Public key serialization to 64 byte uncompressed form

Reason: HMAC needs a byte array as input

HMAC requires a byte array as input for the `key` argument to authenticate a message. This `key` is not intended to be an EC key, it can be anything. Its purpose is to add entropy to the resulting hash value to counter length attacks on the underlying message.

We use HMAC's `key` argument for two purposes:

1. Commit the message `msg` to a specific public key `S`.
2. As entropy for the security of HMAC-SHA256 against length extension attacks.

For the serialization of the public key `S`, we rely on the *de facto* standard format for uncompressed public keys in Bitcoin, which is followed by libraries like [rust-secp256k1](https://docs.rs/secp256k1/0.20.1/src/secp256k1/key.rs.html#290-306). However, this results in a 65 byte array with the first byte being the prefix having the value `0x04`, denoting an uncompressed public key. However, the first byte doesn't add any entropy and a `key` larger than 64 byte causes HMAC-SH256 to do an additional round of hashing. Therefore, we use `rust-secp256k1`' s `key.serialize_uncompressed()` function, but strip the first byte from the resulting value, so we end up with a 64 byte array of:

* 32 bytes representing the x coordinate in big-endian order,
* followed by 32 bytes representing the y coordinate in big-endian order.

#### Use of protocol tags

Reason: prevention of cross-protocol collision attacks

The use of protocol-specific, double tagged hashes was originally proposed by Peter Wuille in \[4] and \[5] in order to prevent potential replay-attacks for interpreting messages under different protocols. The choice of a duplicate SHA256 prefix hash was made according to Peter Wuille because it is not yet used in any existing bitcoin protocol, which increases compatibility and reduces chances of collisions with existing protocols.

#### Protocol failures

The protocol may fail during some of the **commitment** procedure steps:

* when the *tweaking factor* `f` exceeds the order `n` of the generator point `G` for the selected elliptic curve.
* when the multiplication of the Secp256k1 generator point `G` on the *tweaking factor* `f` results in `F` being equal to the point at infinity.
* when the summation of the members of public key set `P` at any stage, or the addition of the point `F` with the original public key `Po`, results in the point at infinity.

The probabilities of these failures are infinitesimal; for instance the probability of the SHA256 hash value of a random message exceeding `G` order `n` is `(2^256 - n) / n`, which is many orders of magnitude less than the probability of a CPU failure. The probability of the second or third failure is even lower, since the point at infinity may be obtained only if `F` is equal to `-G` or `-P`, i.e. the probability of private key collision, equal to the inverse of Secp256k1 curve generator point order `n`. The only reason why this kind of failure may happen is when the original public key set was forged in a way that some of its keys are equivalent to the negation of other keys.

These cases may be ignored by a protocol user -- or, alternatively, in case of the protocol failure the user may change `P`'s value(s) and re-run the protocol.

Protocol failures during the verification procedure may happen only during its repetition of the original commitment. This means that the original commitment is invalid, since it was not possible to create a commitment with the given original data. Thus, such failure will simply indicate a negative result of the verification procedure.

#### Choice of elliptic curve generator point order `n` over field order `p`

While it is possible to ignore elliptic curve overflow over its order `n` during public key addition, since it does not provide a security risk for the commitment, it was chosen to stick to this scheme because of the following:

* Current implementation of Secp256k1 library (libsecp256k1) fails on overflow during key tweaking procedure. Since this library is widely used in the Bitcoin ecosystem (and Bitcoin Core), it is desirable to maintain LNPBP-1 compatible with this functionality.
* Probability of an overflow is still infinissimal, being comparable to probability of `3.7*10^-66`, for a tweaking factor not fitting into the elliptic curve field order `p`.

#### No nonce

In certain circumstances a simple hash based commitment might be vulnerable to brute force vocabulary attacks, if the syntax and semantics of the invoking protocol are known to the attacker. This is usually countered with adding additional entropy (e.g. a nonce) to each hash. In our case the public key `S` already provides enough entropy, which - when added via HMAC-SHA256 to the whole `msg` – sufficiently counters such vocabulary attacks, preventing an attacker from successfully guessing the original message, even for short and standard messages.

### Reference implementation

```rust
use std::collections::BTreeSet;

use bitcoin::hashes::{sha256, Hash, HashEngine, Hmac, HmacEngine};
use bitcoin::secp256k1;

lazy_static! {
    /// Global Secp256k1 context object
    pub static ref SECP256K1: secp256k1::Secp256k1<bitcoin::secp256k1::All> = 
      secp256k1::Secp256k1::new();
}

lazy_static! {
    /// Single SHA256 hash of "LNPBP1" string according to LNPBP-1 acting as a
    /// prefix to the message in computing tweaking factor
    pub static ref LNPBP1_HASHED_TAG: [u8; 32] = {
        sha256::Hash::hash(b"LNPBP1").into_inner()
    };
}

/// Deterministically-organized set of all public keys used by this mod
/// internally. 
type Keyset = BTreeSet<secp256k1::PublicKey>;

/// Errors that may happen during LNPBP-1 commitment procedure or because of
/// incorrect arguments provided to [`commit()`] function.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Display, Error, From)]
#[display(doc_comments)]
pub enum Error {
    /// Keyset must include target public key, but no target key found it
    /// the provided set.
    NotKeysetMember,

    /// Elliptic curve point addition resulted in point in infinity; you
    /// must select different source public keys
    SumInfiniteResult,

    /// LNPBP-1 commitment either is outside of Secp256k1 order `n` (this event
    /// has negligible probability <~2^-64), or, when added to the provided
    /// keyset, results in point at infinity. You may try with a different
    /// source message or public keys.
    InvalidTweak,
}

/// Function performs commitment procedure according to LNPBP-1.
pub fn commit(
    // We automatically reduce set to unique keys by using `BTreeSet` in the 
    // underlying `Keyset` data type
    keyset: &mut Keyset,
    target_pubkey: &mut secp256k1::PublicKey,
    // We take a hashed version of the protocol tag for computation efficiency
    // so it can be used in multiple commitments without hash re-computing
    protocol_tag: &sha256::Hash,
    message: &impl AsRef<[u8]>,
) -> Result<[u8; 32], Error> {
    if !keyset.remove(target_pubkey) {
        return Err(Error::NotKeysetMember);
    }

    let pubkey_sum = keyset
        .iter()
        .try_fold(target_pubkey.clone(), |sum, pubkey| sum.combine(pubkey))
        .map_err(|_| Error::SumInfiniteResult)?;

    let mut hmac_engine =
        HmacEngine::<sha256::Hash>::new(&pubkey_sum.serialize_uncompressed());

    hmac_engine.input(&LNPBP1_HASHED_TAG[..]);
    hmac_engine.input(&protocol_tag[..]);
    hmac_engine.input(&sha256::Hash::hash(message.as_ref()));

    // Producing and storing tweaking factor in container
    let hmac = Hmac::from_engine(hmac_engine);
    let tweaking_factor = *hmac.as_inner();

    // Applying tweaking factor to public key
    target_pubkey
        .add_exp_assign(&SECP256K1, &tweaking_factor[..])
        .map_err(|_| Error::InvalidTweak)?;

    keyset.insert(target_pubkey.clone());

    // Returning tweaked public key
    Ok(tweaking_factor)
}

/// Function verifies commitment created according to LNPBP-1.
pub fn verify(
    verified_pubkey: secp256k1::PublicKey,
    original_keyset: &Keyset,
    mut target_pubkey: secp256k1::PublicKey,
    protocol_tag: &sha256::Hash,
    message: &impl AsRef<[u8]>,
) -> bool {
    match commit(
        &mut original_keyset.clone(),
        &mut target_pubkey,
        protocol_tag,
        message,
    ) {
        // If the commitment function fails, it means that it was not able to
        // commit with the provided data, meaning that the commitment was not
        // created. Thus, we return that verification have not passed, and not
        // a error.
        Err(_) => return false,

        // Verification succeeds if the commitment procedure produces public key
        // equivalent to the verified one
        Ok(_) => target_pubkey == verified_pubkey,
    }
}
```

### Acknowledgements

Authors would like to thank:

* Alekos Filini for his initial work on the commitment schemes as a part of early RGB effort \[6];
* ZmnSCPxj for bringing attention to possible Taproot-compatibility issues \[7];
* Peter Wuille for a proposal on the tagged hashes, preventing reply-type of attacks \[5];
* Authors of Sidechains whitepaper for paying attention to the potential length-extension attacks and the introduction of HMAC-based commitments to the original public key \[3];
* Dr Christian Decker for pointing out on Lightning Network incompatibility with all existing cryptographic commitment schemes.

### References

1. Ilja Gerhardt, Timo Hanke. Homomorphic Payment Addresses and the Pay-to-Contract Protocol. arXiv:1212.3257 \[cs.CR] <https://arxiv.org/pdf/1212.3257.pdf>
2. [Eternity Wall's "sign-to-contract" article](https://blog.eternitywall.com/2018/04/13/sign-to-contract/)
3. Adam Back, Matt Corallo, Luke Dashjr, et al. Enabling Blockchain Innovations with Pegged Sidechains (commit5620e43). Appenxix A. <https://blockstream.com/sidechains.pdf>.
4. Pieter Wuille. Schnorr Signatures for secp256k1. <https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki>
5. Pieter Wuille. Taproot: SegWit version 1 spending rules. <https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki>
6. RGB Protocol Specification, version 0.4. "Commitment Scheme" section. <https://github.com/rgb-org/spec/blob/old-master/01-rgb.md#commitment-scheme>
7. <https://github.com/rgb-org/spec/issues/61>

### License

This document is licensed under the Creative Commons CC0 1.0 Universal license.

### Appendix A. Test vectors

All tests done with protocol-specific `tag` value equal to `ProtoTag`. Values for public keys are given in standard compressed pre-Shorr's Bitcoin encoding format; values for tweaking factors are given in little-endian byte order.

#### 1. Correct test vectors

**1.1. Zero-length message**

1. Single public key #1

* Original public key: `03ab1ac1872a38a2f196bed5a6047f0da2c8130fe8de49fc4d5dfb201f7611d8e2`
* Tweaked public key with the commitment: `025d69da2890f85928cb492545a13bd6782168b39d52e69fadd1d3fcb3b1bf9268`
* Tweaking factor value: `9ff4c975950ec102b5eb39df2f976948b2c1a6e3f92ef5bf5af0e1241380dbcf`

2. Single public key #2

* Original public key: `039729247032c0dfcf45b4841fcd72f6e9a2422631fc3466cf863e87154754dd40`
* Tweaked public key with the commitment: `032fdf6c4023453b869294ddd28684f98fcaca604c2cd734c8dd64b8520547b0b4`
* Tweaking factor value: `11db141cfe0143f60e9e9f9db478630033fc65eb4f682905e9044c87869459a5`

3. Set of five public keys

* Original public key: `02383b24fbea14253ac37b0d421263b716a34192516ea0837021a40b5966a06f5e`
* Key set:
  * `02383b24fbea14253ac37b0d421263b716a34192516ea0837021a40b5966a06f5e`
  * `025b178dfaa49e959033cc2ba8b06d78b8b9242496329a574eb8e2b4fad4f88b6f`
  * `03ec8b1cf223dc3cd8eb6d7c5fb11735e983c234b69271a3decad8bbfb2b997994`
  * `021ce48f4b53257be01ccb237986c1b9677a9e698fb962b108d6b2fbdc836727d8`
  * `0388a0fc8d3ba29a93ad07dbad37a6d4b87f2e2672b15d331d1f6bf4f2c9119ffe`
* Tweaked public key with the commitment: `03c153beef57c268ee9a2a68940f2aa7b052ce14c676a27cfe5010c53b41476238`
* Tweaking factor value: `a18417ae90cf36a45311ccc3a911a8ebb1b7afa02c6d79d1d1bd08b2abf67e94` 4). Set of same five public keys, using different original key from the set
* Original public key: `025b178dfaa49e959033cc2ba8b06d78b8b9242496329a574eb8e2b4fad4f88b6f`
* Key set:
  * `02383b24fbea14253ac37b0d421263b716a34192516ea0837021a40b5966a06f5e`
  * `025b178dfaa49e959033cc2ba8b06d78b8b9242496329a574eb8e2b4fad4f88b6f`
  * `03ec8b1cf223dc3cd8eb6d7c5fb11735e983c234b69271a3decad8bbfb2b997994`
  * `021ce48f4b53257be01ccb237986c1b9677a9e698fb962b108d6b2fbdc836727d8`
  * `0388a0fc8d3ba29a93ad07dbad37a6d4b87f2e2672b15d331d1f6bf4f2c9119ffe`
* Tweaked public key with the commitment: `03a224242255c9a024d4e2723c17faa09082b60bf91cea23ce558c9cff3a9627bf`
* Tweaking factor value: `a18417ae90cf36a45311ccc3a911a8ebb1b7afa02c6d79d1d1bd08b2abf67e94`

**1.2. Message consisting of a single zero byte**

1. Single public key #1
   * Original public key: `032564fe9b5beef82d3703a607253f31ef8ea1b365772df434226aee642651b3fa`
   * Tweaked public key with the commitment: `0285f7e0a8cdd801e5fbf84602e84de46a036ba47230b2c37f7767a496aeb4e4c5`
   * Tweaking factor value: `5639647143cb9dc78aa5d251694fcc053f3887cf27b13750f72a42ef04f7bde1`
2. Single public key #2
   * Original public key: `0289637f97580a796e050791ad5a2f27af1803645d95df021a3c2d82eb8c2ca7ff`
   * Tweaked public key with the commitment: `03fcd2e4c31622fcf9fef43e70dabf1daf8abae5685b15125ba6a0e444783c5f0e`
   * Tweaking factor value: `7551544f39a2c3a4d65c34e5915702a825ccbbb914ac581389cbbd98869b4e48`
3. Set of five public keys
   * Original public key: `03ff3d6136ffac5b0cbfc6c5c0c30dc01a7ea3d56c20bd3103b178e3d3ae180068`
   * Key set:
     * `03ff3d6136ffac5b0cbfc6c5c0c30dc01a7ea3d56c20bd3103b178e3d3ae180068`
     * `02308138e71be25e092fdc9da03d5357421bc7280356a1381a6186d63a0ca8dd7f`
     * `03575fc4e82a6deb65d1e5750c85b6862f6ec009281992e206c0dcc568866a3fb1`
     * `0271efa4e26a4179e112860b88fc98658a4bdbc59c7ab6d4f8057c35330c7a89ee`
     * `0289637f97580a796e050791ad5a2f27af1803645d95df021a3c2d82eb8c2ca7ff`
   * Tweaked public key with the commitment: `0289d1313a940f7b668804e223662edce2a7138914894607cd4bf641cc584936f3`
   * Tweaking factor value: `87a5728772e0d14c9938c50ab29b215d5a0d9f59be7b40d16cc4bcac22e027b1`

**1.3. Message of text string `test`**

1. Single public key #1
   * Original public key: `0271efa4e26a4179e112860b88fc98658a4bdbc59c7ab6d4f8057c35330c7a89ee`
   * Tweaked public key with the commitment: `02605b2400618ca83f563e997da456c7ae99df9b38a7939ead5bc8e5b8b29f5d45`
   * Tweaking factor value: `7090ad6b1c6093e025c3b2f1607f9aea65449139a08ee773c61990e9b6e966d3`
2. Single public key #2
   * Original public key: `039729247032c0dfcf45b4841fcd72f6e9a2422631fc3466cf863e87154754dd40`
   * Tweaked public key with the commitment: `032bf20cd8539c2f3154fbae01e64ea3a492bb2431080c86c3f942571f9635ece7`
   * Tweaking factor value: `214570a96bf958124eea266593fd9daed3ee357283b4f89613f99a5d8ac8910a`
3. Set of five public keys
   * Original public key: `03f72a42169a0475c4a342f8da97a1c0bce830183efecd0a3d81637b05d7c0d81a`
   * Key set:
     * `03f72a42169a0475c4a342f8da97a1c0bce830183efecd0a3d81637b05d7c0d81a`
     * `02383b24fbea14253ac37b0d421263b716a34192516ea0837021a40b5966a06f5e`
     * `025b178dfaa49e959033cc2ba8b06d78b8b9242496329a574eb8e2b4fad4f88b6f`
     * `03ec8b1cf223dc3cd8eb6d7c5fb11735e983c234b69271a3decad8bbfb2b997994`
     * `03f0d2dd91c4bcb630616ea9e3b2e95ec7f6f431d81bd627b62d04ac81b91af8c7`
   * Tweaked public key with the commitment: `02da1eea3c29872e9d770efe66bfde4ad2b361f0644e81d1b4d95338eb75b813f1`
   * Tweaking factor value: `63ea2d88f3b3969573ef530132989a9281cb499d6bfda4bfc0ade2cbd7bdf26e`

**1.4. Binary messsage, hex encoding (little-endian byte order)**

Original message for the all cases in this section: `[0xde, 0xad, 0xbe, 0xef]`

1. Single public key #1
   * Original public key: `0352045bcc58e07124a375ea004b3508ac80e625da2106c74f5cb023498de0545f`
   * Tweaked public key with the commitment: `0357f2619c2805794ef65ab7ea7a349f4c1be4cc3f576584f8270f06e830f33e36`
   * Tweaking factor value: `14703d20ec36407889e5d7546d59edbfac4e69f211759a1bd783aa65ee1ae36c`
2. Single public key #2
   * Original public key: `02a153dfe913310b0949de7976146349b95a398cb0de1047290b0f975c172ad712`
   * Tweaked public key with the commitment: `0388bcce7da0bc2edd2ff553134c7ae109232f30bda347b39adca6d0d379a86315`
   * Tweaking factor value: `627573dc2a7a57e5fe83f415d5f9d0e9ee78e51fd7990e926f09e9b8fe6a12b3`
3. Set of five public keys
   * Original public key: `03a9c44838c0ac7417497f770ebd013c91ac715665ec01e740be0e14f44cab2474`
   * Key set:
     * `03a9c44838c0ac7417497f770ebd013c91ac715665ec01e740be0e14f44cab2474`
     * `03ad42e3bd69e30d32d088173e02b9d1cd00e4f7d945aad5c1a6c9439fdc8c5e80`
     * `03713e80a43b19d6f7b46ec5a474e86c8f5769f85f4fcb9a0be76d095b1e2b7981`
     * `025d9e055d7e7a85f097e981779c6e1c40d74b0563e631128c06623609b99a8f87`
     * `0323e518565f25038f16fdf7686ed4dd9a59b02ef95d2d7aa5be948f38701376b7`
   * Tweaked public key with the commitment: `02d739f0fdd7bc395482c52e1ef1547a3c6fc6e2f1393430e74c55624f26023bd7`
   * Tweaking factor value: `d5218633603181303d06320365fc84d06e0c2bb36c0989ee678a57b799f457a7`

**1.5. Keyset changes**

Commitment creation and validation filters repeated keys and does not depend on the key order (since elliptic curve addition is commutative)

1. Set of five public keys containing duplicated keys
   * Message (binary string, little-endian byte order): `[0x00, 0xde, 0xad, 0xbe, 0xef]`
   * Original public key: `025d9e055d7e7a85f097e981779c6e1c40d74b0563e631128c06623609b99a8f87`
   * Key set:
     * `03a9c44838c0ac7417497f770ebd013c91ac715665ec01e740be0e14f44cab2474`
     * `03ad42e3bd69e30d32d088173e02b9d1cd00e4f7d945aad5c1a6c9439fdc8c5e80`
     * `03ad42e3bd69e30d32d088173e02b9d1cd00e4f7d945aad5c1a6c9439fdc8c5e80`
     * `03713e80a43b19d6f7b46ec5a474e86c8f5769f85f4fcb9a0be76d095b1e2b7981`
     * `025d9e055d7e7a85f097e981779c6e1c40d74b0563e631128c06623609b99a8f87`
     * `0323e518565f25038f16fdf7686ed4dd9a59b02ef95d2d7aa5be948f38701376b7`
     * `025d9e055d7e7a85f097e981779c6e1c40d74b0563e631128c06623609b99a8f87`
   * Tweaked public key with the commitment: `027f07015596c7a3af8a1da9e4fe1de0695278f94278ce01534b7ac7a530b43399`
   * Tweaking factor value: `bc47cf269e70e5e654f3079f7316ddd988c529bf7d8c0efb0ec0759719afaeaa`
2. Set of five public keys in changed order
   * Message (binary string, little-endian byte order): `[0x00, 0xde, 0xad, 0xbe, 0xef]`
   * Original public key: `025d9e055d7e7a85f097e981779c6e1c40d74b0563e631128c06623609b99a8f87`
   * Key set:
     * `03713e80a43b19d6f7b46ec5a474e86c8f5769f85f4fcb9a0be76d095b1e2b7981`
     * `03a9c44838c0ac7417497f770ebd013c91ac715665ec01e740be0e14f44cab2474`
     * `025d9e055d7e7a85f097e981779c6e1c40d74b0563e631128c06623609b99a8f87`
     * `0323e518565f25038f16fdf7686ed4dd9a59b02ef95d2d7aa5be948f38701376b7`
     * `03ad42e3bd69e30d32d088173e02b9d1cd00e4f7d945aad5c1a6c9439fdc8c5e80`
   * Tweaked public key with the commitment: `027f07015596c7a3af8a1da9e4fe1de0695278f94278ce01534b7ac7a530b43399`
   * Tweaking factor value: `bc47cf269e70e5e654f3079f7316ddd988c529bf7d8c0efb0ec0759719afaeaa`

#### 2. Invalid test vectors

All these cases are cases for validation procedure, which must fail.

1. Case #1: commitment key created with a different original public key
   * Message: zero-length
   * Original public key: `03ab1ac1872a38a2f196bed5a6047f0da2c8130fe8de49fc4d5dfb201f7611d8e2`
   * Tweaked public key with the commitment: `02a8e7b5f006e3c96eb1e336d40a6956dd9c4889dbfb4542b50da0c90cd2ab64fd`
2. Case #2: original key and commitment are valid, but the message was different
   * Message: `test*`
   * Original public key: `032564fe9b5beef82d3703a607253f31ef8ea1b365772df434226aee642651b3fa`
   * Tweaked public key with the commitment: `0240c2f382fc5335879c3607479c491dbd9bfb47d32c375f7d99e6d210a91f8780`
3. Case #3: commitment was created with correct message and original public key, but using different protocol tag
   * Message (binary string, little-endian byte order): `[0xde, 0xad, 0xbe, 0xef, 0x00]`
   * Original public key: `029a541ac6af794615935c34d088edc824c4433a83bdb5a781030c370111cf5b3a`
   * Tweaked public key with the commitment: `0304d89459380b9d8ff2ebaaf2e20f47ce92dcf0b9dbfde9dbe866513a7819b79c`
4. Case #4: one of original public keys is absent
   * Message: `test`
   * Original public key: `03f72a42169a0475c4a342f8da97a1c0bce830183efecd0a3d81637b05d7c0d81a`
   * Key set:
     * `03f72a42169a0475c4a342f8da97a1c0bce830183efecd0a3d81637b05d7c0d81a`
     * `02383b24fbea14253ac37b0d421263b716a34192516ea0837021a40b5966a06f5e`
     * `03ec8b1cf223dc3cd8eb6d7c5fb11735e983c234b69271a3decad8bbfb2b997994`
     * `03f0d2dd91c4bcb630616ea9e3b2e95ec7f6f431d81bd627b62d04ac81b91af8c7`
   * Tweaked public key with the commitment: `02da1eea3c29872e9d770efe66bfde4ad2b361f0644e81d1b4d95338eb75b813f1`

#### 3. Edge cases: protocol failures

Keyset constructed of a key and it's own negation.

* Expected result: must fail commitment procedure with error indicating that the operation resulted at the point-at-infinity.
* Message: `test`
* Original public key: `0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166`
* Key set:
  * `0218845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166`
  * `0318845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166`


# LNPBP-2: Script

```
LNPBP: 0002
Vertical: Bitcoin protocol
Title: Deterministic embedding of cryptographic commitments into bitcoin 
       transaction output
Authors: Dr Maxim Orlovsky <orlovsky@protonmail.ch>,
         Giacomo Zucco,
         Martino Salvetti,
         Federico Tenga,
         Sosthène
Comments-URI: https://github.com/LNP-BP/lnpbps/issues/4
Status: Proposal
Type: Standards Track
Created: 2019-10-27
License: CC0-1.0
```

* [Abstract](#abstract)
* [Background](#background)
* [Motivation](#motivation)
* [Design](#design)
* [Specification](#specification)
  * [Commitment procedure](#commitment-procedure)
  * [Reveal procedure](#reveal-procedure)
  * [Verification procedure](#verification-procedure)
  * [Deterministic public key extraction from Bitcoin Script](#deterministic-public-key-extraction-from-bitcoin-script)
* [Compatibility](#compatibility)
* [Rationale](#rationale)
  * [Continuing support for P2PK outputs](#continuing-support-for-p2pk-outputs)
  * [Support OP\_RETURN type of outputs](#support-op_return-type-of-outputs)
  * [Unification with OP\_RETURN-based commitments](#unification-with-op_return-based-commitments)
  * [Custom serialization of public keys in OP\_RETURN](#custom-serialization-of-public-keys-in-op_return)
  * [Support for pre-SegWit outputs](#support-for-pre-segwit-outputs)
  * [Committing to the sum of all public keys present in the script](#committing-to-the-sum-of-all-public-keys-present-in-the-script)
  * [Deterministic public key extraction for a Bitcoin script](#deterministic-public-key-extraction-for-a-bitcoin-script)
  * [Use of Taproot intermediate public key](#use-of-taproot-intermediate-public-key)
* [Reference implementation](#reference-implementation)
* [Acknowledgements](#acknowledgements)
* [References](#references)
* [License](#license)
* [Appendix A. Test vectors](#appendix-a-test-vectors)
  * [1. Correct test vectors](#1-correct-test-vectors)
  * [2. Invalid test vectors](#2-invalid-test-vectors)
  * [3. Edge cases: protocol failures](#3-edge-cases-protocol-failures)

### Abstract

The standard defines an algorithm for deterministic embedding and verification of cryptographic commitments based on elliptic-curve public key tweaking procedure defined in [LNPBP-1 standard](/commitment-schemes/lnpbp-0001) inside `scriptPubkey` script for existing types of Bitcoin transaction output.

### Background

Cryptographic commitments embedded into bitcoin transactions is a widely-used practice. Its application include timestamping \[1], single-use seals \[2], pay-to-contract settlement schemes \[3], sidechains \[4], blockchain anchoring \[5], Taproot, Graftroot proposals \[6, 7, 8], Scriptless scripts \[9] and many others.

### Motivation

A number of cryptographic commitment (CC) use cases require the commitment to be present within non-P2(W)PK(H) outputs,which may contain multiple public keys and need a clear definition of how the public key that contain the commitment can be found within the bitcoin script itself. For instance, embedding CC into Lightning Network (LN) payment channel state updates in the current version requires the modification of an offered HTLC and received HTLC transaction outputs\[10], and these transactions contain only a single P2WSH output. With the use of `option_anchor_outputs` \[11] all outputs in the LN commitment transaction becomes P2WSH outputs, also leading to a requirement for a standard and secure way of making CC inside P2(W)SH outputs.

At the same time, P2(W)SH and other non-standard outputs (like explicit bare script outputs, including OP\_RETURN type) are not trivial to use for CC, since CC requires deterministic definition of the actual commitment case. Normally, one of the most secure and standard CC scheme uses homomorphic properties of the public keys \[12]; however multiple public keys may be used within non-P2(W)PK(H) output. Generally, these outputs present a hash of the actual script, hiding the used public keys or their hashes. Moreover, it raises the question of how the public key within Bitcoin Script may be defined/detected, since it is possible to represent the public key in a number of different ways within bitcoin script itself (explicitly or by a hash, and it's not trivial to understand where some hash stands for a public key or other type of preimage data). All this raises a requirement to define a standard way and some best practices for CC in non-P2(W) PK(H) outputs. This proposal tries to address the issue by proposing a common standard on the use of public-key based CC \[12] within all possible transaction output types.

### Design

The protocol requires that exactly one public key of all keys present or referenced in `scriptPubkey` and `redeemScript` must contain the commitment (made with LNPBP-1 procedure) to a given message. This commitment is deterministically singular, i.e. it can be proven that there is no other alternative message that the given transaction output commits to under this protocol. The singularity is achieved by committing to the sum of all original (i.e. before the message commitment procedure) public keys controlling the spending of a given transaction output. Thus, the given protocol covers all possible options for `scriptPubkey` transaction output types.

The commitment consists of the updated `scriptPubkey` value, which may be embed into the transaction output, and an **extra-transaction proof** (ETP), required for the verification of the commitment. The structure and information in the proof depends on the actual `scriptPubkey` type.

The protocol includes an algorithm for deterministic extraction of public keys from a given Bitcoin script, based on Miniscript \[16].

### Specification

#### Commitment procedure

The **committing party**, having a message `msg`, must:

1. Collect all public keys instances (named **original public key set**) related to the given transaction output, defined as:
   * a single public key for P2PK, P2PKH, P2WPK, P2WPK/WSH-in-P2SH type of outputs;
   * If `OP_RETURN` `scriptPubkey` is used, it must contain a single public key serialized in BIP-340 xcoordonly form right after `OP_RETURN` opcode; for all other forms of `OP_RETURN` data algorithm must fail;
   * an internal public key for a Taproot output (P2TR);
   * all public keys from a `redeemScript` (for P2(W)SH and P2WSH-in-P2SH, which in case of SegWit is contained within `witnessScript`) or `scriptPubkey` (for custom bare script outputs), extracted according to the [algorithm](#deterministic-public-key-extraction-from-bitcoin-script).
   * In case of witness version > 1 the procedure must fail. Let's call this set of *n* keys `P`.
2. Select a single public key `Po` from the set of the original public keys, which will contain the commitment. It is advised that the corresponding private key being controlled by the committing party, which will simplify future spending of the output.
3. Run [LNPBP-1 commitment procedure](/commitment-schemes/lnpbp-0001#commitment-procedure) on message `msg`, the set of original public keys `P`, the selected public key `Po` and a protocol-specific `tag`, provided by the upstream protocol using this standard. The procedure returns a tweaked public key `T`.
4. Construct necessary scripts and generate `scriptPubkey` of the required type. If OP\_RETURN `scriptPubkey` format is used, it MUST be serialized according to the following rules:
   * only a single `OP_RETURN` code MUST be present in the `scriptPubkey` and it MUST be the first byte of it;
   * it must be followed by 32-byte push of the public key value `P` from the step 2 of the algorithm, serialized according to the rules from \[15];
   * if the tweaked public key serialized with bitcoin consensus serialization rules does not start with 0x02 as it's first (least significant) byte, the procedure must fail; or it may be repeated with a new public key picked at step 1.
5. Construct and store an **extra-transaction proof** (ETP), which structure depends on the generated `scriptPubkey` type: a) value of `Po`, corresponding to:
   * the original intermediary public key for V1 witness Taproot output;
   * single original public key used in the tweak procedure before the tweak was applied; b) deterministic script reconstruction data, i.e.:
   * untweaked `redeemScript` (for P2SH outputs), or `witnessScript` (for P2WSH SegWit v0 native or P2WSH-in-P2SH SegWit legacy outputs), constructed using set of the *original public keys*;
   * the "taptweak" hash (i.e. the tagged hash of the Merkle root of the TapScript branches) for v1 witness output (Taproot);
   * for other types of outputs no other data are required for the ETP.

#### Reveal procedure

The **reveal protocol** is usually run between the committing and verifying parties; however it may be used by the committing party to make the proofs of the commitment public. These proofs include:

* `scriptPubkey` from the transaction output containing the commitment;
* *original message* `msg` to which the *committing party* has committed;
* *extra-transaction proof* (ETP), constructed at the 5th step of the [commitment protocol](#commitment);
* (optional) proofs that the `scriptPubkey` is a part of a transaction included into the bitcoin chain containing the largest known amount of work at depth satisfying a *verifying party* security policy (these proofs may be reconstructed/verified by the verifying party itself using its trusted Bitcoin Core server);

#### Verification procedure

The verification process runs by repeating steps of the commitment protocol using the information provided during the *reveal phase* and verifying the results for their internal consistency; specifically:

1. Original public key set reconstruction:
   * if *extra-transaction proof* (ETP) provides script data (pt. 5.b from the commitment procedure) parse it according to deterministic key collection [algorithm](#deterministic-public-key-extraction-from-bitcoin-script) and collect all the original public keys from it; fail the verification procedure if parsing fails;
   * otherwise use an original public key provided as a part of ETP as a single- element set
2. Run LNPBP-1 verification procedure repeating step 3 from the commitment procedure, using original public key value from the *extra-transaction proof*
3. Construct `scriptPubkey'`, matching the type of the `scriptPubkey` in the transaction and matching *extra-transaction proof* data using the tweaked version of the public key in the same way as was perfomed at step 4 of the commitment procedure. If there can be multiple matching `scriptPubkey` types for a given data, construct a variant for each of them.
4. Make sure that one of the `scriptPubkey'` values generated at the previous step, matches byte by byte the `scriptPubkey` provided during the *reveal phase*; otherwise fail the verification.

#### Deterministic public key extraction from Bitcoin Script

1. The provided script MUST be parsed with Miniscript \[16] parser; if the parser fails the procedure MUST fail.
2. Iterate over all branches of the abstract syntax tree generated by the Miniscript parser, running the following algorithm for each node:
   * if a public key hash is met (`pk_h` Miniscript command) and it can't be resolved against known public keys or other public keys extracted from the script, fail the procedure;
   * if a public key is found (`pk`) add it to the list of the collected public keys;
   * for all other types of Miniscript commands iterate over their branches.
3. Select unique public keys (i.e. if some public key is repeated in different parts of the script/in different script branches, pick a single instance of it). Compressed and uncompressed versions of the same public key must be treated as the same public key under this procedure.
4. If no public keys were found fail the procedure; return the collected keys otherwise.

By "miniscript" we mean usage of `rust-miniscript` library v2.0.0 (commit `463fc1eadac2b46de1cd5ae93e8255a2ab34b906`) which may be found at <https://github.com/LNP-BP/rust-miniscript/commit/463fc1eadac2b46de1cd5ae93e8255a2ab34b906>

### Compatibility

The proposed cryptographic commitment scheme is fully compatible, and works with LNPBP-1 standard \[12] for constructing cryptographic commitments with a set of public keys.

The standard is not compliant with previously used OP\_RETURN-based cryptographic commitments, like OpenTimestamps \[1], since it utilises plain value of the public key with the commitment for the OP\_RETURN push data.

The author is not aware of any P2(W)SH or non-OP\_RETURN cryptographic commitment schemes existing before this proposal, and it is highly probable that the standard is not compatible with ones if they were existing.

The proposed standard is compliant with current Taproot proposal \[14], since it can use intermediate Taproot key to store the commitment.

Standard also should be interoperable with Schnorr's signature proposal \[15], since it uses miniscript supporting detection of public keys serialized with new BIP-340 rules.

### Rationale

#### Continuing support for P2PK outputs

While P2PK outputs are considered obsolete and are vulnerable to a potential quantum computing attacks, it was decided to include them into the specification for unification purposes.

#### Support OP\_RETURN type of outputs

OP\_RETURN was originally designed to reduce the size of memory-kept UTXO data; however it is not recommended to use it since it bloats blockchain space usage. This protocol provides support for this type of outputs only because some hardware (like HSM modules or hardware wallets) can't tweak public keys inside outputs and produce a correct signature after for their spending, and keeping the commitment in OP\_RETURN's can be an only option. For all other cases it is highly recommended not to use OP\_RETURN outputs for the commitments and use tweaking of other types of outputs instead.

#### Unification with OP\_RETURN-based commitments

While it is possible to put a deterministic CC commitments into OP\_RETURN-based outputs like with \[1], their format was modified for unification purposes with the rest of the standard. This will help to reduce the verification and commitment code branching, preventing potential bugs in the implementations.

#### Custom serialization of public keys in OP\_RETURN

This saves one byte of data per output, which is important in case of blockchain space.

While we could pick a new BIP340-based rules for public key serialization \[15], this will require software to support new versions of the secp256k1 libraries and language-specific wrappers, which may be a big issue for legacy software usually used by hardware secure modules, which require presence of OP\_RETURN's (see rationale points above).

#### Support for pre-SegWit outputs

These types of outputs are still widely used in the industry and it was decided to continue their support, which may be dropped in a higher-level requirements by protocols operating on top of LNPBP-2.

#### Committing to the sum of all public keys present in the script

Having some of the public keys tweaked with the message digest, and some left intact will make it impossible to define a simple and deterministic commitment scheme for an arbitrary script and output type that will prevent any potential double-commitments.

#### Deterministic public key extraction for a Bitcoin script

We use determinism of the proposed Miniscript standard to parse the Bitcoin script in an implementation-idependet way and in order to avoid the requirement of the full-fledged Bitcoin Script interpreter for the commitment verification.

The procedure fails on any public key hash present in the script, which prevents multiple commitment vulnerability, when different parties may be provided with different *extra-transaction proof* (ETP) data, such that they will use different value for the `S` public key matching two partial set of the public keys (containing and not containing public keys for the hashed values).

The algorithm does not require that all of the public keys will be used in signature verification for spending the given transaction output (i.e. public keys may not be prefixed with `[v]c:` code in Miniscript \[16]), so the committing parties may have a special public key shared across them for embedding the commitment, without requiring to know the corresponding private key to spend the output.

#### Use of Taproot intermediate public key

With Taproot we can't tweak the public key contained in the `scriptPubkey` directly since it will invalidate its commitment to the Tapscript and to the intermediate key, rendering output unspendable. Thus, we put tweak into the underlying intermediate public key as the only available option.

### Reference implementation

<https://github.com/LNP-BP/rust-lnpbp/blob/master/src/bp/dbc/lockscript.rs>

### Acknowledgements

Authors would like to thank:

* Giacomo Zucco and Alekos Filini for their initial work on the commitment schemes as a part of early RGB effort \[13];
* Dr Christian Decker for pointing out on Lightning Network incompatibility with all existing cryptographic commitment schemes.

### References

1. Peter Todd. OpenTimestamps: Scalable, Trust-Minimized, Distributed Timestamping with Bitcoin. <https://petertodd.org/2016/opentimestamps-announcement>
2. Peter Todd. Preventing Consensus Fraud with Commitments and Single-Use-Seals. <https://petertodd.org/2016/commitments-and-single-use-seals>
3. [Eternity Wall's "sign-to-contract" article](https://blog.eternitywall.com/2018/04/13/sign-to-contract/)
4. Adam Back, Matt Corallo, Luke Dashjr, et al. Enabling Blockchain Innovations with Pegged Sidechains (commit5620e43). Appenxix A. <https://blockstream.com/sidechains.pdf>.
5. <https://exonum.com/doc/version/latest/advanced/bitcoin-anchoring/>
6. Pieter Wuille. Taproot proposal. <https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2019-May/016914.html>
7. Gregory Maxwell. Taproot: Privacy preserving switchable scripting. <https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-January/015614.html>
8. Gregory Maxwell. Graftroot: Private and efficient surrogate scripts under the taproot assumption. <https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-February/015700.html>
9. Andrew Poelstra. Scriptless scripts. <http://diyhpl.us/wiki/transcripts/layer2-summit/2018/scriptless-scripts/>
10. Lightning Network BOLT-3 standard, version 1.0. Sections \["Offered HTLC Outputs"] <https://github.com/lightningnetwork/lightning-rfc/blob/v1.0/03-transactions.md#offered-htlc-outputs> and \["Received HTLC Outputs"] <https://github.com/lightningnetwork/lightning-rfc/blob/v1.0/03-transactions.md#received-htlc-outputs>.
11. [BOLT-3 Lightning network specification](https://github.com/lightningnetwork/lightning-rfc/blob/master/03-transactions.md#to_remote-output)
12. Maxim Orlovsky, et al. Key tweaking: collision-resistant elliptic curve-based commitments (LNPBP-1 Standard). <https://github.com/LNP-BP/lnpbps/blob/master/lnpbp-0001.md>
13. RGB Protocol Specification, version 0.4. "Commitment Scheme" section. <https://github.com/rgb-org/spec/blob/old-master/01-rgb.md#commitment-scheme>
14. Pieter Wuille. Taproot: SegWit version 1 spending rules. <https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki>
15. Pieter Wuille. Schnorr Signatures for secp256k1. <https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki>
16. Pieter Wuille, Andrew Poelsta. Miniscript. <http://bitcoin.sipa.be/miniscript/>

### License

This document is licensed under the Creative Commons CC0 1.0 Universal license.

### Appendix A. Test vectors

#### 1. Correct test vectors

TBD

#### 2. Invalid test vectors

TBD

#### 3. Edge cases: protocol failures

TBD


# LNPBP-3: Tx output

```
LNPBP: 0003
Vertical: Bitcoin protocol
Title: Deterministic definition of transaction output containing cryptographic
       commitment
Authors: Giacomo Zucco,
         Dr Maxim Orlovsky <orlovsky@protonmail.ch>,
         Federico Tenga,
         Martino Salvetti
Comments-URI: https://github.com/LNP-BP/lnpbps/issues/5
Status: Proposal
Type: Standards Track
Created: 2019-10-27
License: CC0-1.0
```

* [Abstract](#abstract)
* [Background](#background)
* [Motivation](#motivation)
* [Specification](#specification)
* [Compatibility](#compatibility)
* [Rationale](#rationale)
* [Reference implementation](#reference-implementation)
* [Acknowledgements](#acknowledgements)
* [References](#references)
* [License](#license)
* [Test vectors](#test-vectors)

### Abstract

The standard defines an algorithm for deterministic definition of the transaction output containing cryptographic commitments made under the standards LNPBP-1 \[1] and LNPBP-2 \[2].

### Background

Embedding cryptographic commitments into Bitcoin blockchain has become a common practice \[3]. Bitcoin blockchain provides strong guarantees on the underlying data immutability, presenting a reliable, distributed and censorship-resitent proof-of-publication \[4] medium. While existing standards defines how the cryptographic commitments can be used with public keys on SECP256k1 elliptic curve (used by Bitcoin) and embedded within transaction outputs, it still has to be defined how the interested parties may detect which of a Bitcoin transaction output contains the commitment, created under some specific protocol, including those interoperable with LNPBP-1 and LNPBP-2 standards.

### Motivation

A number of use cases for cryptographic commitments (CC) require some commitment to be unique. For instance, single-use seals \[5] may utilize them to achieve it's one-time commitment properties, as may be required in some of the applications \[6], \[7]. While the deterministic way for embedding into Bitcoin transactions (like "always use the first output) may be defined on a per-protocol basis, it seems that some best-practices, defining the best privacy-preserving and secure algorithm for such deterministic commitments in Bitcoin transactions may also be useful for the industry.

Some of the protocols relies on the first OP\_RETURN output present in the transaction to contain the commitment \[3]. However, this would not work for commitments supporting other output types (\[2], \[8]), and for may introduce collisions with other protocols using OP\_RETURN, like OMNI Layer \[9].

Static definition of the output containing the commitment will be incompatible with BIP-69 \[10], defining deterministic transaction output ordering and will not work with current Lightning Network implementation following the same rules \[11].

### Specification

Cryptographic commitments under this standard are made according to LNPBP-1 \[1] and LNPBP-2 \[2] standards.

To deterministically define the number of transaction output that contains CC under some protocol `P`, the committing party "Alice" `A` (which may be represented by a single person or some m-of-n federation) and the verifying party "Bob" `B` (which may be represented by a single person or some m-of-n federation) need to agree on three parameters:

1. A protocol-defined parameter `s`, acting as a seed for all protocol-wide commitments, this must be a 8-bit value;
2. A commitment-specific parameter `c`, which should not be directly reflected in the transaction, containing the given CC. This parameter under some circumstances (agreed by the parties beforehand) may be absent. The value of `c` must be a 8-bit value.

These two parameters serve as a "salt" for the deterministic procedure, preventing third-parties from guessing the information of the actual commitment, thus avoiding possible censorship by the miners and on-chain based transaction analysis.

Alice, creating the transaction containing CC, and Bob, verifying it, must use the following procedure:

1. Compute the transaction fee `f`, as a difference between total transaction output amounts in satoshis and total inputs amounts, in satoshis:\
   `f = sum(outputs) - sum(inputs)`.\
   This can be done, for instance, by utilizing data from a partially-singed bitcoin transaction, or by contacting Electrum Server or Bitcoin Core backend. It should be noted, that according to Bitcoin consensus rules, this amount must always be positive and greater than zero(`f > 0`); otherwise it is not a valid Bitcoin transaction and the protocol must fail.
2. Compute the adjusted fee `a` as a 32-bit modulo of the potentially-64 bit number `f`:\
   `a = f mod 2^32`.
3. Add to this number a previously-agreed values of `s` and `c` (if `c` was not defined, use `0` for `c` value by default). This will give a commitment-factor `x`:\
   `x = a + s + c`.\
   Since `s` and `c` is a 8-bit numbers and `a` is a 32-bit number, the result will fit a 64-bit number without overflow.
4. Get the number of outputs `n` for the transaction containing the output with the given cryptographic commitment.
5. Compute `d` as `d = x mod n`. The `d` will represent an index of the output which must contain a cryptographic commitment. All other transaction outputs will not be a valid outputs for a contain cryptographic commitment under the used protocol.

### Compatibility

The proposed standard is incompatible with many of existing practices for definition of the transaction output containing cryptographic commitment, including OpenTimestamps, which uses first transaction output for storing the commitment \[1]

Nevertheless, use of protocol-specific pre-defined salt may be utilised as a flag signalling the support of the current standard, which will help to avoid possible commitment collisions across different protocols.

Future SIGHASH\_NOINPUT standard BIP-118 \[12] may be compatible with this proposal, since a protocol utilizing the present standard may define that any transaction commitment with an input signature flag set to SIGHASH\_NOINPUT must default to the zero value of commitment-specific parameter `c`. This will still preserve the privacy from the onchain analysis tools due to the presence of the protocol-specific parameter `s`, which will be unknown for any party that does know which protocol is used by some transaction (given the fact that the used protocol can't be guessed from the transaction itself).

### Rationale

The rationale for the technical decisions is provided within the specification text.

### Reference implementation

<https://github.com/BP-WG/bp-core/blob/master/dbc/src>

### Acknowledgements

Authors would like to thank Giacomo Zucco and Alekos Filini for their initial work on the commitment schemes as a part of early RGB effort \[7].

### References

1. Maxim Orlovsky, et al. Key tweaking: collision-resistant elliptic curve-based commitments (LNPBP-1 Standard). <https://github.com/LNP-BP/lnpbps/blob/master/lnpbp-0001.md>
2. Maxim Orlovsky, et al. Deterministic embedding of elliptic curve-based commitments into transaction output scriptPubkey (LNPBP-2 standard). <https://github.com/LNP-BP/lnpbps/blob/master/lnpbp-0002.md>
3. Peter Todd. OpenTimestamps: Scalable, Trust-Minimized, Distributed Timestamping with Bitcoin. <https://petertodd.org/2016/opentimestamps-announcement>
4. Peter Todd. Setting the record straight on Proof-of-Publication. <https://petertodd.org/2014/setting-the-record-proof-of-publication>
5. Peter Todd. Preventing Consensus Fraud with Commitments and Single-Use-Seals. <https://petertodd.org/2016/commitments-and-single-use-seals>
6. Peter Todd. Scalable Semi-Trustless Asset Transfer via Single-Use-Seals and Proof-of-Publication. <https://petertodd.org/2017/scalable-single-use-seal-asset-transfer>
7. OpenSeals Framework <https://github.com/rgb-org/spec/blob/v1.0/01-OpenSeals.md>
8. Omni Protocol Specification (formerly Mastercoin). <https://github.com/OmniLayer/spec>
9. RGB Protocol Specification, version 0.4. <https://github.com/rgb-org/spec/blob/old-master/01-rgb.md>
10. Lexicographical Indexing of Transaction Inputs and Outputs (BIP-69 standard). <https://github.com/bitcoin/bips/blob/master/bip-0069.mediawiki>
11. Lightning Network BOLT-3 standard. <https://github.com/lightningnetwork/lightning-rfc/blob/v1.0/03-transactions.md>
12. Christian Decker. SIGHASH\_NOINPUT. <https://github.com/bitcoin/bips/blob/master/bip-0118.mediawiki>

### License

This document is licensed under the Creative Commons CC0 1.0 Universal license.

### Test vectors

TBD


# LNPBP-81: Tagged Merkle trees

```
LNPBP: 0081
Vertical: Cryptographic primitives
Title: Tagged merkle trees for client-side-validation
Author: Dr Maxim Orlovsky  <orlovsky@protonmail.ch>,
        Peter Todd
Comments-URI: https://github.com/LNP-BP/lnpbps/issues/<____>
Status: Draft
Type: Standards Track
Created: 2021-05-11
License: CC0-1.0
```

* [Abstract](#abstract)
* [Background](#background)
* [Motivation](#motivation)
* [Design](#design)
* [Specification](#specification)
* [Compatibility](#compatibility)
* [Rationale](#rationale)
* [Reference implementation](#reference-implementation)
* [Acknowledgements](#acknowledgements)
* [References](#references)
* [Copyright](#copyright)
* [Test vectors](#test-vectors)

### Abstract

### Background

### Motivation

Problems with modern merkle trees:

* Depth extension attack: no commitment to the tree depth

### Design

Based on bitcoin merklization with following modifications:

* Tagged hashing for source data
* Tagged hashing of each tree object
* Commitments to depth, width and height of the tree
* Custom placeholders for empty objects
* Restricting tree source to 2^16 elements (height is always <=16)

### Specification

Merkle node is represented by a single SHA256 hash over the following data,\
serialized as a byte stream without any separators:

* branch type (byte)
* tag (128-bit number)
* depth (byte)
* width (4 bytes, little-endian)
* child node 1 (32 bytes)
* child node 2 (32 bytes)

If one or both of the child nodes are absent, a constant consisting of 16 `0xFF`\
bytes is used.

The root is produced via `CommitmentId` procedure

### Compatibility

### Rationale

### Reference implementation

### Acknowledgements

### References

### Copyright

This document is licensed under the Creative Commons CC0 1.0 Universal license.

### Test vectors


# LNPBP-4: Multi-protocol

```
LNPBP: 0004
Vertical: Client-validated data (3)
Title: Multi-message commitment scheme with zero-knowledge provable unique properties
Author: Dr Maxim Orlovsky <orlovsky@protonmail.ch>
Comments-URI: https://github.com/LNP-BP/lnpbps/issues/8
Status: Proposal
Type: Standards Track
Created: 2019-10-28
Finalized: not yet
License: CC0-1.0
```

* [Abstract](#abstract)
* [Background and Motivation](#background-and-motivation)
* [Design](#design)
* [Specification](#specification)
  * [Commitment](#commitment)
  * [Partial reveal](#partial-reveal)
  * [Reveal with full disclosure](#reveal-with-full-disclosure)
  * [Per-message verification](#per-message-verification)
  * [Verification of the full disclosure](#verification-of-the-full-disclosure)
* [Compatibility](#compatibility)
* [Rationale](#rationale)
  * [Maximum buffer size restrictions](#maximum-buffer-size-restrictions)
* [Reference implementation](#reference-implementation)
* [Acknowledgements](#acknowledgements)
* [References](#references)
* [Copyright](#copyright)
* [Test vectors](#test-vectors)

### Abstract

The standard defines a way to commit to a multiple independent messages with a single digest such that the fact of each particular commitment, and a protocol under which the commitment is made may be proven without exposing the information about the other messages and used protocols.

### Background and Motivation

LNPBP-3 defines a standard for embedding cryptographic commitment into bitcoin transaction in a deterministic & provable way \[2]. The standard is based on LNPBP-1 public key tweaking procedure \[1], which prevents multiple commitments inside a tweak. However, this may result in two potential problems.

First, there could be two different protocols willing to put different commitments into a single transaction output; and only one of the protocols will succeed due to the LNPBP-2 & LNPBP-1 design.

Second, it is possible that some protocol may require committing to a number of messages within a single transaction and public key with the requirement that some dedicated information from these messages (like the message type) should be unique across the whole message set. For instance, this is required for state updates, where such updates separated into different blocks (messages) and should be kept private, such that a single party will know information about a single update and should not be disclosed any information about the rest. However, in such case, there should be a proof that the other state updates do not affect the state of the analyzed update, excluding state collisions. In such a setup, each state may be assigned a unique integer identifier (like cryptographic digest), and a special form of zero-knowledge proof should be utilized to proof the fact that all the states are different without exposing the actual state ids.

While both cases are impossible at the level of LNPBP-3 & LNPBP-1 standards, the current proposal defines a procedure for structuring multiple independent messages in a privacy-preserving (zero-knowledge) way, allowing that some properties of the committed messages may be proven in a zero-knowledge way, i.e. without revealing any information about the source messages or the properties themselves.

### Design

The protocol follows dea of Bloom filters \[5], which are already used for keeping confidentiality of the information requested from Bitcoin Core by SPV clients \[6].

Multiple commitments under different protocols are identified with a unique per-protocol 256-bit identifiers (like tagged hashes of protocol name and/or characteristic parameters) and serialized into 256-bit slots within `N * 32` byte buffer such as `N >> M`, where `M` is the number of the individual commitments. The rest of the slots is filled with random data deterministically generated from a single entropy source. The position `n` for a commitment with the identifier `id` is computed as `n = id mod N`, guaranteeing that no two commitments under the same protocol with a given `id` may be simultaneously present.

![LNPBP4 visualisation](/files/-Mchk2NOTUrLHyEd-h_q)

### Specification

#### Commitment

For a given set of `M` messages `msg1`..`msgM` under protocols with corresponding unique ids `id`..`idM` the commitment procedure runs as follows:

1. Pick 64 bits of entropy from uniform entropy source (like the same which is used for generating private keys). This entropy will be identified with `entropy_seed` hereinafter.
2. Pick a 16-bit number `N >> M`, for instance `N = M * 2` and allocate `32*N` byte buffer (such that the maximum buffer length MUST not exceed 2^21, i. e 2 MB).
3. For each of the messages:
   * create a corresponding cryptographic commitment `cI` according to the per-message protocol,
   * compute `n = idI mod N` (if the protocol identifier is a hash, it should be converted into unsigned integer of appropriate dimensionality using little- endian notation),
   * if the slot `n` is not used, serialize a `cI` hash into it using bitcoin-style hash serialization format; otherwise go to step 3 and generate a new `N' >> N`.
4. For each of the slots that remain empty (the slot number is represented by `j`):
   * compute SHA256-tagged hash of `seed_entropy || j`, where both values are serialized as little-endian byte strings (the total length of resulting byte string for hashing should be 272 bits). The tagged hash procedure must run according to BIP-340 \[4] using UTF-8 representation of `LNPBP4:entropy` string as the tag.
5. Compute commitment to the resulting buffer with LNPBP-1 \[1], LNPBP-2 \[2] or other protocol using `LNPBP4` as the protocol-specific tag.

#### Partial reveal

A party needing to reveal the proofs for the commitment to the message `msgA` under this scheme and conceal the rest of the messages and protocols participating in the commitment has to publish the following data:

1. A source of the message `msgA` and information about its protocol with id `idA`.
2. A full byte sequence of the buffer resulting from the step 5 of the [commitment procedure](#commitment).

#### Reveal with full disclosure

A party needing to reveal the proofs for all commitments to all the messages and prove that there were no other commitments made must publish the following data:

1. A source of the messages `msg1`..`msgM` and information about their protocols with id `id1`..`idM`.
2. A full byte sequence of the buffer resulting from the step 5 of the [commitment procedure](#commitment).
3. An entropy value `entropy_seed` from the step 2 of the [commitment procedure](#commitment).

#### Per-message verification

A party provided with the data from the [partial reveal procedure](#partial-reveal) and wishing to verify the commitment to the message MUST use the following procedure:

1. Compute `n = idA mod N`, where `idA` is the message-specific protocol id and `N` is the length of the commitment buffer in bytes divided on 32.
2. Compute commitment to the message by following the procedure from the step 3 of the [commitment scheme](#commitment)
3. Verify that the resulting 32-bit commitment is equal to the commitment stored in `n`'s 32-byte slot of the commitment buffer; fail verification otherwise.

#### Verification of the full disclosure

A party provided with the data from the [reveal with full disclosure procedure](#reveal-with-full-disclosure) may verify that the provided commitment buffer contains only commitment to the provided messages (and no other commitments) by allocating a new empty (all bytes set to `0x00`) commitment buffer of the same length as the revealed commitment buffer, and re-running steps 4-6 from the [commitment procedure](#commitment) . If the new buffer match per-byte the revealed commitment buffer, then the verification succeeded; otherwise it has failed.

### Compatibility

TBD

### Rationale

#### Maximum buffer size restrictions

The maximum buffer size defines the potential size of the data provided for client-side-validation, and may represent a form of DoS attack vector, when the party allocating/creating buffer defines a storage and network data transfer requirements for all the future verifying parties. From the other side, the maximum buffer size defines the upper bound for the maximum number of commitments that may be embedded within a single transaction output. We have selected a 16-bit limit for the number of slots, limiting the maximum buffer size to 2 MBs, and maximum theoretical number of simultaneous commitments under the same transaction output to 2^16. However, in practice, the latter limit will never be reached, because assuming the uniform distribution of protocol-specific identifier hashes a committing party will be able to produce simultaneous commitment under `1^8` different protocols in average.

### Reference implementation

Reference implementation can be found inside client-side-validation foundation rust library <<https://github.com/LNP-BP/client\\_side\\_validation/blob/master> /commit\_verify/src/multi\_commit.rs> and represents integral part of this standard.

### Acknowledgements

### References

1. Maxim Orlovsky, et al. Key tweaking: collision-resistant elliptic curve-based commitments (LNPBP-1 Standard). <https://github.com/LNP-BP/lnpbps/blob/master/lnpbp-0001.md>
2. Maxim Orlovsky, et al. Deterministic embedding of LNPBP1-type commitments into `scriptPubkey` of a transaction output (LNPBP-2 Standard). <https://github.com/LNP-BP/lnpbps/blob/master/lnpbp-0002.md>
3. Giacomo Zucco, et al. Deterministic definition of transaction output containing cryptographic commitment (LNPBP-3 Standard). <https://github.com/LNP-BP/lnpbps/blob/master/lnpbp-0003.md>
4. Pieter Wuille, et al. BIP-340: Schnorr Signatures for secp256k1. <https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki>
5. Bloom, Burton H. (1970), "Space/Time Trade-offs in Hash Coding with Allowable Errors", Communications of the ACM, 13 (7): 422–426, doi:10. 1145/362686.362692. <https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.641.9096>
6. Mike Hearn, Matt Corallo. BIP-37: Connection Bloom filtering. <https://github.com/bitcoin/bips/blob/master/bip-0037.mediawiki>

### Copyright

This document is licensed under the Creative Commons CC0 1.0 Universal license.

### Test vectors

TBD


# LNPBP-6: PayTweak

```
LNPBP: 0006
Vertical: Bitcoin protocol
Title: Deterministic bitcoin commitments
Author: Dr Maxim Orlovsky <orlovsky@lnp-bp.org>
Comments-URI: https://github.com/LNP-BP/lnpbps/pulls/116
Status: Rejected
Type: Standards Track
Created: 2021-11-15
Finalized: not yet
License: CC0-1.0
Related standards: LNPBP-1, 2, 4, 7, 9, 92
```

### Abstract

The proposal provides standard mechanism for creating, structuring & verifying deterministic bitcoin commitments ("anchoring") to multiple extra-transaction data (client-side-validated etc).

### Background

### Motivation

### Design

Miltiple protocols may commit to external (non-transaction and non-blockchain) data by constructing a special data structure called *anchor* and committing to its content inside transaction input or output.

### Specification

#### Commitment procedure

A party needing to commit to multiple data coming from distinct protocols MUST follow the algorithm:

1. Construct LNPBP-4 multi-message commitment;
2. Deterministically define transaction input or output which will contain the final commitment. This algorithm is not a part of the current specification and must be defined at upper protocol level (see for instance LNPBP-10).
3. Run commitment embedding procedure:
   * If commitment will be placed into transaction output, construct *extra-transaction proof* using procedure from LNPBP-2; fail algorithm if the LNPBP-2 requirements can't be fulfilled.
   * If commitment will be placed into transaction input, construct *extra-transaction proof* using procedure from LNPBP-92; fail algorithm if the LNPBP-92 requirements can't be fulfilled.
4. Construct *anchor* data structure (see below), encode it and persist the data as long as it will be required to provide proofs of the commitment.

If algorithm failed the party creating commitment MAY change the structure of the transaction and try to repeat the commitment procedure.

#### Verification procedure

The verification process runs by repeating steps of the commitment protocol using the information provided during the *reveal phase* and verifying the result is equal to the provided proofs. If the commitment procedure fails at any of the steps, the verification procedure MUST also fail.

#### Anchor structure and serialization

Anchor consists of the following fields, serialized according to the strict serialization rules (see LNPBP-7):

1. `txid`: 32-byte transaction id
2. `commitment`: a commutment block structure from LNPBP-4
3. `proof`: a deterministic commitment proof which has the same structure for both LNPBP-2 and LNPBP-92 commitment:
   1. `original_pubkey`: original 33-byte value of the pubkey before tweak; for pay-to-signature (LNPBP-92) tweaks this is `R` value generated from a nonce. BIP-340 keys MUST be encoded as 33 byte value having first byte `0x02`.
   2. `script_info`: an enum, encoded with a first byte representing enum variant
      * `0x00 = SinglePubkey`: always used by LNPBP-92 and by LNPBP-2 commitments based on P2PK, P2PKH, P2WPKH, legacy SegWit v0 P2WPKH-in-P2SH, P2TR with key spending only (self-tweaked), OP\_RETURN and other bare script outputs.
      * `0x01 = LockScript`: a Bitcoin script source which knowledge is required to satisfy spending for pre-SegWit P2SH, native SegWit v0 P2WSH. The enum variant byte MUST be followed by a strict-encoded representation of binary script data. This script MUST match `redeemScript` for P2SH and `witnessScript` for P2WSH.
      * `0x02 = WrappedWitnessScript`: Bitcoin script source which knowledge is required to satisfy spending for legacy (P2SH-wrapped) SegWit v0, P2WSH-in-P2SH outputs (and, potentially, fututre SegWit versions). The enum variant byte MUST be followed by a strict-encoded representation of binary script data. This script MUST match `witnessScript` for P2WSH; for P2SH wrapped version it also must be a `witnessScript` and not `redeemScript`.
      * `0x03 = TaprootScript`: a Merkle root of the script spending path of the taproot output or a value of a tweak applied to the internal taproot key if and only if this tweak is not a self-tweak. Must be followed by exactly 32 bytes (without length prefix) of the tweak data in little endinan order.

The list of `script_info` variants is non-exhaustive. If a future version of script info variant byte is met the deserialization of anchor data MUST fail with explicit error and the anchor MUST not be verified.

If the anchor data does not match the provided script pubkey (for instance, being encoded as P2WSH-in-P2SH instead of P2WSH) the verifying party MUST fail verification even if other option is satisfied with other (non-specified) encoding.

#### Concealment of the anchor data

Anchor data contain extra information which is not required for the DBC validation and represents additional proofs for non-DBC validation procedures. This information is contained in `commitment` field of the *anchor* data structure containing LNPBP-4 multi-message commitment entrypy value, used for proving the absence of some specific protocol within the commitment tree. This information MAY be discarded for privacy reasons when the *anchor* data are passed to a third-party with a special *conceal* procedure as described in LNPBP-4 and LNPBP-9 standards.

### Compatibility

### Rationale

#### Why not to use `0x03` variant for keeping key spend path-only Taproot info

Using `0x03` variant (`TaprootScript`) for Taproot outputs having no script path spending conditions (i.e. self-tweaked keys) instead of `0x00` (`SinglePubkey`) will result in storing additional 32 bytes on the client side per each output of this type, while providing no privacy gains: a user hacing access to the anchor data can always make sure that the value of the script tweak is equal to the self-tweak and still acquire knowledge that the output does not contain a script path spending condition.

#### Why not to use single `0x01` variant for all types of scripts

P2WSH-in-P2SH require its own script info variant (`0x02`, `WrappedWitnessScript`) since this allows to simplify verification algorithm by avoiding trying multiple script encodings (native P2SH and legacy P2WSH-in-P2SH). This does not reduce forward compatibility: we may have 252 more variants for script info value, which is exceeds a possible number of future bitcoin script pubkey encoding (15 possible future witness values).

### Reference implementation

The reference implementation is version `1.0` of [`bp-dbc` crate](https://github.com/LNP-BP/LNPBPs/blob/master/bp-dbc/README.md), which is a part of the [BP Core Library](https://github.com/LNP-BP/LNPBPs/blob/master/bp-core/README.md) developed and maintained by LNP/BP Strandards Association.

If the implementation differs from the spec, the spec has a higher priority.

### Acknowledgements

### References

### Copyright

This document is licensed under the Creative Commons CC0 1.0 Universal license.

### Test vectors


# LNPBP-12: TapRet

```
LNPBP: 0012
Vertical: Bitcoin protocol
Title: Tapret: taproot-based OP_RETURN deterministic bitcoin commitments
Author: Dr Maxim Orlovsky <orlovsky@lnp-bp.org>,
        Peter Todd
Comments-URI: https://github.com/LNP-BP/discussions
Status: Draft
Type: Standards Track
Created: 2022-04-01
Finalized: not yet
License: CC0-1.0
Related standards: LNPBP-4, BIP-341
```

* [Abstract](#abstract)
* [Background](#background)
* [Motivation](#motivation)
* [Design](#design)
* [Specification](#specification)
* [Compatibility](#compatibility)
* [Rationale](#rationale)
* [Reference implementation](#reference-implementation)
* [Acknowledgements](#acknowledgements)
* [References](#references)
* [Copyright](#copyright)
* [Test vectors](#test-vectors)

### Abstract

The proposal provides standard mechanism for creating, structuring & verifying deterministic bitcoin commitments, which puts the commitment in a leaf tapscript with `OP_RETURN` opcode in the taproot script tree.

### Background

TBD

### Motivation

TBD

### Design

Tapret commitment is structured as an `OP_RETURN`-based script, containing the commitment to the LNPBP-4 message, constructed under multiple protocols. The commitment script (**tapret leaf script**) always consists of [64 bytes](#why-64-byte-tapscript).

The leaf with the tapret leaf script is always put into the same depth of the taproot script tree, and this [depth is 1](#why-script-depth-1) (in 0-based indexing of depth levels, where depth 0 corresponds to the merkle tree root). The commitment is always put into the rightmost node of the tree by using consensus ordering of the nodes, as it is defined in BIP-341 merkle path construction (lexicographic ordering). This precise definition of the possible place of the commitment allows to prove the uniqueness of the commitment, i.e. the absence of any alternative tapret commitment in the same tree.

If at depth 7 in the rightmost position of the tree another taproot node is present (either leaf script or branch), an additional branch node is created with both tapret leaf script and the parent of the rightmost depth-7 node becoming its children. This new branch node is added instead of the original parent at depth 6, efficiently shifting the previous subtree from that position one level down.

If the original taproot script tree does not have depth 7 nodes on its right-side (in terms of consensus lexicographic ordering of each branch child hashes), a subtree (**tapret subtree**) consisting of repeated tapret script leaves is created and inserted at the depth of the last node of the tree on the right-side merkle path. The height of the subtree is selected to put the taproot script leaves at depth 7.

Since addition of the new node will change the merkle hashes of all its parents, and the merkle hash value is used in the lexicographic ordering of the tree, this operation with `1 - 1/(2 ^ 7) = 99.22%` probability will make just inserted tapret subtree merkle root to be non-rightmost node of the modified tree. Since the deterministic nature of the tapret commitments requires ability to prove the absence of any alternative commitment in the same tree, two components are used to keep the determinism of the commitment position and ability to prove its uniqueness.

First, a special one-byte variable (nonce) is added to the taproot leaf script, which allows "mining" the hash value in a way that the added subtree will appear at the right-side of the tree. At depth 7 there might be only 2^7=128 possible tree position, and 256 iterations (per one nonce value) should be enough to solve the issue.

Second, if it was not possible to solve the issue with the nonce, a special **uniqueness proof** is produced, which ensures that none of the nodes at depth 7 on the right side of the tree does not contain alternative commitment. This proof includes leaf script (for leaf nodes) or two child node hashes (for branch nodes) for each of the nodes right to the tapret leaf script.

The tapret commitment is put into a transaction output `scriptPubkey` as a modified BIP-341 output key value, which is produced from the same internal key and new merkle root of the taproot script tree containing the embedded tapret commitment. The number of the transaction output with the commitment, if multiple taproot outputs are present in the same transaction, must be deterministically defined by an upper-level protocol using the present tapret commitment scheme.

Internal key value, merkle proof and uniqueness proof are combined to construct **tapret proof**, passed to the validators as off-chain data for client-side validation.

### Specification

#### Tapret proof

Tapret proof must consist of the following data, serialized exactly in the given order:

1. 32 bytes: internal key value, representing x-only public key serialized according to BIP-341;
2. 1 byte: **nonce value** used in constructing tapret script;
3. 1 byte: number `n` of merkle proof elements (see below), must be in range `0..=7`, otherwise the proof must be considered invalid;
4. `n*32` bytes: sequence of **merkle proof** elements, ordered by their depth in the tree. Each of the elements consists of 32 bytes representing hash of the taproot script tree hashing partner;
5. 1 byte: number `u` of uniqueness proof elements (see below), must be less or equal to `2^(n+1) - 2`, otherwise the proof must be considered invalid;
6. sequence of `m` **uniqueness proofs**, each consisting of: 6.1. 1 byte: proof type, either `0x00`, `0x01` or `0x02`. The proof type defines length of the proof data and their semantic meaning: 6.1. the proof type `0x00` (called `empty`) means that node is absent at the depth 7. The proof type is followed by one byte indicating the depth of the last script leaf present in the tree, followed by the structure described in pt. 6.3. below; 6.2. for the proof type `0x01` (called `branch`) two 32-byte hash values are given; these hash values represents hashes of taproot script tree nodes; 6.3. for the proof type `0x02` (called `leaf`) a following structure is used: 6.3.1. 1 byte containing script leaf version, 6.3.2. 2 bytes containing script length `l` in little endian encoding, 6.3.3. `l` bytes of raw leaf script data.

#### Tapret verification

First, a **tapret script leaf** is constructed. The version of the script must be `0xC0` (tapscript) and the script must be equal to the byte sequence (in hex) `FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF01<nonce>6A20` followed by a 32-byte serialization of LNPBP-4 multiprotocol commitment. The provided byte sequence represent tapscript consisting of 28 `OP_INVALIDOPCODE`, followed by `OP_PUSHBYTES_1`, nonce byte (taken from tapret proof), `OP_RETURN` and `OP_PUSHBYTES_32` op-codes\[^why-64-bytes].

Then, **tapret subtree** is constructed from the *tapret script leaves*. The tree should be a valid taproot script tree under BIP-341 standard, consisting of `8-n` depth levels, where at depth = 7 (for zero-based depth indexing, representing merkle root level) the subtree must contain `2^(7-n)` *tapret script leaves*. For the edge case of `n=7` the subtree must consist of a single *tapret script leaf* which `TapLeaf`-tagged hash will be the hash of the subtree merkle root.

The merkle root hash of the *tapret subtree* is used together with the provided node hash partner values from the perkle proof data of the tapret proof to receive the final merkle tree root value. Combined with the value of the internal key from the tapret proof according to BIP-341 algorithm it must produce exactly the same output key value as present in the `scriptPubkey` of the transaction output containing the commitment; otherwise validation procedure fails.

Finally, the validity of the uniqueness proof must be checked. The uniqueness proof data are used to reconstruct each and all the right-side merkle tree hashing partners, which must match the exact number and values of the hasing partners from the merkle proof, which values were grater than the value of the parent of the tapret leaf script at that depth. If this procedure fails, the validation procedure must fail.

#### Tapret construction

TBD

### Compatibility

TBD

### Reference implementation

<https://github.com/BP-WG/bp-core/blob/master/dbc/src/tapret>

### Rationale

#### Tapret proof size estimation

Due to the use of nonce "mining" mechanism, in the most of cases the proof size should not exceed 290 bytes. Since the most of the taproot script trees will not have a depth more than 1 or 2, the actual size in these cases will be 66 or 98 bytes.

#### Why 64 byte tapscript

This allows distinguishing of tapret leaf script from a data used in production of taproot branch hash, such that the proof of the absence of an alternative tapret commitment can be validated by simple comparison of the first of the child node hashes to the tapret leaf script prefix.

#### Why script depth 1

This helps to keep client-side-validated proof size smaller.

### Acknowledgements

TBD

### References

TBD

### Copyright

This document is licensed under the Creative Commons CC0 1.0 Universal license.

### Test vectors

TBD


# LNPBP-8: Single-use-seals

```
LNPBP: 0008
Vertical: Cryptographic primitives
Title: Single-use-seals
Author: Peter Todd
Comments-URI: https://github.com/LNP-BP/lnpbps/issues/117
Status: Proposal
Type: Standards Track
Created: 2017-12-05
Finalized: 2021-11-16
Based on: https://petertodd.org/2017/scalable-single-use-seal-asset-transfer
License: CC0-1.0
```

* [Abstract](#abstract)
* [Background](#background)
* [Motivation](#motivation)
* [Design](#design)
* [Specification](#specification)
* [Trust](#trust)
* [Reference implementation](#reference-implementation)
* [References](#references)
* [Copyright](#copyright)

### Abstract

A single-use-seal is an abstract mechanism to prevent double-spends. The current proposal defines core single-use-seal terminology and procedures which must be supported and implemented according to this guidelines by any specific single-use-seal implementation.

### Background

Concept of single-use-seal was developed as a result of research work on cryptographic commitments, consensus protocols in distributed systems and client-side-validation \[1, 2, 3, 4].

### Motivation

Existing cryptographic commitment primitives does not allow to create "two-level" commitments, whether at initial stage a commiter commits to commit to a certain (potentially yet unknown) message in the future, once and only once. Given a trustless way of performing verification of such commitments the primitive may be a basic building block for creating decentralized, private and censorship-resistant state machines and smart contracting systems which will be protected from "double-spend" attacks.

### Design

Analogous to the real-world, physical, single-use-seals used to secure shipping containers, a single-use-seal primitive is a unique object that can be closed over a message exactly once. In short, a single-use-seal is an abstract mechanism to prevent double-spends.

### Specification

For a given data structure $l$ providing *single-use-seal definition* and a *messag*e $m$ single-use-seal implementation MUST support two fundamental operations:

* *Close seal* $l$ over *message* $m$, producing a *witness* $w\_l$:

  `Close(`$l$,$m$`)`→$w\_l$
* *Verify* that the *seal* $l$ was closed over *message* $m$:

  `Verify(`$l$,$w\_l$,$m$`)`→`bool`

A single-use-seal implementation is secure if it is impossible for an attacker to cause the `Verify` function to return true for two distinct messages $m1$, $m2$, when applied to the same seal (it is acceptable, although non-ideal, for there to exist multiple witnesses for the same seal/message pair).

Practical single-use-seal implementations will also obviously require some way of generating new single-use-seals. Secondly, authentication is generally useful. Thus we have:

* *Generate* a new seal bound to pubkey p:

  `Gen(`$p$`)`→$l$
* *Close seal* $l$ over *message* $m$, authenticated by signature $s$ valid for pubkey $p$:

  `Close(`$l$,$m$,$s$`)`→$w\_l$

  Obviously, in the above, pubkey can be replaced by any cryptographic identity scheme, such as a Bitcoin-style predicate script, zero-knowledge proof, etc.
* Finally, while some single-use-seal implementations MAY support the ability to prove that a seal is open, e.g. as of a given block height or point in time. This however is optional, and as it can be difficult to implement, it is suggested that seal-using protocols SHOULD avoid depending on this functionality existing.

### Trust

An obvious single-use-seal implementation is to simply have a trusted notary, with each seal committing to that notary’s identity, and witnesses being cryptographic signatures produced by that notary. A further obvious refinement is to use disposable keys, with a unique private key being generated by the notary for each seal, and the private key being securely destroyed when the seal is closed.

For a scalable, trust-minimized, single-use-seal implementation we can use a proof-of-publication ledger, where consensus over the state of the ledger is achieved in a trust-minimized manner (i.e. Bitcoin blockchain).

### Reference implementation

The reference implementation is version `1.0` of [`single_use_seals` crate](https://github.com/LNP-BP/LNPBPs/blob/master/single_use_seals/README.md), which is a part of the [client-side-validation library](https://github.com/LNP-BP/LNPBPs/blob/master/client_side_validation/README.md) developed and maintained Dr Maxim Orlovsky at LNP/BP Strandards Association.

If the implementation differs from the spec, the spec has a higher priority.

### References

1. Peter Todd. Preventing Consensus Fraud with Commitments and Single-Use-Seals <https://petertodd.org/2016/commitments-and-single-use-seals>
2. Peter Todd. Scalable Semi-Trustless Asset Transfer via Single-Use-Seals and Proof-of-Publication. <https://petertodd.org/2017/scalable-single-use-seal-asset-transfer>
3. Peter Todd. Closed Seal Sets and Truth Lists for Better Privacy and Censorship Resistance. <https://petertodd.org/2016/closed-seal-sets-and-truth-lists-for-privacy>
4. Peter Todd. Building Blocks of the State Machine Approach to Consensus. <https://petertodd.org/2016/state-machine-consensus-building-blocks>

### Copyright

This document is licensed under the Creative Commons CC0 1.0 Universal license.


# LNPBP-10: TxO seals

```
LNPBP: 0010
Vertical: Bitcoin protocol
Title: Bitcoin transaction output-based single-use-seals
Authors: Dr Maxim Orlovsky <orlovsky@pandoracore.com>,
         Peter Todd <pete@petertodd.org>,
         Federico Tenga, 
         Giacomo Zucco
Comments-URI:
Status: Proposal
Type: Standards Track
Created: 2019-05-12
License: CC0-1.0
```

* [Abstract](#abstract)
* [Background](#background)
* [Motivation](#motivation)
* [Design](#design)
* [Specification](#specification)
  * [Terms and definitions](#terms-and-definitions)
  * [Seal definition](#seal-definition)
  * [Closing seal over a message](#closing-seal-over-a-message)
  * [Verification](#verification)
  * [Single-use-seal concealment](#single-use-seal-concealment)
  * [Strict encoding](#strict-encoding)
* [Privacy considerations](#privacy-considerations)
  * [UTXO and TxO ownership](#utxo-and-txo-ownership)
  * [Chain analysis](#chain-analysis)
  * [Private data](#private-data)
* [Compatibility](#compatibility)
  * [Version 1 transactions](#version-1-transactions)
  * [Pre-segwit outputs](#pre-segwit-outputs)
  * [Segregated witness v0](#segregated-witness-v0)
  * [Taproot](#taproot)
  * [Future segregated witness variants](#future-segregated-witness-variants)
  * [Bitcoin sidechains](#bitcoin-sidechains)
  * [Pay-to-address](#pay-to-address)
  * [Hardware wallets](#hardware-wallets)
  * [Software wallets](#software-wallets)
* [Rationale](#rationale)
  * [Representation of transaction output numbers](#representation-of-transaction-output-numbers)
* [Reference implementation](#reference-implementation)
* [Acknowledgements](#acknowledgements)
* [References](#references)
* [Copyright](#copyright)
* [Test vectors](#test-vectors)

## Abstract

The proposal standardises single-use-seal-based cryptographic commitment scheme utilizing bitcoin blockchain and bitcoin transaction graph as a proof-of-publication medium, using bitcoin transaction outputs as seal definitions and spending bitcoin transactions as proofs of seal close and containers for a commitment to a message over which the seal is closed. The verification procedure requires storing part of the single-use-seal witness data on the client side (*extra-transaction proof*).

## Background

Single-use-seal is a cryptographic commitment primitive originally proposed by Peter Todd in 2016 and standardized as LNPBP-8 standard. However, Here we define a specific commitment scheme based on that standard using bitcoin transactions.

## Motivation

## Design

Bitcoin transaction output-based single-use-seals (TxOSUS) is a particular application of [single-use-seals](/commitment-schemes/lnpbp-0006) to bitcoin transaction graph, either as a part of any bitcoin blockchain (longest PoW chain, federated sidechain etc) or state channel (Lightning network channel and other types of state channels), i.e. in terms of single-use-seals, seal medium is represented by a bitcoin transaction graph.

The parties running protocol agree on some transaction output in any given bitcoin transaction graph as a place with special meaning ("seal"), and require that a future transaction spending this output ("witness transaction") contained a [deterministic bitcoin commitment](/commitment-schemes/lnpbp-0008) to some a message. Any independent party having access to the transaction graph MUST:

1. not be able to detect the presence of the commitment in a given transaction graph (*hiding* property of TxOSUS) even if the original message is known,
2. being provided information about specific protocol used for message commitments and access to deterministic bitcoin proof data (see [LNPBP-8](/commitment-schemes/lnpbp-0008)) be able to verify the commitment such as it will be valid only and only for the message with which the original commitment was created (*verifiably* property of TxOSUS).

The defined procedure is not the only way in which bitcoin blockchain or transaction graph can be used as a seal medium for single-use seals (for instance, a seal may be defined as a first time some specific public key appears in the blockchain); however these options are not part of the current standard.

## Specification

### Terms and definitions

**Seal** or **defined seal**: Bitcoin transaction outpoint: a combination of transaction identifier (consensus-defined double SHA256 hash of fully-signed valid bitcoin transaction) and transaction output number. Transaction output number MUST be represented as a 32-bit unsigned integer[1](https://github.com/LNP-BP/LNPBPs/blob/master/lnpbp-0039.md#Representation-of-transaction-output-numbers).

**Witness transaction**: transaction spending an output specified by a given seal.

**Closed seal**: a seal for which a transaction spending output matching seal definition is known. This transaction MAY be part of longest block chain, or MAY not be a part of it (existing only within a Lightning network channel or as a part of any other off-chain transaction graph). It's up to particular implementation to decide whether such transaction (named **witness transaction**) should be considered valid or not; however this rules MUST require that the witness transaction MUST be a valid bitcoin transaction (i.e. it can be validated with libbitcoinconsensus or Bitcoin Core instance).

### Seal definition

Defined seal consists of 256-bit consensus-defined double SHA-256 hash of a fully-signed valid bitcoin transaction and 32-bit transaction output index.

Seal MUST be considered defined only and only all of transaction data are known, the transaction is fully signed and both transaction structure and signatures validated with bitcoin consensus rules using libbitcoinconsensus or Bitcoin Core.

NP: Parties participating the protocol MUST agree on an implementatio-specific entropy used in deterministic bitcoin commiemtnes as required by [LNPBP-8](/commitment-schemes/lnpbp-0008) and [LNPBP-3](/commitment-schemes/lnpbp-0003) protocols.

### Closing seal over a message

1. Fully sign the transaction containing output acting as a defined seal.
2. Construct a transaction spending the transaction output defined by the seal. The transaction may have any number
3. Create a commitment to the message and embed it into the unsigned witness transaction with the deterministic bitcoin commitment embed procedure as defined in [LNPBP-8](/commitment-schemes/lnpbp-0008), store the proof.
4. Fully sign the witness transaction.

NB: Transactions and proof MUST be persisted for further verification procedure.

### Verification

A party verifying that the seal is indeed closed over a message MUST run the following procedure:

1. Make sure that the seal definition is fully known, otherwise fail the verification.
2. Verify transaction containing the defined seal:

* the transaction MUST be a valid bitcoin transaction;
* the transaction MUST contain all transaction data required for it's verification;
* bitcoin-defined consensus transaction identifier MUST correspond to the transaction identifier provided as a part of seal definition;
* transaction output number contained in the seal definition MUST be present in transaction (i.e. transaction MUST contain exactly that numbers or more of trsansaciton outputs);
* the transaction MUST be fully-signed for all of its inputs;
* the transaction MUST signatures pass validation with bitcoin consensus rules using libbitcoinconsensus or Bitcoin Core. If any of these conditions are not met, fail the verification.

3. Verify the witness transaction spending the transaction output defined as the seal subjected to the current verification procedure:

* the transaction MUST be a valid bitcoin transaction;
* the transaction MUST contain all transaction data required for it's verification;
* the transaction MUST spend transaction output defined as the seal verified by the current procedure;
* bitcoin-defined consensus transaction identifier MUST correspond to the transaction identifier provided as a part of seal definition;
* transaction output number contained in the seal definition MUST be present in transaction (i.e. transaction MUST contain exactly that numbers or more of trsansaciton outputs);
* the transaction MUST be fully-signed for all of its inputs;
* the transaction MUST signatures pass validation with bitcoin consensus rules using libbitcoinconsensus or Bitcoin Core. If any of these conditions are not met, fail the verification.

4. Verify the deterministic bitcoin commitment to the given message with the provided deterministic bitcoin commitment proof according to the [LNPBP-8](/commitment-schemes/lnpbp-0008) procedure; fail the verification if this procedure fails.

### Single-use-seal concealment

### Strict encoding

Any implementation of the standard MUST follow [strict encoding](https://github.com/LNP-BP/LNPBPs/blob/master/lnpbp-0007.md) rules, in particular

Defined seal MUST be serialized as fixed-length 36 byte-long structure:

* 32 bytes of transaction identifier encoded according to bitcoin transaction identifier consensus serialization rules in little-endian format
* 4 bytes of transaction output in little-endian format

Deterministic bitcoin commitment proofs MUST be serialized using strict encoding rules defined in \[...].

There are no specific requirements to the message encoding or content; they MAY be defined as a part of other protocols using the current standard.

Bitcoin transactions and their parts, when needed, MUST be serialized according to bitcoin consensus serialization rules (which MAY differ from strict encoding requirements).

## Privacy considerations

### UTXO and TxO ownership

### Chain analysis

### Private data

## Compatibility

### Version 1 transactions

### Pre-segwit outputs

### Segregated witness v0

### Taproot

### Future segregated witness variants

### Bitcoin sidechains

### Pay-to-address

### Hardware wallets

### Software wallets

## Rationale

### Representation of transaction output numbers

While bitcoin normally uses VarInt to represent the number of transaction outputs that may be contained in a given transaction, it uses 32-bit unsigned integers to reference specific transaction output from other's transaction input. Even while with the current current block size limit the maximum number of transaction outputs that may be contained within a transaction is still below 2^16, we stick to the internal bitcoin transaction limits, which, in this case, is defined by transaction input structure (it's impossible to spend transaction output with index number >2^32).

## Reference implementation

<https://github.com/LNP-BP/rust-lnpbp/tree/develop/src/bp/seals>

## Acknowledgements

## References

## Copyright

This document is licensed under the Creative Commons CC0 1.0 Universal license.

## Test vectors


# LNPBP-5: Short tx ids

```
LNPBP: 0005
Vertical: Bitcoin protocol
Title: Universal short Bitcoin identifiers for blocks, transactions and
       transaction inputs & outputs
Author: Dr Christian Decker <decker.christian@gmail.com>,
        Dr Maxim Orlovsky <orlovsky@protonmail.ch>
Comments-URI: https://github.com/LNP-BP/lnpbps/issues/<____>
Status: Proposal
Type: Standards Track
Created: 2020-02-17
License: CC0-1.0
```

* [Abstract](#abstract)
* [Background](#background)
* [Motivation](#motivation)
* [Specification](#specification)
  * [Bitwise structure of the identifier](#bitwise-structure-of-the-identifier)
  * [Distinguishing different types of identifier](#distinguishing-different-types-of-identifier)
* [Compatibility](#compatibility)
* [Rationale](#rationale)
  * [Estimating ranges for bit-based values](#estimating-ranges-for-bit-based-values)
* [Reference implementation](#reference-implementation)
* [Acknowledgements](#acknowledgements)
* [References](#references)
* [Copyright](#copyright)
* [Test vectors](#test-vectors)

### Abstract

The work introduces short 64-bit identifiers able to uniquely distinguish bitcoin blocks, transactions, transaction inputs and outputs for both on-chain transactions and off-chain transactions, representing sufficient collision resistance for the common tasks of blockchain and transaction data indexing, search and compact archive storage. This format may be useful for different Layer 2 and 3 applications, as well as user-based clients and indexing services.

### Background

Bitcoin transactions are normally identified by 256-bit integers, representing double SHA256 hashes of the conservative transaction data serialized according to the original Satoshi Bitcoin client code \[1] and SegWit BIP-141 specification \[2]. These identifiers are unique: two distinct transactions has probability of \~2^256 that their identifiers would collide. While such security is undoubtedly required to maintain global identifiers for all possible transactions, for the transactions already included in Bitcoin blockchain it may be unnecessary for multiple cases. The main drawback of using 256-bit integers is inconveniences for normal computing tasks: modern CPUs and databases can easily handle up to 64-bit integers, but not 256-bit. This introduces unnecessary load for indexing and search tasks; increases storage requirements and network traffic.

Lightning network protocol (LNP) has introduced the use of short channel identifiers \[3], a 64-bit integers composed of the channel funding transaction data:

* block height (occupying the most significant 3 bytes)
* transaction index within the block (the next 3 bytes)
* output index funding the channel (least significant 2 bytes)

The introduction of this data structure was reasonable, since Lightning network operates only channels funded with transactions secure from deep re-orgs, thus introduction of blockchain-based identifiers was safe.

Here we propose more generic scheme, that follows the design ideas from LNP extending the concept of short identifiers beyond addressing transaction outputs only.

### Motivation

Normally, references to blockchain blocks, transactions, their inputs and outputs occupy 32 - or up to 37 bytes (in case of inputs/outputs). For the existing set of transactions residing in blockchain just listing all existing data will require gigabytes of storage space. Many user applications and services, However, require cross-referencing and indexing - like `JOIN` SQL queries connecting different tables (like transactions, outputs and inputs) with primary/foreign keys, where the keys are 32-byte values. This is both extremely inefficient in terms of performance and index storage space. While it may be a normal practice to use incremental 32-bit indexing, the full identifiers still should be kept, and two different databases created by the same software after some re-orgs will not match by their indexes.

Thus, we are proposing a format for 64-bit identifiers, that are both collision- and reorg-resistant (with \~1/256 probability) and can be used for an efficient indexing, primary/foreign key values and referencing.

### Specification

#### Bitwise structure of the identifier

The identifier is a 64-bit number, where value of the most significant bit defines format for the rest of the bits. This first bit represents a flag distinguishing on-chain and off-chain transactions and items. If the flag is set to 0, the bits MUST have the following meaning:

```
_ _ _ _  _ _ _ _   _ _ _ _  _ _ _ _   _ _ _ _  _ _ _ _   _ _ _ _  _ _ _ _   _ _ _ _  _ _ _ _   _ _ _ _  _ _ _ _   _ _ _ _  _ _ _ _   _ _ _ _  _ _ _ _
^ ^                                                  ^   ^              ^   ^                                 ^   ^ ^                               ^
| |                                                  |   |              |   |                                 |   | |                               |
| +--------------------------------------------------+   +--------------+   +---------------------------------+   | +-------------------------------+
|                 Block height, 23 bits                 BlockHash checksum   Transaction position in the block    |     TxIn/TxOut index, 15 bits
Off-chain flag, set to 0                                      8 bits                     16 bits                  TxIn/TxOut flag
```

| Bits\* | No bits | Possible no of values | Meaning                                                                                                                                  |
| -----: | ------: | --------------------: | ---------------------------------------------------------------------------------------------------------------------------------------- |
|      0 |       1 |                     2 | Flag indicating the structure for the rest of bits; MUST be set to 0 for the provided case                                               |
|   1-23 |      23 |             8'388'608 | Block height; sufficient to cover >160 years of blockchain history                                                                       |
|  24-31 |       8 |                   256 | Checksum for block hash value: binary XOR of it's 8 bytes                                                                                |
|  32-47 |      16 |                65'536 | Transaction position in the block; with 1 MB block size limit sufficient to cover all transactions even if their average size is 15 only |
|     48 |       1 |                     2 | Flag indicating whether the next 15 bits represents transaction input (0) or output (1) index                                            |
|  49-63 |      15 |                32'768 | Transaction input or output index (starting from 1)                                                                                      |

* In "most significant bit goes first" order

If the most significant bit of the short identifier is set to 1, the bits MUST have the following meaning:

```
_ _ _ _  _ _ _ _   _ _ _ _  _ _ _ _   _ _ _ _  _ _ _ _   _ _ _ _  _ _ _ _   _ _ _ _  _ _ _ _   _ _ _ _  _ _ _ _   _ _ _ _  _ _ _ _   _ _ _ _  _ _ _ _
^ ^                                                                                                           ^   ^ ^                               ^
| |                                                                                                           |   | |                               |
| +-----------------------------------------------------------------------------------------------------------+   | +-------------------------------+
|                                          Highest 47 bits from transaction id                                    |     TxIn/TxOut index, 15 bits
Off-chain flag, set to 1                                                                                          TxIn/TxOut flag
```

| Bits\* | No bits |       Possible no of values | Meaning                                                                                       |
| -----: | ------: | --------------------------: | --------------------------------------------------------------------------------------------- |
|      0 |       1 |                           2 | Flag indicating the structure for the rest of bits; MUST be set to 1 for the provided case    |
|   1-47 |      47 | >140 trillions (1.4\*10^14) | Highest 47 bits from transaction id                                                           |
|     48 |       1 |                           2 | Flag indicating whether the next 15 bits represents transaction input (0) or output (1) index |
|  49-63 |      15 |                      32'768 | Transaction input or output index (starting from 1)                                           |

* Using big endian (network) byte order

#### Distinguishing different types of identifier

The identifier may be used to denote 7 different types of Bitcoin blockchain- related entities:

| Entity             | Kind      | Distinguishing factor                                                                         |
| ------------------ | --------- | --------------------------------------------------------------------------------------------- |
| Block              | On-chain  | First bit set to 0, bits 32-63 set to 0                                                       |
| Transaction        | On-chain  | First bit set to 0, bits 48-63 set to 0                                                       |
| Transaction input  | On-chain  | First bit set to 0, bit 48 set to 0, at least one of the bits in range of 49-63 is a non-zero |
| Transaction output | On-chain  | First bit set to 0, bit 48 set to 1, at least one of the bits in range of 49-63 is a non-zero |
| Transaction        | Off-chain | First bit set to 1, bits 48-63 set to 0                                                       |
| Transaction input  | Off-chain | First bit set to 1, bit 48 set to 0, at least one of the bits in range of 49-63 is a non-zero |
| Transaction output | Off-chain | First bit set to 1, bit 48 set to 1, at least one of the bits in range of 49-63 is a non-zero |

It should be noted, that coinbase transactions has the same identifier as the block itself (since transaction indexes within the block are 0-based, unlike transaction input and output indexes, which are 1-based): in this regard coinbase transaction can be seen as a natural part of the block data. Nevertheless, identifiers for coinbase transaction outputs and inputs are distinguished from the unique short block identifier.

### Compatibility

The proposed format is incompatible with previously existing block, transaction, transaction input and output identifiers, including `short_channel_id` from Lightning network protocols.

The format is highly compatible with the requirements of modern databases, including both SQL and No-SQL databases, as well as generic CPU capabilities and programming languages, since all of them are able to deal with 64-bit numbers in highly efficient manner.

### Rationale

#### Estimating ranges for bit-based values

The minimum size of transaction input is:

* 32 bytes reference to txid spent by this input
* 4 bytes for index of transaction output spent by this input,
* 1 byte for variable-length int denoting zero-size `sigScript`,
* 4 bytes for `nSeq`,

41 byte in total.

With 1 MB block size limit and the only one transaction fitting into the block, it may have at most 2^20 / 41 <= 26'000 transaction inputs; which is lower than the maximum value of 15-bit number referencing transaction input index (2^15 = 32'768).

The minimum size of transaction output is:

* 8 bytes for amount (in satoshis)
* 1 byte for variable-length int denoting zero-size `scriptPubkey`,

for nonce/anyone can spent output, or at least

* 8 bytes for amount (in satoshis)
* 1 byte for `scriptPubkey` length fields
* 33 bytes for the shortest possible spendable version of `scriptPubkey` controlled by public key(s): 1 byte SegWit push of `0x01` (for Taproot) followed by 32-bytes of witness program \[2], representing a serialized Taproot public key according to \[5].

I.e. 42 bytes in total, meaning that the same equation valid for transaction inputs above stands for transaction outputs: no meaningful bitcoin transaction can't hold more than 2^15 outputs with the current validation rules.

### Reference implementation

<https://github.com/LNP-BP/rust-lnpbp/pull/14>

### Acknowledgements

### References

1. <https://github.com/bitcoin/bitcoin>
2. Eric Lombrozo, Johnson Lau, Pieter Wuille. BIP-141: Segregated Witness (Consensus layer). <https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#Transaction_ID>
3. BOLT #7: P2P Node and Channel Discovery. <https://github.com/lightningnetwork/lightning-rfc/blob/master/07-routing-gossip.md#definition-of-short_channel_id>
4. Pieter Wuille, Jonas Nick, Anthony Towns. BIP-341 Taproot: SegWit version 1 output spending rules. <https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki>
5. Pieter Wuille, Jonas Nick, Tim Ruffing. BIP-340: Schnorr Signatures for secp256k1. <https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki>

### Copyright

This document is licensed under the Creative Commons CC0 1.0 Universal license.

### Test vectors

TBD


# LNPBP-13: RGB consensus


# RGB-20: Fungible assets


# RGB-21: NFT collectibles


# RGB-22: Digital identity


# RGB-23: Audit logs


# RGB-24: Domain names


# LNPBP-31: Standard contractum lib


# LNPBP-37: Invoices (rejected)

```
LNPBP: 0037
Vertical: Smart contracts
Title: Invoicing formats for RGB-20 fungible assets schema
Authors: Alekos Filini <alekos.filini@gmail.com>
Comments-URI: hhttps://github.com/LNP-BP/LNPBPs/pull/23
Status: Rejected
Type: Standards Track
Created: 2020-04-02
License: CC0-1.0
```

> Note: This standard has been superseded by [LNPBP-38 Universal LNP/BP invoices](https://github.com/LNP-BP/invoices) due to incompatibility with Lightning, Coinjoin, and consignment metadata.

* [Abstract](#abstract)
* [Background](#background)
* [Motivation](#motivation)
* [Specification](#specification)
  * ["On-Chain" Addresses](#on-chain-addresses)
    * [UTXO-based addresses](#utxo-based-addresses)
      * [Extended Variant](#extended-variant)
      * [Short Variant](#short-variant)
  * [Lightning Invoices](#lightning-invoices)
* [Compatibility](#compatibility)
* [Rationale](#rationale)
  * [UTXO-based addresses](#utxo-based-addresses-1)
* [Reference implementation](#reference-implementation)
* [Acknowledgements](#acknowledgements)
* [References](#references)
* [Copyright](#copyright)
* [Test vectors](#test-vectors)

### Abstract

This work proposes a way to levearge existing standards on Bitcoin and the Lightning Network to embed extra details related to assets and other protocol-specific informations into payment URIs and Lightning invoices.

### Background

Bitcoin addresses by themselves sometimes are not enough to convey all the necessary informations about a payment. A merchant might want to get paid a specific amount, or in the case of Lightning they might want to ask the payer to use a specific route over the nodes graph. For this reason, standards have been developed to encode these extra details in a way that could be easily encoded as a text string or in a QR code.

Specifically, BIP-21\[1] describes a way to create a "payment URI" given a Bitcoin address and some extra customizable parameters like an amount, while BOLT-11\[3] describes a way to encode a large number of fields into single, relatively long, strings of text, normally called "invoices".

This standard builds on top of them to extend their capabilities to multiasset protocols.

### Motivation

Multiasset protocols generally needs to embed more informations into a payment URI or invoice, compared to Bitcoin: above everything some kind of asset identifier, which is implicit in Bitcoin invoices because it's the only asset that is natively part of the network.

Other more complex protocols like RGB also need extra parameters to help payer and payee connect to each other and exchange the client-validated part of the data.

### Specification

#### "On-Chain" Addresses

Given a Bitcoin address and an `asset-identifier`, the payment invoice is generated by following the procedure describted by BIP-21\[1], with the following changes:

1. The URI prefix MUST be unique and represent the asset protocol, like `rgb`.
2. The `asset-identifier` MUST be present, and it should be encoded as a Base58\[5] string **without** checksum.

Optionally, like in any normal BIP-21 URIs, an `amount` field can be added. If present, the `amount` MUST be encoded as a floating-point number with the precision factor already applied, if the assets protocol supports it.

Any other protocol-specific field can be added as described in BIP-21, with or without the `req-` prefix depending on whether or not the field should be considered "required".

Specifically, the RGB protocol defines an extra field `req-endpoint` that indicates where the sender is supposed to upload the client validated history of the tokens. It should be equal to a V2 or V3 Tor onion endpoint, optionally followed by an explicit port if the listening server is running on a non-standard port.

**UTXO-based addresses**

Assets protocols that support a "send-to-existing-utxo" feature, can replace the Bitcoin address with a representation of said UTXO. For this purpose, this standard also defines a new type of address encoded in two possible ways:

**Extended Variant**

1. Encode the `txid` in the network binary format (reverse of the hex string usually displayed) in a temporary buffer.
2. Append the `vout` encoded as a 32 bit long unsigned big endian integer.
3. Encode the 36-byte long buffer as a Bech32 address, as specified in BIP-173\[2], using the human-redable part of the network where the UTXO is defined and a witness version of `0`.

**Short Variant**

1. Generate the LNPBP-0005\[4] identifier for the UTXO and represent it as a 64 bit long unsigned big endian. integer in a temporary buffer.
2. Encode the 8-byte long buffer as a Bech32 address, as specified in BIP-173\[2], using the human-redable part of the network where the UTXO is defined and a witness version of `0`.

#### Lightning Invoices

Assets-aware Lightning network invoices should be generated like any normal BOLT-11\[3] invoice, with the following changes:

1. The human readable part MUST be `ln + <unique prefix>`.
2. An extra tagged field with type `a` MUST be present, and MUST be set to the binary representation of the `asset-identifier`
3. Optional fallback addresses (`f` fields) MAY be present and they MAY contain UTXO-based addresses, if the assets protocol supports them. Any other field that would normally be required by the specific asset protocol in its "On-Chain Addresses" MUST also be added with a unique field type defined by the protocol.

Specifically, the RGB protocol requires an extra field tagged with `e` (endpoint) if at least one `f` field is present, serialized in a string as described in the "On-Chain Address" part of this standard. Multiple `e` fields MAY be specified in an implied preferred order.

### Compatibility

This protocol is somewhat a generalization of the Bitcoin and Lightning counterparty, and while it tries to be very similar both implementation-wise and end-result-wise (to look more familiar to people already using the existing protocols), some changes make it incompatible with existing standards. This acts as an extra precaution to avoid loss of funds from people that might mistake a Bitcoin URI with an asset-enabled one.

### Rationale

#### UTXO-based addresses

UTXO-based addresses are encoded exactly like standard Bech32 addresses with witness version of 0 (more commonly known as P2WPKH and P2WSH), however this proposal doesn't conflict in any way with them because, because neither of them has the same length as one of the existing type of addresses. From BIP-173\[2]:

> Decoders SHOULD enforce known-length restrictions on witness programs. For example, BIP141 specifies If the version byte is 0, but the witness program is neither 20 nor 32 bytes, the script must fail.

Introducing this new types of addresses of length 36 and 8 is in fact safer than bumping the version number and potentially have a conflict with a future upgrade of Bitcoin.

### Reference implementation

### Acknowledgements

* Dr Maxim Orlovsky and Giacomo Zucco for the extensive conversation that led to this proposal.

### References

1. Nils Schneider, Matt Corallo. BIP-21: URI Scheme. <https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki>
2. Pieter Wuille, Greg Maxwell. BIP-173: Base32 address format for native v0-16 witness outputs. <https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki>
3. BOLT#11: Invoice Protocol for Lightning Payments <https://github.com/lightningnetwork/lightning-rfc/blob/master/11-payment-encoding.md>
4. Dr Christian Decker, Dr Maxim Orlovsky. LNPBP-5: Universal short Bitcoin identifiers for blocks, transactions and transaction inputs & outputs. <https://github.com/LNP-BP/lnpbps/blob/master/lnpbp-0005.md>
5. Base58 Encoding Format. <https://en.bitcoin.it/wiki/Base58Check_encoding>

### Copyright

This document is licensed under the Creative Commons CC0 1.0 Universal license.

### Test vectors

TBD


# LNPBP-46: LN derivations

```
LNPBP: 0046
Vertical: Lightning network protocol
Title: Deterministic derivation paths for LNP
Author: Dr Maxim Orlovsky <orlovsky@protonmail.ch>,
Comments-URI: https://github.com/LNP-BP/LNPBPs/pull/120
Status: Draft
Type: Standards Track
Created: 2021-12-07
Finalized: not yet
Based on: BIP-32, BIP-43, BOLT-3
License: CC0-1.0
```

* [Abstract](#abstract)
* [Background](#background)
* [Motivation](#motivation)
* [Design](#design)
* [Specification](#specification)
* [Compatibility](#compatibility)
  * [c-Lightning](#c-lightning)
  * [LND](#lnd)
  * [Eclair](#eclair)
  * [LNP Node](#lnp-node)
  * [Electrum](#electrum)
* [Rationale](#rationale)
  * [Choice of `9735h` for BIP-43 purpose](#choice-of-9735h-for-bip-43-purpose)
  * [Use of channel ids for channel basepoint derivation](#use-of-channel-ids-for-channel-basepoint-derivation)
  * [Selection of bits for channel basepoint](#selection-of-bits-for-channel-basepoint)
  * [Use of unhardeded derivation between basepoints](#use-of-unhardeded-derivation-between-basepoints)
  * [Shutdown key derived from funding wallet](#shutdown-key-derived-from-funding-wallet)
  * [Using unhardened indexes for per-commitment points](#using-unhardened-indexes-for-per-commitment-points)
* [Reference implementation](#reference-implementation)
* [Acknowledgements](#acknowledgements)
* [References](#references)
* [Copyright](#copyright)
* [Test vectors](#test-vectors)

### Abstract

The proposal standardizes derivation paths used by lightning nodes, for both BOLT-compatible and Bifrost networks.

### Background

BOLT-3 define a number of "basepoints" - public and private keys used in channel transaction construction and the rules for derivation of the specific keys for each of the transactions out of the basepoint set.

This proposal fills in the gap of how these basepoints may be deterministically derived from a single extended key.

### Motivation

A standard for deterministic derivation of keys used in channel transaction construction will allow users to always recover the whole information out of a seed phrase independently from a specific node implementation used for channel creation.

### Design

We define a **extended lightning key** as an extended master private key used for all derivations of channel basepoints, funding wallet and **node key**. This key is derivable from the extended master key / seed phrase using a specific derivation path purpose value `9735'`.

### Specification

**Extended lightning key** should be derived from a extended master key using the following derivation path:

`m/9735'/`

where `9735'` is a BIP-43 purpose field reserved for this standard.

**Node key** is derived from the *extended lightning key* using `/chain'/0'/node_index'` derivation, where `chain'` is a hardened index specifying blockchain operated by the node, and `node_index'` is a hardened incremental index for the node among all nodes managed by a seed owner.

**Channel basepoint** is derived from the *extended lightning key* using `/chain'/1'/ln_ver'/channel'` derivation, where:

* `channel'` is a hardened index constructed from the *initial channel id* most significant bits starting from 1 to 32 using zero-based indexing. For BOLT-defined lightning channels *initial channel id* is the temporary channel id value; for Bifrost channel it is the channel id value.
* `ln_ver'` is a hardened index set to `0'` for BOLT-defined lightning channels and `1'` for Bifrost channels.

Derivation paths for the base points are the following:

Basepoint name | Derivation suffix | Full derivation path -------------- | ------------------------------------------- Funding | `/0` | `m/9735'/chain'/1'/ln_ver'/channel'/0` Payment | `/1` | `m/9735'/chain'/1'/ln_ver'/channel'/1` Delayed | `/2` | `m/9735'/chain'/1'/ln_ver'/channel'/2` Revocation | `/3` | `m/9735'/chain'/1'/ln_ver'/channel'/3` Per-commitment | `/4/*` | `m/9735'/chain'/1'/ln_ver'/channel'/4/0` HTLC | `/5` | `m/9735'/chain'/1'/ln_ver'/channel'/5` PTLC | `/6` | `m/9735'/chain'/1'/ln_ver'/channel'/6`

**Funding wallet** used for keeping funds by a lightning node for constructing funding transactions is derived with `/chain'/2'/case/index` path, where `case` is an equivalent of `change` field with RGB extensions (see \_\_\_) and `index` is a sequential index number.

Example of extended keys used by lightning node #0 on bitcoin network for a BOLT-defined channel with temporary channel id `2938ce5c0cae4b2af072065dc7dcea68de5e3de0c936742e27e045c8650c6a79`:

| Extended keys         | Derivation                                                   |
| --------------------- | ------------------------------------------------------------ |
| Lightning key         | `m/9735'/`                                                   |
| Node key              | `m/9735'/0'/0'/0'`                                           |
| Channel basepoint     | `m/9735'/0'/1'/0'/691588700'` (index equals to `0x2938ce5c`) |
| Per-commitment points | `m/9735'/0'/1'/0'/691588700'/4/<per_commitment_no>`          |
| Funding wallet        | `m/9735'/0'/2'/0/*`                                          |
| Funding wallet change | `m/9735'/0'/2'/1/*`                                          |
| Shutdown              | `m/9735'/0'/2'/2/*`                                          |
| Funding wallet RGB20  | `m/9735'/0'/2'/200/*`                                        |
| RGB20 change          | `m/9735'/0'/2'/201/*`                                        |
| Shutdown RGB20        | `m/9735'/0'/2'/202/*`                                        |

Please note that the channel shutdown key is derived from a funding wallet - and not from a channel basepoint.

### Compatibility

TBD: investigate derivation paths used by specific lightning nodes

#### c-Lightning

#### LND

#### Eclair

#### LNP Node

LNP Node is fully compatible with the standard

#### Electrum

### Rationale

#### Choice of `9735h` for BIP-43 purpose

BIP-43 defines that new purposes must be created with new BIPs and their hardened index representations must match that BIP number. Since we this standard is created before BIP proposal for a new purpose, we need to choose some large number which will not be used by BIPs in a foreseable future. `9735` is the unicode character value for lightning (☇) also used as a port number in lightning network.

#### Use of channel ids for channel basepoint derivation

Channels may be created asynchronously and it is hard to get sequential numbering within the lightning node. Also, if the node data are lost, it will be hard to guess which channel had which sequence index. Thus, the only way to get a channel-specific derivation index is to use some of channel id bits.

We can't use channel funding transaction id since it will be known only upon key derivation.

#### Selection of bits for channel basepoint

We can use only 31 bits, since the most significant bit of derivation index is occupied by hardering flag (see BIP-32). We start with the second most significant channel bit to make it easy visually compare index with channel id without any bit shifts.

#### Use of unhardeded derivation between basepoints

Each channel is derived with hardened derivation, which allows to separate node from channels: if a node-level extended public – or even extended private key is leaked, it still be impossible to guess from the key information which channels ere created or closed with that node. From the other hand, if one needs to disclose the full information about the channel transaction it will be sufficient to have a single extended public key for **channel basepoint** to derive all other public keys any channel transaction.

#### Shutdown key derived from funding wallet

Funding wallet may be a separate process - or separate cold wallet, isolated from the rest of the lightning node. Deriving shutdown key from funding wallet allows it to use funds from closed channels for funding new channels without the need for additional interactivity with the lightning node.

#### Using unhardened indexes for per-commitment points

This allows user to reconstruct channel history without the need to access channel extended private key.

### Reference implementation

The reference implementation of this derivation standard is done in a [LNP Core Library](https://github.com/LNP-BP/lnp-core) as a part of `legacy::channel::Keyset`, `bifrost::channel::Keyset` and `NodeAccount` structures.

### Acknowledgements

### References

### Copyright

This document is licensed under the Creative Commons CC0 1.0 Universal license.

### Test vectors


# LNPBP-50: Bifrost P2P

```
LNPBP: 0050
Vertical: Lightning network protocol
Title: Bifrost: generalized Lightning network protocol core
Author: Dr Maxim Orlovsky <orlovsky@lnp-bp.org>
Comments-URI: https://github.com/LNP-BP/lnpbps/pulls/97
Status: Draft
Type: Standards Track
Created: 2021-11-01
Finalized: not yet
License: CC0-1.0
```

* [Abstract](#abstract)
* [Background](#background)
* [Motivation](#motivation)
* [Design](#design)
* [Specification](#specification)
  * [Announcing Bifrost connectivity](#announcing-bifrost-connectivity)
  * [Bifrost URLs](#bifrost-urls)
  * [Bifrost initiation from legacy Lightning messaging](#bifrost-initiation-from-legacy-lightning-messaging)
  * [Establishing connection](#establishing-connection)
* [Compatibility](#compatibility)
  * [Channels](#channels)
  * [Invoices](#invoices)
* [Rationale](#rationale)
  * [Use of dedicated port](#use-of-dedicated-port)
  * [Why URL uses plus instead of at symbol](#why-url-uses-plus-instead-of-at-symbol)
  * [Using local features](#using-local-features)
  * [Feature bit selection](#feature-bit-selection)
* [Reference implementation](#reference-implementation)
* [Acknowledgements](#acknowledgements)
* [References](#references)
* [Copyright](#copyright)
* [Test vectors](#test-vectors)

### Abstract

### Background

### Motivation

Extending existing lightning network messaging system, defined as part of multiple BOLTs, is hard. The first problem is the necessity to introduce changes to multiple independent standards for each atomic feature; making review and acceptance process very time-consuming. Next, it is hard to implement these features one by one, since they are defined in different places. Finally, there is no place to put feature-specific test vectors in the existing BOLT structure.

The second problem is separation of new and not yet well tested/experimental functionality from the well-tested existing lightning network core. The separation of experimental protocols and existing tested core functionality is good from the security point of view.

The third reason is the fact that Lightning network was designed as a payment network and for payment purposes. At the same time, it is possible to create much more advanced forms of non-payment state channels basing on bitcoin transactions (useful for storage and different forms of financial smart contracts), or use lightning network for non-payment data communication (like messaging or DEX). These extensions when put into existing LN spec framework, not suited for such extensibility, will require constant introduction of multiple hacks or complete refactoring of the BOLT specifications.

Finally, some of lightning network design decisions were proven to be non-efficient in context of more broad applications, for instance use of BigInt encoding is not advised for client-side-validated data \[…]. It will be impossible to fix such issues without introducing new network communication protocol.

Bifrost is a proposed new set of standards, defined as a part of LNPBP standards suite, that includes extensible core networking protocol (LNPBP-50, this specification), and specific extensions for different forms of state channel management and network data communications. Current standard is built on top of other LNPBP standards (like strict encoding), BIPs (partially signed bitcoin transactions), parts of BOLT standards (Noise\_XK protocol), extracted as a separate LNPBP standards, and puts them into a single well-abstracted protocol suite.

### Design

Design goals:

1. Extensibility, including
   * support for non-payment / custom lightning channels
   * support for non-payment network messaging & communications
   * support for arbitrary extension of channel transaction structure (combining different types of channels)
   * support for custom / new route discovery mechanisms
2. Maximal use of existing LNPBP standards, in particular
   * LNPBP-7 commitments for structural and hierarchical data \[…]
   * LNPBP-9 client-side-validation \[…]
   * LNPBP-15 Noise\_XK handshake & network encryption (BOLT-8 extract) \[…]
   * LNPBP-18 Native message framing (BOLT-8 extract) \[…]
   * LNPBP-16 handshake over WebSockets \[…]
3. Privacy: improved re-use of onion messaging from Lightning network

### Specification

Bifrost operates using TCP connection, on top of LNPBP-15 (session & encryption layer) and LNPBP-18 (message framing layer) as application protocol. Default port for Bifrost connection is 9913 (see [rationale](#use-of-dedicated-port)).

All message fields are encoded with strict encoding instead of other types of encoding used in BOLTs / legacy Lightning network.

#### Announcing Bifrost connectivity

Support for Bifrost protocol can be announced as a part of local features flag ([see why not global](#using-local-features)) in legacy lightning network `init` message, inside `node_announcement`, `channel_announcement` and `channel_update` messages (`INC` context in terms of BOLT-9). Bifrost feature flags should not be used with BOLT-11 invoices; instead, all Bifrost channels MUST use LNPBP-38 invoicing.

Since BOLT-9 provides no ability to add arbitrary feature flags from outside of the BOLT-defined protocol scope, this feature will be a non-standard. We reserve flag number 255/256 for it (see [rationale](#feature-bit-selection)).

#### Bifrost URLs

Bifrost URLs are designed to be compliant with RFC 3986 \[1] and consists of `bifrost` as *scheme name*, *authority* in form of node public key, combined with optional network address details, channel id as a *path* and feature parameters and route suggestion as *query*, where both *path* and *query* parts are optional (emphasized words stand for RFC 3986-defined terms):

`<schema>://<authority>[/<path>][?<query>]` => `bifrost://<host>[/<channel-id>][?<feature-params> | <route-suggestion>]`

Host part MUST always include node public key, optionally followed by either IPv4, IPv6 or ONION v3 Tor address. IPv4 and IPv6 addresses may include optional port number, which becomes mandatory if a non-standard Bifrost port is used. The address, if present, MUST be separated from the public key by `+` symbol (see [rationale](#why-URL-uses-plus-instead-of-at-symbol)).

`bifrost://<key>[+ <IPv4 | IPv6>[:<port>] | <ONIONv3>]/[<channel-id>][?<feature-params> | <route-suggestion>]`

Example:

* Node with a known IPv4 address operating non-standard port: `bifrost://02b39e7040cd9233e1cf86823ea321c1c799534c622c9e8b563a689409962657c7+124.155.54.210:9935`
* Node with Onion v3 address and path suggestion: `bifrost://02b39e7040cd9233e1cf86823ea321c1c799534c622c9e8b563a689409962657c7+worldehc62cgugrgj7oc76tcna45fme47oqjrei4d4aa7xorw7fyvcyd/?`

#### Bifrost initiation from legacy Lightning messaging

Two nodes connected via Lightning network may send each other specific message indicating intent to open Bifrost connection. The message uses onion routing, enabling NAT bypassing, such that a party without NAT may “hole punch” NAT of another party by asking to establish Bifrost connection to its explicit IP address.

#### Establishing connection

### Compatibility

#### Channels

Bifrost may be used to operate channels created using legacy Lightning network protocols – until there are changes into the channel structure which make them incompatible with existing BOLT specifications. Also, channels created with Bifrost can be accessed via legacy lightning network until they become incompatible (in their structure) with BOLT specifications.

Thus, to prevent undefined behavior, it is advised that nodes will maintain each channel either under legacy LN or under Bifrost using the following rules:

1. If the channel was created in legacy LN it can be moved into Bifrost once and only once – and a dedicated gossip `channel_update` message must be published to the legacy LN with Bifrost even flag set.
2. If the channel was created in Bifrost network, it MAY be announced in the legacy LN only with odd (required) Bifrost flag set.
3. Bifrost channels can’t be operated using legacy LN messaging; a node receiving message referencing to a Bifrost server over the legacy LN MUST respond with `error` message.
4. Legacy LN channels MUST not be operated from Bifrost network before their movement according to the pt. 1. A node receiving Bifrost message for legacy LN channel MUST respond with `error` message.

   In order to enable fallback for Bifrost-managed channels in case of bugs discovered in Bifrost, the following rules SHOULD be supported by Lightning node implementations, but SHOULD not be used until a fallback scenario:
5. Bifrost channels which maintain BOLT compatibility can be moved back into legacy Lightning network by properly announcing removal of the channel in Bifrost network – and publishing `channel_announcement` (for previously non-announced channels) or `channel_update` gossip messages with all Bifrost feature flags removed

#### Invoices

All bifrost-operated channels MUST use LNPBP-38 invoices. BOLT-11 invoices MUST NOT be created for any channel which was moved into Bifrost network.

### Rationale

#### Use of dedicated port

Bifrost requires use of a non-LN port to enable simultaneous and independent operations of lightning nodes using both legacy LN messages and Bifrost messages.

#### Why URL uses plus instead of at symbol

While at\* symbol (`@`) is broadly used in legacy Lightning node addresses (`<pubkey>@<host>[:<port>]` form), it can’t be used as a proper part of Bifrost URL since in RFC 3986 it is reserved as a separator for optional username prefix before mandatory host name part – while pubkey is not optional in Bifrost and host is optional. Thus, we replace `@` usage with `+`, since `+` is allowed in RFC 3986 as a separator in host name part of authority field and it semantically defines “additional information”, which is a network address of the node for a given public key.

#### Using local features

Bifrost support is specified in the local features field of the `init` message since it is against BOLT-9 to use feature bits greater than 13 in the global features field.

#### Feature bit selection

Bits 255/256 are the largest bit numbers which may be stored by a 32-byte value. It is still far enough from the current used feature bits in BOLT-9 (26/27), allowing another 5 to 10 years without the risk of the conflict (until Bifrost will be recognized) and at the same time does not over-enlarges the size of the feature flag field in `init` and other messages.

### Reference implementation

The current Bifrost reference implementation is provided by [`LNP Core Library`](https://github.com/LNP-BP/lnp-core) and [`LNP Node`](https://github.com/LNP-BP/lnp-node)

### Acknowledgements

The authors are thankful to Giacomo Zucco, Christian Decker and Martin Habovštiak for multiple discussions and ideas which led to the creation and shaping of this specification.

### References

1. RFC 3986. Uniform Resource Identifier (URI): Generic Syntax. <https://www.rfc-editor.org/rfc/rfc3986#section-3.1>

### Copyright

This document is licensed under the Creative Commons CC0 1.0 Universal license.

### Test vectors

TBD


# LNPBP-51: Bifrost channels

```
LNPBP: 0051
Vertical: Lightning network protocol
Title: Bifrost: channel management protocol
Author: Dr Maxim Orlovsky <orlovsky@lnp-bp.org>
Comments-URI: https://github.com/LNP-BP/lnpbps/pulls/97
Status: Draft
Type: Standards Track
Created: 2021-11-01
Finalized: not yet
License: CC0-1.0
```

* [Abstract](#abstract)
* [Background](#background)
* [Motivation](#motivation)
* [Design](#design)
* [Specification](#specification)
  * [Bifrost transaction requirements](#bifrost-transaction-requirements)
  * [Channel coordination](#channel-coordination)
    * [Channel workflows](#channel-workflows)
* [Channel creation workflow](#channel-creation-workflow)
* [Compatibility](#compatibility)
* [Rationale](#rationale)
* [Reference implementation](#reference-implementation)
* [Acknowledgements](#acknowledgements)
* [References](#references)
* [Copyright](#copyright)
* [Test vectors](#test-vectors)

### Abstract

### Background

### Motivation

### Design

### Specification

#### Bifrost transaction requirements

Bifrost requires all off-chain transactions always be of version 2. Transaction outputs which are internal to the channel (i.e. spend by other offchain transactions participating in channel) MUST use v1 witness P2TR outputs (or later witness versions). The scripts in taproot key path spends MUST be miniscript-compatible.

For on-chain funding transactions and funding outputs of channel level 1 this requirement is released to witness v0 or above. The reason for lower requirement is the interoperability with the legacy lightning network, allowing migration of existing channels opened in legacy network to Bifrost.

There is no specific requirements for outputs which are not internal for the channel.

#### Channel coordination

For channel operations we assume that any channel may be a multi-peer channel. Thus, for channel updates it is required that all parties cooperate and sign the latest version of updated channel transactions. This is achieved by introducing concept of *channel coordinator*. Channel coordinator is the lightning node that has originally proposed channel. It is responsible for orchestrating message flow between all nodes which are the parts of the channel and keeping them up-to-date. Also, the channel coordinator is the only party required to have direct connections with other channel participants – and each of channel participants is required to be connected at least to the channel coordinator.

If a multiple nested channels are present, for all higher-level channels channel coordinator MUST be the same as channel coordinator for the base (level 1) channel; the list of participants for the nested channels MUST be a subset of the participants of the topmost level 1 channel.

**Channel workflows**

There are following workflows affecting channel status / existence. Each of these workflows represent a set of P2P messages exchanged by channel peers.

* Channel creation
* Moving channel from legacy to Bifrost LN
* Removing channel from Bifrost to legacy LN
* Changing channel status (pausing etc)
* Upgrading channel to support more protocols
* Downgrading channel by removing specific protocol
* Cooperatively closing channel

Workflow can be initiated only by a *channel coordinator*, and specific P2P messages inside the workflow can be sent either from the *channel coordinator* to a peer – or, in response, from a peer to the *channel coordinator*.

Normal channel operations are covered by application-specific business logic and messages and are not part of any listed channel workflow. Unlike workflows, they may be initiated by any of the channel peers sending message to the channel coordinator, however whenever they involve other peers or external channels, after being initiated they must be coordinated by the channel coordinator.

### Channel creation workflow

Considering generic case of multi-peer channel setup channel creation workflow is organized with the following algorithm:

1. First, all parties agree on the structure of the *funding transaction* and overall transaction graph within the channel – simultaneously signing *refund transaction* (which, upon channel creation, will become first version of the channel *commitment transaction*). This is done using `ProposeChannel` requests sent by the *channel coordinator* to each of the peers, replying with either `AcceptChannel` (containing updated transaction graph with signed refund transaction) or `Error`. peers must wait for `CHANNEL_CREATION_TIMEOUT` period and discard all provisional channel data from their memory.
2. Once the refund transaction is fully signed – implying that the transaction graph if agreed between participants – channel coordinator starts next phase, where the funding transaction gets fully signed. Coordinator sends `FinalizeChannel` message to each of the peers and collects signatures, publishing the final transaction either to bitcoin blockchain (for level 1 channels) or updating the state of the top-level channel (for nested channels above level 1). Peers track upper level channel or blockchain to detect funding transaction, and upon transaction mining starts operate channel in active mode, not requiring any other messages from the channel coordinator (NB: this differs from the legacy LN channel creation workflow).
3. Replacing funding by fee (RBF): channel coordinator SHOULD initiate RBF subworkflow for level 1 channels if the funding transaction was not mined after reasonable amount of time, which should be less than `ChannelParams::funding_timeout`. With RGB subworkflow coordinator updates funding transaction – and propagates it with `FinalizeChannel` request, collecting new signatures (peers MUST reset their funding timeout counters).
4. Cancelling channel creation: if any of the peer nodes replied with `Error` on any of the channel construction requests within the channel creation workflow – or if the coordinator detected incorrect reply, channel coordinator MUST abandon channel creation – and MUST forward `Error` message to all other peers. A peer posting `Error` MUST provide a valid error code and a message explaining the cause of the error. The coordinator SHOULD also send `Error` message to peers if any of the stages of transaction construction workflow has stuck without a reply from a peer for over `ChannelParams::peer_timeout` time.
5. Timeouts: the coordinator SHOULD send `Error` message to peers if any of the peers at any stage of transaction construction workflow has stuck without a reply for over `ChannelParams::peer_timeout` time. The peers should abandon channel and clear all information about it from the memory regardless whether they have received `Error` message from the coordinator after `ChannelParams::peer_timeout`` * 2` time before `ChannelFinalized` – and if they has not received new `FinalizeChannel` request from the coordinator after `ChannelParams::funding_timeout` time (see pt 3 for RBF subworkflow).

```
Channel coordinator                   Peer 1             Peer 2
        |                               |                  |
(enters ChannelProposed state)          |                  |
        |                               |                  |
        | --(1)- ProposeChannel ------> |                  |
        |                               |                  |
        | --(1)------------ ProposeChannel --------------> |
        |                               |                  |
        |                           (enter ChannelProposed state)
        |                               |                  |
        | <-(2)------------- AcceptChannel --------------- |
        |                               |                  |
        | <-(2)-- AcceptChannel ------- |                  |
        |                               |                  |
 (enters ChannelAccepted state)     (enter ChannelAccepted state)
        |                               |                  |
        | --(3)- FinalizeChannel -----> |                  |
        |                               |                  |
        | --(3)------------ FinalizeChannel -------------> |
        |                               |                  |
        | <-(4)-- FinalizeChannel ----- |                  |
        |                               |                  |
        | <-(4)------------- FinalizeChannel ------------- |
        |                               |                  |
 (enters ChannelFinalized state)    (enter ChannelFinalized state)
        |                               |                  |
(await funding transaction mining or entering the valid super-channel state)
        |                               |                  |
 (enters ChannelActive state)       (enter ChannelActive state)
        |                               |                  |
```

During channel construction workflow channels are identified by `ChannelId`, which is constructed as a tagged SHA-256 hash (using `bifrost:channel-proposal` as tag) of the strict-serialized `ChannelParams` data and coordinator node public key.

### Compatibility

### Rationale

### Reference implementation

### Acknowledgements

### References

### Copyright

This document is licensed under the Creative Commons CC0 1.0 Universal license.

### Test vectors


# LNPBP-53: Multipeer channels

```
LNPBP: 0053
Layer: OSI Application (i7)
Vertical: Lightning network protocol
Title: Muli-peer payment channels for Bifrost
Author: Dr Maxim Orlovsky <orlovsky@lnp-bp.org>
Comments-URI: https://github.com/LNP-BP/lnpbps/pulls/97
Status: Draft
Type: Standards Track
Created: 2021-11-14
Finalized: not yet
License: CC0-1.0
```

### Abstract

This specification proposes a batch of improvements for lightning payment channels: (1) generalization of channels to have an arbitrary number of participants (multi-peer channels), (2) abstraction from specific peyment routing syncrhronization algorithm (HTLC, PTLC), (3) ability to extend and change channel parameters and structure on-the-go, (4) use of Schnorr signatures, MuSig, Taproot and miniscript-based descriptors. It achieves this properties by leveraging Bifrost protocol, specifically LNPBP-50 and LNPBP-51 standards.

### Background

Lightning network enables scalable and more private bitcoin payments by using pre-signed off-chain transactions, composing so-called state channels. Still, existing lightning network, defined by a set of BOLT standards, has multiple limitations. LNP/BP standards LNPBP-50, 51, 52 proposed an extended version of the lightning network called Bifrost. It is a part of more general Lightning network protocol and allows creation of more complex, functional and secure forms of payment channels, which is the aim of this proposal.

### Motivation

Current standards defining lightning network (BOLTs) were created in the eraly SegWit era. They were created to cover single use case (unilaterally funded dual party payment channels) with a very restricted functionality (no channel splits, channel factories, nested channels, extensions for channel structure etc). Since LN launch a multiple enhancemend had been deployed on Bitcoin maiinnet, including Shnorr signatures, unlocking more compact multisigs (with MuSig scheme), scriptless scripts & adaptor signatures, enabling alternative payment routing synchronization mechanism (PTLC), replacing vulnerable HTLC; Taproot, enabling stronger privacy properties and more compact witnesses; client-side-validation applications, including RGB smart contracts; different complex Bitcoin finance applications (BiFi), like descrete log contracts, lightspeed protocol and many others. The current standard is aiming at generalizing concept of lightning payment channels as a part of LNP (lightning network protocol) family of standards, leveraging new set of functionality offered by Bifrost protocol.

### Design

First, we separate the core of the payment channel operations from other channel-related protocols, like payment routing. This enables us real-time upgradability and composability for channel structure and use of different protocols within the scope of the same channel (like HTLC, PTLC etc).

Second, we update channel transactions to use Taproot, Schnorr signatures, MuSig, TapScript – and enable sign-to-contract and pay-to-contract commitments required for client-side-validation (like RGB smart contracts).

Third, we generalize the structure of payment channel transactions for an arbitrary number of participants.

Finally, we re-define a set of messages controlling channel creation and oprations using channel proposals, strict encoding and other advancements brought by un underlying Bifrost protocol (LNPBP-50 and 51).

### Specification

#### Funding transaction

Transaction containing multiple inputs, each of which MUST signal S2C commitment type.

Output descriptor: `tr(musig(KEY_LOCAL_FUNDING, KEY_REMOTE_1_FUNDING, KEY_REMOTE_2_FUDING, ...))`

#### Commitment transaction

Input:

* Spends funding output
* nSeq: `0x80800000 + COMMITMENT_NO & 0xFFFF` (signals S2C DBC)
* Witness stack:
  * `KEY_LOCAL_FUNDING + KEY_REMOTE_1_FUNDING + KEY_REMOTE_2_FUNDING + ...`
  * `MUSIG*(KEY_LOCAL_FUNDING + KEY_REMOTE_1_FUNDING + KEY_REMOTE_2_FUNDING + ...)` where \* denotes optional presence of sign-to-contract commitment

Outputs:

* `to_local`: `tr(KEY_REVOCATION, and_v(v:pk(KEY_LOCAL),older(SELF_DELAY)))`
  * `KEY_LOCAL`: proposed by the local node
  * `SELF_DELAY`: proposed by the remote node, may be rejected by local
* `to_remote_n`: `tr(KEY_UNSPENDABLE, and_v(v:pk(KEY_REMOTE_N),older(REMOTE_N_DELAY))`
  * `KEY_REMOTE_N`: propsed by the remote node N
  * `KEY_UNSPENDABLE`: a deterministically-unspendable key computed as `KEY_REMOTE_N + SHA256T("lnpbp53:unspendable", KEY_REMOTE_N) * G`
  * `REMOTE_N_DELAY`: proposed by the channel coordinator, may be rejected by remote node N
* `anchor`: `tr(KEY_UNSPENDABLE, {v:pk(KEY_LOCAL), v:pk(KEY_REMOTE_N)})`
  * The ooutput must contain a fixed amount of satoshis above dust limit proposed by the node adding this output to the channel proposal

#### Messaging

TBD

### Compatibility

#### Upgrade

Any legacy lightning network channel can be upgraded into Bifrost channel using `UPGRADE` Bifrost message.

#### Downgrade

Channel may be downgraded from Bifrost to legacy Lightning network if and only if

* Channel is a 2-peer channel
* It contains only HTLC extensions and no other types of extensions
* It is not used in creation of other channels
* It originates from an on-chain funding transaction
* It does not contain RGB assets or other protocols requiring use of deterministic bitcoin commitments or single-use-seals

Bifrost channel breaking one of these requirements may be made downgradable by removing channel protocols until all of the the requirements are met.

Channel resulting from downgrade will always use `anchor_output` BOLT-9 feature flag.

### Rationale

#### Funding transaction inputs use sign-to-contract scheme

With pay-to-contract commitments if any of channel participants have the same RGB asset or other P2C-committed protocol data they will be required to merge their state transitions, expose the private asset data for all other participants and exchange full RGB consignments before signing funding transaction. This creates significant privacy leak, more attach vectors and requires much more complex protocol design.

#### Channel downgrade

Bifrost is a highly experimental protocol. Ability to downgrade channel to legacy stable lightning network provides a failback mechanism for cases when an attack on Bifrost channels was discovered and participating parties do not want to close the channel.

### Reference implementation

### Acknowledgements

### References

### Copyright

This document is licensed under the Creative Commons CC0 1.0 Universal license.

### Test vectors


# LNPBP-55: Bifrost HTLCs

```
LNPBP: 0055
Layer: OSI Application (i7)
Vertical: Lightning network protocol
Title: HTLC channel synchronization in Bifrost
Author: Dr Maxim Orlovsky <orlovsky@lnp-bp.org>
Comments-URI: https://github.com/LNP-BP/lnpbps/pulls/97
Status: Draft
Type: Standards Track
Created: 2021-11-14
Finalized: not yet
License: CC0-1.0
```

### Abstract

This document specifies upgrade of BOLT-1, 3, 4 and 5-based routed payments in legacy network and covers payment routing via HTLC-based channel synchronization in Bifrost using Taproot, TapScript and miniscript-based bitcoin output descriptors.

### Background

HTLC (hash-time-locked contracts) are used for coordination of state update between multiple UTXO-based channels. This was the first mechanism proposed for payment routing in the original lightning network.

### Motivation

Legacy lightning network uses pre-Taproot scripts and non-Schnorr signatures, which reduces its privacy and requires more onchain space, especially in cases of non- cooperative channel closings.

### Design

### Specification

#### Messaging

HTLC-based payment coordination is performed by using onion message transport from LNPBP-52. This specification defines the following message types embedded as onion payloads:

`HTLC_ADD`

`HTLC_EXPIRE`

`HTLC_FULFILL`

`HTLC_MALFORMED`

It also re-uses `SIG_UPDATE` and `REVOKE` messages from the core Bifrost protocol (LNPBP-50).

#### Transactions

Each HTLC contract adds an output to the *commitment transaction*. The output depends on whether this is an offered HTLC or received one.

**Offered HTLC outputs**

```
tr(KEY_REVOCATION, { 
    and_v(
        v:milti_a(2, KEY_HTLC_REMOTE, KEY_HTLC_LOCAL), 
        older(SELF_DELAY)), 
    and_v(
        and_v(
            v:pk(KEY_HTLC_REMOTE), 
            v:hash160(HASH)), 
        older(SELF_DELAY)) 
})
```

**Received HTLC outputs**

```
tr(KEY_REVOCATION, {
    and_v(
        and_v(
            v:multi_a(2, KEY_HTLC_LOCAL, KEY_HTLC_REMOTE), 
            after(CLTV_EXPIRE)), 
        older(SELF_DELAY),
    and_v(
        and_v(
            v:multi_a(2, KEY_HTLC_LOCAL, KEY_HTLC_REMOTE), 
            v:hash160(HASH)), 
        older(SELF_DELAY)
})
```

These outputs are constructed after BOLT-3 with `option_anchors` (see rationale).

**HTLC spending transactions**

The input of *HTLC spending transactions* spends *offered HTLC* (for *HTLC timeout transaction*) or *received HTLC* (for *HTLC success transaction*) output from the commitment transaction.

* nLockTime:
  * 0 for HTLC-success
  * `CLTV_EXPIRY` for HTLC-timeout
* Input:
  * nSeq: `SELF_DELAY` (must be even to use P2C deterministic bitcoin commitments)
  * control block: `0xC0/0xC1 <first branch tapleaf-hash>`
  * rest of witness stack for *HTLC-success*:
    * `KEY_HTLC_LOCAL`
    * `SIG(KEY_HTLC_LOCAL)`
    * `KEY_HTLC_REMOTE`
    * `SIG(KEY_HTLC_REMOTE)`
    * `HASH_PREIMAGE`
  * rest of witness stack for *HTLC-timeout*:
    * `KEY_HTLC_REMOTE`
    * `SIG(KEY_HTLC_REMOTE)`
    * `KEY_HTLC_LOCAL`
    * `SIG(KEY_HTLC_LOCAL)`
* Output descriptor:

  ```
  tr(KEY_REVOCATION*, and_v(
      v:pk(KEY_LOCAL_DELAYED),
      older(SELF_DELAY)
  ))
  ```

  (\* denotes that the internal taproot key `KEY_REVOCATION` may be tweaked with pay-to-contract commitment)

**On-chain protocol**

TBD

### Compatibility

### Rationale

#### Use of `OP_CHECKSIGADD`

There are multiple ways to create multisig scheme in Taproot & TapScript \[1]. In script-path spending leafs we choose to use `OP_CHECKSIGADD`-based scripts, defined by miniscript `multi_a` descriptors. This allows to avoid multiple interactive communications required for composinng aggregated MuSig signatures. The downside of this approach is a large witness stack size (and higher transaction cost), which may be mitigated by adopting PTLC-based scriptless- script contracts \[2].

#### Use of `option_anchors`

HTLC construction in Bifrost always requires use of equivalent of legacy BOLT-9 "anchored outputs" option. This addresses a vulnerability caused by the absence of self-delay seqnence lock, where local party had an incentive to non-cooperatively close the channel in order to instantly get access to the local funds.

### Reference implementation

### Acknowledgements

### References

1. <https://github.com/bitcoin/bips/blob/master/bip-0342.mediawiki#cite_note-5>
2. LNPBP-0056

### Copyright

This document is licensed under the Creative Commons CC0 1.0 Universal license.

### Test vectors


