# BOLT04

Utilities for working with Lightning Network [BOLT 04][bolt-04]

[bolt-04]: https://github.com/lightning/bolts/blob/master/04-onion-routing.md

## Methods

- [blindedPathFromHops](#blindedpathfromhops) - Blind a path of nodes to a
    destination that ends with a path id
- [blindedPathToNode](#blindedpathtonode) - Blind a path of nodes culminating
    in a destination
- [decryptBlindedPath](#decryptblindedpath) - Decrypt the data of a hop in a
    blinded path
- [decryptPaymentOnion](#decryptpaymentonion) - Decrypt the layer of a
    payment onion for a hop
- [encryptFailure](#encryptfailure) - Encrypt a failure as the erring hop to
    return it to the payment sender
- [onionEphemeralKey](#onionephemeralkey) - Get the public key to do ECDH
    with to decrypt an onion
- [onionForPath](#onionforpath) - Construct an onion message packet to send
    into a published blinded path
- [paymentPathFromChannels](#paymentpathfromchannels) - Blind a payment path
    through channels to a destination with payment relay data

### blindedPathFromHops

Create a blinded path from a series of hops to a destination

The final hop is the destination, which is given a path `id` for reference.

    {
      hops: [<Relaying Node Public Key Id Hex String>]
      [id]: <Path Identifier Hex String>
    }

    @throws
    <Error>

    @returns
    {
      id: <Path Identifier Hex String>
      key: <Path Key Hex String>
      path: [{
        encrypted_data: <Encrypted Data Hex String>
        relay_key: <Blinded Node Public Key Hex String>
      }]
    }

Example:

```node
const {blindedPathFromHops} = require('bolt04');

// Blind a path through a forwarding node to the destination with a path id
const {id, key, path} = blindedPathFromHops({
  hops: [forwardingNodePublicKey, destinationNodePublicKey],
});
```

### blindedPathToNode

Create a blinded path from a series of hops culminating in a destination

This makes a path for sending an onion message. The destination is not given
a path id to check, so to publish a path to yourself use
`blindedPathFromHops`.

    {
      hops: [<Relaying Node Public Key Hex String>]
    }

    @throws
    <Error>

    @returns
    {
      key: <Path Key Hex String>
      path: [{
        encrypted_data: <Encrypted Data Hex String>
        relay_key: <Blinded Node Public Key Hex String>
      }]
    }

Example:

```node
const {blindedPathToNode} = require('bolt04');

// Blind a path through a forwarding node to a destination node id
const {key, path} = blindedPathToNode({
  hops: [forwardingNodePublicKey, destinationNodePublicKey],
});
```

### decryptBlindedPath

Decrypt the data of a hop in a blinded path

`secret` is a shared secret computed from the node identity and the path key

`features` are a total whitelist of feature bits allowed on the path

`records` are every record of the decrypted data, including unknown even
types. The node processing the path applies the rules that depend on its
context: a payment hop fails when both `next_channel_id` and `next_node_id`
are present, and a hop fails for unknown even types or for `features` bits
that it does not know.

    {
      encrypted: <Encrypted Data Hex String>
      key: <Path Key Public Key Hex String>
      secret: <Path Key Shared Secret Hex String>
    }

    @throws
    <Error>

    @returns
    {
      data: <Decrypted Data TLV Stream Hex String>
      features: [<Allowed Feature Bit Number>]
      [id]: <Path Identifier Hex String>
      [next_channel_id]: <Next Hop Standard Format Channel Id String>
      [next_node_id]: <Next Node Public Key Hex String>
      next_path_key: <Next Hop Path Key Public Key Hex String>
      records: [{
        type: <Record Type Number String>
        value: <Record Value Hex String>
      }]
    }

Example:

```node
const {decryptBlindedPath} = require('bolt04');

// The node derives the shared secret with the path key using its private key
const {secret} = await ecdh({public_key: receivedPathKey});

// A forwarding hop forwards to the next node id with the next path key
const {id, next_node_id, next_path_key} = decryptBlindedPath({
  encrypted: encryptedRecipientData,
  key: receivedPathKey,
  secret,
});
```

### decryptPaymentOnion

Decrypt the layer of a payment onion for a hop, revealing its payload and the
onion to forward to the next hop

`shared_secret` is the shared secret of the hop and the ephemeral public key
of the onion packet, the 33 bytes after the version byte: the SHA256 hash of
the compressed shared point. A blinded hop after the introduction node does
ECDH with the public key from `onionEphemeralKey` instead.

The onion is not returned when the hop is the final hop.

Replays are not detected: keep the shared secrets of decrypted onions and
reject an onion with a shared secret that was already seen.

    {
      onion: <Received Payment Onion Packet Hex String>
      payment_hash: <Payment Hash Hex String>
      shared_secret: <Hop Onion Shared Secret Hex String>
    }

    @throws
    <Error>

    @returns
    {
      [onion]: <Next Hop Onion Packet Hex String>
      payload: <Hop Payload TLV Stream Hex String>
    }

Example:

```node
const {decryptPaymentOnion} = require('bolt04');

// The onion ephemeral public key is the 33 bytes after the version byte
const {secret} = await ecdh({public_key: receivedOnion.slice(2, 68)});

// A forwarding hop decrypts its layer to get the onion for the next hop
const {onion, payload} = decryptPaymentOnion({
  onion: receivedOnion,
  payment_hash: paymentHash,
  shared_secret: secret,
});
```

### encryptFailure

Encrypt a failure as the erring hop to return it to the payment sender

`message` is the failure message: the failure code followed by its data

`shared_secrets` are the onion shared secrets of the hops from the hop that
received the `onion` to the erring hop. Each is the shared secret of the hop
and the ephemeral public key of its onion packet: the SHA256 hash of the
compressed shared point. The last shared secret authenticates the failure
so the sender can tell which hop it came from, and each hop obfuscates it.

The failure message is padded to 256 bytes to conceal its real length, and
`padded_length` pads it to another length of at least 256 bytes. A failure
message longer than 256 bytes is not padded unless `padded_length` is set.
Older nodes may not read a failure that is not padded to 256 bytes.

When the payment `onion` the first hop received is passed along with the
`payment_hash`, each shared secret is checked against its layer of the onion
so that a failure the sender cannot attribute is not made, and `is_final`
says if the erring hop is the final hop of the payment. It is not set when
the erring hop onion payload cannot be decoded.

An onion with an unknown version or an invalid ephemeral public key is not
accepted: the erring node fails the HTLC with `update_fail_malformed_htlc`
instead, and the previous hop encrypts the failure.

Inside a blinded path, a node that received a `path_key` with the HTLC does
not use this: it fails the HTLC with `update_fail_malformed_htlc` and
`invalid_onion_blinding`. An introduction node that is not the final hop
encrypts `invalid_onion_blinding` for any failure.

Attribution data is not created, so a node relying on this should not
advertise `option_attribution_data`.

    {
      message: <Failure Message Hex String>
      [onion]: <First Hop Received Payment Onion Packet Hex String>
      [padded_length]: <Padded Failure Message Byte Length Number>
      [payment_hash]: <Payment Hash Hex String>
      shared_secrets: [<Hop Onion Shared Secret Hex String>]
    }

    @throws
    <Error>

    @returns
    {
      encrypted: <Encrypted Failure Packet Hex String>
      [is_final]: <Erring Hop Is Payment Final Hop Bool>
    }

Example:

```node
const {encryptFailure} = require('bolt04');

// The erring node derives the onion shared secret using its private key
const {secret} = await ecdh({public_key: receivedOnion.slice(2, 68)});

// incorrect_or_unknown_payment_details (PERM|15) has the amount and height
const details = Buffer.alloc(12);

details.writeBigUInt64BE(BigInt(htlcMillitokens));
details.writeUInt32BE(currentBlockHeight, 8);

const message = `400f${details.toString('hex')}`;

// Check the shared secret against the received onion to encrypt the failure
const {encrypted, is_final} = encryptFailure({
  message,
  onion: receivedOnion,
  payment_hash: paymentHash,
  shared_secrets: [secret],
});
```

### onionEphemeralKey

Get the public key to do ECDH with to derive the shared secret of an onion

The shared secret for `decryptPaymentOnion` is the ECDH shared secret of the
hop private key and this public key: the SHA256 hash of the compressed
shared point.

`path_key_secret` is the ECDH shared secret of the hop private key and the
`path_key` the hop was given, which tweaks the ephemeral key to the blinded
node id. Without it, the onion packet ephemeral public key is used as is.

A payment onion is encoded to the real node id of the introduction node,
which finds its path key in its payload, so it has no `path_key_secret`.
Blinded hops after it are given a `path_key` with the HTLC.

An onion message is encoded to the blinded node id of every hop in a blinded
path, including the introduction node: each hop is given a `path_key` with
the `onion_message`.

    {
      onion: <Received Onion Packet Hex String>
      [path_key_secret]: <Path Key Shared Secret Hex String>
    }

    @throws
    <Error>

    @returns
    {
      public_key: <ECDH Public Key Hex String>
    }

Example:

```node
const {decryptPaymentOnion} = require('bolt04');
const {onionEphemeralKey} = require('bolt04');

// A blinded hop derives the path key shared secret using its private key
const pathKey = await ecdh({public_key: htlcPathKey});

// The path key secret tweaks the onion ephemeral key to the blinded node id
const {public_key} = onionEphemeralKey({
  onion: receivedOnion,
  path_key_secret: pathKey.secret,
});

const {secret} = await ecdh({public_key});

const {onion, payload} = decryptPaymentOnion({
  onion: receivedOnion,
  payment_hash: paymentHash,
  shared_secret: secret,
});
```

### onionForPath

Create an onion for a given path

`inbound` are the blinded hops of the published blinded path

`is_large` sizes the onion to the large onion message size even when it fits
within the standard size

`outbound` are nodes to reach the blinded path, ending with its introduction

`records` are added to the payload of the final hop

`reply` is a route back to the sender that ends with the sender's node id

Send the `onion` to the first `outbound` node with the path's `key`

`secret` must be a new random key for every onion and is generated when it is
not specified: a repeated secret repeats the encryption of the outbound hops

    {
      inbound: [{
        encrypted_data: <Encrypted Data Hex String>
        relay_key: <Blinded Relaying Public Key Into Destination Hex String>
      }]
      [is_large]: <Use Large Onion Message Size Bool>
      key: <Inbound Path Key Public Key Hex String>
      outbound: [<Relaying Node Public Key Out of Source Hex String>]
      [records]: [{
        type: <Final Hop Additional Record Type Number String>
        value: <Final Hop Additional Record Value Hex String>
      }]
      [reply]: [<Reply Relaying Node Public Key Back To Sender Hex String>]
      [secret]: <Outbound Path Key Secret Private Key Hex String>
    }

    @throws
    <Error>

    @returns
    {
      [id]: <Reply Path Identifier Hex String>
      key: <Path Key To Send With Onion Public Key Hex String>
      onion: <Onion Packet Hex String>
    }

Example:

```node
const {onionForPath} = require('bolt04');

// Send through a relaying peer into a published blinded path with a message,
// with a reply path back through the relaying peer to get an answer over
const {id, key, onion} = onionForPath({
  inbound: publishedHops.map(hop => ({
    encrypted_data: hop.encrypted_data,
    relay_key: hop.blinded_public_key,
  })),
  key: publishedFirstPathKey,
  outbound: [relayingPeerPublicKey, publishedFirstNodeId],
  records: [{type: '65537', value: message}],
  reply: [relayingPeerPublicKey, ownPublicKey],
});
```

### paymentPathFromChannels

Create a blinded payment path from a series of channels to a destination

`id` is the path id given to the destination in the final hop data. It is
random when not specified.

For BLIP 39 set the `id` to the `payment` identifier of the invoice: the 32
byte payment secret that the receiver makes for the invoice. The receiver
finds the invoice of a received payment by the decrypted path id.

    {
      [blocks_until_expiry]: <Blocks Until Path Expires Number>
      channels: [{
        id: <Standard Format Channel Id String>
        policies: [{
          base_fee_mtokens: <Base Fee Millitokens String>
          cltv_delta: <Locktime Delta Number>
          fee_rate: <Fees Charged in Millitokens Per Million Number>
          max_htlc_mtokens: <Maximum HTLC Millitokens Value String>
          min_htlc_mtokens: <Minimum HTLC Millitokens Value String>
          public_key: <Node Identity Public Key Hex String>
        }]
      }]
      cltv_delta: <Final Hop CLTV Delta Number>
      current_block_height: <Current Block Height Number>
      destination: <Destination Node Public Key Hex String>
      [receiver_base_fee_mtokens]: <Receiver Base Fee Millitokens String>
      [receiver_fee_rate]: <Receiver Fee Rate Millitokens Per Million Number>
      [hop_count]: <Total Padding Inclusive Blinded Hop Count Number>
      [id]: <Path Identifier Hex String>
      max_mtokens: <Maximum Millitokens Number Allowed Through Path String>
    }

    @throws
    <Error>

    @returns
    {
      base_fee_mtokens: <Accumulated Base Fee Millitokens String>
      cltv_delta: <Accumulated CLTV Expiry Delta Number>
      fee_rate: <Accumulated Fee Rate Millitokens Per Million Number>
      hops: [{
        encrypted_data: <Encrypted Recipient Data Hex String>
        relay_key: <Blinded Node Public Key Hex String>
      }]
      id: <Path Identifier Hex String>
      introduction_node: <Introduction Node Public Key Hex String>
      key: <First Hop Path Key Public Key Hex String>
      max_htlc_mtokens: <Maximum HTLC Millitokens String>
      min_htlc_mtokens: <Minimum HTLC Millitokens String>
    }

Example:

```node
const {paymentPathFromChannels} = require('bolt04');

// Blind a path through a peer's channel to include in an invoice with its fees
const path = paymentPathFromChannels({
  channels: [{id: peerChannelId, policies: [peerPolicy, ownPolicy]}],
  cltv_delta: finalCltvDelta,
  current_block_height: currentBlockHeight,
  destination: ownPublicKey,
  max_mtokens: invoiceMtokens,
});
```
