Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.update
import kotlin.time.Duration
import kotlin.time.Duration.Companion.hours
import kotlin.time.Duration.Companion.minutes
Expand Down Expand Up @@ -157,6 +158,7 @@ data class NodeParams(
val paymentRecipientExpiryParams: RecipientCltvExpiryParams,
val zeroConfPeers: Set<PublicKey>,
val liquidityPolicy: MutableStateFlow<LiquidityPolicy>,
val compactOfferKeys: MutableStateFlow<Set<PublicKey>>,
val usePeerStorage: Boolean,
) {
val nodePrivateKey get() = keyManager.nodeKeys.nodeKey.privateKey
Expand Down Expand Up @@ -247,6 +249,7 @@ data class NodeParams(
maxAllowedFeeCredit = 0.msat
)
),
compactOfferKeys = MutableStateFlow(emptySet()),
usePeerStorage = true,
)

Expand All @@ -272,4 +275,26 @@ data class NodeParams(
return OfferManager.deterministicOffer(chainHash, nodePrivateKey, trampolineNodeId, amount, description, nonce)
}

/**
* Generate a compact Bolt 12 offer based on the node's seed and its trampoline node.
* A compact offer is smaller since it allows the encryptedData payload to be empty for
* the final recipient (us) within the blinded path. This allows it to fit in restricted
* spaces (e.g. bolt card)
*
* Each generated offer is unique, since a random nonce is used to generate the blindedPathSessionKey.
* This offer will stay valid after restoring the seed on a different device: we will
* automatically keep accepting payments for this offer.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't seem compatible with the requirement to store the key in compactOfferKeys which will not be restored from the seed.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. That was not accurate. Fixed in 1226ecc

*
* The caller must store the returned `OfferAndKey.privateKey.publicKey`,
* and set/update the NodeParams.compactOfferKeys with the value.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does the caller need to do it, it seems that the function already does it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point. Lightning-kmp does automatically update the value. But those values aren't persisted to disk. So the next time the app restarts, it's the callers responsibility to restore the set. I've updated the text to be more specific in 1226ecc

*
* @return a compact offer and the private key that will sign invoices for this offer.
*/
fun compactOffer(trampolineNodeId: PublicKey): OfferTypes.OfferAndKey {
// We generate a random nonce to ensure that this offer is unique.
val nonce = randomBytes32()
val result = OfferManager.deterministicCompactOffer(chainHash, nodePrivateKey, trampolineNodeId, nonce)
compactOfferKeys.update { it.plus(result.privateKey.publicKey()) }
return result
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -68,25 +68,30 @@ object RouteBlinding {
* @param sessionKey session key of the blinded path, the corresponding public key will be the first path key.
* @param publicKeys public keys of each node on the route, starting from the introduction point.
* @param payloads payloads that should be encrypted for each node on the route.
* @param allowCompactFormat when true, allows the encryptedData to be empty for the final recipient
* @return a blinded route.
*/
fun create(sessionKey: PrivateKey, publicKeys: List<PublicKey>, payloads: List<ByteVector>): BlindedRouteDetails {
fun create(sessionKey: PrivateKey, publicKeys: List<PublicKey>, payloads: List<ByteVector>, allowCompactFormat: Boolean = false): BlindedRouteDetails {
require(publicKeys.size == payloads.size) { "a payload must be provided for each node in the blinded path" }
var e = sessionKey
val (blindedHops, pathKeys) = publicKeys.zip(payloads).map { pair ->
val (publicKey, payload) = pair
val pathKey = e.publicKey()
val sharedSecret = Sphinx.computeSharedSecret(publicKey, e)
val blindedPublicKey = Sphinx.blind(publicKey, Sphinx.generateKey("blinded_node_id", sharedSecret))
val rho = Sphinx.generateKey("rho", sharedSecret)
val (encryptedPayload, mac) = ChaCha20Poly1305.encrypt(
rho.toByteArray(),
Sphinx.zeroes(12),
payload.toByteArray(),
byteArrayOf()
)
e *= PrivateKey(Crypto.sha256(pathKey.value.toByteArray() + sharedSecret.toByteArray()))
Pair(BlindedHop(blindedPublicKey, ByteVector(encryptedPayload + mac)), pathKey)
if (payload.isEmpty() && allowCompactFormat) {
Pair(BlindedHop(blindedPublicKey, payload), pathKey)
} else {
val rho = Sphinx.generateKey("rho", sharedSecret)
val (encryptedPayload, mac) = ChaCha20Poly1305.encrypt(
rho.toByteArray(),
Sphinx.zeroes(12),
payload.toByteArray(),
byteArrayOf()
)
Pair(BlindedHop(blindedPublicKey, ByteVector(encryptedPayload + mac)), pathKey)
}
}.unzip()
return BlindedRouteDetails(BlindedRoute(EncodedNodeId(publicKeys.first()), pathKeys.first(), blindedHops), pathKeys.last())
}
Expand Down Expand Up @@ -117,19 +122,23 @@ object RouteBlinding {
encryptedPayload: ByteVector
): Either<InvalidTlvPayload, Pair<ByteVector, PublicKey>> {
val sharedSecret = Sphinx.computeSharedSecret(pathKey, privateKey)
val rho = Sphinx.generateKey("rho", sharedSecret)
return try {
val decrypted = ChaCha20Poly1305.decrypt(
rho.toByteArray(),
Sphinx.zeroes(12),
encryptedPayload.dropRight(16).toByteArray(),
byteArrayOf(),
encryptedPayload.takeRight(16).toByteArray()
)
val nextPathKey = Sphinx.blind(pathKey, Sphinx.computeBlindingFactor(pathKey, sharedSecret))
Either.Right(Pair(ByteVector(decrypted), nextPathKey))
} catch (_: Throwable) {
Either.Left(CannotDecodeTlv(OnionPaymentPayloadTlv.EncryptedRecipientData.tag))
val nextPathKey = Sphinx.blind(pathKey, Sphinx.computeBlindingFactor(pathKey, sharedSecret))
if (encryptedPayload.isEmpty()) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The compact format should still be disallowed for payments and for standard offers. We should enable it explicitly only when we need it.

return Either.Right(Pair(encryptedPayload, nextPathKey))
} else {
return try {
val rho = Sphinx.generateKey("rho", sharedSecret)
val decrypted = ChaCha20Poly1305.decrypt(
rho.toByteArray(),
Sphinx.zeroes(12),
encryptedPayload.dropRight(16).toByteArray(),
byteArrayOf(),
encryptedPayload.takeRight(16).toByteArray()
)
Either.Right(Pair(ByteVector(decrypted), nextPathKey))
} catch (_: Throwable) {
Either.Left(CannotDecodeTlv(OnionPaymentPayloadTlv.EncryptedRecipientData.tag))
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ object OnionMessages {
fun buildRouteToRecipient(
sessionKey: PrivateKey,
intermediateNodes: List<IntermediateNode>,
recipient: Destination.Recipient
recipient: Destination.Recipient,
allowCompactFormat: Boolean = false
): RouteBlinding. BlindedRouteDetails {
val intermediatePayloads = buildIntermediatePayloads(intermediateNodes, recipient.nodeId)
val tlvs = setOfNotNull(
Expand All @@ -66,7 +67,8 @@ object OnionMessages {
return RouteBlinding.create(
sessionKey,
intermediateNodes.map { it.nodeId.publicKey } + recipient.nodeId.publicKey,
intermediatePayloads + lastPayload
intermediatePayloads + lastPayload,
allowCompactFormat
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,9 @@ class OfferManager(val nodeParams: NodeParams, val walletParams: WalletParams, v
/** This function verifies that the offer provided was generated by us. */
private fun isOurOffer(offer: OfferTypes.Offer, pathId: ByteVector?, blindedPrivateKey: PrivateKey): Boolean = when {
pathId != null && pathId.size() != 32 -> false
// Compact offers are randomly generated, but they don't store the nonce in the path_id to save space.
// It is instead the wallet's responsibility to store the corresponding blinded public key(s).
pathId == null && nodeParams.compactOfferKeys.value.contains(blindedPrivateKey.publicKey()) -> true
Comment on lines +239 to +241
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"compact offers" are not real offers in the sense that we won't accept invoice requests for them, so they don't need to be handled here.

Copy link
Member

@t-bast t-bast Nov 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually they are real offers, we do want to accept payments for them (for example when merchant does a refund or cashback). It's also handy to use that card simply to provide our offer that anyone can pay, so I think it's worth handling them here?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, then we should at least check that it has only a blinded route and no other field (no description that we would commit to).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

By tapping the card, we give permission to the other party to collect a (small) payment. It seems weird and unsafe to reuse this interaction to also mean "pay me".

else -> {
val expected = deterministicOffer(nodeParams.chainHash, nodeParams.nodePrivateKey, walletParams.trampolineNode.id, offer.amount, offer.description, pathId?.let { ByteVector32(it) })
expected == OfferTypes.OfferAndKey(offer, blindedPrivateKey)
Expand Down Expand Up @@ -272,5 +275,22 @@ class OfferManager(val nodeParams: NodeParams, val walletParams: WalletParams, v
val sessionKey = PrivateKey(Crypto.sha256(tweak + trampolineNodeId.value + nodePrivateKey.value).byteVector32())
return OfferTypes.Offer.createBlindedOffer(chainHash, nodePrivateKey, trampolineNodeId, amount, description, Features.empty, sessionKey, pathId)
}

fun deterministicCompactOffer(
chainHash: BlockHash,
nodePrivateKey: PrivateKey,
trampolineNodeId: PublicKey,
nonce: ByteVector32
): OfferTypes.OfferAndKey {
// We generate a deterministic session key based on:
// - a custom tag indicating that this is used in the Bolt 12 context
// - the compact offer parameters (nonce)
// - our trampoline node, which is used as an introduction node for the offer's blinded path
// - our private key, which ensures that nobody else can generate the same path key secret
val tweak = "bolt 12 compact offer".encodeToByteArray().byteVector() +
Crypto.sha256("offer nonce".encodeToByteArray().byteVector() + nonce)
val sessionKey = PrivateKey(Crypto.sha256(tweak + trampolineNodeId.value + nodePrivateKey.value).byteVector32())
return OfferTypes.Offer.createBlindedOffer(chainHash, nodePrivateKey, trampolineNodeId, null, null, Features.empty, sessionKey, null, allowCompactFormat = true)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -809,12 +809,14 @@ object OfferTypes {
features: Features,
blindedPathSessionKey: PrivateKey,
pathId: ByteVector? = null,
allowCompactFormat: Boolean = false
): OfferAndKey {
require(amount == null || description != null) { "an offer description must be provided if the amount isn't null" }
val blindedRouteDetails = OnionMessages.buildRouteToRecipient(
blindedPathSessionKey,
listOf(OnionMessages.IntermediateNode(EncodedNodeId.WithPublicKey.Plain(trampolineNodeId))),
OnionMessages.Destination.Recipient(EncodedNodeId.WithPublicKey.Wallet(nodePrivateKey.publicKey()), pathId)
OnionMessages.Destination.Recipient(EncodedNodeId.WithPublicKey.Wallet(nodePrivateKey.publicKey()), pathId),
allowCompactFormat
)
val tlvs = setOfNotNull(
if (chainHash != Block.LivenetGenesisBlock.hash) OfferChains(listOf(chainHash)) else null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,12 @@ class OfferTypesTestsCommon : LightningTestSuite() {
assertEquals(key.publicKey(), path.route.blindedNodeIds.last())
val expectedOffer = Offer.decode("lno1zrxq8pjw7qjlm68mtp7e3yvxee4y5xrgjhhyf2fxhlphpckrvevh50u0qf70a6j2x2akrhazctejaaqr8y4qtzjtjzmfesay6mzr3s789uryuqsr8dpgfgxuk56vh7cl89769zdpdrkqwtypzhu2t8ehp73dqeeq65lsqvlx5pj8mw2kz54p4f6ct66stdfxz0df8nqq7svjjdjn2dv8sz28y7z07yg3vqyfyy8ywevqc8kzp36lhd5cqwlpkg8vdcqsfvz89axkmv5sgdysmwn95tpsct6mdercmz8jh2r82qqscrf6uc3tse5gw5sv5xjdfw8f6c").get()
assertEquals(expectedOffer, offer)
val (compactOffer, _) = nodeParams.compactOffer(trampolineNode)
val defaultOfferData = Offer.tlvSerializer.write(offer.records)
val compactOfferData = Offer.tlvSerializer.write(compactOffer.records)
assertTrue { compactOfferData.size < defaultOfferData.size }
assertTrue { defaultOfferData.size == 206 }
assertTrue { compactOfferData.size == 190 }
}

@Test
Expand Down