bolt2

Lightning peer protocol, per BOLT #2 (docs.ppad.tech/bolt2).
git clone git://git.ppad.tech/bolt2.git
Log | Files | Refs | README | LICENSE

02-peer-protocol.md (174595B)


      1 # BOLT #2: Peer Protocol for Channel Management
      2 
      3 The peer channel protocol has three phases: establishment, normal
      4 operation, and closing.
      5 
      6 # Table of Contents
      7 
      8   * [Channel](#channel)
      9     * [Definition of `channel_id`](#definition-of-channel_id)
     10     * [Interactive Transaction Construction](#interactive-transaction-construction)
     11       * [Set-Up and Vocabulary](#set-up-and-vocabulary)
     12       * [Fee Responsibility](#fee-responsibility)
     13       * [Overview](#overview)
     14       * [The `tx_add_input` Message](#the-tx_add_input-message)
     15       * [The `tx_add_output` Message](#the-tx_add_output-message)
     16       * [The `tx_remove_input` and `tx_remove_output` Messages](#the-tx_remove_input-and-tx_remove_output-messages)
     17       * [The `tx_complete` Message](#the-tx_complete-message)
     18       * [The `tx_signatures` Message](#the-tx_signatures-message)
     19       * [The `tx_init_rbf` Message](#the-tx_init_rbf-message)
     20       * [The `tx_ack_rbf` Message](#the-tx_ack_rbf-message)
     21       * [The `tx_abort` Message](#the-tx_abort-message)
     22     * [Channel Establishment v1](#channel-establishment-v1)
     23       * [The `open_channel` Message](#the-open_channel-message)
     24       * [The `accept_channel` Message](#the-accept_channel-message)
     25       * [The `funding_created` Message](#the-funding_created-message)
     26       * [The `funding_signed` Message](#the-funding_signed-message)
     27       * [The `channel_ready` Message](#the-channel_ready-message)
     28     * [Channel Establishment v2](#channel-establishment-v2)
     29       * [The `open_channel2` Message](#the-open_channel2-message)
     30       * [The `accept_channel2` Message](#the-accept_channel2-message)
     31       * [Funding Composition](#funding-composition)
     32       * [The `commitment_signed` Message](#the-commitment_signed-message)
     33       * [Sharing funding signatures: `tx_signatures`](#sharing-funding-signatures-tx_signatures)
     34       * [Fee bumping: `tx_init_rbf` and `tx_ack_rbf`](#fee-bumping-tx_init_rbf-and-tx_ack_rbf)
     35     * [Channel Quiescence](#channel-quiescence)
     36     * [Channel Splicing](#channel-splicing)
     37       * [The `splice_init` Message](#the-splice_init-message)
     38       * [The `splice_ack` Message](#the-splice_ack-message)
     39       * [Splice Transaction Construction](#splice-transaction-construction)
     40       * [Splice Completion](#splice-completion)
     41     * [Channel Close](#channel-close)
     42       * [Closing Initiation: `shutdown`](#closing-initiation-shutdown)
     43       * [Closing Negotiation: `closing_complete` and `closing_sig`](#closing-negotiation-closing_complete-and-closing_sig)
     44       * [Legacy Closing Negotiation: `closing_signed`](#legacy-closing-negotiation-closing_signed)
     45     * [Normal Operation](#normal-operation)
     46       * [Forwarding HTLCs](#forwarding-htlcs)
     47       * [`cltv_expiry_delta` Selection](#cltv_expiry_delta-selection)
     48       * [Adding an HTLC: `update_add_htlc`](#adding-an-htlc-update_add_htlc)
     49       * [Removing an HTLC: `update_fulfill_htlc`, `update_fail_htlc`, and `update_fail_malformed_htlc`](#removing-an-htlc-update_fulfill_htlc-update_fail_htlc-and-update_fail_malformed_htlc)
     50       * [Batching channel messages](#batching-channel-messages)
     51       * [Committing Updates So Far: `commitment_signed`](#committing-updates-so-far-commitment_signed)
     52       * [Completing the Transition to the Updated State: `revoke_and_ack`](#completing-the-transition-to-the-updated-state-revoke_and_ack)
     53       * [Updating Fees: `update_fee`](#updating-fees-update_fee)
     54     * [Message Retransmission: `channel_reestablish` message](#message-retransmission)
     55   * [Authors](#authors)
     56 
     57 # Channel
     58 
     59 ## Definition of `channel_id`
     60 
     61 Some messages use a `channel_id` to identify the channel. It's
     62 derived from the funding transaction by combining the `funding_txid`
     63 and the `funding_output_index`, using big-endian exclusive-OR
     64 (i.e. `funding_output_index` alters the last 2 bytes).
     65 
     66 Prior to channel establishment, a `temporary_channel_id` is used,
     67 which is a random nonce.
     68 
     69 Note that as duplicate `temporary_channel_id`s may exist from different
     70 peers, APIs which reference channels by their channel id before the funding
     71 transaction is created are inherently unsafe. The only protocol-provided
     72 identifier for a channel before funding_created has been exchanged is the
     73 (source_node_id, destination_node_id, temporary_channel_id) tuple. Note that
     74 any such APIs which reference channels by their channel id before the funding
     75 transaction is confirmed are also not persistent - until you know the script
     76 pubkey corresponding to the funding output nothing prevents duplicative channel
     77 ids.
     78 
     79 ### `channel_id`, v2
     80 
     81 For channels established using the v2 protocol, the `channel_id` is the
     82 `SHA256(lesser-revocation-basepoint || greater-revocation-basepoint)`,
     83 where the lesser and greater is based off the order of the basepoint.
     84 
     85 When sending `open_channel2`, the peer's revocation basepoint is unknown.
     86 A `temporary_channel_id` must be computed by using a zeroed out basepoint
     87 for the non-initiator.
     88 
     89 When sending `accept_channel2`, the `temporary_channel_id` from `open_channel2`
     90 must be used, to allow the initiator to match the response to its request.
     91 
     92 #### Rationale
     93 
     94 The revocation basepoints must be remembered by both peers for correct
     95 operation anyway. They're known after the first exchange of messages,
     96 obviating the need for a `temporary_channel_id` in subsequent messages.
     97 By mixing information from both sides, they avoid `channel_id` collisions,
     98 and they remove the dependency on the funding txid.
     99 
    100 ## Interactive Transaction Construction
    101 
    102 Interactive transaction construction allows two peers to collaboratively
    103 build a transaction for broadcast.  This protocol is the foundation
    104 for dual-funded channels establishment (v2).
    105 
    106 ### Set-Up and Vocabulary
    107 
    108 There are two parties to a transaction construction: an *initiator*
    109 and a *non-initiator*.
    110 The *initiator* is the peer which initiates the protocol, e.g.
    111 for channel establishment v2 the *initiator* would be the peer which
    112 sends `open_channel2`.
    113 
    114 The protocol makes the following assumptions:
    115 
    116 - The `feerate` for the transaction is known.
    117 - The `dust_limit` for the transaction is known.
    118 - The `nLocktime` for the transaction is known.
    119 - The `nVersion` for the transaction is known.
    120 
    121 ### Fee Responsibility
    122 
    123 The *initiator* is responsible for paying the fees for the following fields,
    124 to be referred to as the `common fields`.
    125 
    126   - version
    127   - segwit marker + flag
    128   - input count
    129   - output count
    130   - locktime
    131 
    132 The rest of the transaction bytes' fees are the responsibility of
    133 the peer who contributed that input or output via `tx_add_input` or
    134 `tx_add_output`, at the agreed upon `feerate`.
    135 
    136 ### Overview
    137 
    138 The *initiator* initiates the interactive transaction construction
    139 protocol with `tx_add_input`. The *non-initiator* responds with any
    140 of `tx_add_input`, `tx_add_output`, `tx_remove_input`, `tx_remove_output`, or
    141 `tx_complete`. The protocol continues with the synchronous exchange
    142 of interactive transaction protocol messages until both nodes have sent
    143 and received a consecutive `tx_complete`. This is a turn-based protocol.
    144 
    145 Once peers have exchanged consecutive `tx_complete`s, the
    146 interactive transaction construction protocol is considered concluded.
    147 Both peers should construct the transaction and fail the negotiation
    148 if an error is discovered.
    149 
    150 This protocol is expressly designed to allow for parallel, multi-party
    151 sessions to collectively construct a single transaction. This preserves
    152 the ability to open multiple channels in a single transaction. While
    153 `serial_id`s are generally chosen randomly, to maintain consistent transaction
    154 ordering across all peer sessions, it is simplest to reuse received
    155 `serial_id`s when forwarding them to other peers, inverting the bottom bit as
    156 necessary to satisfy the parity requirement.
    157 
    158 Here are a few example exchanges.
    159 
    160 #### *initiator* only
    161 
    162 A, the *initiator*, has two inputs and an output (the funding output).
    163 B, the *non-initiator* has nothing to contribute.
    164 
    165         +-------+                       +-------+
    166         |       |--(1)- tx_add_input -->|       |
    167         |       |<-(2)- tx_complete ----|       |
    168         |       |--(3)- tx_add_input -->|       |
    169         |   A   |<-(4)- tx_complete ----|   B   |
    170         |       |--(5)- tx_add_output ->|       |
    171         |       |<-(6)- tx_complete ----|       |
    172         |       |--(7)- tx_complete --->|       |
    173         +-------+                       +-------+
    174 
    175 #### *initiator* and *non-initiator*
    176 
    177 A, the *initiator*, contributes 2 inputs and an output that they
    178 then remove.  B, the *non-initiator*, contributes 1 input and an output,
    179 but waits until A adds a second input before contributing.
    180 
    181 Note that if A does not send a second input, the negotiation will end without
    182 B's contributions.
    183 
    184         +-------+                         +-------+
    185         |       |--(1)- tx_add_input ---->|       |
    186         |       |<-(2)- tx_complete ------|       |
    187         |       |--(3)- tx_add_output --->|       |
    188         |       |<-(4)- tx_complete ------|       |
    189         |       |--(5)- tx_add_input ---->|       |
    190         |   A   |<-(6)- tx_add_input -----|   B   |
    191         |       |--(7)- tx_remove_output >|       |
    192         |       |<-(8)- tx_add_output ----|       |
    193         |       |--(9)- tx_complete ----->|       |
    194         |       |<-(10) tx_complete ------|       |
    195         +-------+                         +-------+
    196 
    197 ### The `tx_add_input` Message
    198 
    199 This message contains a transaction input.
    200 
    201 1. type: 66 (`tx_add_input`)
    202 2. data:
    203     * [`channel_id`:`channel_id`]
    204     * [`u64`:`serial_id`]
    205     * [`u16`:`prevtx_len`]
    206     * [`prevtx_len*byte`:`prevtx`]
    207     * [`u32`:`prevtx_vout`]
    208     * [`u32`:`sequence`]
    209     * [`tx_add_input_tlvs`:`tlvs`]
    210 
    211 1. `tlv_stream`: `tx_add_input_tlvs`
    212 2. types:
    213    1. type: 0 (`shared_input_txid`)
    214    2. data:
    215      * [`sha256`:`funding_txid`]
    216 
    217 #### Requirements
    218 
    219 The sending node:
    220   - MUST add all sent inputs to the transaction
    221   - MUST use a unique `serial_id` for each input currently added to the
    222     transaction
    223   - MUST set `sequence` to be less than or equal to 4294967293 (`0xFFFFFFFD`)
    224   - MUST NOT re-transmit inputs it has received from the peer
    225   - if is the *initiator*:
    226     - MUST send even `serial_id`s
    227   - if is the *non-initiator*:
    228     - MUST send odd `serial_id`s
    229 
    230 The receiving node:
    231   - MUST add all received inputs to the transaction
    232   - MUST fail the negotiation if:
    233     - `sequence` is set to `0xFFFFFFFE` or `0xFFFFFFFF`
    234     - if `prevtx_len` is `0`:
    235       - `shared_input_txid` is not set
    236       - `shared_input_txid` and `prevtx_vout` don't match the previous funding output
    237       - a previously added (and not removed) input already exists with `shared_input_txid` set
    238     - if `prevtx_len` is not `0`:
    239       - `prevtx` and `prevtx_vout` are identical to a previously added (and not removed) input
    240       - `prevtx` is not a valid transaction
    241       - `prevtx_vout` is greater or equal to the number of outputs on `prevtx`
    242       - the `scriptPubKey` of the `prevtx_vout` output of `prevtx` is not exactly a 1-byte push
    243         opcode (for the numeric values `0` to `16`) followed by a data push between 2 and 40 bytes
    244     - the `serial_id` is already included in the transaction
    245     - the `serial_id` has the wrong parity
    246     - if has received 4096 `tx_add_input` messages during this negotiation
    247 
    248 #### Rationale
    249 
    250 Each node must know the set of the transaction inputs. The *non-initiator*
    251 MAY omit this message.
    252 
    253 `serial_id` is a randomly chosen number which uniquely identifies this input.
    254 Inputs in the constructed transaction MUST be sorted by `serial_id`.
    255 
    256 `prevtx` is the serialized transaction that contains the output this input
    257 spends, used to verify that the input is non-malleable. It can be ommitted
    258 (`prevtx_len` set to `0`) when both peers already know that the input is
    259 non-malleable (e.g. when it is the previous funding output).
    260 
    261 `prevtx_vout` is the index of the output being spent.
    262 
    263 `sequence` is the sequence number of this input: it must signal
    264 replaceability, and the same value should be used across implementations
    265 to avoid on-chain fingerprinting.
    266 
    267 #### Liquidity griefing
    268 
    269 When sending `tx_add_input`, senders have no guarantee that the remote node
    270 will complete the protocol in a timely manner. Malicious remote nodes could
    271 delay messages or stop responding, which can result in a partially created
    272 transaction that cannot be broadcast by the honest node. If the honest node
    273 is locking the corresponding UTXO exclusively for this remote node, this can
    274 be exploited to lock up the honest node's liquidity.
    275 
    276 It is thus recommended that implementations keep UTXOs unlocked and actively
    277 reuse them in concurrent sessions, which guarantees that transactions created
    278 with honest nodes double-spend pending transactions with malicious nodes at
    279 no additional cost for the honest node.
    280 
    281 Unfortunately, this will also create conflicts between concurrent sessions
    282 with honest nodes. This is a reasonable trade-off though because:
    283 
    284 * on-chain funding attempts are relatively infrequent operations
    285 * honest nodes should complete the protocol quickly, reducing the risk of
    286   conflicts
    287 * failed attempts can simply be retried at no cost
    288 
    289 ### The `tx_add_output` Message
    290 
    291 This message adds a transaction output.
    292 
    293 1. type: 67 (`tx_add_output`)
    294 2. data:
    295     * [`channel_id`:`channel_id`]
    296     * [`u64`:`serial_id`]
    297     * [`u64`:`sats`]
    298     * [`u16`:`scriptlen`]
    299     * [`scriptlen*byte`:`script`]
    300 
    301 #### Requirements
    302 
    303 Either node:
    304   - MAY omit this message
    305 
    306 The sending node:
    307   - MUST add all sent outputs to the transaction
    308   - if is the *initiator*:
    309     - MUST send even `serial_id`s
    310   - if is the *non-initiator*:
    311     - MUST send odd `serial_id`s
    312 
    313 The receiving node:
    314   - MUST add all received outputs to the transaction
    315   - MUST accept P2WSH, P2WPKH, P2TR `script`s
    316   - MAY fail the negotiation if `script` is non-standard
    317   - MUST fail the negotiation if:
    318     - the `serial_id` is already included in the transaction
    319     - the `serial_id` has the wrong parity
    320     - it has received 4096 `tx_add_output` messages during this negotiation
    321     - the `sats` amount is less than the `dust_limit`
    322     - the `sats` amount is greater than 2,100,000,000,000,000 (`MAX_MONEY`)
    323 
    324 #### Rationale
    325 
    326 Each node must know the set of the transaction outputs.
    327 
    328 `serial_id` is a randomly chosen number which uniquely identifies this output.
    329 Outputs in the constructed transaction MUST be sorted by `serial_id`.
    330 
    331 `sats` is the satoshi value of the output.
    332 
    333 `script` is the scriptPubKey for the output (with its length omitted).
    334 `script`s are not required to follow standardness rules: non-standard
    335 scripts such as `OP_RETURN` may be accepted, but the corresponding
    336 transaction may fail to relay across the network.
    337 
    338 ### The `tx_remove_input` and `tx_remove_output` Messages
    339 
    340 This message removes an input from the transaction.
    341 
    342 1. type: 68 (`tx_remove_input`)
    343 2. data:
    344     * [`channel_id`:`channel_id`]
    345     * [`u64`:`serial_id`]
    346 
    347 This message removes an output from the transaction.
    348 
    349 1. type: 69 (`tx_remove_output`)
    350 2. data:
    351     * [`channel_id`:`channel_id`]
    352     * [`u64`:`serial_id`]
    353 
    354 #### Requirements
    355 
    356 The sending node:
    357   - MUST NOT send a `tx_remove` with a `serial_id` it did not add
    358     to the transaction or has already been removed
    359 
    360 The receiving node:
    361   - MUST remove the indicated input or output from the transaction
    362   - MUST fail the negotiation if:
    363     - the input or output identified by the `serial_id` was not added by the
    364       sender
    365     - the `serial_id` does not correspond to a currently added input (or output)
    366 
    367 ### The `tx_complete` Message
    368 
    369 This message signals the conclusion of a peer's transaction
    370 contributions.
    371 
    372 1. type: 70 (`tx_complete`)
    373 2. data:
    374     * [`channel_id`:`channel_id`]
    375 
    376 #### Requirements
    377 
    378 The nodes:
    379   - MUST send this message in succession to conclude this protocol
    380 
    381 The receiving node:
    382   - MUST use the negotiated inputs and outputs to construct a transaction
    383   - MUST fail the negotiation if:
    384     - the peer's total input satoshis is less than their outputs. One MUST
    385       account for the peer's portion of the funding output when verifying
    386       compliance with this requirement.
    387     - the peer's paid feerate does not meet or exceed the agreed `feerate`
    388       (based on the `minimum fee`).
    389     - if is the *non-initiator*:
    390       - the *initiator*'s fees do not cover the `common` fields
    391     - there are more than 252 inputs
    392     - there are more than 252 outputs
    393     - the estimated weight of the tx is greater than 400,000 (`MAX_STANDARD_TX_WEIGHT`)
    394 
    395 #### Rationale
    396 
    397 To signal the conclusion of exchange of transaction inputs and outputs.
    398 
    399 Upon successful exchange of `tx_complete` messages, both nodes
    400 should construct the transaction and proceed to the next portion of the
    401 protocol. For channel establishment v2, exchanging commitment transactions.
    402 
    403 For the `minimum fee` calculation see [BOLT #3](03-transactions.md#calculating-fees-for-collaborative-transaction-construction).
    404 
    405 The maximum inputs and outputs are capped at 252. This effectively fixes
    406 the byte size of the input and output counts on the transaction to one (1).
    407 
    408 ### The `tx_signatures` Message
    409 
    410 1. type: 71 (`tx_signatures`)
    411 2. data:
    412     * [`channel_id`:`channel_id`]
    413     * [`sha256`:`txid`]
    414     * [`u16`:`num_witnesses`]
    415     * [`num_witnesses*witness`:`witnesses`]
    416     * [`tx_signatures_tlvs`:`tlvs`]
    417 
    418 1. subtype: `witness`
    419 2. data:
    420     * [`u16`:`len`]
    421     * [`len*byte`:`witness_data`]
    422 
    423 1. `tlv_stream`: `tx_signatures_tlvs`
    424 2. types:
    425    1. type: 0 (`shared_input_signature`)
    426    2. data:
    427      * [`signature`:`signature`]
    428 
    429 #### Requirements
    430 
    431 The sending node:
    432   - if it has the lowest total satoshis contributed, as defined by total
    433     `tx_add_input` values, or both peers have contributed equal amounts
    434     but it has the lowest `node_id` (sorted lexicographically):
    435     - MUST transmit their `tx_signatures` first
    436   - MUST order the `witnesses` by the `serial_id` of the input they
    437     correspond to
    438   - `num_witnesses`s MUST equal the number of inputs they added
    439   - MUST use the `SIGHASH_ALL` (0x01) flag on each signature
    440 
    441 The receiving node:
    442   - MUST fail the negotiation if:
    443     - the message contains an empty `witness`
    444     - the number of `witnesses` does not equal the number of inputs
    445       added by the sending node
    446     - the `txid` does not match the txid of the transaction
    447     - the `witnesses` are non-standard
    448     - a signature uses a flag that is not `SIGHASH_ALL` (0x01)
    449   - SHOULD apply the `witnesses` to the transaction and broadcast it
    450   - MUST reply with their `tx_signatures` if not already transmitted
    451 
    452 #### Rationale
    453 
    454 A strict ordering is used to decide which peer sends `tx_signatures` first.
    455 This prevents deadlocks where each peer is waiting for the other peer to
    456 send `tx_signatures`, and enables multiparty tx collaboration.
    457 
    458 The `witness_data` is encoded as per bitcoin's wire protocol (a CompactSize number
    459 of elements, with each element a CompactSize length and that many bytes following).
    460 
    461 While the `minimum fee` is calculated and verified at `tx_complete` conclusion,
    462 it is possible for the fee for the exchanged witness data to be underpaid.
    463 It is the responsibility of the sending peer to correctly account for the
    464 required fee.
    465 
    466 ### The `tx_init_rbf` Message
    467 
    468 This message initiates a replacement of the transaction after it's been
    469 completed.
    470 
    471 1. type: 72 (`tx_init_rbf`)
    472 2. data:
    473    * [`channel_id`:`channel_id`]
    474    * [`u32`:`locktime`]
    475    * [`u32`:`feerate`]
    476    * [`tx_init_rbf_tlvs`:`tlvs`]
    477 
    478 1. `tlv_stream`: `tx_init_rbf_tlvs`
    479 2. types:
    480     1. type: 0 (`funding_output_contribution`)
    481     2. data:
    482         * [`s64`:`satoshis`]
    483    1. type: 2 (`require_confirmed_inputs`)
    484 
    485 #### Requirements
    486 
    487 The sender:
    488   - MUST set `feerate` greater than or equal to the maximum of:
    489     - 25/24 times the `feerate` of the previously constructed transaction,
    490       rounded down.
    491     - 25 sat per kw greater than the `feerate` of the previously
    492       constructed transaction.
    493   - If it contributes to the transaction's funding output:
    494     - MUST set `funding_output_contribution`
    495   - If it requires the receiving node to only use confirmed inputs:
    496     - MUST set `require_confirmed_inputs`
    497   - If it contributed to previous transactions:
    498     - MUST ensure that the new transaction double-spends all other attempts,
    499       by sending `tx_add_input` with at least one input
    500       from each previous transaction construction attempt.
    501 
    502 The recipient:
    503   - MUST respond either with `tx_abort` or with `tx_ack_rbf`
    504   - MUST respond with `tx_abort` if:
    505     - the `feerate` is not greater than or equal to the maximum of:
    506       - 25/24 times the `feerate` of the last successfully constructed
    507         transaction, rounded down.
    508       - 25 sat per kw greater than the `feerate` of the last successfully
    509         constructed transaction
    510   - MAY send `tx_abort` for any reason
    511   - MUST fail the negotiation if:
    512     - `require_confirmed_inputs` is set but it cannot provide confirmed inputs
    513 
    514 #### Rationale
    515 
    516 `feerate` is the feerate this transaction will pay. It must be at least
    517 the maximum of 25/24 times the previous `feerate` (rounded down) and 25
    518 sat per kw above the previous `feerate`. The multiplicative rule ensures
    519 progress at higher feerates, while the additive floor of 25 sat per kw
    520 (0.1 sat/vB) ensures that the replacement transaction meets BIP125's
    521 minimum relay fee requirement (default `incrementalRelayFee` of 0.1
    522 sat/vB since Bitcoin Core v30.0), which the multiplicative increase alone
    523 could fail to satisfy at low feerates.
    524 
    525 E.g. if the last `feerate` was 520, the next sent `feerate` must be at
    526 least 545 (max(520 * 25 / 24, 520 + 25) = max(541, 545) = 545).
    527 
    528 If the previous transaction confirms in the middle of an RBF attempt,
    529 the attempt MUST be abandoned.
    530 
    531 `funding_output_contribution` is the amount of satoshis that this peer
    532 will contribute to the funding output of the transaction, when there is
    533 such an output. Note that it may be different from the contribution
    534 made in the previously completed transaction. If omitted, the sender is
    535 not contributing to the funding output.
    536 
    537 ### The `tx_ack_rbf` Message
    538 
    539 1. type: 73 (`tx_ack_rbf`)
    540 2. data:
    541    * [`channel_id`:`channel_id`]
    542    * [`tx_ack_rbf_tlvs`:`tlvs`]
    543 
    544 
    545 1. `tlv_stream`: `tx_ack_rbf_tlvs`
    546 2. types:
    547     1. type: 0 (`funding_output_contribution`)
    548     2. data:
    549         * [`s64`:`satoshis`]
    550    1. type: 2 (`require_confirmed_inputs`)
    551 
    552 #### Requirements
    553 
    554 The sender:
    555   - If it contributes to the transaction's funding output:
    556     - MUST set `funding_output_contribution`
    557   - If it requires the receiving node to only use confirmed inputs:
    558     - MUST set `require_confirmed_inputs`
    559   - If it contributed to previous transactions:
    560     - MUST ensure that the new transaction double-spends all other attempts,
    561       by sending `tx_add_input` with at least one input
    562       from each previous transaction construction attempt.
    563 
    564 The recipient:
    565   - MUST respond with `tx_abort` or with a `tx_add_input` message,
    566     restarting the interactive tx collaboration protocol.
    567   - MUST fail the negotiation if:
    568     - `require_confirmed_inputs` is set but it cannot provide confirmed inputs
    569 
    570 #### Rationale
    571 
    572 `funding_output_contribution` is the amount of satoshis that this peer
    573 will contribute to the funding output of the transaction, when there is
    574 such an output. Note that it may be different from the contribution
    575 made in the previously completed transaction. If omitted, the sender is
    576 not contributing to the funding output.
    577 
    578 It's recommended that a peer, rather than fail the RBF negotiation due to
    579 a large feerate change, instead stop contributing to the funding output,
    580 and decline to participate further in the transaction (by not contributing,
    581 they may obtain incoming liquidity at no cost).
    582 
    583 ### The `tx_abort` Message
    584 
    585 1. type: 74 (`tx_abort`)
    586 2. data:
    587    * [`channel_id`:`channel_id`]
    588    * [`u16`:`len`]
    589    * [`len*byte`:`data`]
    590 
    591 #### Requirements
    592 
    593 A sending node:
    594   - MUST NOT have already transmitted `tx_signatures`
    595   - SHOULD forget the current negotiation and reset their state.
    596   - MAY send an empty `data` field.
    597   - when failure was caused by an invalid signature check:
    598     - SHOULD include the raw, hex-encoded transaction in reply to a
    599       `tx_signatures` or `commitment_signed` message.
    600 
    601 A receiving node:
    602   - if they have already sent `tx_signatures` to the peer:
    603     - MUST NOT forget the channel until any inputs to the negotiated tx
    604       have been spent.
    605   - if they have not sent `tx_signatures`:
    606     - SHOULD forget the current negotiation and reset their state.
    607   - if they have not sent `tx_abort`:
    608     - MUST echo back `tx_abort`
    609   - if `data` is not composed solely of printable ASCII characters (For
    610     reference: the printable character set includes byte values 32 through
    611     126, inclusive):
    612     - SHOULD NOT print out `data` verbatim.
    613 
    614 #### Rationale
    615 
    616 A receiving node, if they've already sent their `tx_signatures` has no guarantee
    617 that the transaction won't be signed and published by their peer. They must remember
    618 the transaction and channel (if appropriate) until the transaction is no longer
    619 eligible to be spent (i.e. any input has been spent in a different transaction).
    620 
    621 The `tx_abort` message allows for the cancellation of an in progress negotiation,
    622 and a return to the initial starting state. It is distinct from the `error`
    623 message, which triggers a channel close.
    624 
    625 Echoing back `tx_abort` allows the peer to ack that they've seen the abort message,
    626 permitting the originating peer to terminate the in-flight process without
    627 worrying about stale messages.
    628 
    629 ## Channel Establishment v1
    630 
    631 After authenticating and initializing a connection ([BOLT #8](08-transport.md)
    632 and [BOLT #1](01-messaging.md#the-init-message), respectively), channel establishment may begin.
    633 
    634 There are two pathways for establishing a channel, a legacy version presented here,
    635 and a second version ([below](#channel-establishment-v2)). Which channel
    636 establishment protocols are available for use is negotiated in the `init` message.
    637 
    638 This consists of the funding node (funder) sending an `open_channel` message,
    639 followed by the responding node (fundee) sending `accept_channel`. With the
    640 channel parameters locked in, the funder is able to create the funding
    641 transaction and both versions of the commitment transaction, as described in
    642 [BOLT #3](03-transactions.md#bolt-3-bitcoin-transaction-and-script-formats).
    643 The funder then sends the outpoint of the funding output with the `funding_created`
    644 message, along with the signature for the fundee's version of the commitment
    645 transaction. Once the fundee learns the funding outpoint, it's able to
    646 generate the signature for the funder's version of the commitment transaction and send it
    647 over using the `funding_signed` message.
    648 
    649 Once the channel funder receives the `funding_signed` message, it
    650 must broadcast the funding transaction to the Bitcoin network. After
    651 the `funding_signed` message is sent/received, both sides should wait
    652 for the funding transaction to enter the blockchain and reach the
    653 specified depth (number of confirmations). After both sides have sent
    654 the `channel_ready` message, the channel is established and can begin
    655 normal operation. The `channel_ready` message includes information
    656 that will be used to construct channel authentication proofs.
    657 
    658         +-------+                              +-------+
    659         |       |--(1)---  open_channel  ----->|       |
    660         |       |<-(2)--  accept_channel  -----|       |
    661         |       |                              |       |
    662         |   A   |--(3)--  funding_created  --->|   B   |
    663         |       |<-(4)--  funding_signed  -----|       |
    664         |       |                              |       |
    665         |       |--(5)---  channel_ready  ---->|       |
    666         |       |<-(6)---  channel_ready  -----|       |
    667         +-------+                              +-------+
    668 
    669         - where node A is 'funder' and node B is 'fundee'
    670 
    671 If this fails at any stage, or if one node decides the channel terms
    672 offered by the other node are not suitable, the channel establishment
    673 fails.
    674 
    675 Note that multiple channels can operate in parallel, as all channel
    676 messages are identified by either a `temporary_channel_id` (before the
    677 funding transaction is created) or a `channel_id` (derived from the
    678 funding transaction).
    679 
    680 ### The `open_channel` Message
    681 
    682 This message contains information about a node and indicates its
    683 desire to set up a new channel. This is the first step toward creating
    684 the funding transaction and both versions of the commitment transaction.
    685 
    686 1. type: 32 (`open_channel`)
    687 2. data:
    688    * [`chain_hash`:`chain_hash`]
    689    * [`32*byte`:`temporary_channel_id`]
    690    * [`u64`:`funding_satoshis`]
    691    * [`u64`:`push_msat`]
    692    * [`u64`:`dust_limit_satoshis`]
    693    * [`u64`:`max_htlc_value_in_flight_msat`]
    694    * [`u64`:`channel_reserve_satoshis`]
    695    * [`u64`:`htlc_minimum_msat`]
    696    * [`u32`:`feerate_per_kw`]
    697    * [`u16`:`to_self_delay`]
    698    * [`u16`:`max_accepted_htlcs`]
    699    * [`point`:`funding_pubkey`]
    700    * [`point`:`revocation_basepoint`]
    701    * [`point`:`payment_basepoint`]
    702    * [`point`:`delayed_payment_basepoint`]
    703    * [`point`:`htlc_basepoint`]
    704    * [`point`:`first_per_commitment_point`]
    705    * [`byte`:`channel_flags`]
    706    * [`open_channel_tlvs`:`tlvs`]
    707 
    708 1. `tlv_stream`: `open_channel_tlvs`
    709 2. types:
    710     1. type: 0 (`upfront_shutdown_script`)
    711     2. data:
    712         * [`...*byte`:`shutdown_scriptpubkey`]
    713     1. type: 1 (`channel_type`)
    714     2. data:
    715         * [`...*byte`:`type`]
    716 
    717 The `chain_hash` value denotes the exact blockchain that the opened channel will
    718 reside within. This is usually the genesis hash of the respective blockchain.
    719 The existence of the `chain_hash` allows nodes to open channels
    720 across many distinct blockchains as well as have channels within multiple
    721 blockchains opened to the same peer (if it supports the target chains).
    722 
    723 The `temporary_channel_id` is used to identify this channel on a per-peer basis until the
    724 funding transaction is established, at which point it is replaced
    725 by the `channel_id`, which is derived from the funding transaction.
    726 
    727 `funding_satoshis` is the amount the sender is putting into the
    728 channel. `push_msat` is an amount of initial funds that the sender is
    729 unconditionally giving to the receiver. `dust_limit_satoshis` is the
    730 threshold below which outputs should not be generated for this node's
    731 commitment or HTLC transactions (i.e. HTLCs below this amount plus
    732 HTLC transaction fees are not enforceable on-chain). This reflects the
    733 reality that tiny outputs are not considered standard transactions and
    734 will not propagate through the Bitcoin network. `channel_reserve_satoshis`
    735 is the minimum amount that the other node is to keep as a direct
    736 payment. `htlc_minimum_msat` indicates the smallest value HTLC this
    737 node will accept.
    738 
    739 `max_htlc_value_in_flight_msat` is a cap on total value of outstanding
    740 HTLCs offered by the remote node, which allows the local node to limit its
    741 exposure to HTLCs; similarly, `max_accepted_htlcs` limits the number of
    742 outstanding HTLCs the remote node can offer.
    743 
    744 `feerate_per_kw` indicates the initial fee rate in satoshi per 1000-weight
    745 (i.e. 1/4 the more normally-used 'satoshi per 1000 vbytes') that this
    746 side will pay for commitment and HTLC transactions, as described in
    747 [BOLT #3](03-transactions.md#fee-calculation) (this can be adjusted
    748 later with an `update_fee` message).
    749 
    750 `to_self_delay` is the number of blocks that the other node's to-self
    751 outputs must be delayed, using `OP_CHECKSEQUENCEVERIFY` delays; this
    752 is how long it will have to wait in case of breakdown before redeeming
    753 its own funds.
    754 
    755 `funding_pubkey` is the public key in the 2-of-2 multisig script of
    756 the funding transaction output.
    757 
    758 The various `_basepoint` fields are used to derive unique
    759 keys as described in [BOLT #3](03-transactions.md#key-derivation) for each commitment
    760 transaction. Varying these keys ensures that the transaction ID of
    761 each commitment transaction is unpredictable to an external observer,
    762 even if one commitment transaction is seen; this property is very
    763 useful for preserving privacy when outsourcing penalty transactions to
    764 third parties.
    765 
    766 `first_per_commitment_point` is the per-commitment point to be used
    767 for the first commitment transaction,
    768 
    769 Only the least-significant bit of `channel_flags` is currently
    770 defined: `announce_channel`. This indicates whether the initiator of
    771 the funding flow wishes to advertise this channel publicly to the
    772 network, as detailed within [BOLT #7](07-routing-gossip.md#bolt-7-p2p-node-and-channel-discovery).
    773 
    774 The `shutdown_scriptpubkey` allows the sending node to commit to where
    775 funds will go on mutual close, which the remote node should enforce
    776 even if a node is compromised later.
    777 
    778 The `option_support_large_channel` is a feature used to let everyone 
    779 know this node will accept `funding_satoshis` greater than or equal to 2^24.
    780 Since it's broadcast in the `node_announcement` message other nodes can use it to identify peers 
    781 willing to accept large channel even before exchanging the `init` message with them. 
    782 
    783 #### Defined Channel Types
    784 
    785 Channel types are an explicit enumeration: for convenience of future
    786 definitions they reuse even feature bits, but they are not an
    787 arbitrary combination (they represent the persistent features which
    788 affect the channel operation).
    789 
    790 The currently defined basic types are:
    791   - `option_static_remotekey` (bit 12)
    792   - `option_anchors` and `option_static_remotekey` (bits 22 and 12)
    793   - `zero_fee_commitments` (bit 40)
    794 
    795 Each basic type has the following variations allowed:
    796   - `option_scid_alias` (bit 46)
    797   - `option_zeroconf` (bit 50)
    798 
    799 #### Requirements
    800 
    801 The sending node:
    802   - MUST ensure the `chain_hash` value identifies the chain it wishes to open the channel within.
    803   - MUST ensure `temporary_channel_id` is unique from any other channel ID with the same peer.
    804   - if both nodes advertised `option_support_large_channel`:
    805     - MAY set `funding_satoshis` greater than or equal to 2^24 satoshi.
    806   - otherwise:
    807     - MUST set `funding_satoshis` to less than 2^24 satoshi.
    808   - MUST set `push_msat` to equal or less than 1000 * `funding_satoshis`.
    809   - MUST set `funding_pubkey`, `revocation_basepoint`, `htlc_basepoint`, `payment_basepoint`, and `delayed_payment_basepoint` to valid secp256k1 pubkeys in compressed format.
    810   - MUST set `first_per_commitment_point` to the per-commitment point to be used for the initial commitment transaction, derived as specified in [BOLT #3](03-transactions.md#per-commitment-secret-requirements).
    811   - MUST set `channel_reserve_satoshis` greater than or equal to `dust_limit_satoshis`.
    812   - MUST set undefined bits in `channel_flags` to 0.
    813   - if both nodes advertised the `option_upfront_shutdown_script` feature:
    814     - MUST include `upfront_shutdown_script` with either a valid `shutdown_scriptpubkey` as required by `shutdown` `scriptpubkey`, or a zero-length `shutdown_scriptpubkey` (ie. `0x0000`).
    815   - otherwise:
    816     - MAY include `upfront_shutdown_script`.
    817   - if it includes `open_channel_tlvs`:
    818     - MUST include `upfront_shutdown_script`.
    819     - MUST set `channel_type`:
    820       - MUST set it to a defined type representing the type it wants.
    821       - MUST use the smallest bitmap possible to represent the channel type.
    822       - SHOULD NOT set it to a type containing a feature which was not negotiated.
    823       - if `channel_type` includes `zero_fee_commitments`:
    824         - MUST set `feerate_per_kw` to `0`.
    825       - if `announce_channel` is `true` (not `0`):
    826         - MUST NOT send `channel_type` with the `option_scid_alias` bit set.
    827 
    828 The sending node SHOULD:
    829   - set `to_self_delay` sufficient to ensure the sender can irreversibly spend a commitment transaction output, in case of misbehavior by the receiver.
    830   - set `dust_limit_satoshis` to a sufficient value to allow commitment transactions to propagate through the Bitcoin network.
    831   - set `htlc_minimum_msat` to the minimum value HTLC it's willing to accept from this peer.
    832   - when using `zero_fee_commitments` or `option_anchors`:
    833     - set `dust_limit_satoshis` to a sufficient value to ensure that it is economical to spend, taking the cost of HTLC transactions into account.
    834   - otherwise (not using `zero_fee_commitments` or `option_anchors`):
    835     - set `feerate_per_kw` to at least the rate it estimates would cause the transaction to be immediately included in a block.
    836 
    837 The receiving node MUST:
    838   - ignore undefined bits in `channel_flags`.
    839   - if the message doesn't include a `channel_type`:
    840     - fail the channel.
    841   - if the connection has been re-established after receiving a previous
    842  `open_channel`, BUT before receiving a `funding_created` message:
    843     - accept a new `open_channel` message.
    844     - discard the previous `open_channel` message.
    845   - if `option_dual_fund` has been negotiated:
    846     - fail the channel.
    847 
    848 The receiving node MAY fail the channel if:
    849   - `announce_channel` is `false` (`0`), yet it wishes to publicly announce the channel.
    850   - `funding_satoshis` is too small.
    851   - it considers `htlc_minimum_msat` too large.
    852   - it considers `max_htlc_value_in_flight_msat` too small.
    853   - it considers `channel_reserve_satoshis` too large.
    854   - it considers `max_accepted_htlcs` too small.
    855   - it considers `dust_limit_satoshis` too large (see [BOLT 3](03-transactions.md#dust-limits)).
    856 
    857 The receiving node MUST fail the channel if:
    858   - the `chain_hash` value is set to a hash of a chain that is unknown to the receiver.
    859   - `push_msat` is greater than `funding_satoshis` * 1000.
    860   - `to_self_delay` is unreasonably large.
    861   - `channel_type` includes `zero_fee_commitments` and:
    862     - `max_accepted_htlcs` is greater than 114.
    863     - `feerate_per_kw` is not `0`.
    864   - `channel_type` does not include `zero_fee_commitments` and:
    865     - `max_accepted_htlcs` is greater than 483.
    866     - it considers `feerate_per_kw` too small for timely processing or unreasonably large.
    867   - `funding_pubkey`, `revocation_basepoint`, `htlc_basepoint`, `payment_basepoint`, or `delayed_payment_basepoint`
    868 are not valid secp256k1 pubkeys in compressed format.
    869   - `dust_limit_satoshis` is greater than `channel_reserve_satoshis`.
    870   - `dust_limit_satoshis` is smaller than `354 satoshis` (see [BOLT 3](03-transactions.md#dust-limits)).
    871   - the funder's amount for the initial commitment transaction is not sufficient for full [fee payment](03-transactions.md#fee-payment).
    872   - both `to_local` and `to_remote` amounts for the initial commitment transaction are less than or equal to `channel_reserve_satoshis` (see [BOLT 3](03-transactions.md#commitment-transaction-outputs)).
    873   - `funding_satoshis` is greater than or equal to 2^24 and the receiver does not support `option_support_large_channel`.
    874   - the `channel_type` is not suitable.
    875   - the `channel_type` includes `option_zeroconf` and it does not trust the sender to open an unconfirmed channel.
    876 
    877 The receiving node MUST NOT:
    878   - consider funds received, using `push_msat`, to be received until the funding transaction has reached sufficient depth.
    879 
    880 #### Rationale
    881 
    882 The requirement for `funding_satoshis` to be less than 2^24 satoshi was a temporary self-imposed limit while implementations were not yet considered stable, it can be lifted by advertising `option_support_large_channel`.
    883 
    884 The *channel reserve* is specified by the peer's `channel_reserve_satoshis`: 1% of the channel total is suggested. Each side of a channel maintains this reserve so it always has something to lose if it were to try to broadcast an old, revoked commitment transaction. Initially, this reserve may not be met, as only one side has funds; but the protocol ensures that there is always progress toward meeting this reserve, and once met, it is maintained.
    885 
    886 The sender can unconditionally give initial funds to the receiver using a non-zero `push_msat`, but even in this case we ensure that the funder has sufficient remaining funds to pay fees and that one side has some amount it can spend (which also implies there is at least one non-dust output). Note that, like any other on-chain transaction, this payment is not certain until the funding transaction has been confirmed sufficiently (with a danger of double-spend until this occurs) and may require a separate method to prove payment via on-chain confirmation.
    887 
    888 The `feerate_per_kw` is generally only of concern to the sender (who pays the fees), but there is also the fee rate paid by HTLC transactions; thus, unreasonably large fee rates can also penalize the recipient.
    889 
    890 Separating the `htlc_basepoint` from the `payment_basepoint` improves security: a node needs the secret associated with the `htlc_basepoint` to produce HTLC signatures for the protocol, but the secret for the `payment_basepoint` can be in cold storage.
    891 
    892 The requirement that `channel_reserve_satoshis` is not considered dust
    893 according to `dust_limit_satoshis` eliminates cases where all outputs
    894 would be eliminated as dust.  The similar requirements in
    895 `accept_channel` ensure that both sides' `channel_reserve_satoshis`
    896 are above both `dust_limit_satoshis`.
    897 
    898 The receiver should not accept large `dust_limit_satoshis`, as this could be
    899 used in griefing attacks, where the peer publishes its commitment with a lot
    900 of dust htlcs, which effectively become miner fees. But it must allow values
    901 higher than the standard Bitcoin Core dust limits, since HTLC outputs need to
    902 be spent by a second-stage transaction at a feerate matching the current
    903 on-chain feerate.
    904 
    905 Details for how to handle a channel failure can be found in [BOLT 5:Failing a Channel](05-onchain.md#failing-a-channel).
    906 
    907 ### The `accept_channel` Message
    908 
    909 This message contains information about a node and indicates its
    910 acceptance of the new channel. This is the second step toward creating the
    911 funding transaction and both versions of the commitment transaction.
    912 
    913 1. type: 33 (`accept_channel`)
    914 2. data:
    915    * [`32*byte`:`temporary_channel_id`]
    916    * [`u64`:`dust_limit_satoshis`]
    917    * [`u64`:`max_htlc_value_in_flight_msat`]
    918    * [`u64`:`channel_reserve_satoshis`]
    919    * [`u64`:`htlc_minimum_msat`]
    920    * [`u32`:`minimum_depth`]
    921    * [`u16`:`to_self_delay`]
    922    * [`u16`:`max_accepted_htlcs`]
    923    * [`point`:`funding_pubkey`]
    924    * [`point`:`revocation_basepoint`]
    925    * [`point`:`payment_basepoint`]
    926    * [`point`:`delayed_payment_basepoint`]
    927    * [`point`:`htlc_basepoint`]
    928    * [`point`:`first_per_commitment_point`]
    929    * [`accept_channel_tlvs`:`tlvs`]
    930 
    931 1. `tlv_stream`: `accept_channel_tlvs`
    932 2. types:
    933     1. type: 0 (`upfront_shutdown_script`)
    934     2. data:
    935         * [`...*byte`:`shutdown_scriptpubkey`]
    936     1. type: 1 (`channel_type`)
    937     2. data:
    938         * [`...*byte`:`type`]
    939 
    940 #### Requirements
    941 
    942 The `temporary_channel_id` MUST be the same as the `temporary_channel_id` in
    943 the `open_channel` message.
    944 
    945 The sender:
    946   - if `channel_type` includes `option_zeroconf`:
    947     - MUST set `minimum_depth` to zero.
    948   - otherwise:
    949     - SHOULD set `minimum_depth` to a number of blocks it considers reasonable to avoid double-spending of the funding transaction.
    950   - MUST set `channel_reserve_satoshis` greater than or equal to `dust_limit_satoshis` from the `open_channel` message.
    951   - MUST set `dust_limit_satoshis` less than or equal to `channel_reserve_satoshis` from the `open_channel` message.
    952   - MUST set `channel_type` to the `channel_type` from `open_channel`.
    953 
    954 The receiver:
    955   - if `minimum_depth` is unreasonably large:
    956     - MAY fail the channel.
    957   - if `channel_reserve_satoshis` is less than `dust_limit_satoshis` within the `open_channel` message:
    958     - MUST fail the channel.
    959   - if `channel_reserve_satoshis` from the `open_channel` message is less than `dust_limit_satoshis`:
    960     - MUST fail the channel.
    961   - if the message doesn't include a `channel_type`:
    962     - MUST fail the channel.
    963   - if `channel_type` does not match the `channel_type` from `open_channel`:
    964     - MUST fail the channel.
    965 
    966 Other fields have the same requirements as their counterparts in `open_channel`.
    967 
    968 ### The `funding_created` Message
    969 
    970 This message describes the outpoint which the funder has created for
    971 the initial commitment transactions. After receiving the peer's
    972 signature, via `funding_signed`, it will broadcast the funding transaction.
    973 
    974 1. type: 34 (`funding_created`)
    975 2. data:
    976     * [`32*byte`:`temporary_channel_id`]
    977     * [`sha256`:`funding_txid`]
    978     * [`u16`:`funding_output_index`]
    979     * [`signature`:`signature`]
    980 
    981 #### Requirements
    982 
    983 The sender MUST set:
    984   - `temporary_channel_id` the same as the `temporary_channel_id` in the `open_channel` message.
    985   - `funding_txid` to the transaction ID of a non-malleable transaction,
    986     - and MUST NOT broadcast this transaction.
    987   - `funding_output_index` to the output number of that transaction that corresponds the funding transaction output, as defined in [BOLT #3](03-transactions.md#funding-transaction-output).
    988   - `signature` to the valid signature using its `funding_pubkey` for the initial commitment transaction, as defined in [BOLT #3](03-transactions.md#commitment-transaction).
    989 
    990 The sender:
    991   - when creating the funding transaction:
    992     - SHOULD use only BIP141 (Segregated Witness) inputs.
    993     - SHOULD ensure the funding transaction confirms in the next 2016 blocks.
    994 
    995 The recipient:
    996   - if `signature` is incorrect OR non-compliant with LOW-S-standard rule<sup>[LOWS](https://github.com/bitcoin/bitcoin/pull/6769)</sup>:
    997     - MUST send a `warning` and close the connection, or send an
    998       `error` and fail the channel.
    999 
   1000 #### Rationale
   1001 
   1002 The `funding_output_index` can only be 2 bytes, since that's how it's packed into the `channel_id` and used throughout the gossip protocol. The limit of 65535 outputs should not be overly burdensome.
   1003 
   1004 A transaction with all Segregated Witness inputs is not malleable, hence the funding transaction recommendation.
   1005 
   1006 The funder may use CPFP on a change output to ensure that the funding transaction confirms before 2016 blocks,
   1007 otherwise the fundee may forget that channel.
   1008 
   1009 ### The `funding_signed` Message
   1010 
   1011 This message gives the funder the signature it needs for the first
   1012 commitment transaction, so it can broadcast the transaction knowing that funds
   1013 can be redeemed, if need be.
   1014 
   1015 This message introduces the `channel_id` to identify the channel. It's derived from the funding transaction by combining the `funding_txid` and the `funding_output_index`, using big-endian exclusive-OR (i.e. `funding_output_index` alters the last 2 bytes).
   1016 
   1017 1. type: 35 (`funding_signed`)
   1018 2. data:
   1019     * [`channel_id`:`channel_id`]
   1020     * [`signature`:`signature`]
   1021 
   1022 #### Requirements
   1023 
   1024 Both peers:
   1025   - MUST use the negotiated `channel_type` for all commitment transactions.
   1026 
   1027 The sender MUST set:
   1028   - `channel_id` by exclusive-OR of the `funding_txid` and the `funding_output_index` from the `funding_created` message.
   1029   - `signature` to the valid signature, using its `funding_pubkey` for the initial commitment transaction, as defined in [BOLT #3](03-transactions.md#commitment-transaction).
   1030 
   1031 The recipient:
   1032   - if `signature` is incorrect OR non-compliant with LOW-S-standard rule<sup>[LOWS](https://github.com/bitcoin/bitcoin/pull/6769)</sup>:
   1033     - MUST send a `warning` and close the connection, or send an
   1034       `error` and fail the channel.
   1035   - MUST NOT broadcast the funding transaction before receipt of a valid `funding_signed`.
   1036   - on receipt of a valid `funding_signed`:
   1037     - SHOULD broadcast the funding transaction.
   1038 
   1039 #### Rationale
   1040 
   1041 We generate the commitment transaction at this point, using the `channel_type`
   1042 that was communicated in the `open_channel` and `accept_channel` messages.
   1043 This `channel_type` determines the channel commitment format for the total
   1044 lifetime of the channel.
   1045 
   1046 ### The `channel_ready` Message
   1047 
   1048 This message (which used to be called `funding_locked`) indicates that the funding transaction has sufficient confirms for channel use. Once both nodes have sent this, the channel enters normal operating mode.
   1049 
   1050 Note that the opener is free to send this message at any time (since it presumably trusts itself), but the
   1051 accepter would usually wait until the funding has reached the `minimum_depth` asked for in `accept_channel`.
   1052 
   1053 1. type: 36 (`channel_ready`)
   1054 2. data:
   1055     * [`channel_id`:`channel_id`]
   1056     * [`point`:`second_per_commitment_point`]
   1057     * [`channel_ready_tlvs`:`tlvs`]
   1058 
   1059 1. `tlv_stream`: `channel_ready_tlvs`
   1060 2. types:
   1061     1. type: 1 (`short_channel_id`)
   1062     2. data:
   1063         * [`short_channel_id`:`alias`]
   1064 
   1065 #### Requirements
   1066 
   1067 The sender:
   1068   - MUST NOT send `channel_ready` unless outpoint of given by `funding_txid` and
   1069    `funding_output_index` in the `funding_created` message pays exactly `funding_satoshis` to the scriptpubkey specified in [BOLT #3](03-transactions.md#funding-transaction-output).
   1070   - if it is not the node opening the channel:
   1071     - SHOULD wait until the funding transaction has reached `minimum_depth` before
   1072       sending this message.
   1073     - MUST wait for at least 100 blocks if the funding transaction is the coinbase transaction.
   1074   - MUST set `second_per_commitment_point` to the per-commitment point to be used
   1075   for commitment transaction #1, derived as specified in
   1076   [BOLT #3](03-transactions.md#per-commitment-secret-requirements).
   1077   - if `option_scid_alias` was negotiated:
   1078     - MUST set `short_channel_id` `alias`.
   1079   - otherwise:
   1080     - MAY set `short_channel_id` `alias`.
   1081   - if it sets `alias`:
   1082     - if the `announce_channel` bit was set in `open_channel`:
   1083       - SHOULD initially set `alias` to value not related to the real `short_channel_id`.
   1084     - otherwise:
   1085       - MUST set `alias` to a value not related to the real `short_channel_id`.
   1086     - MUST NOT send the same `alias` for multiple peers or use an alias which
   1087       collides with a `short_channel_id`  of a channel on the same node.
   1088     - MUST always recognize the `alias` as a `short_channel_id` for incoming HTLCs to this channel.
   1089     - if `channel_type` has `option_scid_alias` set:
   1090       - MUST NOT allow incoming HTLCs to this channel using the real `short_channel_id`
   1091     - MAY send multiple `channel_ready` messages to the same peer with different `alias` values.
   1092   - otherwise:
   1093     - MUST wait until the funding transaction has reached `minimum_depth` before sending this message.
   1094 
   1095 
   1096 The sender:
   1097 
   1098 A non-funding node (fundee):
   1099   - SHOULD forget the channel if it does not see the correct funding
   1100     transaction after a timeout of 2016 blocks.
   1101 
   1102 The receiver:
   1103   - MAY use any of the `alias` it received, in BOLT 11 `r` fields.
   1104   - if `channel_type` has `option_scid_alias` set:
   1105     - MUST NOT use the real `short_channel_id` in BOLT 11 `r` fields.
   1106 
   1107 From the point of waiting for `channel_ready` onward, either node MAY
   1108 send an `error` and fail the channel if it does not receive a required response from the
   1109 other node after a reasonable timeout.
   1110 
   1111 #### Rationale
   1112 
   1113 The non-funder can simply forget the channel ever existed, since no
   1114 funds are at risk. If the fundee were to remember the channel forever, this
   1115 would create a Denial of Service risk; therefore, forgetting it is recommended
   1116 (even if the promise of `push_msat` is significant).
   1117 
   1118 If the fundee forgets the channel before it was confirmed, the funder will need
   1119 to broadcast the commitment transaction to get his funds back and open a new
   1120 channel. To avoid this, the funder should ensure the funding transaction
   1121 confirms in the next 2016 blocks.
   1122 
   1123 The `alias` here is required for two distinct use cases. The first one is
   1124 for routing payments through channels that are not confirmed yet (since
   1125 the real `short_channel_id` is unknown until confirmation). The second one
   1126 is to provide one or more aliases to use for private channels (even once
   1127 a real `short_channel_id` is available).
   1128 
   1129 While a node can send multiple `alias`, it must remember all of the
   1130 ones it has sent so it can use them should they be requested by
   1131 incoming HTLCs.  The recipient only need remember one, for use in
   1132 `r` route hints in BOLT 11 invoices.
   1133 
   1134 If an RBF negotiation is in progress when a `channel_ready` message is
   1135 exchanged, the negotiation must be abandoned.
   1136 
   1137 ## Channel Establishment v2
   1138 
   1139 This is a revision of the channel establishment protocol.
   1140 It changes the previous protocol to allow the `accept_channel2` peer
   1141 (the *accepter*/*non-initiator*) to contribute inputs to the funding
   1142 transaction, via the interactive transaction construction protocol.
   1143 
   1144         +-------+                              +-------+
   1145         |       |--(1)--- open_channel2  ----->|       |
   1146         |       |<-(2)--- accept_channel2 -----|       |
   1147         |       |                              |       |
   1148     --->|       |      <tx collaboration>      |       |
   1149     |   |       |                              |       |
   1150     |   |       |--(3)--  commitment_signed -->|       |
   1151     |   |       |<-(4)--  commitment_signed ---|       |
   1152     |   |   A   |                              |   B   |
   1153     |   |       |<-(5)--  tx_signatures -------|       |
   1154     |   |       |--(6)--  tx_signatures ------>|       |
   1155     |   |       |                              |       |
   1156     |   |       |--(a)--- tx_init_rbf -------->|       |
   1157     ----|       |<-(b)--- tx_ack_rbf ----------|       |
   1158         |       |                              |       |
   1159         |       |    <tx rbf collaboration>    |       |
   1160         |       |                              |       |
   1161         |       |--(c)--  commitment_signed -->|       |
   1162         |       |<-(d)--  commitment_signed ---|       |
   1163         |       |                              |       |
   1164         |       |<-(e)--  tx_signatures -------|       |
   1165         |       |--(f)--  tx_signatures ------>|       |
   1166         |       |                              |       |
   1167         |       |--(7)--- channel_ready  ----->|       |
   1168         |       |<-(8)--- channel_ready  ------|       |
   1169         +-------+                              +-------+
   1170 
   1171         - where node A is *opener*/*initiator* and node B is
   1172           *accepter*/*non-initiator*
   1173 
   1174 ### The `open_channel2` Message
   1175 
   1176 This message initiates the v2 channel establishment workflow.
   1177 
   1178 1. type: 64 (`open_channel2`)
   1179 2. data:
   1180    * [`chain_hash`:`chain_hash`]
   1181    * [`channel_id`:`temporary_channel_id`]
   1182    * [`u32`:`funding_feerate_perkw`]
   1183    * [`u32`:`commitment_feerate_perkw`]
   1184    * [`u64`:`funding_satoshis`]
   1185    * [`u64`:`dust_limit_satoshis`]
   1186    * [`u64`:`max_htlc_value_in_flight_msat`]
   1187    * [`u64`:`htlc_minimum_msat`]
   1188    * [`u16`:`to_self_delay`]
   1189    * [`u16`:`max_accepted_htlcs`]
   1190    * [`u32`:`locktime`]
   1191    * [`point`:`funding_pubkey`]
   1192    * [`point`:`revocation_basepoint`]
   1193    * [`point`:`payment_basepoint`]
   1194    * [`point`:`delayed_payment_basepoint`]
   1195    * [`point`:`htlc_basepoint`]
   1196    * [`point`:`first_per_commitment_point`]
   1197    * [`point`:`second_per_commitment_point`]
   1198    * [`byte`:`channel_flags`]
   1199    * [`opening_tlvs`:`tlvs`]
   1200 
   1201 1. `tlv_stream`: `opening_tlvs`
   1202 2. types:
   1203    1. type: 0 (`upfront_shutdown_script`)
   1204    2. data:
   1205        * [`...*byte`:`shutdown_scriptpubkey`]
   1206    1. type: 1 (`channel_type`)
   1207    2. data:
   1208         * [`...*byte`:`type`]
   1209    1. type: 2 (`require_confirmed_inputs`)
   1210 
   1211 Rationale and Requirements are the same as for [`open_channel`](#the-open_channel-message),
   1212 with the following additions.
   1213 
   1214 #### Requirements
   1215 
   1216 If nodes have negotiated `option_dual_fund`:
   1217   - the opening node:
   1218     - MUST NOT send `open_channel`
   1219 
   1220 The sending node:
   1221   - MUST set `channel_type`
   1222   - MUST set `funding_feerate_perkw` to the feerate for this transaction
   1223   - if `channel_type` includes `zero_fee_commitments`:
   1224     - MUST set `commitment_feerate_perkw` to `0`.
   1225   - If it requires the receiving node to only use confirmed inputs:
   1226     - MUST set `require_confirmed_inputs`
   1227 
   1228 The receiving node:
   1229   - MAY fail the negotiation if:
   1230     - the `locktime` is unacceptable
   1231     - the `funding_feerate_perkw` is unacceptable
   1232   - MUST fail the negotiation if:
   1233     - `channel_type` includes `zero_fee_commitments` and `commitment_feerate_perkw` is not `0`.
   1234     - `require_confirmed_inputs` is set but it cannot provide confirmed inputs
   1235     - `channel_type` is not set
   1236 
   1237 #### Rationale
   1238 
   1239 `temporary_channel_id` MUST be derived using a zeroed out basepoint for the
   1240 peer's revocation basepoint. This allows the peer to return channel-assignable
   1241 errors before the *accepter*'s revocation basepoint is known.
   1242 
   1243 `funding_feerate_perkw` indicates the fee rate that the opening node will
   1244 pay for the funding transaction in satoshi per 1000-weight, as described
   1245 in [BOLT-3, Appendix F](03-transactions.md#appendix-f-dual-funded-transaction-test-vectors).
   1246 
   1247 `locktime` is the locktime for the funding transaction.
   1248 
   1249 The receiving node, if the `locktime` or `funding_feerate_perkw` is considered
   1250 out of an acceptable range, may fail the negotiation. However, it is
   1251 recommended that the *accepter* permits the channel open to proceed
   1252 without their participation in the channel's funding.
   1253 
   1254 Note that `open_channel`'s `channel_reserve_satoshi` has been omitted.
   1255 Instead, the channel reserve is fixed at 1% of the total channel balance
   1256 (`open_channel2`.`funding_satoshis` + `accept_channel2`.`funding_satoshis`)
   1257 rounded down to the nearest whole satoshi or the `dust_limit_satoshis`,
   1258 whichever is greater.
   1259 
   1260 Note that `push_msat` has been omitted.
   1261 
   1262 `second_per_commitment_point` is now sent here (as well as in `channel_ready`)
   1263 as a convenience for implementations.
   1264 
   1265 The sending node may require the other participant to only use confirmed inputs.
   1266 This ensures that the sending node doesn't end up paying the fees of a low
   1267 feerate unconfirmed ancestor of one of the other participant's inputs.
   1268 
   1269 ### The `accept_channel2` Message
   1270 
   1271 This message contains information about a node and indicates its
   1272 acceptance of the new channel.
   1273 
   1274 1. type: 65 (`accept_channel2`)
   1275 2. data:
   1276     * [`channel_id`:`temporary_channel_id`]
   1277     * [`u64`:`funding_satoshis`]
   1278     * [`u64`:`dust_limit_satoshis`]
   1279     * [`u64`:`max_htlc_value_in_flight_msat`]
   1280     * [`u64`:`htlc_minimum_msat`]
   1281     * [`u32`:`minimum_depth`]
   1282     * [`u16`:`to_self_delay`]
   1283     * [`u16`:`max_accepted_htlcs`]
   1284     * [`point`:`funding_pubkey`]
   1285     * [`point`:`revocation_basepoint`]
   1286     * [`point`:`payment_basepoint`]
   1287     * [`point`:`delayed_payment_basepoint`]
   1288     * [`point`:`htlc_basepoint`]
   1289     * [`point`:`first_per_commitment_point`]
   1290     * [`point`:`second_per_commitment_point`]
   1291     * [`accept_tlvs`:`tlvs`]
   1292 
   1293 1. `tlv_stream`: `accept_tlvs`
   1294 2. types:
   1295    1. type: 0 (`upfront_shutdown_script`)
   1296    2. data:
   1297        * [`...*byte`:`shutdown_scriptpubkey`]
   1298    1. type: 1 (`channel_type`)
   1299    2. data:
   1300         * [`...*byte`:`type`]
   1301    1. type: 2 (`require_confirmed_inputs`)
   1302 
   1303 Rationale and Requirements are the same as listed above,
   1304 for [`accept_channel`](#the-accept_channel-message) with the following
   1305 additions.
   1306 
   1307 #### Requirements
   1308 
   1309 The accepting node:
   1310   - MUST use the `temporary_channel_id` of the `open_channel2` message.
   1311   - MUST set `channel_type` to the `channel_type` from `open_channel2`.
   1312   - MAY respond with a `funding_satoshis` value of zero.
   1313   - If it requires the opening node to only use confirmed inputs:
   1314     - MUST set `require_confirmed_inputs`.
   1315 
   1316 The receiving node:
   1317   - MUST fail the negotiation if:
   1318     - `require_confirmed_inputs` is set but it cannot provide confirmed inputs.
   1319     - `channel_type` is not set.
   1320 
   1321 #### Rationale
   1322 
   1323 The `funding_satoshis` is the amount of bitcoin in satoshis
   1324 the *accepter* will be contributing to the channel's funding transaction.
   1325 
   1326 Note that `accept_channel`'s `channel_reserve_satoshi` has been omitted.
   1327 Instead, the channel reserve is fixed at 1% of the total channel balance
   1328 (`open_channel2`.`funding_satoshis` + `accept_channel2`.`funding_satoshis`)
   1329 rounded down to the nearest whole satoshi or the `dust_limit_satoshis`,
   1330 whichever is greater.
   1331 
   1332 ### Funding Composition
   1333 
   1334 Funding composition for channel establishment v2 makes use of the
   1335 [Interactive Transaction Construction](#interactive-transaction-construction)
   1336 protocol, with the following additional caveats.
   1337 
   1338 #### The `tx_add_input` Message
   1339 
   1340 ##### Requirements
   1341 
   1342 The sending node:
   1343   - if the receiver set `require_confirmed_inputs` in `open_channel2`,
   1344     `accept_channel2`, `tx_init_rbf` or `tx_ack_rbf`:
   1345     - MUST NOT send a `tx_add_input` that contains an unconfirmed input
   1346 
   1347 #### The `tx_add_output` Message
   1348 
   1349 ##### Requirements
   1350 
   1351 The sending node:
   1352   - if is the *opener*:
   1353     - MUST send at least one `tx_add_output`,  which contains the
   1354       channel's funding output
   1355 
   1356 ##### Rationale
   1357 
   1358 The channel funding output must be added by the *opener*, who pays its fees.
   1359 
   1360 #### The `tx_complete` Message
   1361 
   1362 Upon receipt of consecutive `tx_complete`s, the receiving node:
   1363   - if is the *accepter*:
   1364     - MUST fail the negotiation if:
   1365       - no funding output was received
   1366       - the value of the funding output is not equal to the sum of
   1367         `open_channel2`.`funding_satoshis` and `accept_channel2`.
   1368         `funding_satoshis`
   1369       - the value of the funding output is less than the `dust_limit`
   1370   - if this is an RBF attempt:
   1371     - MUST fail the negotiation if:
   1372       - the transaction's total fees is less than the last
   1373         successfully negotiated transaction's fees
   1374       - the transaction does not share at least one input with
   1375         each previous funding transaction
   1376   - if it has sent `require_confirmed_inputs` in `open_channel2`,
   1377     `accept_channel2`, `tx_init_rbf` or `tx_ack_rbf`:
   1378     - MUST fail the negotiation if:
   1379       - one of the inputs added by the other peer is unconfirmed
   1380 
   1381 ### The `commitment_signed` Message
   1382 
   1383 This message is exchanged by both peers. It contains the signatures for
   1384 the first commitment transaction, which uses a format determined by the
   1385 `channel_type` sent in `open_channel2` and `accept_channel2`.
   1386 
   1387 Rationale and Requirements are the same as listed below,
   1388 for [`commitment_signed`](#committing-updates-so-far-commitment_signed) with the following additions.
   1389 
   1390 #### Requirements
   1391 
   1392 The sending node:
   1393   - MUST send zero HTLCs.
   1394   - MUST remember the details of this funding transaction.
   1395 
   1396 The receiving node:
   1397   - if the message has one or more HTLCs:
   1398     - MUST fail the negotiation
   1399   - if it has not already transmitted its `commitment_signed`:
   1400     - MUST send `commitment_signed`
   1401   - Otherwise:
   1402     - MUST send `tx_signatures` if it should sign first, as specified
   1403       in the [`tx_signatures` requirements](#the-tx_signatures-message)
   1404 
   1405 #### Rationale
   1406 
   1407 The first commitment transaction has no HTLCs.
   1408 
   1409 Once peers are ready to exchange commitment signatures, they must remember
   1410 the details of the funding transaction to allow resuming the signatures
   1411 exchange if a disconnection happens.
   1412 
   1413 ### Sharing funding signatures: `tx_signatures`
   1414 
   1415 After a valid `commitment_signed` has been received
   1416 from the peer and a `commitment_signed` has been sent, a peer:
   1417   - MUST transmit `tx_signatures` with their signatures for the funding
   1418     transaction, following the order specified in the
   1419     [`tx_signatures` requirements](#the-tx_signatures-message)
   1420 
   1421 #### Requirements
   1422 
   1423 The sending node:
   1424   - MUST verify it has received a valid commitment signature from its peer
   1425   - MUST remember the details of this funding transaction
   1426   - if it has NOT received a valid `commitment_signed` message:
   1427     - MUST NOT send a `tx_signatures` message
   1428 
   1429 The receiving node:
   1430   - if has already sent or received a `channel_ready` message for this
   1431     channel:
   1432     - MUST ignore this message
   1433   - if the `witness` weight lowers the effective `feerate`
   1434     below the *opener*'s feerate for the funding transaction and the effective
   1435     `feerate` is determined by the receiving node to be insufficient for
   1436     getting the transaction confirmed in a timely manner:
   1437     - SHOULD broadcast their commitment transaction, closing the channel
   1438     - SHOULD double-spend their channel inputs when there is a productive
   1439       opportunity to do so; effectively canceling this channel open
   1440   - SHOULD apply `witnesses` to the funding transaction and broadcast it
   1441 
   1442 #### Rationale
   1443 
   1444 A peer sends their `tx_signatures` after receiving a valid `commitment_signed`
   1445 message, following the order specified in the [`tx_signatures` section](#the-tx_signatures-message).
   1446 
   1447 In the case where a peer provides valid witness data that causes their paid
   1448 feerate to fall beneath the `open_channel2.funding_feerate_perkw`, the channel
   1449 should be considered failed and the channel should be double-spent when
   1450 there is a productive opportunity to do so. This should disincentivize
   1451 peers from underpaying fees.
   1452 
   1453 ### Fee bumping: `tx_init_rbf` and `tx_ack_rbf`
   1454 
   1455 After the funding transaction has been broadcast, it can be replaced by
   1456 a transaction paying more fees to make the channel confirm faster.
   1457 
   1458 #### Requirements
   1459 
   1460 The sender of `tx_init_rbf`:
   1461   - MAY be either the *initiator* or the *accepter*
   1462     - If the sender is the accepter, it becomes the initiator of the `interactive-tx` session and thus:
   1463       - MUST send `tx_add_output` for the channel output
   1464       - MUST pay the fees for the shared transaction fields
   1465   - MUST NOT have sent or received a `channel_ready` message.
   1466 
   1467 The recipient:
   1468   - MUST fail the negotiation if they have already sent or received
   1469     `channel_ready`
   1470   - MAY fail the negotiation for any reason
   1471 
   1472 #### Rationale
   1473 
   1474 If a valid `channel_ready` message is received in the middle of an
   1475 RBF attempt, the attempt MUST be abandoned.
   1476 
   1477 Peers can use different values in `tx_init_rbf.funding_output_contribution`
   1478 and `tx_ack_rbf.funding_output_contribution` from the amounts transmitted
   1479 in `open_channel2` and `accept_channel2`: they are allowed to change how
   1480 much they wish to commit to the funding output.
   1481 
   1482 It's recommended that a peer, rather than fail the RBF negotiation due to
   1483 a large feerate change, instead sets their `sats` to zero, and decline to
   1484 participate further in the channel funding: by not contributing, they
   1485 may obtain incoming liquidity at no cost.
   1486 
   1487 We allow both nodes to initiate RBF, because any one of them may want to take
   1488 this opportunity to contribute additional funds to the channel without
   1489 waiting for the initial funding transaction to confirm.
   1490 
   1491 ## Channel Quiescence
   1492 
   1493 Various fundamental changes, in particular protocol upgrades, are
   1494 easiest on channels where both commitment transactions match, and no
   1495 pending updates are in flight.  We define a protocol to quiesce the
   1496 channel by indicating that "SomeThing Fundamental is Underway".
   1497 
   1498 ### `stfu`
   1499 
   1500 1. type: 2 (`stfu`)
   1501 2. data:
   1502     * [`channel_id`:`channel_id`]
   1503     * [`u8`:`initiator`]
   1504 
   1505 ### Requirements
   1506 
   1507 The sender of `stfu`:
   1508   - MUST NOT send `stfu` unless `option_quiesce` is negotiated.
   1509   - MUST NOT send `stfu` if any of the sender's htlc additions, htlc removals
   1510     or fee updates are pending for either peer.
   1511   - MUST NOT send `stfu` twice.
   1512   - if it is replying to an `stfu`:
   1513     - MUST set `initiator` to 0
   1514   - otherwise:
   1515     - MUST set `initiator` to 1
   1516   - MUST set `channel_id` to the id of the channel to quiesce.
   1517   - MUST now consider the channel to be quiescing.
   1518   - MUST NOT send an update message after `stfu`.
   1519 
   1520 The receiver of `stfu`:
   1521   - if it has sent `stfu` then:
   1522     - MUST now consider the channel to be quiescent
   1523   - otherwise:
   1524     - SHOULD NOT send any more update messages.
   1525     - MUST reply with `stfu` once it can do so.
   1526 
   1527 Both nodes:
   1528   - MUST disconnect after 60 seconds of quiescence if the HTLCs are pending.
   1529 
   1530 Upon disconnection:
   1531   - the channel is no longer considered quiescent.
   1532 
   1533 Dependent Protocols:
   1534   - MUST specify all states that terminate quiescence.
   1535     - NOTE: this prevents batching executions of protocols that depend on
   1536       quiescence.
   1537 
   1538 ### Rationale
   1539 
   1540 The normal use would be to cease sending updates, then wait for all
   1541 the current updates to be acknowledged by both peers, then start
   1542 quiescence.  For some protocols, choosing the initiator matters,
   1543 so this flag is sent.
   1544 
   1545 If both sides send `stfu` simultaneously, they will both set
   1546 `initiator` to `1`, in which case the "initiator" is arbitrarily
   1547 considered to be the channel funder (the sender of `open_channel`).
   1548 The quiescence effect is exactly the same as if one had replied to the
   1549 other.
   1550 
   1551 Dependent protocols have to specify termination conditions to prevent the need
   1552 for disconnection to resume channel traffic. An explicit resume message was
   1553 [considered but rejected](https://github.com/rustyrussell/lightning-rfc/pull/14)
   1554 since it introduces a number of edge cases that make bilateral consensus of
   1555 channel state significantly more complex to maintain. This introduces the
   1556 derivative property that it is impossible to batch multiple downstream protocols
   1557 in the same quiescence session.
   1558 
   1559 ## Channel Splicing
   1560 
   1561 Splicing is the term given for replacing the funding transaction with
   1562 a new one. For simplicity, splicing takes place once a channel is
   1563 [quiescent](#channel-quiescence).
   1564 
   1565 Operation returns to normal once the splice transaction has been signed
   1566 (while waiting for one of the splice transactions to confirm), at which
   1567 point the channel isn't quiescent anymore.
   1568 
   1569 The splice is finally terminated when both sides send `splice_locked`
   1570 to indicate that one of the splice transactions reached acceptable depth.
   1571 
   1572         +-------+                               +-------+
   1573         |       |--- splice_init -------------->|       |
   1574         |   A   |<--------------- splice_ack ---|   B   |
   1575         |       |                               |       |
   1576         |       |--- tx_add_input ------------->|       |
   1577         |       |<------------- tx_add_input ---|       |
   1578         |       |--- tx_add_input ------------->|       |
   1579         |       |<------------ tx_add_output ---|       |
   1580         |       |--- tx_add_output ------------>|       |
   1581         |       |<-------------- tx_complete ---|       |
   1582         |       |--- tx_add_output ------------>|       |
   1583         |       |<-------------- tx_complete ---|       |
   1584         |       |--- tx_complete -------------->|       |
   1585         |       |                               |       |
   1586         |       |--- commit_sig --------------->|       |
   1587         |       |<--------------- commit_sig ---|       |
   1588         |       |--- tx_signatures ------------>|       |
   1589         |       |<------------ tx_signatures ---|       |
   1590         |       |                               |       |
   1591         |       |       <RESUME CHANNEL>        |       |
   1592         |       |                               |       |
   1593         |       |--- update_add_htlc ---------->|       |
   1594         |       |--- commit_sig --------------->|       |
   1595         |       |--- commit_sig --------------->|       |
   1596         |       |<----------- revoke_and_ack ---|       |
   1597         |       |<--------------- commit_sig ---|       |
   1598         |       |<--------------- commit_sig ---|       |
   1599         |       |--- revoke_and_ack ----------->|       |
   1600         |       |                               |       |
   1601         |       |             <RBF>             |       |
   1602         |       |                               |       |
   1603         |       |<-------------- tx_init_rbf ---|       |
   1604         |       |--- tx_ack_rbf --------------->|       |
   1605         |       |<------------- tx_add_input ---|       |
   1606         |       |--- tx_add_input ------------->|       |
   1607         |       |<------------- tx_add_input ---|       |
   1608         |       |--- tx_add_output ------------>|       |
   1609         |       |<------------ tx_add_output ---|       |
   1610         |       |--- tx_complete -------------->|       |
   1611         |       |<------------ tx_add_output ---|       |
   1612         |       |--- tx_complete -------------->|       |
   1613         |       |<-------------- tx_complete ---|       |
   1614         |       |                               |       |
   1615         |       |<--------------- commit_sig ---|       |
   1616         |       |--- commit_sig --------------->|       |
   1617         |       |--- tx_signatures ------------>|       |
   1618         |       |<------------ tx_signatures ---|       |
   1619         |       |                               |       |
   1620         |       |       <RESUME CHANNEL>        |       |
   1621         |       |                               |       |
   1622         |       |--- update_add_htlc ---------->|       |
   1623         |       |--- commit_sig --------------->|       |
   1624         |       |--- commit_sig --------------->|       |
   1625         |       |--- commit_sig --------------->|       |
   1626         |       |<----------- revoke_and_ack ---|       |
   1627         |       |<--------------- commit_sig ---|       |
   1628         |       |<--------------- commit_sig ---|       |
   1629         |       |<--------------- commit_sig ---|       |
   1630         |       |--- revoke_and_ack ----------->|       |
   1631         |       |                               |       |
   1632         |       |      <SPLICE COMPLETION>      |       |
   1633         |       |                               |       |
   1634         |       |--- splice_locked ------------>|       |
   1635         |       |<------------ splice_locked ---|       |
   1636         |       |                               |       |
   1637         |       |       <RESUME CHANNEL>        |       |
   1638         |       |                               |       |
   1639         |       |--- update_add_htlc ---------->|       |
   1640         |       |--- commit_sig --------------->|       |
   1641         |       |<----------- revoke_and_ack ---|       |
   1642         |       |<--------------- commit_sig ---|       |
   1643         |       |--- revoke_and_ack ----------->|       |
   1644         |       |                               |       |
   1645         +-------+                               +-------+
   1646 
   1647 ### The `splice_init` Message
   1648 
   1649 1. type: 80 (`splice_init`)
   1650 2. data:
   1651     * [`channel_id`:`channel_id`]
   1652     * [`s64`:`funding_contribution_satoshis`]
   1653     * [`u32`:`funding_feerate_perkw`]
   1654     * [`u32`:`locktime`]
   1655     * [`point`:`funding_pubkey`]
   1656     * [`splice_init_tlvs`:`tlvs`]
   1657 
   1658 1. `tlv_stream`: `splice_init_tlvs`
   1659 2. types:
   1660    1. type: 2 (`require_confirmed_inputs`)
   1661 
   1662 `funding_contribution_satoshis` is the amount the sender is adding to their
   1663 channel balance (splice-in) or removing from their channel balance (splice-out).
   1664 
   1665 #### Requirements
   1666 
   1667 The sending node:
   1668   - MUST NOT send `splice_init` if the channel is not quiescent.
   1669   - MUST NOT send `splice_init` if it is not the quiescence initiator.
   1670   - MUST NOT send `splice_init` before sending and receiving `channel_ready`.
   1671   - MUST NOT send `splice_init` while another splice is being negotiated.
   1672   - MUST NOT send `splice_init` if another splice has been negotiated but
   1673     `splice_locked` has not been sent and received.
   1674   - MUST NOT send `splice_init` if it has previously sent `shutdown`.
   1675   - MUST set `funding_feerate_perkw` to the feerate for the splice transaction.
   1676   - If it is splicing funds out of the channel:
   1677     - MUST set `funding_contribution_satoshis` to a negative value matching
   1678       the amount that will be subtracted from its current channel balance.
   1679   - If it is splicing funds into the channel:
   1680     - MUST set `funding_contribution_satoshis` to a positive value matching
   1681       the amount that will be added to its current channel balance.
   1682   - If it requires the receiving node to only use confirmed inputs:
   1683     - MUST set `require_confirmed_inputs`.
   1684   - SHOULD use a different `funding_pubkey` than the one used for the
   1685     previous funding transaction.
   1686 
   1687 The receiving node:
   1688   - If the channel is not quiescent:
   1689     - MUST send a `warning` and close the connection or send an `error`
   1690       and fail the channel.
   1691   - If the sending node is not the quiescence initiator:
   1692     - MUST send a `warning` and close the connection or send an `error`
   1693       and fail the channel.
   1694   - If another splice is already being negotiated:
   1695     - MUST send a `warning` and close the connection or send an `error`
   1696       and fail the channel.
   1697   - If another splice has been negotiated but isn't locked yet:
   1698     - MUST send a `warning` and close the connection or send an `error`
   1699       and fail the channel.
   1700   - If it has received `shutdown`:
   1701     - MUST send a `warning` and close the connection or send an `error`
   1702       and fail the channel.
   1703   - If the `funding_feerate_perkw` is unacceptable:
   1704     - MUST respond with `tx_abort`.
   1705   - If `funding_contribution_satoshis` is negative and its absolute value is
   1706     greater than the sending node's current channel balance:
   1707     - MUST send a `warning` and close the connection or send an `error`
   1708       and fail the channel.
   1709   - If it accepts the splice attempt:
   1710     - MUST respond with `splice_ack`.
   1711   - Otherwise (it rejects the splice):
   1712     - MUST respond with `tx_abort`.
   1713 
   1714 ### The `splice_ack` Message
   1715 
   1716 1. type: 81 (`splice_ack`)
   1717 2. data:
   1718     * [`channel_id`:`channel_id`]
   1719     * [`s64`:`funding_contribution_satoshis`]
   1720     * [`point`:`funding_pubkey`]
   1721     * [`splice_ack_tlvs`:`tlvs`]
   1722 
   1723 1. `tlv_stream`: `splice_ack_tlvs`
   1724 2. types:
   1725    1. type: 2 (`require_confirmed_inputs`)
   1726 
   1727 #### Requirements
   1728 
   1729 The sending node:
   1730   - SHOULD use a different `funding_pubkey` than the one used for the
   1731     previous funding transaction.
   1732   - MAY set `funding_contribution_satoshis` to `0` if they don't want
   1733     to contribute to the splice.
   1734   - If it requires the receiving node to only use confirmed inputs:
   1735     - MUST set `require_confirmed_inputs`.
   1736 
   1737 The receiving node:
   1738   - If it has sent `splice_init`:
   1739     - If `funding_contribution_satoshis` is negative and its absolute value is
   1740       greater than the sending node's current channel balance:
   1741       - MUST send a `warning` and close the connection or send an `error`
   1742         and fail the channel.
   1743     - If it accepts the splice attempt:
   1744       - MUST start an `interactive-tx` session to create the splice transaction.
   1745     - Otherwise:
   1746       - MUST reject the splice attempt by sending `tx_abort`.
   1747   - Otherwise (it has not sent `splice_init`):
   1748     - MUST send a `warning` and close the connection or send an `error`
   1749       and fail the channel.
   1750 
   1751 ### Splice Transaction Construction
   1752 
   1753 The splice transaction is created using the
   1754 [Interactive Transaction Construction](#interactive-transaction-construction)
   1755 protocol, with the following additional requirements.
   1756 
   1757 #### The `tx_add_input` Message
   1758 
   1759 ##### Requirements
   1760 
   1761 The sending node:
   1762   - If it is the splice initiator:
   1763     - MUST add the current channel input to the splice transaction by
   1764       sending `tx_add_input` with `shared_input_txid` containing the
   1765       `txid` of the previous funding transaction.
   1766       - MUST NOT include `prevtx` for that shared input.
   1767       - MUST set `prevtx_vout` to the previous funding output index.
   1768   - If the receiver set `require_confirmed_inputs` in `splice_init`,
   1769     `splice_ack`, `tx_init_rbf` or `tx_ack_rbf`:
   1770     - MUST NOT send a `tx_add_input` that contains an unconfirmed input.
   1771 
   1772 The receiving node:
   1773   - If `shared_input_txid` is set:
   1774     - If it doesn't match the `txid` of the previous funding transaction:
   1775       - MUST fail the negotiation by sending `tx_abort`.
   1776     - If `prevtx_vout` doesn't match the previous funding output index:
   1777       - MUST fail the negotiation by sending `tx_abort`.
   1778 
   1779 ##### Rationale
   1780 
   1781 The splice transaction must spend the current channel funding output. The
   1782 splice initiator is responsible for adding that input to the transaction,
   1783 and pay the fees for its weight. It would be wasteful to transmit the
   1784 previous funding transaction in the `prevtx` field, and wouldn't even
   1785 be possible for funding transactions that exceed 65kB, so we only transmit
   1786 its `txid` using the `shared_input_txid` field.
   1787 
   1788 #### The `tx_add_output` Message
   1789 
   1790 ##### Requirements
   1791 
   1792 The sending node:
   1793   - If it is the splice initiator:
   1794     - MUST send at least one `tx_add_output`, which contains the new 
   1795       channel's funding output based on the `funding_pubkey`s from
   1796       `splice_init` and `splice_ack`.
   1797       - MUST set the amount of that `tx_add_output` to the previous
   1798         channel capacity with the `funding_contribution_satoshis`s from
   1799         `splice_init` and `splice_ack` applied.
   1800 
   1801 ##### Rationale
   1802 
   1803 The splice initiator is responsible for adding the new channel funding
   1804 output to the transaction and paying the fees for its weight.
   1805 
   1806 #### The `tx_complete` Message
   1807 
   1808 ##### Requirements
   1809 
   1810 The receiving node:
   1811   - MUST compute the channel balance for each side by adding their respective
   1812     `funding_contribution_satoshis` to their previous channel balance.
   1813   - MUST fail the negotiation by sending `tx_abort` if:
   1814     - There is not exactly one input spending the current funding transaction.
   1815     - There is not exactly one channel funding output using the funding public
   1816       keys and funding contributions from `splice_init` and `splice_ack`.
   1817     - This is an RBF attempt and the transaction's total fees is less than
   1818       the last successfully negotiated splice transaction's fees.
   1819     - Either side has added an output other than the channel funding output
   1820       and the balance for that side is less than the channel reserve that
   1821       matches the new channel capacity.
   1822 
   1823 ##### Rationale
   1824 
   1825 If a side does not meet the reserve requirements, that's OK: but if they take
   1826 funds out of the channel, they must ensure that they do meet them. If your peer
   1827 adds a massive amount to the channel, then you only have to add more reserve if
   1828 you want to contribute to the splice (and you can use `tx_remove_output` and/or
   1829 `tx_remove_input` part-way through if this happens).
   1830 
   1831 #### The `commitment_signed` Message
   1832 
   1833 After exchanging `tx_complete`, both peers send `commitment_signed` to commit
   1834 to the splice transaction by creating a commitment transaction spending the
   1835 new channel funding output.
   1836 
   1837 The usual [`commitment_signed`](#committing-updates-so-far-commitment_signed)
   1838 requirements apply with the following additions.
   1839 
   1840 ##### Requirements
   1841 
   1842 The sending node:
   1843   - MUST create a commitment transaction that spends the splice funding output and:
   1844     - Adds `funding_contribution_satoshis` from `splice_init` and `splice_ack`
   1845       to the main balance of their respective sender.
   1846     - Uses the same feerate as the existing commitment transaction.
   1847     - Uses the same `commitment_number` as the existing commitment transaction.
   1848   - MUST send signatures for pending HTLCs.
   1849   - MUST remember the details of this splice transaction.
   1850 
   1851 The receiving node:
   1852   - MUST NOT respond with `revoke_and_ack`.
   1853   - If it has not already transmitted its `commitment_signed`:
   1854     - MUST send `commitment_signed`.
   1855   - If it should sign first, as specified in the [`tx_signatures` requirements](#the-tx_signatures-message):
   1856     - MUST send `tx_signatures`.
   1857     - Note that since the initiator sends `tx_add_input` for the shared input
   1858       (corresponding to the previous channel output), 100% of the previous channel
   1859       capacity is attributed to the initiator when computing who must send
   1860       `tx_signatures` first (instead of using each node's previous balance).
   1861 
   1862 On reconnection:
   1863   - If `next_funding` matches the splice transaction:
   1864     - MUST retransmit `commitment_signed`.
   1865 
   1866 ##### Rationale
   1867 
   1868 Once peers are ready to exchange commitment signatures, they must remember
   1869 the details of the splice transaction to allow resuming the signatures
   1870 exchange if a disconnection happens.
   1871 
   1872 #### The `tx_signatures` Message
   1873 
   1874 ##### Requirements
   1875 
   1876 The sending node:
   1877   - MUST set `shared_input_signature` to a valid ECDSA signature for the
   1878     `tx_add_input` spending the previous channel funding output using the
   1879     `funding_pubkey` that matches this input.
   1880 
   1881 The receiving node:
   1882   - If `shared_input_signature` is not set:
   1883     - MUST send an `error` and fail the channel.
   1884   - If `shared_input_signature` is not valid or non-compliant with the
   1885     LOW-S-standard rule<sup>[LOWS](https://github.com/bitcoin/bitcoin/pull/6769)</sup>:
   1886     - MUST send an `error` and fail the channel.
   1887   - MUST consider the channel no longer quiescent.
   1888 
   1889 On reconnection:
   1890   - If `next_funding` matches the splice transaction:
   1891     - MUST retransmit `tx_signatures`.
   1892 
   1893 ##### Rationale
   1894 
   1895 Spending the channel funding output requires a signature from both peers.
   1896 Each peer transmits its own signature, which allows creating a valid
   1897 witness for the shared input without adding an additional message.
   1898 
   1899 Once `tx_signatures` have been exchanged, the splice transaction can be
   1900 broadcast. The channel is no longer quiescent: normal operation can resume
   1901 while waiting for the transaction to confirm and `splice_locked` messages
   1902 to be exchanged.
   1903 
   1904 #### The `tx_init_rbf` Message
   1905 
   1906 ##### Requirements
   1907 
   1908 The sending node:
   1909   - MUST NOT send `tx_init_rbf` if the channel is not quiescent.
   1910   - MUST NOT send `tx_init_rbf` if it is not the quiescence initiator.
   1911   - MAY send `tx_init_rbf` even if it is not the splice initiator.
   1912   - If there are more than 10 pending RBF attempts:
   1913     - MUST set a high enough `feerate` to ensure quick confirmation.
   1914   - MUST NOT send `tx_init_rbf` if it has previously sent `splice_locked`.
   1915   - MUST NOT send `tx_init_rbf` if `option_zeroconf` has been negotiated.
   1916   - MAY set `funding_output_contribution` to a different value than the
   1917     `funding_contribution_satoshis` used in `splice_init` or `splice_ack`,
   1918     or in previous RBF attempts.
   1919 
   1920 The receiving node:
   1921   - If the channel is not quiescent:
   1922     - MUST send a `warning` and close the connection or send an `error`
   1923       and fail the channel.
   1924   - If the sending node is not the quiescence initiator:
   1925     - MUST send a `warning` and close the connection or send an `error`
   1926       and fail the channel.
   1927   - If another RBF attempt has been created recently:
   1928     - SHOULD send `tx_abort` to reject this RBF attempt and wait for the
   1929       previous RBF attempt to confirm.
   1930   - If there are more than 10 pending RBF attempts and the `feerate` is not
   1931     high enough to ensure quick confirmation:
   1932     - SHOULD send `tx_abort` to reject the RBF attempt.
   1933   - If the sender previously sent `splice_locked`:
   1934     - MUST send a `warning` and close the connection or send an `error`
   1935       and fail the channel.
   1936   - If `option_zeroconf` has been negotiated:
   1937     - MUST send a `warning` and close the connection or send an `error`
   1938       and fail the channel.
   1939   - If `funding_output_contribution` is negative and its absolute value is
   1940     greater than the sending node's current channel balance:
   1941     - MUST send a `warning` and close the connection or send an `error`
   1942       and fail the channel.
   1943 
   1944 ##### Rationale
   1945 
   1946 Splice transactions can be RBF-ed to react to changes in the mempool feerate.
   1947 We allow both nodes to initiate RBF, because any one of them may want to take
   1948 this opportunity to splice additional funds into or out of the channel without
   1949 waiting for the initial splice transaction to confirm.
   1950 
   1951 We limit the number of pending RBF attempts, otherwise we may reach the
   1952 `batch_size` limit defined in [`start_batch`](#batching-channel-messages).
   1953 We require using a large enough feerate when we've already created many RBF
   1954 attempts, and we wait between RBF attempts to allow a previous attempt to
   1955 confirm.
   1956 
   1957 Since splice transactions always spend the current channel funding output, the
   1958 RBF attempts automatically double-spend each other. We thus disallow RBF when
   1959 `option_zeroconf` has been negotiated, because that creates a risk of losing
   1960 funds.
   1961 
   1962 #### The `tx_ack_rbf` Message
   1963 
   1964 ##### Requirements
   1965 
   1966 The sending node:
   1967   - MAY set `funding_output_contribution` to a different value than the
   1968     `funding_contribution_satoshis` used in `splice_init` or `splice_ack`,
   1969     or in previous RBF attempts.
   1970 
   1971 The receiving node:
   1972   - If `funding_output_contribution` is negative and its absolute value is
   1973     greater than the sending node's current channel balance:
   1974     - MUST send a `warning` and close the connection or send an `error`
   1975       and fail the channel.
   1976 
   1977 ### Splice Completion
   1978 
   1979 Once splice transactions have been signed but haven't reached acceptable
   1980 depth, channel operations go back to normal and HTLCs can be exchanged,
   1981 with the caveat that payments must be valid for all splice transactions.
   1982 
   1983 Nodes keep track of multiple commitment transactions (one for the current
   1984 funding transaction and one for each splice transaction) and exchange
   1985 signatures for each of these commitment transactions.
   1986 
   1987 ```
   1988 +------------+        +-----------+
   1989 | Funding Tx |---+--->| Commit Tx |
   1990 +------------+   |    +-----------+
   1991                  |    +-----------+            +-----------+
   1992                  +--->| Splice Tx |----------->| Commit Tx |
   1993                  |    +-----------+            +-----------+
   1994                  |    +---------------+        +-----------+
   1995                  +--->| Splice RBF #1 |------->| Commit Tx |
   1996                  |    +---------------+        +-----------+
   1997                  |    +---------------+        +-----------+
   1998                  +--->| Splice RBF #2 |------->| Commit Tx |
   1999                       +---------------+        +-----------+
   2000 ```
   2001 
   2002 The splice completes by exchanging `splice_locked` messages, at which point
   2003 the locked transaction replaces the previous funding transaction.
   2004 
   2005 #### The `splice_locked` Message
   2006 
   2007 1. type: 77 (`splice_locked`)
   2008 2. data:
   2009    * [`channel_id`:`channel_id`]
   2010    * [`sha256`:`splice_txid`]
   2011 
   2012 ##### Requirements
   2013 
   2014 Each node:
   2015   - If any splice transaction reaches acceptable depth:
   2016     - MUST send `splice_locked` with the `txid` of that transaction.
   2017   - If `option_zeroconf` has been negotiated:
   2018     - SHOULD send `splice_locked` immediately after exchanging `tx_signatures`.
   2019 
   2020 The receiving node:
   2021   - If `splice_txid` doesn't match any of its pending splice transactions:
   2022     - MUST send a `warning` and close the connection, or send an `error` and
   2023       fail the channel.
   2024 
   2025 Once a node has sent and received `splice_locked`:
   2026   - If the `splice_txid`s match:
   2027     - MUST stop sending `commitment_signed` for RBF attempts and ancestors
   2028       of this splice transaction.
   2029     - MAY discard RBF attempts and ancestor transactions.
   2030     - If `announce_channel` is set for this channel:
   2031       - MUST send `announcement_signatures` with `short_channel_id` matching
   2032         this splice transaction.
   2033   - If the `splice_txid`s are for different RBF candidates:
   2034     - SHOULD ignore the message.
   2035     - MAY send an `error` and fail the channel.
   2036 
   2037 ##### Rationale
   2038 
   2039 If nodes are on a different fork of the blockchain, they may disagree on which
   2040 RBF attempt has been confirmed: in that case nodes can either close the channel
   2041 or simply ignore `splice_locked` and wait for one of the forks to eventually
   2042 replace the other, at which point both nodes should agree on which RBF attempt
   2043 confirmed and exchange `splice_locked` for the same `splice_txid` to complete
   2044 the splice.
   2045 
   2046 ## Channel Close
   2047 
   2048 Nodes can negotiate a mutual close of the connection, which unlike a
   2049 unilateral close, allows them to access their funds immediately and
   2050 can be negotiated with lower fees.
   2051 
   2052 Closing happens in two stages:
   2053 1. one side indicates it wants to clear the channel (and thus will accept no new HTLCs)
   2054 2. once all HTLCs are resolved, the final channel close negotiation begins.
   2055 
   2056         +-------+                                                          +-------+
   2057         |       | shutdown(scriptA1)                                       |       |
   2058         |       |--------------------------------------------------------->|       |
   2059         |       |                                       shutdown(scriptB1) |       |
   2060         |       |<---------------------------------------------------------|       |
   2061         |       |                                                          |       |
   2062         |       |               <complete all pending HTLCs>               |       |
   2063         |   A   |                           ....                           |   B   |
   2064         |       |                                                          |       |
   2065         |       | closing_complete(scriptA1, scriptB1, 1000 sat)           |       |
   2066         |       |--------------------------------------------------------->|       |
   2067         |       |            closing_complete(scriptB1, scriptA1, 750 sat) |       |
   2068         |       |<---------------------------------------------------------|       |
   2069         |       |                closing_sig(scriptA1, scriptB1, 1000 sat) |       |
   2070         |       |<---------------------------------------------------------|       |
   2071         |       | closing_sig(scriptB1, scriptA1, 750 sat)                 |       |
   2072         |       |--------------------------------------------------------->|       |
   2073         |       |                                                          |       |
   2074         |       |                 <A updates their script>                 |       |
   2075         |       |                                                          |       |
   2076         |       | closing_complete(scriptA2, scriptB1, 1100 sat)           |       |
   2077         |       |--------------------------------------------------------->|       |
   2078         |       |                closing_sig(scriptA2, scriptB1, 1100 sat) |       |
   2079         |       |<---------------------------------------------------------|       |
   2080         |       |                                                          |       |
   2081         |       |                           ....                           |       |
   2082         |       |                                                          |       |
   2083         |       |                 <B RBFs their previous tx>               |       |
   2084         |       |                                                          |       |
   2085         |       |            closing_complete(scriptB1, scriptA2, 850 sat) |       |
   2086         |       |<---------------------------------------------------------|       |
   2087         |       | closing_sig(scriptB1, scriptA2, 850 sat)                 |       |
   2088         |       |--------------------------------------------------------->|       |
   2089         |       |                                                          |       |
   2090         |       |                           ....                           |       |
   2091         |       |                                                          |       |
   2092         |       |        <A and B concurrently update their script>        |       | (*) Note that this is a very rare race condition
   2093         |       |                                                          |       |
   2094         |       | closing_complete(scriptA3, scriptB1, 1250 sat)           |       |
   2095         |       |----------------------------->                            |       |
   2096         |       |            closing_complete(scriptB2, scriptA2, 900 sat) |       |
   2097         |       |                   <--------------------------------------|       |
   2098         |       |                                         closing_complete |       |
   2099         |       |                              --------------------------->|       |
   2100         |       |                                                  warning |       | (*) B sends a warning because A is not using scriptB2
   2101         |       |                   <--------------------------------------|       |
   2102         |       | closing_complete                                         |       |
   2103         |       |<------------------                                       |       |
   2104         |       | warning                                                  |       | (*) A sends a warning because B is not using scriptA3
   2105         |       |--------------------------------------------------------->|       |
   2106         |       | warning                                                  |       |
   2107         |       |<------------------                                       |       |
   2108         |       |                                                          |       |
   2109         |       |                       <disconnect>                       |       | (*) A and B reconnect to resolve the race condition
   2110         |       |                                                          |       |
   2111         |       | channel_reestablish                                      |       |
   2112         |       |--------------------------------------------------------->|       |
   2113         |       |                                      channel_reestablish |       |
   2114         |       |<---------------------------------------------------------|       |
   2115         |       | shutdown(scriptA3)                                       |       |
   2116         |       |--------------------------------------------------------->|       |
   2117         |       |                                       shutdown(scriptB2) |       |
   2118         |       |<---------------------------------------------------------|       |
   2119         |       |                                                          |       |
   2120         |       |            <A retries with B's latest script>            |       |
   2121         |       |                                                          |       |
   2122         |       | closing_complete(scriptA3, scriptB2, 1250 sat)           |       |
   2123         |       |--------------------------------------------------------->|       |
   2124         |       |                closing_sig(scriptA3, scriptB2, 1250 sat) |       |
   2125         |       |<---------------------------------------------------------|       |
   2126         |       |                                                          |       |
   2127         |       |            <B retries with A's latest script>            |       |
   2128         |       |                                                          |       |
   2129         |       |            closing_complete(scriptB2, scriptA3, 900 sat) |       |
   2130         |       |<---------------------------------------------------------|       |
   2131         |       | closing_sig(scriptB2, scriptA3, 900 sat)                 |       |
   2132         |       |--------------------------------------------------------->|       |
   2133         |       |                                                          |       |
   2134         +-------+                                                          +-------+
   2135 
   2136 ### Closing Initiation: `shutdown`
   2137 
   2138 Either node (or both) can send a `shutdown` message to initiate closing,
   2139 along with the `scriptpubkey` it wants to be paid to.
   2140 
   2141 1. type: 38 (`shutdown`)
   2142 2. data:
   2143    * [`channel_id`:`channel_id`]
   2144    * [`u16`:`len`]
   2145    * [`len*byte`:`scriptpubkey`]
   2146 
   2147 #### Requirements
   2148 
   2149 A sending node:
   2150   - if it hasn't sent a `funding_created` (if it is a funder) or a `funding_signed` (if it is a fundee):
   2151     - MUST NOT send a `shutdown`
   2152   - MAY send a `shutdown` before a `channel_ready`, i.e. before the funding transaction has reached `minimum_depth`.
   2153   - if there are updates pending on the receiving node's commitment transaction:
   2154     - MUST NOT send a `shutdown`.
   2155   - MUST NOT send multiple `shutdown` messages.
   2156   - MUST NOT send `shutdown` if there is a splice transaction that isn't locked yet.
   2157   - MUST NOT send an `update_add_htlc` after a `shutdown`.
   2158   - if no HTLCs remain in either commitment transaction (including dust HTLCs)
   2159     and neither side has a pending `revoke_and_ack` to send:
   2160     - MUST NOT send any `update` message after that point.
   2161   - SHOULD fail to route any HTLC added after it has sent `shutdown`.
   2162   - if it sent a non-zero-length `shutdown_scriptpubkey` in `open_channel` or `accept_channel`:
   2163     - MUST send the same value in `scriptpubkey`.
   2164   - MUST set `scriptpubkey` in one of the following forms:
   2165 
   2166     1. `OP_0` `20` 20-bytes (version 0 pay to witness pubkey hash), OR
   2167     2. `OP_0` `32` 32-bytes (version 0 pay to witness script hash), OR
   2168     3. if (and only if) `option_shutdown_anysegwit` is negotiated:
   2169       * `OP_1` through `OP_16` inclusive, followed by a single push of 2 to 40 bytes
   2170         (witness program versions 1 through 16)
   2171     4. if (and only if) `option_simple_close` is negotiated:
   2172       * `OP_RETURN` followed by one of:
   2173         * `6` to `75` inclusive followed by exactly that many bytes
   2174         * `76` followed by `76` to `80` followed by exactly that many bytes
   2175 
   2176 A receiving node:
   2177   - if it hasn't received a `funding_signed` (if it is a funder) or a `funding_created` (if it is a fundee):
   2178     - SHOULD send an `error` and fail the channel.
   2179   - if the `scriptpubkey` is not in one of the above forms:
   2180     - SHOULD send a `warning`.
   2181   - if it hasn't sent a `channel_ready` yet:
   2182     - MAY reply to a `shutdown` message with a `shutdown`
   2183   - once there are no outstanding updates on the peer, UNLESS it has already sent a `shutdown`:
   2184     - MUST reply to a `shutdown` message with a `shutdown`
   2185   - if both nodes advertised the `option_upfront_shutdown_script` feature, and the receiving node received a non-zero-length `shutdown_scriptpubkey` in `open_channel` or `accept_channel`, and that `shutdown_scriptpubkey` is not equal to `scriptpubkey`:
   2186     - MAY send a `warning`.
   2187     - MUST fail the connection.
   2188 
   2189 #### Rationale
   2190 
   2191 If channel state is always "clean" (no pending changes) when a
   2192 shutdown starts, the question of how to behave if it wasn't is avoided:
   2193 the sender always sends a `commitment_signed` first.
   2194 
   2195 As shutdown implies a desire to terminate, it implies that no new
   2196 HTLCs will be added or accepted.  Once any HTLCs are cleared, there are no commitments
   2197 for which a revocation is owed, and all updates are included on both commitment
   2198 transactions, the peer may immediately begin closing negotiation, so we ban further
   2199 updates to the commitment transaction (in particular, `update_fee` would be
   2200 possible otherwise). However, while there are HTLCs on the commitment transaction,
   2201 the initiator may find it desirable to increase the feerate as there may be pending
   2202 HTLCs on the commitment which could timeout.
   2203 
   2204 The `scriptpubkey` forms include only standard segwit forms accepted by
   2205 the Bitcoin network, which ensures the resulting transaction will
   2206 propagate to miners. However old nodes may send non-segwit scripts, which
   2207 may be accepted for backwards-compatibility (with a caveat to force-close
   2208 if this output doesn't meet dust relay requirements).
   2209 
   2210 The `option_upfront_shutdown_script` feature means that the node
   2211 wanted to pre-commit to `shutdown_scriptpubkey` in case it was
   2212 compromised somehow.  This is a weak commitment (a malevolent
   2213 implementation tends to ignore specifications like this one!), but it
   2214 provides an incremental improvement in security by requiring the cooperation
   2215 of the receiving node to change the `scriptpubkey`.
   2216 
   2217 The `shutdown` response requirement implies that the node sends `commitment_signed` to commit any outstanding changes before replying; however, it could theoretically reconnect instead, which would simply erase all outstanding uncommitted changes.
   2218 
   2219 `OP_RETURN` is only standard if followed by PUSH opcodes, and the total script
   2220 is 83 bytes or less. We are slightly stricter, to only allow a single PUSH, but
   2221 there are two forms in script: one which pushes up to 75 bytes, and a longer
   2222 one (`OP_PUSHDATA1`) which is needed for 76-80 bytes.
   2223 
   2224 
   2225 ### Closing Negotiation: `closing_complete` and `closing_sig`
   2226 
   2227 Once shutdown is complete, the channel is empty of HTLCs, there are no commitments
   2228 for which a revocation is owed, and all updates are included on both commitments,
   2229 the final current commitment transactions will have no HTLCs.
   2230 
   2231 If `option_simple_close` is not negotiated, see [Legacy Closing
   2232 Negotiation](#legacy-closing-negotiation-closing_signed) below.
   2233 
   2234 Each peer creates their own closing transaction where they pay the fee, and sends
   2235 `closing_complete` to the other peer with the transaction details. The other peer
   2236 simply signs that transaction and sends back `closing_sig`. Each peer will thus
   2237 independently send `closing_complete` and receive `closing_sig`, resulting in two
   2238 independent (but conflicting) closing transactions being created.
   2239 
   2240 The lesser-paid peer (if either is) can opt to omit their own output from the
   2241 closing transaction.
   2242 
   2243 This process can be repeated multiple times by sending `closing_complete` again,
   2244 which allows increasing the fees and changing the output script.
   2245 
   2246 1. type: 40 (`closing_complete`)
   2247 2. data:
   2248    * [`channel_id`:`channel_id`]
   2249    * [`u16`:`closer_scriptpubkey_len`]
   2250    * [`closer_scriptpubkey_len*byte`:`closer_scriptpubkey`]
   2251    * [`u16`:`closee_scriptpubkey_len`]
   2252    * [`closee_scriptpubkey_len*byte`:`closee_scriptpubkey`]
   2253    * [`u64`:`fee_satoshis`]
   2254    * [`u32`:`locktime`]
   2255    * [`closing_tlvs`:`tlvs`]
   2256 
   2257 1. type: 41 (`closing_sig`)
   2258 2. data:
   2259    * [`channel_id`:`channel_id`]
   2260    * [`u16`:`closer_scriptpubkey_len`]
   2261    * [`closer_scriptpubkey_len*byte`:`closer_scriptpubkey`]
   2262    * [`u16`:`closee_scriptpubkey_len`]
   2263    * [`closee_scriptpubkey_len*byte`:`closee_scriptpubkey`]
   2264    * [`u64`:`fee_satoshis`]
   2265    * [`u32`:`locktime`]
   2266    * [`closing_tlvs`:`tlvs`]
   2267 
   2268 1. `tlv_stream`: `closing_tlvs`
   2269 2. types:
   2270     1. type: 1 (`closer_output_only`)
   2271     2. data:
   2272         * [`signature`:`sig`]
   2273     1. type: 2 (`closee_output_only`)
   2274     2. data:
   2275         * [`signature`:`sig`]
   2276     1. type: 3 (`closer_and_closee_outputs`)
   2277     2. data:
   2278         * [`signature`:`sig`]
   2279 
   2280 #### Requirements
   2281 
   2282 Note: the details and requirements for the transaction being signed are in [BOLT 3](03-transactions.md#closing-transaction).
   2283 
   2284 An output is *dust* if the amount is less than the [Bitcoin Core Dust Thresholds](03-transactions.md#dust-limits).
   2285 
   2286 Note: These requirements only apply if `option_simple_close` is
   2287 negotiated, otherwise the requirements are in [Legacy Closing
   2288 Negotiation](#legacy-closing-negotiation-closing_signed).
   2289 
   2290 Both nodes:
   2291   - After a `shutdown` has been sent and received, AND no HTLCs remain in either commitment transaction:
   2292     - SHOULD send a `closing_complete` message.
   2293 
   2294 The sender of `closing_complete` (aka. "the closer"):
   2295   - MUST set `fee_satoshis` to a fee less than or equal to its outstanding balance, rounded down to whole satoshis.
   2296   - MUST set `fee_satoshis` so that at least one output is not dust.
   2297   - MUST set `closer_scriptpubkey` to its desired output script.
   2298   - MUST set `closee_scriptpubkey` to the last script it received from its peer (from `closing_complete` or from the initial `shutdown`).
   2299   - MUST set `locktime` to the desired `nLockTime` of the closing transaction.
   2300   - If the local outstanding balance (in millisatoshi) is less than the remote outstanding balance:
   2301     - MUST NOT set `closer_output_only`.
   2302     - MUST set `closee_output_only` if the local output amount is dust.
   2303     - MAY set `closee_output_only` if it considers the local output amount uneconomical AND its `closer_scriptpubkey` is not `OP_RETURN`.
   2304   - Otherwise (not lesser amount, cannot remove its own output):
   2305     - MUST NOT set `closee_output_only`.
   2306     - If it considers the local output amount uneconomical:
   2307       - MAY send a `closer_scriptpubkey` that is a valid `OP_RETURN` script. 
   2308       - If it does, the output value MUST be set to zero so that all funds go to fees, as specified in [BOLT #3](03-transactions.md#closing-transaction).
   2309     - If the closee's output amount is dust:
   2310       - MUST set `closer_output_only`.
   2311       - MUST NOT set `closer_and_closee_outputs`.
   2312     - Otherwise:
   2313       - MUST set both `closer_output_only` and `closer_and_closee_outputs`.
   2314   - MUST generate its closing transaction as specified in [BOLT #3](03-transactions.md#closing-transaction).
   2315   - MUST set `signature` fields as valid signature using its `funding_pubkey` of:
   2316     - `closer_output_only`: closing transaction with only the local ("closer") output.
   2317     - `closee_output_only`: closing transaction with only the remote ("closee") output.
   2318     - `closer_and_closee_outputs`: closing transaction with both the closer and closee outputs.
   2319   - If it wants to send another `closing_complete` (e.g. with a different `fee_satoshis` or `closer_scriptpubkey`):
   2320     - MUST wait until it has received `closing_sig` first.
   2321     - SHOULD close the connection if it doesn't receive `closing_sig`.
   2322 
   2323 The receiver of `closing_complete` (aka. "the closee"):
   2324   - If `fee_satoshis` is greater than the closer's outstanding balance:
   2325     - MUST either send a `warning` and close the connection, or send an `error` and fail the channel.
   2326   - If `closee_scriptpubkey` does not match the last script it sent (from `closing_complete` or from the initial `shutdown`):
   2327     - SHOULD ignore `closing_complete`.
   2328     - SHOULD send a `warning`.
   2329     - SHOULD close the connection.
   2330   - If `closer_scriptpubkey` is invalid (as detailed in the [`shutdown` requirements](#closing-initiation-shutdown)):
   2331     - SHOULD ignore `closing_complete`.
   2332     - SHOULD send a `warning`.
   2333     - SHOULD close the connection.
   2334   - If `closer_scriptpubkey` is a valid `OP_RETURN` script:
   2335     - MUST set the closer's output amount to zero so that all funds go to fees, as specified in [BOLT #3](03-transactions.md#closing-transaction).
   2336   - MUST generate the remote closing transaction as specified in [BOLT #3](03-transactions.md#closing-transaction).
   2337   - Select a signature for validation:
   2338     - If the local output amount is dust:
   2339       - MUST use `closer_output_only`.
   2340     - Otherwise, if it considers the local output amount uneconomical AND its `closee_scriptpubkey` is not `OP_RETURN`:
   2341       - MUST use `closer_output_only`.
   2342     - Otherwise, if `closer_and_closee_outputs` is present:
   2343       - MUST use `closer_and_closee_outputs`.
   2344     - Otherwise:
   2345       - MUST use `closee_output_only`.
   2346   - If the selected signature field does not exist:
   2347     - MUST either send a `warning` and close the connection, or send an `error` and fail the channel.
   2348   - If the signature field is not valid for the corresponding closing transaction specified in [BOLT #3](03-transactions.md#closing-transaction):
   2349     - MUST either send a `warning` and close the connection, or send an `error` and fail the channel.
   2350   - If the signature field is non-compliant with LOW-S-standard rule<sup>[LOWS](https://github.com/bitcoin/bitcoin/pull/6769)</sup>:
   2351     - MUST either send a `warning` and close the connection, or send an `error` and fail the channel.
   2352   - MUST sign and broadcast the corresponding closing transaction.
   2353   - MUST send `closing_sig` with a single valid signature in the same TLV field as the `closing_complete`.
   2354   - MUST use `closer_scriptpubkey` for its own future `closing_complete` messages.
   2355 
   2356 The receiver of `closing_sig`:
   2357   - If `closer_scriptpubkey`, `closee_scriptpubkey`, `fee_satoshis` or `locktime` don't match what was sent in `closing_complete`:
   2358     - MUST either send a `warning` and close the connection, or send an `error` and fail the channel.
   2359   - If `tlvs` does not contain exactly one signature:
   2360     - MUST either send a `warning` and close the connection, or send an `error` and fail the channel.
   2361   - If `tlvs` does not contain one of the TLV fields sent in `closing_complete`:
   2362     - MUST either send a `warning` and close the connection, or send an `error` and fail the channel.
   2363   - If the signature field is not valid for the corresponding closing transaction specified in [BOLT #3](03-transactions.md#closing-transaction):
   2364     - MUST either send a `warning` and close the connection, or send an `error` and fail the channel.
   2365   - If the signature field is non-compliant with LOW-S-standard rule<sup>[LOWS](https://github.com/bitcoin/bitcoin/pull/6769)</sup>:
   2366     - MUST either send a `warning` and close the connection, or send an `error` and fail the channel.
   2367   - otherwise:
   2368     - MUST broadcast the corresponding closing transaction.
   2369   - MAY send another `closing_complete` (e.g. with a different `fee_satoshis` or `closer_scriptpubkey`).
   2370 
   2371 ### Rationale
   2372 
   2373 The close protocol is designed to avoid any failure scenarios caused by fee disagreement,
   2374 since each side offers to pay its own desired fee.
   2375 
   2376 If one side has less funds than the other, it may choose to omit its own output, and in this case
   2377 dust MUST be omitted, to ensure that the resulting transaction can be broadcast.
   2378 
   2379 The corner case where fees are so high that both outputs are dust is addressed in two ways: paying
   2380 a low fee to avoid the problem, or using an `OP_RETURN` (which is never "dust"). If one side
   2381 chooses to use an `OP_RETURN` output, its amount must be 0 to ensure that the resulting transaction
   2382 can be broadcast.
   2383 
   2384 Note that there is usually no reason to pay a high fee for rapid processing, since an urgent child
   2385 could pay the fee on the closing transactions' behalf. If rapid processing is desired and CPFP is
   2386 not an option, the closer can RBF its previous closing transactions by sending `closing_complete`
   2387 again.
   2388 
   2389 Sending a new `closing_complete` message overrides previous ones, so you can negotiate again (even
   2390 changing the output address if `upfront_shutdown_script` was not negotiated). This creates a rare
   2391 race condition if both nodes send `closing_complete` to change their `closer_scriptpubkey` at the
   2392 same time: when that happens, the `closing_complete` they receive will be using their previous
   2393 output script, so they shouldn't sign the corresponding transaction. When that happens, we simply
   2394 reconnect, which provides the opportunity for both nodes to send their latest output script in
   2395 `shutdown` and restart the signing flow. We include the closer and closee scripts in `closing_sig`
   2396 to allow our peer to detect a script mismatch and correctly ignore the signatures, which also
   2397 helps debugging race conditions.
   2398 
   2399 If the closer proposes a transaction which will not relay (an output is dust, or the fee rate it
   2400 proposes is too low), it doesn't harm the closee to sign the transaction.
   2401 
   2402 Similarly, if the closer proposes a high fee, it doesn't harm the closee to sign the transaction,
   2403 as the closer is paying.
   2404 
   2405 There's a slight game where each side would prefer the other side pay the fee, and proposes a
   2406 minimal fee. If neither side proposes a fee which will relay, the negotiation can occur again,
   2407 or the final commitment transaction can be spent. In practice, the opener has an incentive to
   2408 offer a reasonable closing fee, as they would pay the fee for the commitment transaction, which
   2409 also costs more to spend.
   2410 
   2411 ### Legacy Closing Negotiation: `closing_signed`
   2412 
   2413 Once shutdown is complete, the channel is empty of HTLCs, there are no commitments
   2414 for which a revocation is owed, and all updates are included on both commitments,
   2415 the final current commitment transactions will have no HTLCs, and closing fee
   2416 negotiation begins: if `option_simple_close` is negotiated, the section above applies,
   2417 otherwise this legacy section applies.
   2418 
   2419 The funder chooses a fee it thinks is fair, and
   2420 signs the closing transaction with the `scriptpubkey` fields from the
   2421 `shutdown` messages (along with its chosen fee) and sends the signature;
   2422 the other node then replies similarly, using a fee it thinks is fair.  This
   2423 exchange continues until both agree on the same fee or when one side fails
   2424 the channel.
   2425 
   2426 In the modern method, the funder sends its permissible fee range, and the
   2427 non-funder has to pick a fee in this range. If the non-funder chooses the same
   2428 value, negotiation is complete after two messages, otherwise the funder will
   2429 reply with the same value (completing after three messages).
   2430 
   2431 1. type: 39 (`closing_signed`)
   2432 2. data:
   2433    * [`channel_id`:`channel_id`]
   2434    * [`u64`:`fee_satoshis`]
   2435    * [`signature`:`signature`]
   2436    * [`closing_signed_tlvs`:`tlvs`]
   2437 
   2438 1. `tlv_stream`: `closing_signed_tlvs`
   2439 2. types:
   2440     1. type: 1 (`fee_range`)
   2441     2. data:
   2442         * [`u64`:`min_fee_satoshis`]
   2443         * [`u64`:`max_fee_satoshis`]
   2444 
   2445 #### Requirements
   2446 
   2447 Note: These requirements only apply if `option_simple_close` is NOT
   2448 negotiated, otherwise the requirements [Closing Negotiation:
   2449 `closing_complete` and `closing_sig`](#closing-negotiation-closing_complete-and-closing_sig) apply.
   2450 
   2451 The funding node:
   2452   - after `shutdown` has been received, AND no HTLCs remain in either commitment transaction:
   2453     - SHOULD send a `closing_signed` message.
   2454 
   2455 The sending node:
   2456   - SHOULD set the initial `fee_satoshis` according to its estimate of cost of
   2457   inclusion in a block.
   2458   - SHOULD set `fee_range` according to the minimum and maximum fees it is
   2459   prepared to pay for a close transaction.
   2460   - if it doesn't receive a `closing_signed` response after a reasonable amount of time:
   2461     - MUST fail the channel
   2462   - if it is not the funder:
   2463     - SHOULD set `max_fee_satoshis` to at least the `max_fee_satoshis` received
   2464     - SHOULD set `min_fee_satoshis` to a fairly low value
   2465   - MUST set `signature` to the Bitcoin signature of the close transaction,
   2466   as specified in [BOLT #3](03-transactions.md#closing-transaction).
   2467 
   2468 The receiving node:
   2469   - if the `signature` is not valid for either variant of closing transaction
   2470   specified in [BOLT #3](03-transactions.md#closing-transaction) OR non-compliant with LOW-S-standard rule<sup>[LOWS](https://github.com/bitcoin/bitcoin/pull/6769)</sup>:
   2471     - MUST send a `warning` and close the connection, or send an
   2472       `error` and fail the channel.
   2473   - if `fee_satoshis` is equal to its previously sent `fee_satoshis`:
   2474     - SHOULD sign and broadcast the final closing transaction.
   2475     - MAY close the connection.
   2476   - if `fee_satoshis` matches its previously sent `fee_range`:
   2477     - SHOULD use `fee_satoshis` to sign and broadcast the final closing transaction
   2478     - SHOULD reply with a `closing_signed` with the same `fee_satoshis` value if it is different from its previously sent `fee_satoshis`
   2479     - MAY close the connection.
   2480   - if the message contains a `fee_range`:
   2481     - if there is no overlap between that and its own `fee_range`:
   2482       - SHOULD send a warning
   2483       - MUST fail the channel if it doesn't receive a satisfying `fee_range` after a reasonable amount of time
   2484     - otherwise:
   2485       - if it is the funder:
   2486         - if `fee_satoshis` is not in the overlap between the sent and received `fee_range`:
   2487           - MUST fail the channel
   2488         - otherwise:
   2489           - MUST reply with the same `fee_satoshis`.
   2490       - otherwise (it is not the funder):
   2491         - if it has already sent a `closing_signed`:
   2492           - if `fee_satoshis` is not the same as the value it sent:
   2493             - MUST fail the channel
   2494         - otherwise:
   2495           - MUST propose a `fee_satoshis` in the overlap between received and (about-to-be) sent `fee_range`.
   2496   - otherwise, if `fee_satoshis` is not strictly between its last-sent `fee_satoshis`
   2497   and its previously-received `fee_satoshis`, UNLESS it has since reconnected:
   2498     - SHOULD send a `warning` and close the connection, or send an
   2499       `error` and fail the channel.
   2500   - otherwise, if the receiver agrees with the fee:
   2501     - SHOULD reply with a `closing_signed` with the same `fee_satoshis` value.
   2502   - otherwise:
   2503     - MUST propose a value "strictly between" the received `fee_satoshis`
   2504     and its previously-sent `fee_satoshis`.
   2505 
   2506 The receiving node:
   2507   - if one of the outputs in the closing transaction is below the dust limit for its `scriptpubkey` (see [BOLT 3](03-transactions.md#dust-limits)):
   2508     - MUST fail the channel
   2509 
   2510 #### Rationale
   2511 
   2512 When `fee_range` is not provided, the "strictly between" requirement ensures
   2513 that forward progress is made, even if only by a single satoshi at a time.
   2514 To avoid keeping state and to handle the corner case, where fees have shifted
   2515 between disconnection and reconnection, negotiation restarts on reconnection.
   2516 
   2517 Note there is limited risk if the closing transaction is
   2518 delayed, but it will be broadcast very soon; so there is usually no
   2519 reason to pay a premium for rapid processing.
   2520 
   2521 Note that the non-funder is not paying the fee, so there is no reason for it
   2522 to have a maximum feerate. It may want a minimum feerate, however, to ensure
   2523 that the transaction propagates. It can always use CPFP later to speed up
   2524 confirmation if necessary, so that minimum should be low.
   2525 
   2526 It may happen that the closing transaction doesn't meet bitcoin's default relay
   2527 policies (e.g. when using a non-segwit shutdown script for an output below 546
   2528 satoshis, which is possible if `dust_limit_satoshis` is below 546 satoshis).
   2529 No funds are at risk when that happens, but the channel must be force-closed as
   2530 the closing transaction will likely never reach miners.
   2531 
   2532 ## Normal Operation
   2533 
   2534 Once both nodes have exchanged `channel_ready` (and optionally [`announcement_signatures`](07-routing-gossip.md#the-announcement_signatures-message)), the channel can be used to make payments via Hashed Time Locked Contracts.
   2535 
   2536 Changes are sent in batches: one or more `update_` messages are sent before a
   2537 `commitment_signed` message, as in the following diagram:
   2538 
   2539         +-------+                               +-------+
   2540         |       |--(1)---- update_add_htlc ---->|       |
   2541         |       |--(2)---- update_add_htlc ---->|       |
   2542         |       |<-(3)---- update_add_htlc -----|       |
   2543         |       |                               |       |
   2544         |       |--(4)--- commitment_signed --->|       |
   2545         |   A   |<-(5)---- revoke_and_ack ------|   B   |
   2546         |       |                               |       |
   2547         |       |<-(6)--- commitment_signed ----|       |
   2548         |       |--(7)---- revoke_and_ack ----->|       |
   2549         |       |                               |       |
   2550         |       |--(8)--- commitment_signed --->|       |
   2551         |       |<-(9)---- revoke_and_ack ------|       |
   2552         +-------+                               +-------+
   2553 
   2554 Counter-intuitively, these updates apply to the *other node's*
   2555 commitment transaction; the node only adds those updates to its own
   2556 commitment transaction when the remote node acknowledges it has
   2557 applied them via `revoke_and_ack`.
   2558 
   2559 Thus each update traverses through the following states:
   2560 
   2561 1. pending on the receiver
   2562 2. in the receiver's latest commitment transaction
   2563 3. ... and the receiver's previous commitment transaction has been revoked,
   2564    and the update is pending on the sender
   2565 4. ... and in the sender's latest commitment transaction
   2566 5. ... and the sender's previous commitment transaction has been revoked
   2567 
   2568 
   2569 As the two nodes' updates are independent, the two commitment
   2570 transactions may be out of sync indefinitely. This is not concerning:
   2571 what matters is whether both sides have irrevocably committed to a
   2572 particular update or not (the final state, above).
   2573 
   2574 ### Forwarding HTLCs
   2575 
   2576 In general, a node offers HTLCs for two reasons: to initiate a payment of its own,
   2577 or to forward another node's payment. In the forwarding case, care must
   2578 be taken to ensure the *outgoing* HTLC cannot be redeemed unless the *incoming*
   2579 HTLC can be redeemed. The following requirements ensure this is always true.
   2580 
   2581 The respective **addition/removal** of an HTLC is considered *irrevocably committed* when:
   2582 
   2583 1. The commitment transaction **with/without** it is committed to by both nodes, and any
   2584 previous commitment transaction **without/with** it has been revoked, OR
   2585 2. The commitment transaction **with/without** it has been irreversibly committed to
   2586 the blockchain.
   2587 
   2588 #### Requirements
   2589 
   2590 A node:
   2591   - until an incoming HTLC has been irrevocably committed:
   2592     - MUST NOT offer the corresponding outgoing HTLC (`update_add_htlc`) in response to that incoming HTLC.
   2593   - until the removal of an outgoing HTLC is irrevocably committed, OR until the outgoing on-chain HTLC output has been spent via the HTLC-timeout transaction (with sufficient depth):
   2594     - MUST NOT fail the incoming HTLC (`update_fail_htlc`) that corresponds
   2595 to that outgoing HTLC.
   2596   - once the `cltv_expiry` of an incoming HTLC has been reached, OR if `cltv_expiry` minus `current_height` is less than `cltv_expiry_delta` for the corresponding outgoing HTLC:
   2597     - MUST fail that incoming HTLC (`update_fail_htlc`).
   2598   - if an incoming HTLC's `cltv_expiry` is unreasonably far in the future:
   2599     - SHOULD fail that incoming HTLC (`update_fail_htlc`).
   2600   - upon receiving an `update_fulfill_htlc` for an outgoing HTLC, OR upon discovering the `payment_preimage` from an on-chain HTLC spend:
   2601     - MUST fulfill the incoming HTLC that corresponds to that outgoing HTLC.
   2602 
   2603 #### Rationale
   2604 
   2605 In general, one side of the exchange needs to be dealt with before the other.
   2606 Fulfilling an HTLC is different: knowledge of the preimage is, by definition,
   2607 irrevocable and the incoming HTLC should be fulfilled as soon as possible to
   2608 reduce latency.
   2609 
   2610 An HTLC with an unreasonably long expiry is a denial-of-service vector and
   2611 therefore is not allowed. Note that the exact value of "unreasonable" is currently unclear
   2612 and may depend on network topology.
   2613 
   2614 ### `cltv_expiry_delta` Selection
   2615 
   2616 Once an HTLC has timed out, it can either be fulfilled or timed-out;
   2617 care must be taken around this transition, both for offered and received HTLCs.
   2618 
   2619 Consider the following scenario, where A sends an HTLC to B, who
   2620 forwards to C, who delivers the goods as soon as the payment is
   2621 received.
   2622 
   2623 1. C needs to be sure that the HTLC from B cannot time out, even if B becomes
   2624    unresponsive; i.e. C can fulfill the incoming HTLC on-chain before B can
   2625    time it out on-chain.
   2626 
   2627 2. B needs to be sure that if C fulfills the HTLC from B, it can fulfill the
   2628    incoming HTLC from A; i.e. B can get the preimage from C and fulfill the incoming
   2629    HTLC on-chain before A can time it out on-chain.
   2630 
   2631 The critical settings here are the `cltv_expiry_delta` in
   2632 [BOLT #7](07-routing-gossip.md#the-channel_update-message) and the
   2633 related `min_final_cltv_expiry_delta` in [BOLT #11](11-payment-encoding.md#tagged-fields).
   2634 `cltv_expiry_delta` is the minimum difference in HTLC CLTV timeouts, in
   2635 the forwarding case (B). `min_final_cltv_expiry_delta` is the minimum difference
   2636 between HTLC CLTV timeout and the current block height, for the
   2637 terminal case (C).
   2638 
   2639 Note that a node is at risk if it accepts an HTLC in one channel and
   2640 offers an HTLC in another channel with too small of a difference between
   2641 the CLTV timeouts.  For this reason, the `cltv_expiry_delta` for the
   2642 *outgoing* channel is used as the delta across a node.
   2643 
   2644 The worst-case number of blocks between outgoing and
   2645 incoming HTLC resolution can be derived, given a few assumptions:
   2646 
   2647 * a worst-case reorganization depth `R` blocks
   2648 * a grace-period `G` blocks after HTLC timeout before giving up on
   2649   an unresponsive peer and dropping to chain
   2650 * a number of blocks `S` between transaction broadcast and the
   2651   transaction being included in a block
   2652 
   2653 The worst case is for a forwarding node (B) that takes the longest
   2654 possible time to spot the outgoing HTLC fulfillment and also takes
   2655 the longest possible time to redeem it on-chain:
   2656 
   2657 1. The B->C HTLC times out at block `N`, and B waits `G` blocks until
   2658    it gives up waiting for C. B or C commits to the blockchain,
   2659    and B spends HTLC, which takes `S` blocks to be included.
   2660 2. Bad case: C wins the race (just) and fulfills the HTLC, B only sees
   2661    that transaction when it sees block `N+G+S+1`.
   2662 3. Worst case: There's reorganization `R` deep in which C wins and
   2663    fulfills. B only sees transaction at `N+G+S+R`.
   2664 4. B now needs to fulfill the incoming A->B HTLC, but A is unresponsive: B waits `G` more
   2665    blocks before giving up waiting for A. A or B commits to the blockchain.
   2666 5. Bad case: B sees A's commitment transaction in block `N+G+S+R+G+1` and has
   2667    to spend the HTLC output, which takes `S` blocks to be mined.
   2668 6. Worst case: there's another reorganization `R` deep which A uses to
   2669    spend the commitment transaction, so B sees A's commitment
   2670    transaction in block `N+G+S+R+G+R` and has to spend the HTLC output, which
   2671    takes `S` blocks to be mined.
   2672 7. B's HTLC spend needs to be at least `R` deep before it times out,
   2673    otherwise another reorganization could allow A to timeout the
   2674    transaction.
   2675 
   2676 Thus, the worst case is `3R+2G+2S`, assuming `R` is at least 1. Note that the
   2677 chances of three reorganizations in which the other node wins all of them is
   2678 low for `R` of 2 or more. Since high fees are used (and HTLC spends can use
   2679 almost arbitrary fees), `S` should be small during normal operation; although,
   2680 given that block times are irregular, empty blocks still occur, fees may vary
   2681 greatly, and the fees cannot be bumped on HTLC transactions, `S=12` should be
   2682 considered a minimum. `S` is also the parameter that may vary the most under
   2683 attack, so a higher value may be desirable when non-negligible amounts are at
   2684 risk. The grace period `G` can be low (1 or 2), as nodes are required to timeout
   2685 or fulfill as soon as possible; but if `G` is too low it increases the risk of
   2686 unnecessary channel closure due to networking delays.
   2687 
   2688 There are four values that need be derived:
   2689 
   2690 1. the `cltv_expiry_delta` for channels, `3R+2G+2S`: if in doubt, a
   2691    `cltv_expiry_delta` of at least 34 is reasonable (R=2, G=2, S=12).
   2692 
   2693 2. the deadline for offered HTLCs: the deadline after which the channel has to
   2694    be failed and timed out on-chain. This is `G` blocks after the HTLC's
   2695    `cltv_expiry`: 1 or 2 blocks is reasonable.
   2696 
   2697 3. the deadline for received HTLCs this node has fulfilled: the deadline after
   2698    which the channel has to be failed and the HTLC fulfilled on-chain before
   2699    its `cltv_expiry`. See steps 4-7 above, which imply a deadline of `2R+G+S`
   2700    blocks before `cltv_expiry`: 18 blocks is reasonable.
   2701 
   2702 4. the minimum `cltv_expiry` accepted for terminal payments: the
   2703    worst case for the terminal node C is `2R+G+S` blocks (as, again, steps
   2704    1-3 above don't apply). The default in [BOLT #11](11-payment-encoding.md) is
   2705    18, which matches this calculation.
   2706 
   2707 #### Requirements
   2708 
   2709 An offering node:
   2710   - MUST estimate a timeout deadline for each HTLC it offers.
   2711   - MUST NOT offer an HTLC with a timeout deadline before its `cltv_expiry`.
   2712   - if an HTLC which it offered is in either node's current
   2713   commitment transaction, AND is past this timeout deadline:
   2714     - SHOULD send an `error` to the receiving peer (if connected).
   2715     - MUST fail the channel.
   2716 
   2717 A fulfilling node:
   2718   - for each HTLC it is attempting to fulfill:
   2719     - MUST estimate a fulfillment deadline.
   2720   - MUST fail (and not forward) an HTLC whose fulfillment deadline is already past.
   2721   - if an HTLC it has fulfilled is in either node's current commitment
   2722   transaction, AND is past this fulfillment deadline:
   2723     - SHOULD send an `error` to the offering peer (if connected).
   2724     - MUST fail the channel.
   2725 
   2726 ### Bounding exposure to trimmed in-flight HTLCs: `max_dust_htlc_exposure_msat`
   2727 
   2728 When an HTLC in a channel is below the "trimmed" threshold in [BOLT3 #3](03-transactions.md),
   2729 the HTLC cannot be claimed on-chain, instead being turned into additional miner
   2730 fees if either party unilaterally closes the channel. Because the threshold is
   2731 per-HTLC, the total exposure to such HTLCs may be substantial if there are many
   2732 dust HTLCs committed when the channel is force-closed.
   2733 
   2734 This can be exploited in griefing attacks or even in miner-extractable-value attacks,
   2735 if the malicious entity wins <sup>[mining capabilities](https://lists.linuxfoundation.org/pipermail/lightning-dev/2020-May/002714.html)</sup>.
   2736 
   2737 The total exposure is given by the following back-of-the-envelope computation:
   2738 
   2739 	remote `max_accepted_htlcs` * (`HTLC-success-kiloweight` * `feerate_per_kw` + remote `dust_limit_satoshis`)
   2740 		+ local `max_accepted_htlcs` * (`HTLC-timeout-kiloweight` * `feerate_per_kw` + remote `dust_limit_satoshis`)
   2741 
   2742 To mitigate this scenario, a `max_dust_htlc_exposure_msat` threshold can be
   2743 applied when sending, forwarding and receiving HTLCs.
   2744 
   2745 A node:
   2746   - when receiving an HTLC:
   2747     - if the HTLC's `amount_msat` is smaller than the remote `dust_limit_satoshis` plus the HTLC-timeout fee at `feerate_per_kw`:
   2748       - if the `amount_msat` plus the dust balance of the remote transaction is greater than `max_dust_htlc_exposure_msat`:
   2749         - SHOULD fail this HTLC once it's committed
   2750         - SHOULD NOT reveal a preimage for this HTLC
   2751     - if the HTLC's `amount_msat` is smaller than the local `dust_limit_satoshis` plus the HTLC-success fee at `feerate_per_kw`:
   2752       - if the `amount_msat` plus the dust balance of the local transaction is greater than `max_dust_htlc_exposure_msat`:
   2753         - SHOULD fail this HTLC once it's committed
   2754         - SHOULD NOT reveal a preimage for this HTLC
   2755   - when offering an HTLC:
   2756     - if the HTLC's `amount_msat` is smaller than the remote `dust_limit_satoshis` plus the HTLC-success fee at `feerate_per_kw`:
   2757       - if the `amount_msat` plus the dust balance of the remote transaction is greater than `max_dust_htlc_exposure_msat`:
   2758         - SHOULD NOT send this HTLC
   2759         - SHOULD fail the corresponding incoming HTLC (if any)
   2760     - if the HTLC's `amount_msat` is inferior to the holder's `dust_limit_satoshis` plus the HTLC-timeout fee at the `feerate_per_kw`:
   2761       - if the `amount_msat` plus the dust balance of the local transaction is greater than `max_dust_htlc_exposure_msat`:
   2762         - SHOULD NOT send this HTLC
   2763         - SHOULD fail the corresponding incoming HTLC (if any)
   2764 
   2765 The `max_dust_htlc_exposure_msat` is an upper bound on the trimmed balance from
   2766 dust exposure. The exact value used is a matter of node policy.
   2767 
   2768 For channels that don't use `zero_fee_commitments` or `option_anchors`, an
   2769 increase of the `feerate_per_kw` may trim multiple htlcs from commitment
   2770 transactions, which could create a large increase in dust exposure.
   2771 
   2772 ### Adding an HTLC: `update_add_htlc`
   2773 
   2774 Either node can send `update_add_htlc` to offer an HTLC to the other,
   2775 which is redeemable in return for a payment preimage. Amounts are in
   2776 millisatoshi, though on-chain enforcement is only possible for whole
   2777 satoshi amounts greater than the dust limit (in commitment transactions these are rounded down as
   2778 specified in [BOLT #3](03-transactions.md)).
   2779 
   2780 The format of the `onion_routing_packet` portion, which indicates where the payment
   2781 is destined, is described in [BOLT #4](04-onion-routing.md).
   2782 
   2783 1. type: 128 (`update_add_htlc`)
   2784 2. data:
   2785    * [`channel_id`:`channel_id`]
   2786    * [`u64`:`id`]
   2787    * [`u64`:`amount_msat`]
   2788    * [`sha256`:`payment_hash`]
   2789    * [`u32`:`cltv_expiry`]
   2790    * [`1366*byte`:`onion_routing_packet`]
   2791 
   2792 1. `tlv_stream`: `update_add_htlc_tlvs`
   2793 2. types:
   2794     1. type: 0 (`blinded_path`)
   2795     2. data:
   2796         * [`point`:`path_key`]
   2797 
   2798 #### Requirements
   2799 
   2800 A sending node:
   2801   - if `zero_fee_commitments` has not been negotiated:
   2802     - if it is _responsible_ for paying the Bitcoin fee:
   2803       - MUST NOT offer `amount_msat` if, after adding that HTLC to its commitment
   2804       transaction, it cannot pay the fee for either the local or remote commitment
   2805       transaction at the current `feerate_per_kw` while maintaining its channel
   2806       reserve (see [Updating Fees](#updating-fees-update_fee)).
   2807       - if `option_anchors` applies to this commitment transaction and the sending
   2808       node is the funder:
   2809         - MUST be able to additionally pay for `to_local_anchor` and
   2810         `to_remote_anchor` above its reserve.
   2811       - SHOULD NOT offer `amount_msat` if, after adding that HTLC to its commitment
   2812       transaction, its remaining balance doesn't allow it to pay the commitment
   2813       transaction fee when receiving or sending a future additional non-dust HTLC
   2814       while maintaining its channel reserve. It is recommended that this "fee spike
   2815       buffer" can handle twice the current `feerate_per_kw` to ensure predictability
   2816       between implementations.
   2817     - if it is _not responsible_ for paying the Bitcoin fee:
   2818       - SHOULD NOT offer `amount_msat` if, once the remote node adds that HTLC to
   2819       its commitment transaction, it cannot pay the fee for the updated local or
   2820       remote transaction at the current `feerate_per_kw` while maintaining its
   2821       channel reserve.
   2822   - MUST offer `amount_msat` greater than 0.
   2823   - MUST NOT offer `amount_msat` below the receiving node's `htlc_minimum_msat`
   2824   - MUST set `cltv_expiry` less than 500000000.
   2825   - if result would be offering more than the remote's
   2826   `max_accepted_htlcs` HTLCs, in the remote commitment transaction:
   2827     - MUST NOT add an HTLC.
   2828   - if the total value of offered HTLCs would exceed the remote's
   2829 `max_htlc_value_in_flight_msat`:
   2830     - MUST NOT add an HTLC.
   2831   - for the first HTLC it offers:
   2832     - MUST set `id` to 0.
   2833   - MUST increase the value of `id` by 1 for each successive offer.
   2834   - if it is relaying a payment inside a blinded route:
   2835     - MUST set `path_key` (see [Route Blinding](04-onion-routing.md#route-blinding))
   2836   - if a splice is pending:
   2837     - MUST ensure that requirements are met for all commmitment transactions.
   2838 
   2839 `id` MUST NOT be reset to 0 after the update is complete (i.e. after `revoke_and_ack` has
   2840 been received). It MUST continue incrementing instead.
   2841 
   2842 A receiving node:
   2843   - receiving an `amount_msat` equal to 0, OR less than its own `htlc_minimum_msat`:
   2844     - SHOULD send a `warning` and close the connection, or send an
   2845       `error` and fail the channel.
   2846   - receiving an `amount_msat` that the sending node cannot afford at the current `feerate_per_kw` (while maintaining its channel reserve and any `to_local_anchor` and `to_remote_anchor` costs):
   2847     - SHOULD send a `warning` and close the connection, or send an
   2848       `error` and fail the channel.
   2849   - if a sending node adds more than receiver `max_accepted_htlcs` HTLCs to
   2850     its local commitment transaction, OR adds more than receiver `max_htlc_value_in_flight_msat` worth of offered HTLCs to its local commitment transaction:
   2851     - SHOULD send a `warning` and close the connection, or send an
   2852       `error` and fail the channel.
   2853   - if sending node sets `cltv_expiry` to greater or equal to 500000000:
   2854     - SHOULD send a `warning` and close the connection, or send an
   2855       `error` and fail the channel.
   2856   - MUST allow multiple HTLCs with the same `payment_hash`.
   2857   - if the sender did not previously acknowledge the commitment of that HTLC:
   2858     - MUST ignore a repeated `id` value after a reconnection.
   2859   - if other `id` violations occur:
   2860     - MAY send a `warning` and close the connection, or send an
   2861       `error` and fail the channel.
   2862   - MUST decrypt `onion_routing_packet` as described in [Onion Decryption](04-onion-routing.md#onion-decryption) to extract a `payload`.
   2863     - MUST use `path_key` (if specified).
   2864     - MUST use `payment_hash` as `associated_data`.
   2865   - If decryption fails, the result is not a valid `payload` TLV, or it contains unknown even types:
   2866     - MUST respond with an error as detailed in [Failure Messages](04-onion-routing.md#failure-messages)
   2867   - Otherwise:
   2868     - MUST follow the requirements for the reader of `payload` in [Payload Format](04-onion-routing.md#payload-format)
   2869   - If a splice is pending:
   2870     - MUST ensure that requirements are met for all commmitment transactions.
   2871 
   2872 The `onion_routing_packet` contains an obfuscated list of hops and instructions for each hop along the path.
   2873 It commits to the HTLC by setting the `payment_hash` as associated data, i.e. includes the `payment_hash` in the computation of HMACs.
   2874 This prevents replay attacks that would reuse a previous `onion_routing_packet` with a different `payment_hash`.
   2875 
   2876 #### Rationale
   2877 
   2878 Invalid amounts are a clear protocol violation and indicate a breakdown.
   2879 
   2880 If a node did not accept multiple HTLCs with the same payment hash, an
   2881 attacker could probe to see if a node had an existing HTLC. This
   2882 requirement, to deal with duplicates, leads to the use of a separate
   2883 identifier; it's assumed a 64-bit counter never wraps.
   2884 
   2885 Retransmissions of unacknowledged updates are explicitly allowed for
   2886 reconnection purposes; allowing them at other times simplifies the
   2887 recipient code (though strict checking may help debugging).
   2888 
   2889 `max_accepted_htlcs` is limited to 483 to ensure that, even if both
   2890 sides send the maximum number of HTLCs, the `commitment_signed` message will
   2891 still be under the maximum message size. It also ensures that
   2892 a single penalty transaction can spend the entire commitment transaction,
   2893 as calculated in [BOLT #5](05-onchain.md#penalty-transaction-weight-calculation).
   2894 When using `zero_fee_commitments`, we further limit `max_accepted_htlcs` to
   2895 114 because v3 transactions are limited to 10kvB, which decreases the number
   2896 of outputs the commitment transaction can have.
   2897 
   2898 `cltv_expiry` values equal to or greater than 500000000 would indicate a time in
   2899 seconds, and the protocol only supports an expiry in blocks.
   2900 
   2901 When `zero_fee_commitments` is not used, the node _responsible_ for paying
   2902 the Bitcoin fee should maintain a "fee spike buffer" on top of its reserve
   2903 to accommodate a future fee increase.
   2904 Without this buffer, the node _responsible_ for paying the Bitcoin fee may
   2905 reach a state where it is unable to send or receive any non-dust HTLC while
   2906 maintaining its channel reserve (because of the increased weight of the
   2907 commitment transaction), resulting in a degraded channel. See [#728](https://github.com/lightningnetwork/lightning-rfc/issues/728)
   2908 for more details.
   2909 
   2910 If splicing is supported, there can be more than one commitment transaction
   2911 at a time: proposed changes must be valid for all of them.
   2912 
   2913 ### Removing an HTLC: `update_fulfill_htlc`, `update_fail_htlc`, and `update_fail_malformed_htlc`
   2914 
   2915 For simplicity, a node can only remove HTLCs added by the other node.
   2916 There are four reasons for removing an HTLC: the payment preimage is supplied,
   2917 it has timed out, it has failed to route, or it is malformed.
   2918 
   2919 To supply the preimage:
   2920 
   2921 1. type: 130 (`update_fulfill_htlc`)
   2922 2. data:
   2923    * [`channel_id`:`channel_id`]
   2924    * [`u64`:`id`]
   2925    * [`32*byte`:`payment_preimage`]
   2926 1. `tlv_stream`: `update_fulfill_htlc_tlvs`
   2927 2. types:
   2928     1. type: 1 (`attribution_data`)
   2929     2. data:
   2930         * [`20*u32`:`htlc_hold_times`]
   2931         * [`210*sha256[..4]`:`truncated_hmacs`]
   2932     1. type: 3 (`fulfillment_payload`)
   2933     2. data:
   2934         * [`...*byte`:`fulfillment_payload`]
   2935 
   2936 The `fulfillment_payload` field is an opaque encrypted blob for the benefit of
   2937 the original HTLC initiator, as defined in
   2938 [BOLT #4](04-onion-routing.md#successful-payments). It mirrors the `reason`
   2939 field of `update_fail_htlc`: the final node originates it, and intermediate
   2940 nodes obfuscate and relay it.
   2941 
   2942 For a timed out or route-failed HTLC:
   2943 
   2944 1. type: 131 (`update_fail_htlc`)
   2945 2. data:
   2946    * [`channel_id`:`channel_id`]
   2947    * [`u64`:`id`]
   2948    * [`u16`:`len`]
   2949    * [`len*byte`:`reason`]
   2950 1. `tlv_stream`: `update_fail_htlc_tlvs`
   2951 2. types:
   2952     1. type: 1 (`attribution_data`)
   2953     2. data:
   2954         * [`20*u32`:`htlc_hold_times`]
   2955         * [`210*sha256[..4]`:`truncated_hmacs`]
   2956 
   2957 The `reason` field is an opaque encrypted blob for the benefit of the
   2958 original HTLC initiator, as defined in [BOLT #4](04-onion-routing.md);
   2959 however, there's a special malformed failure variant for the case where
   2960 the peer couldn't parse it: in this case the current node instead takes action, encrypting
   2961 it into a `update_fail_htlc` for relaying.
   2962 
   2963 For an unparsable HTLC:
   2964 
   2965 1. type: 135 (`update_fail_malformed_htlc`)
   2966 2. data:
   2967    * [`channel_id`:`channel_id`]
   2968    * [`u64`:`id`]
   2969    * [`sha256`:`sha256_of_onion`]
   2970    * [`u16`:`failure_code`]
   2971 
   2972 #### Requirements
   2973 
   2974 A node:
   2975   - SHOULD remove an HTLC as soon as it can.
   2976   - SHOULD fail an HTLC which has timed out.
   2977   - until the corresponding HTLC is irrevocably committed in both sides'
   2978   commitment transactions:
   2979     - MUST NOT send an `update_fulfill_htlc`, `update_fail_htlc`, or
   2980 `update_fail_malformed_htlc`.
   2981   - When failing an incoming HTLC:
   2982     - If `current_path_key` is set in the onion payload and it is not the
   2983       final node:
   2984       - MUST send an `update_fail_htlc` error using the `invalid_onion_blinding`
   2985         failure code for any local or downstream errors.
   2986       - SHOULD use the `sha256_of_onion` of the onion it received.
   2987       - MAY use an all zero `sha256_of_onion`.
   2988       - SHOULD add a random delay before sending `update_fail_htlc`.
   2989     - If `path_key` is set in the incoming `update_add_htlc`:
   2990       - MUST send an `update_fail_malformed_htlc` error using the
   2991         `invalid_onion_blinding` failure code for any local or downstream errors.
   2992       - SHOULD use the `sha256_of_onion` of the onion it received.
   2993       - MAY use an all zero `sha256_of_onion`.
   2994   - When supporting `option_attribution_data`:
   2995     - if `path_key` is not set in the incoming `update_add_htlc`:
   2996       - MUST initialize `attribution_data` and include it in `update_fail_htlc` and `update_fulfill_htlc`. See [BOLT04](04-onion-routing.md).
   2997     - if a `fulfillment_payload` is present in the `update_fulfill_htlc` received from the downstream node:
   2998       - MUST obfuscate and relay it in the outgoing `update_fulfill_htlc`, including in a blinded path. See [BOLT04](04-onion-routing.md).
   2999 
   3000 A receiving node:
   3001   - if the `id` does not correspond to an HTLC in its current commitment transaction:
   3002     - MUST send a `warning` and close the connection, or send an
   3003       `error` and fail the channel.
   3004   - if the `payment_preimage` value in `update_fulfill_htlc`
   3005   doesn't SHA256 hash to the corresponding HTLC `payment_hash`:
   3006     - MUST send a `warning` and close the connection, or send an
   3007       `error` and fail the channel.
   3008   - if the `fulfillment_payload` in `update_fulfill_htlc` is longer than 32768 bytes (32 KiB):
   3009     - MUST send an `error` and fail the channel.
   3010   - if the `BADONION` bit in `failure_code` is not set for
   3011   `update_fail_malformed_htlc`:
   3012     - MUST send a `warning` and close the connection, or send an
   3013       `error` and fail the channel.
   3014   - if the `sha256_of_onion` in `update_fail_malformed_htlc` doesn't match the
   3015   onion it sent and is not all zero:
   3016     - MAY retry or choose an alternate error response.
   3017   - otherwise, a receiving node which has an outgoing HTLC canceled by `update_fail_malformed_htlc`:
   3018     - MUST return an error in the `update_fail_htlc` sent to the link which
   3019       originally sent the HTLC, using the `failure_code` given and setting the
   3020       data to `sha256_of_onion`.
   3021 
   3022 #### Rationale
   3023 
   3024 A node that doesn't time out HTLCs risks channel failure (see
   3025 [`cltv_expiry_delta` Selection](#cltv_expiry_delta-selection)).
   3026 
   3027 A node that sends `update_fulfill_htlc`, before the sender, is also
   3028 committed to the HTLC and risks losing funds.
   3029 
   3030 If the onion is malformed, the upstream node won't be able to extract
   3031 the shared key to generate a response — hence the special failure message, which
   3032 makes this node do it.
   3033 
   3034 The node can check that the SHA256 that the upstream is complaining about
   3035 does match the onion it sent, which may allow it to detect random bit
   3036 errors. However, without re-checking the actual encrypted packet sent,
   3037 it won't know whether the error was its own or the remote's; so
   3038 such detection is left as an option.
   3039 
   3040 Nodes inside a blinded route must use `invalid_onion_blinding` to avoid
   3041 leaking information to senders trying to probe the blinded route.
   3042 
   3043 ### Batching channel messages
   3044 
   3045 Multiple channel messages can be grouped together as a single logical message
   3046 using the `start_batch` message.
   3047 
   3048 1. type: 127 (`start_batch`)
   3049 2. data:
   3050    * [`channel_id`:`channel_id`]
   3051    * [`u16`:`batch_size`]
   3052 
   3053 1. `tlv_stream`: `start_batch_tlvs`
   3054 2. types:
   3055    1. type: 1 (`message_type`)
   3056    2. data:
   3057      * [`u16`:`message_type`]
   3058 
   3059 #### Requirements
   3060 
   3061 A sending node:
   3062   - MUST set `batch_size` to a value strictly greater than 1.
   3063   - MUST set `batch_size` to a value lower than or equal to 20.
   3064   - MUST set `message_type` to `132` (`commitment_signed` message type as
   3065     defined in [Bolt 1](./01-messaging.md#lightning-message-format)).
   3066   - After sending `start_batch`:
   3067     - MUST send `batch_size` `commitment_signed` messages for the same
   3068       `channel_id`, without any other unrelated messages in-between.
   3069 
   3070 A receiving node:
   3071   - If `batch_size` is not strictly greater than 1:
   3072     - MUST ignore the `start_batch` message.
   3073     - SHOULD send a `warning`.
   3074   - If `batch_size` is strictly greater than 20:
   3075     - MUST send a `warning` and close the connection, or send an `error` and
   3076       fail the channel.
   3077   - MUST group the next `batch_size` messages and process them together.
   3078   - If one of those messages is not for the specified `channel_id`:
   3079     - MUST send a `warning` and close the connection, or send an `error` and
   3080       fail the channel.
   3081   - If `message_type` is missing or not set to the type for `commitment_signed`:
   3082     - MUST ignore the `start_batch` message and process the following messages
   3083       sequentially.
   3084 
   3085 #### Rationale
   3086 
   3087 The `start_batch` message is only used when sending multiple `commitment_signed`
   3088 messages during splicing. We thus narrow the requirements for this specific
   3089 scenario: they can be relaxed in the future if we use `start_batch` for other
   3090 features.
   3091 
   3092 We limit the `batch_size` to 20 elements to protect against excessive queuing
   3093 that could be abused to DoS receiving nodes. The `start_batch` message is only
   3094 used for splice RBF attempts so far, which shouldn't need that many attempts
   3095 to get transactions confirmed.
   3096 
   3097 ### Committing Updates So Far: `commitment_signed`
   3098 
   3099 When a node has changes for the remote commitment, it can apply them,
   3100 sign the resulting transaction (as defined in [BOLT #3](03-transactions.md)), and send a
   3101 `commitment_signed` message.
   3102 
   3103 1. type: 132 (`commitment_signed`)
   3104 2. data:
   3105    * [`channel_id`:`channel_id`]
   3106    * [`signature`:`signature`]
   3107    * [`u16`:`num_htlcs`]
   3108    * [`num_htlcs*signature`:`htlc_signature`]
   3109    * [`commitment_signed_tlvs`:`tlvs`]
   3110 
   3111 1. `tlv_stream`: `commitment_signed_tlvs`
   3112 2. types:
   3113    1. type: 1 (`funding_txid`)
   3114    2. data:
   3115      * [`sha256`:`funding_txid`]
   3116 
   3117 #### Requirements
   3118 
   3119 A sending node:
   3120   - MUST NOT send a `commitment_signed` message that does not include any
   3121 updates.
   3122   - MAY send a `commitment_signed` message that only
   3123 alters the fee.
   3124   - MAY send a `commitment_signed` message that doesn't
   3125 change the commitment transaction aside from the new revocation number
   3126 (due to dust, identical HTLC replacement, or insignificant or multiple
   3127 fee changes).
   3128   - MUST include one `htlc_signature` for every HTLC transaction corresponding
   3129     to the ordering of the commitment transaction (see [BOLT #3](03-transactions.md#transaction-input-and-output-ordering)).
   3130   - MUST set `funding_txid` to the funding transaction spent by this commitment
   3131     transaction.
   3132   - if it has not recently received a message from the remote node:
   3133       - SHOULD use `ping` and await the reply `pong` before sending `commitment_signed`.
   3134   - If there are `N` pending splice transactions (with `N` greater than `0`):
   3135     - MUST send `start_batch` first with `batch_size` set to `N + 1` and
   3136       `message_type` set to `132` (`commitment_signed`).
   3137     - MUST send `commitment_signed` for the current channel funding output.
   3138     - MUST send `commitment_signed` for each of the splice transactions.
   3139     - MUST set `funding_txid` in each `commitment_signed` message to match the
   3140       funding transaction spent by that commitment transaction.
   3141     - MUST NOT send any other message before it has sent the batch of
   3142       `commitment_signed` messages.
   3143 
   3144 A receiving node:
   3145   - once all pending updates are applied:
   3146     - if `signature` is not valid for its local commitment transaction OR non-compliant with LOW-S-standard rule <sup>[LOWS](https://github.com/bitcoin/bitcoin/pull/6769)</sup>:
   3147       - MUST send a `warning` and close the connection, or send an
   3148         `error` and fail the channel.
   3149     - if `num_htlcs` is not equal to the number of HTLC outputs in the local
   3150     commitment transaction:
   3151       - MUST send a `warning` and close the connection, or send an
   3152         `error` and fail the channel.
   3153   - if any `htlc_signature` is not valid for the corresponding HTLC transaction OR non-compliant with LOW-S-standard rule <sup>[LOWS](https://github.com/bitcoin/bitcoin/pull/6769)</sup>:
   3154     - MUST send a `warning` and close the connection, or send an
   3155       `error` and fail the channel.
   3156   - If there are pending splice transactions and the sending node did not
   3157     send `start_batch` followed by a batch of `commitment_signed` messages:
   3158     - MUST send an `error` and fail the channel.
   3159   - If the sending node sent `start_batch` and we are processing a batch of
   3160     `commitment_signed` messages:
   3161     - If `funding_txid` is missing in one of the `commitment_signed` messages:
   3162       - MUST send an `error` and fail the channel.
   3163     - If there are pending splice transactions:
   3164       - MUST validate each `commitment_signed` based on `funding_txid`.
   3165       - If `commitment_signed` is missing for a funding transaction:
   3166         - MUST send an `error` and fail the channel.
   3167       - Otherwise:
   3168         - MUST respond with a `revoke_and_ack` message.
   3169     - Otherwise (no pending splice transactions):
   3170       - MUST ignore `commitment_signed` where `funding_txid` does not match
   3171         the current funding transaction.
   3172       - If `commitment_signed` is missing for the current funding transaction:
   3173         - MUST send an `error` and fail the channel.
   3174       - Otherwise:
   3175         - MUST respond with a `revoke_and_ack` message.
   3176   - Otherwise:
   3177     - MUST respond with a `revoke_and_ack` message.
   3178 
   3179 #### Rationale
   3180 
   3181 There's little point offering spam updates: it implies a bug.
   3182 
   3183 The `num_htlcs` field is redundant, but makes the packet length check fully self-contained.
   3184 
   3185 The recommendation to require recent messages recognizes the reality
   3186 that networks are unreliable: nodes might not realize their peers are
   3187 offline until after sending `commitment_signed`.  Once
   3188 `commitment_signed` is sent, the sender considers itself bound to
   3189 those HTLCs, and cannot fail the related incoming HTLCs until the
   3190 output HTLCs are fully resolved.
   3191 
   3192 Note that the `htlc_signature` implicitly enforces the time-lock mechanism in
   3193 the case of offered HTLCs being timed out or received HTLCs being spent. This
   3194 is done to reduce fees by creating smaller scripts compared to explicitly
   3195 stating time-locks on HTLC outputs.
   3196 
   3197 Splicing requires us to send and receive additional signatures, as we don't
   3198 know which (if any) of the splice transactions will end up being the new
   3199 channel funding transaction. We use `start_batch` to send a batch of
   3200 `commitment_signed` messages containing signatures for each of the pending
   3201 splice transactions and for the current funding transaction. After sending
   3202 `splice_locked`, we may receive a batch containing obsolete `commitment_signed`
   3203 messages from our peer that they started sending before receiving our
   3204 `splice_locked`: we can safely ignore them by filtering on `funding_txid`.
   3205 
   3206 ### Completing the Transition to the Updated State: `revoke_and_ack`
   3207 
   3208 Once the recipient of `commitment_signed` checks the signature and knows
   3209 it has a valid new commitment transaction, it replies with the commitment
   3210 preimage for the previous commitment transaction in a `revoke_and_ack`
   3211 message.
   3212 
   3213 This message also implicitly serves as an acknowledgment of receipt
   3214 of the `commitment_signed`, so this is a logical time for the `commitment_signed` sender
   3215 to apply (to its own commitment) any pending updates it sent before
   3216 that `commitment_signed`.
   3217 
   3218 The description of key derivation is in [BOLT #3](03-transactions.md#key-derivation).
   3219 
   3220 1. type: 133 (`revoke_and_ack`)
   3221 2. data:
   3222    * [`channel_id`:`channel_id`]
   3223    * [`32*byte`:`per_commitment_secret`]
   3224    * [`point`:`next_per_commitment_point`]
   3225 
   3226 #### Requirements
   3227 
   3228 A sending node:
   3229   - MUST set `per_commitment_secret` to the secret used to generate keys for
   3230   the previous commitment transaction.
   3231   - MUST set `next_per_commitment_point` to the values for its next commitment
   3232   transaction.
   3233   - MUST send a single `revoke_and_ack` message, even if it is responding to
   3234   a batch of `commitment_signed` messages.
   3235 
   3236 A receiving node:
   3237   - if `per_commitment_secret` is not a valid secret key or does not generate the previous `per_commitment_point`:
   3238     - MUST send an `error` and fail the channel.
   3239   - if the `per_commitment_secret` was not generated by the protocol in [BOLT #3](03-transactions.md#per-commitment-secret-requirements):
   3240     - MAY send a `warning` and close the connection, or send an
   3241       `error` and fail the channel.
   3242 
   3243 A node:
   3244   - MUST NOT broadcast old (revoked) commitment transactions,
   3245     - Note: doing so will allow the other node to seize all channel funds.
   3246   - SHOULD NOT sign commitment transactions, unless it's about to broadcast
   3247   them (due to a failed connection),
   3248     - Note: this is to reduce the above risk.
   3249 
   3250 ### Updating Fees: `update_fee`
   3251 
   3252 For channels that don't use `zero_fee_commitments`, an `update_fee`
   3253 message is sent by the node which is paying the Bitcoin fee.
   3254 Like any update, it's first committed to the receiver's
   3255 commitment transaction and then (once acknowledged) committed to the
   3256 sender's. Unlike an HTLC, `update_fee` is never closed but simply
   3257 replaced.
   3258 
   3259 There is a possibility of a race, as the recipient can add new HTLCs
   3260 before it receives the `update_fee`. Under this circumstance, the sender may
   3261 not be able to afford the fee on its own commitment transaction, once the `update_fee`
   3262 is finally acknowledged by the recipient. In this case, the fee will be less
   3263 than the fee rate, as described in [BOLT #3](03-transactions.md#fee-payment).
   3264 
   3265 The exact calculation used for deriving the fee from the fee rate is
   3266 given in [BOLT #3](03-transactions.md#fee-calculation).
   3267 
   3268 1. type: 134 (`update_fee`)
   3269 2. data:
   3270    * [`channel_id`:`channel_id`]
   3271    * [`u32`:`feerate_per_kw`]
   3272 
   3273 #### Requirements
   3274 
   3275 When using `zero_fee_commitments`, nodes:
   3276   - MUST NOT send `update_fee`.
   3277 
   3278 The node _responsible_ for paying the Bitcoin fee:
   3279   - SHOULD send `update_fee` to ensure the current fee rate is sufficient (by a
   3280       significant margin) for timely processing of the commitment transaction.
   3281 
   3282 The node _not responsible_ for paying the Bitcoin fee:
   3283   - MUST NOT send `update_fee`.
   3284 
   3285 A sending node:
   3286   - if `option_anchors` was not negotiated:
   3287     - if the `update_fee` increases `feerate_per_kw`:
   3288       - if the dust balance of the remote transaction at the updated `feerate_per_kw` is greater than `max_dust_htlc_exposure_msat`:
   3289         - MAY NOT send `update_fee`
   3290         - MAY fail the channel
   3291       - if the dust balance of the local transaction at the updated `feerate_per_kw` is greater than `max_dust_htlc_exposure_msat`:
   3292         - MAY NOT send `update_fee`
   3293         - MAY fail the channel
   3294   - if a splice is pending:
   3295     - MUST ensure that requirements are met for all commmitment transactions.
   3296 
   3297 A receiving node:
   3298   - if `zero_fee_commitments` is used:
   3299     - MUST send an `error` and fail the channel.
   3300   - if the `update_fee` is too low for timely processing, OR is unreasonably large:
   3301     - MUST send a `warning` and close the connection, or send an
   3302       `error` and fail the channel.
   3303   - if the sender is not responsible for paying the Bitcoin fee:
   3304     - MUST send a `warning` and close the connection, or send an
   3305       `error` and fail the channel.
   3306   - if the sender cannot afford the new fee rate on the receiving node's
   3307   current commitment transaction:
   3308     - SHOULD send a `warning` and close the connection, or send an
   3309       `error` and fail the channel.
   3310       - but MAY delay this check until the `update_fee` is committed.
   3311     - if `option_anchors` was not negotiated:
   3312       - if the `update_fee` increases `feerate_per_kw`:
   3313         - if the dust balance of the remote transaction at the updated `feerate_per_kw` is greater then `max_dust_htlc_exposure_msat`:
   3314           - MAY fail the channel
   3315       - if the dust balance of the local transaction at the updated `feerate_per_kw` is greater than `max_dust_htlc_exposure_msat`:
   3316           - MAY fail the channel
   3317   - if a splice is pending:
   3318     - MUST ensure that requirements are met for all commmitment transactions.
   3319 
   3320 #### Rationale
   3321 
   3322 Bitcoin fees are required for unilateral closes to be effective.
   3323 With `option_anchors`, `feerate_per_kw` is not as critical anymore to guarantee
   3324 confirmation as it was in the legacy commitment format, but it still needs to
   3325 be enough to be able to enter the mempool (satisfy min relay fee and mempool
   3326 min fee). With `zero_fee_commitments`, transactions can enter the mempool
   3327 as a package with a child transaction paying the fees: channel transactions
   3328 thus don't need to directly include a fee, so this message isn't used.
   3329 
   3330 For the legacy commitment format, there is no general method for the
   3331 broadcasting node to use child-pays-for-parent to increase its effective fee.
   3332 
   3333 Given the variance in fees, and the fact that the transaction may be
   3334 spent in the future, it's a good idea for the fee payer to keep a good
   3335 margin (say 5x the expected fee requirement) for legacy commitment txes; but, due to differing methods of
   3336 fee estimation, an exact value is not specified.
   3337 
   3338 Since the fees are currently one-sided (the party which requested the
   3339 channel creation always pays the fees for the commitment transaction),
   3340 it's simplest to only allow it to set fee levels; however, as the same
   3341 fee rate applies to HTLC transactions, the receiving node must also
   3342 care about the reasonableness of the fee.
   3343 
   3344 If on-chain fees increase while commitments contain many HTLCs that will
   3345 be trimmed at the updated feerate, this could overflow the configured
   3346 `max_dust_htlc_exposure_msat`. Whether to close the channel preemptively
   3347 or not is left as a matter of node policy.
   3348 
   3349 If splicing is supported, there can be more than one commitment transaction
   3350 at a time: proposed changes must be valid for all of them.
   3351 
   3352 ## Message Retransmission
   3353 
   3354 Because communication transports are unreliable, and may need to be
   3355 re-established from time to time, the design of the transport has been
   3356 explicitly separated from the protocol.
   3357 
   3358 Nonetheless, it's assumed our transport is ordered and reliable.
   3359 Reconnection introduces doubt as to what has been received, so there are
   3360 explicit acknowledgments at that point.
   3361 
   3362 This is fairly straightforward in the case of channel establishment
   3363 and close, where messages have an explicit order, but during normal
   3364 operation, acknowledgments of updates are delayed until the
   3365 `commitment_signed` / `revoke_and_ack` exchange; so it cannot be assumed
   3366 that the updates have been received. This also means that the receiving
   3367 node only needs to store updates upon receipt of `commitment_signed`.
   3368 
   3369 Note that messages described in [BOLT #7](07-routing-gossip.md) are
   3370 independent of particular channels; their transmission requirements
   3371 are covered there, and besides being transmitted after `init` (as all
   3372 messages are), they are independent of requirements here.
   3373 
   3374 1. type: 136 (`channel_reestablish`)
   3375 2. data:
   3376    * [`channel_id`:`channel_id`]
   3377    * [`u64`:`next_commitment_number`]
   3378    * [`u64`:`next_revocation_number`]
   3379    * [`32*byte`:`your_last_per_commitment_secret`]
   3380    * [`point`:`my_current_per_commitment_point`]
   3381 
   3382 1. `tlv_stream`: `channel_reestablish_tlvs`
   3383 2. types:
   3384     1. type: 1 (`next_funding`)
   3385     2. data:
   3386         * [`sha256`:`next_funding_txid`]
   3387         * [`byte`:`retransmit_flags`]
   3388     1. type: 5 (`my_current_funding_locked`)
   3389     2. data:
   3390         * [`sha256`:`my_current_funding_locked_txid`]
   3391         * [`byte`:`retransmit_flags`]
   3392 
   3393 `next_commitment_number`: A commitment number is a 48-bit
   3394 incrementing counter for each commitment transaction; counters
   3395 are independent for each peer in the channel and start at 0.
   3396 They're only explicitly relayed to the other node in the case of
   3397 re-establishment, otherwise they are implicit.
   3398 
   3399 The `next_funding.retransmit_flags` bitfield is used to let the
   3400 receiving peer know which messages they must retransmit for the
   3401 corresponding `next_funding_txid` after the reconnection:
   3402 
   3403 | Bit Position  | Name                |
   3404 | ------------- | --------------------|
   3405 | 0             | `commitment_signed` |
   3406 
   3407 The `my_current_funding_locked.retransmit_flags` bitfield is used
   3408 to let our peer know which messages we expect them to retransmit
   3409 after the reconnection:
   3410 
   3411 | Bit Position  | Name                      |
   3412 | ------------- | --------------------------|
   3413 | 0             | `announcement_signatures` |
   3414 
   3415 ### Requirements
   3416 
   3417 A funding node:
   3418   - upon disconnection:
   3419     - if it has broadcast the funding transaction:
   3420       - MUST remember the channel for reconnection.
   3421     - otherwise:
   3422       - SHOULD NOT remember the channel for reconnection.
   3423 
   3424 A non-funding node:
   3425   - upon disconnection:
   3426     - if it has sent the `funding_signed` message:
   3427       - MUST remember the channel for reconnection.
   3428     - otherwise:
   3429       - SHOULD NOT remember the channel for reconnection.
   3430 
   3431 A node:
   3432   - MUST handle continuation of a previous channel on a new encrypted transport.
   3433   - upon disconnection:
   3434     - MUST reverse any uncommitted updates sent by the other side (i.e. all
   3435     messages beginning with `update_` for which no `commitment_signed` has
   3436     been received).
   3437       - Note: a node MAY have already used the `payment_preimage` value from
   3438     the `update_fulfill_htlc`, so the effects of `update_fulfill_htlc` are not
   3439     completely reversed.
   3440   - upon reconnection:
   3441     - if a channel is in an error state:
   3442       - SHOULD retransmit the error packet and ignore any other packets for
   3443       that channel.
   3444     - otherwise:
   3445       - MUST transmit `channel_reestablish` for each channel.
   3446       - MUST wait to receive the other node's `channel_reestablish`
   3447         message before sending any other messages for that channel.
   3448 
   3449 The sending node:
   3450   - MUST set `next_commitment_number` to the commitment number of the
   3451   next `commitment_signed` it expects to receive.
   3452   - MUST set `next_revocation_number` to the commitment number of the
   3453   next `revoke_and_ack` message it expects to receive.
   3454   - MUST set `my_current_per_commitment_point` to a valid point.
   3455   - if `next_revocation_number` equals 0:
   3456     - MUST set `your_last_per_commitment_secret` to all zeroes
   3457   - otherwise:
   3458     - MUST set `your_last_per_commitment_secret` to the last `per_commitment_secret` it received
   3459   - if it has sent `commitment_signed` for an interactive transaction construction but
   3460     it has not received `tx_signatures`:
   3461     - MUST include the `next_funding` TLV.
   3462     - MUST set `next_funding_txid` to the txid of that interactive transaction.
   3463     - if it has not received `commitment_signed` for this `next_funding_txid`:
   3464       - MUST set the `commitment_signed` bit in `retransmit_flags`.
   3465   - otherwise:
   3466     - MUST NOT include the `next_funding` TLV.
   3467   - if `option_splice` was negotiated:
   3468     - if a splice transaction reached acceptable depth while disconnected:
   3469       - MUST include `my_current_funding_locked` with the txid of the latest such transaction.
   3470     - otherwise, if it has already sent `splice_locked` for any transaction:
   3471       - MUST include `my_current_funding_locked` with the txid of the last `splice_locked` it sent.
   3472     - otherwise, if it has already sent `channel_ready`:
   3473       - MUST include `my_current_funding_locked` with the txid of the channel funding transaction.
   3474     - otherwise (it has never sent `channel_ready` or `splice_locked`):
   3475       - MUST NOT include `my_current_funding_locked`.
   3476     - if `my_current_funding_locked` is included:
   3477       - if `announce_channel` is set for this channel:
   3478         - if it has not received `announcement_signatures` for that transaction:
   3479           - MUST set the `announcement_signatures` bit to `1` in `retransmit_flags`.
   3480       - otherwise:
   3481         - MUST set the `announcement_signatures` bit to `0` in `retransmit_flags`.
   3482 
   3483 A node:
   3484   - if `next_commitment_number` is zero:
   3485     - MUST immediately fail the channel and broadcast any relevant latest commitment
   3486       transaction.
   3487   - if `next_commitment_number` is 1 in both the `channel_reestablish` it
   3488     sent and received, and none of those `channel_reestablish` messages
   3489     contain `my_current_funding_locked` or `next_funding` for a splice transaction:
   3490     - MUST retransmit `channel_ready`.
   3491   - otherwise:
   3492     - MUST NOT retransmit `channel_ready`, but MAY send `channel_ready` with
   3493       a different `short_channel_id` `alias` field.
   3494   - upon reconnection:
   3495     - MUST ignore any redundant `channel_ready` it receives.
   3496   - if `next_commitment_number` is equal to the commitment number of
   3497   the last `commitment_signed` message the receiving node has sent:
   3498     - MUST reuse the same commitment number for its next `commitment_signed`.
   3499   - otherwise:
   3500     - if `next_commitment_number` is not equal to the commitment number of the
   3501       next `commitment_signed` that the receiving node would send:
   3502       - SHOULD send an `error` and fail the channel.
   3503   - if `next_revocation_number` is equal to the commitment number of
   3504   the last `revoke_and_ack` the receiving node sent, AND the receiving node
   3505   hasn't already received a `closing_signed`:
   3506     - MUST re-send the `revoke_and_ack`.
   3507     - if it has previously sent a `commitment_signed` that needs to be
   3508     retransmitted:
   3509       - MUST retransmit `revoke_and_ack` and `commitment_signed` in the same
   3510       relative order as initially transmitted.
   3511   - otherwise:
   3512     - if `next_revocation_number` is not equal to 1 greater than the
   3513     commitment number of the last `revoke_and_ack` the receiving node has sent:
   3514       - SHOULD send an `error` and fail the channel.
   3515     - if it has not sent `revoke_and_ack`, AND `next_revocation_number`
   3516     is not equal to 0:
   3517       - SHOULD send an `error` and fail the channel.
   3518 
   3519  A receiving node:
   3520   - MUST ignore `my_current_per_commitment_point`, but MAY require it to be a valid point.
   3521   - if `next_revocation_number` is greater than expected above, AND
   3522     `your_last_per_commitment_secret` is correct for that
   3523     `next_revocation_number` minus 1:
   3524     - MUST NOT broadcast its commitment transaction.
   3525     - SHOULD send an `error` to request the peer to fail the channel.
   3526   - otherwise:
   3527     - if `your_last_per_commitment_secret` does not match the expected values:
   3528       - SHOULD send an `error` and fail the channel.
   3529 
   3530 A receiving node:
   3531   - if the `next_funding` TLV is set:
   3532     - if `next_funding_txid` matches the latest interactive funding transaction:
   3533       - if it has not received `tx_signatures` for that funding transaction:
   3534         - if the `commitment_signed` bit is set in `retransmit_flags`:
   3535           - MUST retransmit its `commitment_signed` for that funding transaction.
   3536         - if it has already received `commitment_signed` and it should sign first,
   3537           as specified in the [`tx_signatures` requirements](#the-tx_signatures-message):
   3538           - MUST send its `tx_signatures` for that funding transaction.
   3539       - if it has already received `tx_signatures` for that funding transaction:
   3540         - MUST send its `tx_signatures` for that funding transaction.
   3541     - if it also sets `next_funding` in its own `channel_reestablish`, but the
   3542       values don't match:
   3543       - MUST send an `error` and fail the channel.
   3544     - otherwise:
   3545       - MUST send `tx_abort` to let the sending node know that they can forget
   3546         this funding transaction.
   3547 
   3548 A receiving node:
   3549   - if splice transactions are pending and `my_current_funding_locked` matches one of
   3550     those splice transactions, for which it hasn't received `splice_locked` yet:
   3551     - MUST process `my_current_funding_locked` as if it was receiving `splice_locked`
   3552       for this `txid`.
   3553   - if `my_current_funding_locked` is included with the `announcement_signatures` bit
   3554     set in the `retransmit_flags`:
   3555     - if `announce_channel` is set for this channel and the receiving node is ready
   3556       to send `announcement_signatures` for the corresponding splice transaction:
   3557       - MUST retransmit `announcement_signatures`.
   3558 
   3559 A node:
   3560   - MUST NOT assume that previously-transmitted messages were lost,
   3561     - if it has sent a previous `commitment_signed` message:
   3562       - MUST handle the case where the corresponding commitment transaction is
   3563       broadcast at any time by the other side,
   3564         - Note: this is particularly important if the node does not simply
   3565         retransmit the exact `update_` messages as previously sent.
   3566   - upon reconnection:
   3567     - if it has sent a previous `shutdown`:
   3568       - MUST retransmit `shutdown`.
   3569 
   3570 ### Rationale
   3571 
   3572 The requirements above ensure that the opening phase is nearly
   3573 atomic: if it doesn't complete, it starts again. The only exception
   3574 is if the `funding_signed` message is sent but not received. In
   3575 this case, the funder will forget the channel, and presumably open
   3576 a new one upon reconnection; meanwhile, the other node will eventually forget
   3577 the original channel, due to never receiving `channel_ready` or seeing
   3578 the funding transaction on-chain.
   3579 
   3580 There's no acknowledgment for `error`, so if a reconnect occurs it's
   3581 polite to retransmit before disconnecting again; however, it's not a MUST,
   3582 because there are also occasions where a node can simply forget the
   3583 channel altogether.
   3584 
   3585 `closing_signed` also has no acknowledgment so must be retransmitted
   3586 upon reconnection (though negotiation restarts on reconnection, so it needs
   3587 not be an exact retransmission).
   3588 The only acknowledgment for `shutdown` is `closing_signed`, so one or the other
   3589 needs to be retransmitted.
   3590 
   3591 The handling of updates is similarly atomic: if the commit is not
   3592 acknowledged (or wasn't sent) the updates are re-sent. However, it's not
   3593 insisted they be identical: they could be in a different order,
   3594 involve different fees, or even be missing HTLCs which are now too old
   3595 to be added. Requiring they be identical would effectively mean a
   3596 write to disk by the sender upon each transmission, whereas the scheme
   3597 here encourages a single persistent write to disk for each
   3598 `commitment_signed` sent or received. But if you need to retransmit both a
   3599 `commitment_signed` and a `revoke_and_ack`, the relative order of these two
   3600 must be preserved, otherwise it will lead to a channel closure.
   3601 
   3602 A re-transmittal of `revoke_and_ack` should never be asked for after a
   3603 `closing_signed` has been received, since that would imply a shutdown has been
   3604 completed — which can only occur after the `revoke_and_ack` has been received
   3605 by the remote node.
   3606 
   3607 Note that the `next_commitment_number` starts at 1, since
   3608 commitment number 0 is created during opening.
   3609 `next_revocation_number` will be 0 until the
   3610 `commitment_signed` for commitment number 1 is send and then
   3611 the revocation for commitment number 0 is received.
   3612 
   3613 `channel_ready` is implicitly acknowledged by the start of normal operation,
   3614 which is known to have begun after a `commitment_signed` has been received
   3615 (hence, the test for a `next_commitment_number` greater than 1) or after a
   3616 splice transaction has been created.
   3617 
   3618 A node, which has somehow fallen
   3619 behind (e.g. has been restored from old backup), can detect that it has fallen
   3620 behind. A fallen-behind node must know it cannot broadcast its current
   3621 commitment transaction — which would lead to total loss of funds — as the
   3622 remote node can prove it knows the revocation preimage. The `error` returned by
   3623 the fallen-behind node should make the other node drop its current commitment
   3624 transaction to the chain. The other node should wait for that `error` to give
   3625 the fallen-behind node an opportunity to fix its state first (e.g by restarting
   3626 with a different backup).
   3627 
   3628 The `next_funding` TLV allows peers to finalize the signing steps of an
   3629 interactive transaction construction, or safely abort that transaction
   3630 if it was not signed by one of the peers, who has thus already removed
   3631 it from its state.
   3632 
   3633 `my_current_funding_locked` is equivalent to sending `splice_locked`, but is
   3634 handled atomically during `channel_reestablish` (instead of requiring a
   3635 retransmission of the `splice_locked` message). This is useful to avoid race
   3636 conditions with channel updates (for more details about this race condition,
   3637 see [this example](./bolt02/splicing-test.md#disconnection-with-concurrent-splice_locked)).
   3638 It handles the case where the `splice_locked` message was lost during the
   3639 disconnection, or when a splice transaction reaches acceptable depth while
   3640 peers are disconnected. It also allows requesting a retransmission of the
   3641 `announcement_signatures` message for the latest splice transaction, in case
   3642 it wasn't received before disconnecting.
   3643 
   3644 # Authors
   3645 
   3646 [ FIXME: Insert Author List ]
   3647 
   3648 ![Creative Commons License](https://i.creativecommons.org/l/by/4.0/88x31.png "License CC-BY")
   3649 <br>
   3650 This work is licensed under a [Creative Commons Attribution 4.0 International License](http://creativecommons.org/licenses/by/4.0/).