Repository navigation
fix: use spark send key in retry #1415
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ovitrif
wants to merge
3
commits into
master
Choose a base branch
from
fix/spark-send-keys
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+369
−11
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| import CryptoKit | ||
| import Foundation | ||
|
|
||
| /// The idempotency key of a Spark send of an invoice. Spark makes one transfer per key, so a retry under the same key | ||
| /// never pays the invoice twice: it gets back the transfer an earlier try committed, or sends when none did. A key whose | ||
| /// payment failed can't send again, so the next attempt takes the next key. | ||
| /// | ||
| /// Keys derive from the wallet seed, the payment hash and the attempt number, so a restored wallet derives the same | ||
| /// keys, no other wallet can, and the operators can't link a transfer to its invoice. Android derives the same keys. | ||
| enum SparkSendKey { | ||
| private static let namespace = UUID(uuidString: "794acd96-39bc-4fd1-a09f-02b269a4a34d")! | ||
| private static let label = Data("bitkit spark send key".utf8) | ||
|
|
||
| /// The secret all send keys derive from: an HMAC-SHA256 of a fixed label, keyed with the BIP39 `seed`. | ||
| static func secret(seed: Data) -> Data { | ||
| Data(HMAC<SHA256>.authenticationCode(for: label, using: SymmetricKey(data: seed))) | ||
| } | ||
|
|
||
| /// The key of attempt `attempt` at paying the invoice with `paymentHash`: a UUIDv5 of `secret`, the hash's 32 bytes | ||
| /// and `attempt` as 4 bytes big-endian. | ||
| static func key(secret: Data, paymentHash: String, attempt: UInt32) -> String { | ||
| var name = secret + paymentHash.hexaData | ||
| withUnsafeBytes(of: attempt.bigEndian) { name.append(contentsOf: $0) } | ||
| var sha1 = Insecure.SHA1() | ||
| withUnsafeBytes(of: namespace.uuid) { sha1.update(bufferPointer: $0) } | ||
| sha1.update(data: name) | ||
| var bytes = Array(sha1.finalize().prefix(16)) | ||
| bytes[6] = bytes[6] & 0x0F | 0x50 | ||
| bytes[8] = bytes[8] & 0x3F | 0x80 | ||
| let uuid = bytes.withUnsafeBytes { $0.loadUnaligned(as: uuid_t.self) } | ||
| return UUID(uuid: uuid).uuidString.lowercased() | ||
| } | ||
| } | ||
|
|
||
| /// The latest attempt at each invoice Spark sent, by payment hash, whose number picks the attempt's `SparkSendKey`. | ||
| enum SparkSendAttempts { | ||
| private static let storageKey = "sparkSendAttempts" | ||
| private static let lock = NSLock() | ||
|
|
||
| private struct Attempt: Codable { | ||
| let attempt: UInt32 | ||
| let expiresAt: UInt64 | ||
| } | ||
|
|
||
| /// The attempt whose key pays the invoice with `paymentHash`: the latest kept one, past each whose key is in | ||
| /// `failedIds`, the ids of the payments Spark lists as failed, as a failed key can't send again. An attempt Spark | ||
| /// may still commit keeps its key, so a retry gets back its payment instead of paying again. | ||
| static func next(paymentHash: String, secret: Data, failedIds: Set<String>) -> UInt32 { | ||
| var attempt = lock.withLock { stored[paymentHash.lowercased()]?.attempt } ?? 0 | ||
| while failedIds.contains(SparkSendKey.key(secret: secret, paymentHash: paymentHash, attempt: attempt)) { | ||
| attempt += 1 | ||
| } | ||
| return attempt | ||
| } | ||
|
|
||
| /// The latest attempt kept for the invoice with `paymentHash`, nil before its first. | ||
| static func latest(paymentHash: String) -> UInt32? { | ||
| lock.withLock { stored[paymentHash.lowercased()]?.attempt } | ||
| } | ||
|
|
||
| /// Keeps `attempt` as the latest at the invoice with `paymentHash`, which expires at `expiresAt`, and drops the | ||
| /// attempts of invoices expired before `now`, both in epoch seconds. | ||
| static func set(paymentHash: String, attempt: UInt32, expiresAt: UInt64, now: UInt64) { | ||
| lock.withLock { | ||
| var attempts = stored.filter { $0.value.expiresAt >= now } | ||
| attempts[paymentHash.lowercased()] = Attempt(attempt: attempt, expiresAt: expiresAt) | ||
| stored = attempts | ||
| } | ||
| } | ||
|
|
||
| /// Puts back `attempt`, the latest kept before a send whose key never reached Spark, or drops the invoice's entry | ||
| /// when it had none. | ||
| static func restore(paymentHash: String, attempt: UInt32?, expiresAt: UInt64) { | ||
| lock.withLock { | ||
| var attempts = stored | ||
| attempts[paymentHash.lowercased()] = attempt.map { Attempt(attempt: $0, expiresAt: expiresAt) } | ||
| stored = attempts | ||
| } | ||
| } | ||
|
|
||
| static func clear() { | ||
| lock.withLock { UserDefaults.standard.removeObject(forKey: storageKey) } | ||
| } | ||
|
|
||
| private static var stored: [String: Attempt] { | ||
| get { | ||
| UserDefaults.standard.data(forKey: storageKey) | ||
| .flatMap { try? JSONDecoder().decode([String: Attempt].self, from: $0) } ?? [:] | ||
| } | ||
| set { | ||
| if let data = try? JSONEncoder().encode(newValue) { | ||
| UserDefaults.standard.set(data, forKey: storageKey) | ||
| } | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If a first send commits a transfer but encounters an operator error, the SDK's internal
with_leafs_spent_retry!can perform leaf selection again and fail—the scenario explicitly acknowledged in this commit's Gaps. Consequently, a leaf-selection error does not prove that a fresh key never reached the operators. HereisReusedKeyremains false throughout that send and its retries, so the error becomesChannelFreeRailSendRefused.LightningService.sendthen clears the uncertainty and releases the recorded attempt, allowing a subsequent payment over LDK before Spark sync exposes the committed transfer. Preserve the uncertain outcome unless there is proof that no operator submission occurred; the same-key retry alone does not protect a later send over another rail.Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Right, this can happen in 0.28.3. If a submission's response is lost,
with_leafs_spent_retry!retries it, can then get a leaves-spent error and refresh the leaves, and selecting again can fail after the first try committed. A short balance after such a retry has the same gap, and master already refuses that under a new key.Holding every fresh-key leaf-selection failure in doubt brings back the endless Pending this change fixes (a payment right after a move to Spark). Holding only the node rail for that invoice until Spark syncs, while the send shows failed, keeps both cases safe. That needs a decision on the trade first; this thread stays open until then.