-
Notifications
You must be signed in to change notification settings - Fork 4
fix: add lsp refund address #732
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
codex/728-lsp-refund-address
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.
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
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
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,232 @@ | ||
| import Foundation | ||
| import LDKNode | ||
|
|
||
| enum BlocktankRefundAddressError: LocalizedError, Equatable { | ||
| case invalidCache | ||
| case invalidAddress | ||
| case indexOutOfRange(UInt32) | ||
| case ownershipMismatch | ||
| case persistenceFailed | ||
|
|
||
| var errorDescription: String? { | ||
| switch self { | ||
| case .invalidCache: | ||
| "The saved Blocktank refund address is invalid." | ||
| case .invalidAddress: | ||
| "The Blocktank refund address is empty." | ||
| case let .indexOutOfRange(index): | ||
| "The Blocktank refund address index is out of range: \(index)." | ||
| case .ownershipMismatch: | ||
| "The saved Blocktank refund address does not belong to the active wallet and network." | ||
| case .persistenceFailed: | ||
| "The Blocktank refund address could not be saved." | ||
| } | ||
| } | ||
| } | ||
|
|
||
| struct BlocktankRefundAddressStore { | ||
| static let legacyKey = "blocktankRefundAddress" | ||
| static var key: String { key(for: Env.network) } | ||
|
|
||
| private let defaults: UserDefaults | ||
| private let network: LDKNode.Network | ||
|
|
||
| private var key: String { | ||
| Self.key(for: network) | ||
| } | ||
|
|
||
| init(defaults: UserDefaults = .standard, network: LDKNode.Network = Env.network) { | ||
| self.defaults = defaults | ||
| self.network = network | ||
| } | ||
|
|
||
| static func key(for network: LDKNode.Network) -> String { | ||
| "\(legacyKey)_\(Env.networkName(for: network))" | ||
| } | ||
|
|
||
| func load() throws -> BlocktankRefundAddress? { | ||
| if let value = try load(forKey: key) { | ||
| return value | ||
| } | ||
|
|
||
| guard let legacy = try load(forKey: Self.legacyKey) else { return nil } | ||
| let matchingNetworks = Self.matchingNetworks(for: legacy.address) | ||
| guard !matchingNetworks.isEmpty else { | ||
| throw BlocktankRefundAddressError.invalidCache | ||
| } | ||
| guard matchingNetworks == [network] else { return nil } | ||
|
|
||
| try save(legacy) | ||
| defaults.removeObject(forKey: Self.legacyKey) | ||
| return legacy | ||
| } | ||
|
|
||
| private func load(forKey key: String) throws -> BlocktankRefundAddress? { | ||
| guard defaults.object(forKey: key) != nil else { return nil } | ||
| guard let data = defaults.data(forKey: key) else { | ||
| throw BlocktankRefundAddressError.invalidCache | ||
| } | ||
|
|
||
| do { | ||
| return try JSONDecoder().decode(BlocktankRefundAddress.self, from: data) | ||
| } catch { | ||
| throw BlocktankRefundAddressError.invalidCache | ||
| } | ||
| } | ||
|
|
||
| func save(_ value: BlocktankRefundAddress) throws { | ||
| let data = try JSONEncoder().encode(value) | ||
| defaults.set(data, forKey: key) | ||
|
|
||
| guard try load(forKey: key) == value else { | ||
| throw BlocktankRefundAddressError.persistenceFailed | ||
| } | ||
| } | ||
|
|
||
| func clear() { | ||
| defaults.removeObject(forKey: key) | ||
|
|
||
| guard defaults.object(forKey: Self.legacyKey) != nil else { return } | ||
| guard let legacy = try? load(forKey: Self.legacyKey) else { | ||
| defaults.removeObject(forKey: Self.legacyKey) | ||
| return | ||
| } | ||
| let matchingNetworks = Self.matchingNetworks(for: legacy.address) | ||
| if matchingNetworks.isEmpty || matchingNetworks == [network] { | ||
| defaults.removeObject(forKey: Self.legacyKey) | ||
| } | ||
| } | ||
|
|
||
| private static func matchingNetworks(for address: String) -> [LDKNode.Network] { | ||
| [LDKNode.Network.bitcoin, .testnet, .signet, .regtest].filter { | ||
| AddressScriptType.nativeSegwit.matchesAddressFormat(address, network: $0) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| @MainActor | ||
| protocol BlocktankRefundAddressProviding: AnyObject { | ||
| func addressForOrder() async throws -> String | ||
| } | ||
|
|
||
| @MainActor | ||
| final class BlocktankRefundAddressProvider: BlocktankRefundAddressProviding { | ||
| static let maximumExternalIndex = UInt32(Int32.max) | ||
|
|
||
| typealias Load = () throws -> BlocktankRefundAddress? | ||
| typealias Save = (BlocktankRefundAddress) throws -> Void | ||
| typealias Lookup = (UInt32) async throws -> BlocktankRefundAddress | ||
| typealias Reveal = (UInt32) async throws -> Void | ||
| typealias IsUsed = (String) async throws -> Bool | ||
| typealias Allocate = () async throws -> BlocktankRefundAddress | ||
|
|
||
| private let load: Load | ||
| private let save: Save | ||
| private let lookup: Lookup | ||
| private let reveal: Reveal | ||
| private let isUsed: IsUsed | ||
| private let allocate: Allocate | ||
| private var inFlight: Task<String, Error>? | ||
|
|
||
| init( | ||
| load: @escaping Load, | ||
| save: @escaping Save, | ||
| lookup: @escaping Lookup, | ||
| reveal: @escaping Reveal, | ||
| isUsed: @escaping IsUsed, | ||
| allocate: @escaping Allocate | ||
| ) { | ||
| self.load = load | ||
| self.save = save | ||
| self.lookup = lookup | ||
| self.reveal = reveal | ||
| self.isUsed = isUsed | ||
| self.allocate = allocate | ||
| } | ||
|
|
||
| convenience init( | ||
| lightningService: LightningService, | ||
| utilityService: UtilityService, | ||
| store: BlocktankRefundAddressStore = .init() | ||
| ) { | ||
| self.init( | ||
| load: { try store.load() }, | ||
| save: { try store.save($0) }, | ||
| lookup: { index in | ||
| let info = try await lightningService.addressInfoForType( | ||
| .nativeSegwit, | ||
| keychain: .external, | ||
| atIndex: index | ||
| ) | ||
| return BlocktankRefundAddress(address: info.address, index: info.index) | ||
| }, | ||
| reveal: { index in | ||
| try await lightningService.revealReceiveAddresses(to: index, forType: .nativeSegwit) | ||
| }, | ||
| isUsed: { address in | ||
| try await utilityService.isAddressUsed(address: address) | ||
| }, | ||
| allocate: { | ||
| let info = try await lightningService.newAddressInfoForType(.nativeSegwit) | ||
| return BlocktankRefundAddress(address: info.address, index: info.index) | ||
| } | ||
| ) | ||
| } | ||
|
|
||
| func addressForOrder() async throws -> String { | ||
| if let inFlight { | ||
| return try await inFlight.value | ||
| } | ||
|
|
||
| let operation = Task { @MainActor [load, save, lookup, reveal, isUsed, allocate] in | ||
| try await Self.resolve( | ||
| load: load, | ||
| save: save, | ||
| lookup: lookup, | ||
| reveal: reveal, | ||
| isUsed: isUsed, | ||
| allocate: allocate | ||
| ) | ||
| } | ||
| inFlight = operation | ||
| defer { inFlight = nil } | ||
| return try await operation.value | ||
| } | ||
|
|
||
| private static func resolve( | ||
| load: Load, | ||
| save: Save, | ||
| lookup: Lookup, | ||
| reveal: Reveal, | ||
| isUsed: IsUsed, | ||
| allocate: Allocate | ||
| ) async throws -> String { | ||
| if let cached = try load() { | ||
| try validate(cached) | ||
|
|
||
| let derived = try await lookup(cached.index) | ||
| guard derived == cached else { | ||
| throw BlocktankRefundAddressError.ownershipMismatch | ||
| } | ||
|
|
||
| try await reveal(cached.index) | ||
| if try await isUsed(cached.address) == false { | ||
| return cached.address | ||
| } | ||
| } | ||
|
|
||
| let generated = try await allocate() | ||
| try validate(generated) | ||
| try save(generated) | ||
| return generated.address | ||
| } | ||
|
|
||
| private static func validate(_ value: BlocktankRefundAddress) throws { | ||
| guard !value.address.isEmpty else { | ||
| throw BlocktankRefundAddressError.invalidAddress | ||
| } | ||
| guard value.index <= maximumExternalIndex else { | ||
| throw BlocktankRefundAddressError.indexOutOfRange(value.index) | ||
| } | ||
| } | ||
| } | ||
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.
This can't distinguish testnet, signet and regtest, so the legacy migration and cleanup never run on any non-mainnet build.
matchesAddressFormat(.nativeSegwit, network:)(Bitkit/Extensions/LDKNode+AddressType.swift:158) computesisMainnet = network == .bitcoinand for every non-mainnet network returnshasPrefix("tb1q") || hasPrefix("bcrt1q"). So abcrt1q…address matches.testnet,.signetand.regtestalike and this returns a 3-element array. Only mainnet (bc1q) can ever yield a singleton.Both consumers compare for equality with a single network —
load()at :57 andclear()at :95 — so both guards are unsatisfiable off mainnet:{bcrt1q…, 7}(written by the first commit on this branch on a regtest device) → namespaced key is nil → falls through to legacy →matchingNetworksreturns[.testnet, .signet, .regtest]→== [network]false → returnsnil. A fresh address is allocated and saved under the namespaced key.clear()hits the same false guard, so the legacy key is never removed. It lingers and is re-parsed on everyload()/clear().This is what
Run Testsis failing on:testLegacyCacheMigratesOnlyOnMatchingNetwork(:217) andtestClearPreservesLegacyCacheFromAnotherNetwork(:234).Worth being clear about what is not broken: the cross-network hard-block I raised earlier is genuinely fixed — a
bcrt1qlegacy value on a mainnet build returnsniland allocates fresh. What's lost is only the "reuse the previously-supplied address" intent and the cleanup.An explicit HRP switch local to this provider fixes both tests without touching the shared helper, whose loose non-mainnet semantics
PrivatePaykitAddressReservationStoreandSettingsViewModel:580rely on:testnet/signet still share
tb1qand correctly stay non-migrating.