sattleme-checkout 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +66 -0
  3. data/LICENSE +21 -0
  4. data/README.md +754 -0
  5. data/SECURITY.md +25 -0
  6. data/lib/sattleme/checkout/cancellation.rb +195 -0
  7. data/lib/sattleme/checkout/client.rb +1438 -0
  8. data/lib/sattleme/checkout/errors.rb +165 -0
  9. data/lib/sattleme/checkout/http_client.rb +294 -0
  10. data/lib/sattleme/checkout/internal/bolt11.rb +187 -0
  11. data/lib/sattleme/checkout/internal/channel.rb +147 -0
  12. data/lib/sattleme/checkout/internal/checkout_link.rb +294 -0
  13. data/lib/sattleme/checkout/internal/concurrency.rb +450 -0
  14. data/lib/sattleme/checkout/internal/crypto.rb +63 -0
  15. data/lib/sattleme/checkout/internal/currencies.rb +47 -0
  16. data/lib/sattleme/checkout/internal/declaration.rb +135 -0
  17. data/lib/sattleme/checkout/internal/derive.rb +153 -0
  18. data/lib/sattleme/checkout/internal/event.rb +110 -0
  19. data/lib/sattleme/checkout/internal/http.rb +129 -0
  20. data/lib/sattleme/checkout/internal/json.rb +457 -0
  21. data/lib/sattleme/checkout/internal/key.rb +116 -0
  22. data/lib/sattleme/checkout/internal/lnurl.rb +238 -0
  23. data/lib/sattleme/checkout/internal/nip44.rb +113 -0
  24. data/lib/sattleme/checkout/internal/onchain/address.rb +58 -0
  25. data/lib/sattleme/checkout/internal/onchain/basics.rb +352 -0
  26. data/lib/sattleme/checkout/internal/onchain/lease.rb +326 -0
  27. data/lib/sattleme/checkout/internal/onchain/merchant_acceptance.rb +168 -0
  28. data/lib/sattleme/checkout/internal/onchain/node.rb +285 -0
  29. data/lib/sattleme/checkout/internal/onchain/payment.rb +345 -0
  30. data/lib/sattleme/checkout/internal/onchain/rest.rb +323 -0
  31. data/lib/sattleme/checkout/internal/onchain/watch.rb +119 -0
  32. data/lib/sattleme/checkout/internal/onchain/witness.rb +260 -0
  33. data/lib/sattleme/checkout/internal/order.rb +228 -0
  34. data/lib/sattleme/checkout/internal/protocol.rb +260 -0
  35. data/lib/sattleme/checkout/internal/rates.rb +373 -0
  36. data/lib/sattleme/checkout/internal/record.rb +179 -0
  37. data/lib/sattleme/checkout/internal/relay_pool.rb +823 -0
  38. data/lib/sattleme/checkout/internal/sales.rb +238 -0
  39. data/lib/sattleme/checkout/internal/secp256k1.rb +234 -0
  40. data/lib/sattleme/checkout/internal/text.rb +144 -0
  41. data/lib/sattleme/checkout/internal/urls.rb +172 -0
  42. data/lib/sattleme/checkout/models.rb +247 -0
  43. data/lib/sattleme/checkout/version.rb +9 -0
  44. data/lib/sattleme/checkout/websocket_client.rb +487 -0
  45. data/lib/sattleme/checkout.rb +72 -0
  46. metadata +112 -0
@@ -0,0 +1,1438 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+
5
+ module Sattleme
6
+ module Checkout
7
+ # A shop's server for one sattle.me integration (SPEC.md §4): makes the invoice of each order (a
8
+ # Lightning invoice, a deposit address of the merchant's wallet, or both), declares it in the
9
+ # merchant's registry, checks its payment. Made for a server that may live for one call: nothing
10
+ # is kept between calls, each call reads the merchant (a removal stops the next invoice) and
11
+ # closes its connections; there is nothing to close. Thread-safe: share one client between
12
+ # threads.
13
+ #
14
+ # client = Sattleme::Checkout::Client.new(key: ENV.fetch("SATTLEME_INTEGRATION_KEY"))
15
+ # invoice = client.create_invoice(ref: "order-1042", fiat: { amount: "24.50", currency: "CHF" })
16
+ # status = client.get_status(invoice)
17
+ class Client
18
+ include Internal::Redacted
19
+
20
+ # The merchant, as the integration's channel gives it: never given to the integrator (its
21
+ # Lightning address, its registry key, its tolerance, its Bitcoin node); and the explorer of
22
+ # the call (Internal::CallExplorer: mempool.space, or the merchant's Bitcoin node with its
23
+ # fallback).
24
+ MerchantChannel = Data.define(:business_name, :lightning_address, :registry, :relays, :checkout_origin,
25
+ :tolerance, :bitcoin_node, :explorer) do
26
+ include Internal::Redacted
27
+
28
+ def inspect = "#<MerchantChannel>"
29
+ alias_method :to_s, :inspect
30
+ end
31
+
32
+ # The last result of each part of an invoice: its Lightning part and its on-chain part
33
+ # (Settled, nil when it has none), its rest part (Payments::RestPart, nil without an address).
34
+ Parts = Data.define(:lightning, :onchain, :rests)
35
+
36
+ # A deposit address leased for an order, with its lease's event (its mark).
37
+ Leased = Data.define(:address, :event)
38
+
39
+ # What the reads of the explorer of one call share (SPEC.md §31, "in the same call"): when the
40
+ # merchant's Bitcoin node failed (Internal::NodeFailures), and, for wait_for_payment, what
41
+ # hears which node each check's channel names (`on_node.call(node)`, nil: mempool.space).
42
+ ExplorerCall = Data.define(:failures, :on_node)
43
+
44
+ # Where warnings go by default: standard error, a line each (written as it is, whatever Ruby's
45
+ # own warnings are set to). Never given a secret.
46
+ class StandardErrorLogger
47
+ def warn(message)
48
+ $stderr.write("#{message}\n")
49
+ nil
50
+ end
51
+ end
52
+
53
+ # Builds a client. `key` is the integration's secret key ("Integrations" in the merchant's
54
+ # app), from the environment or a vault: InvalidKeyError unless it is one. The others are
55
+ # optional (SPEC.md §4), each checked here, before any request (InvalidOptionError naming it):
56
+ #
57
+ # - `rate_source:` where invoices priced in a currency get their rate: "coingecko", "mempool",
58
+ # "opennode", "coinbase", "kraken" (Strings or Symbols), a callable of yours (`currency` →
59
+ # a decimal String, or `{ price:, time: }`; with two parameters, the call's Cancellation as
60
+ # the second), or a list of them asked in order. The default list by default.
61
+ # - `coingecko_api_key:` CoinGecko's Demo API key, sent to CoinGecko only.
62
+ # - `relay_timeout_ms:` per relay request, connection included, and `http_timeout_ms:` per HTTP
63
+ # request, body included: 100 to 60 000, 10 000 by default.
64
+ # - `http_client:` (HttpClient by default), `websocket_client:` (WebSocketClient by
65
+ # default): for proxies and tests. They get `http://` and `ws://` URLs only for the merchant's
66
+ # Bitcoin node on a local network (SPEC.md §31): in clear, or a failure, and its fallback.
67
+ # - `logger:` anything with `warn(message)` (a Logger): standard error by default.
68
+ # - `now:` a callable giving the time in Unix seconds, `random:` a callable giving that many
69
+ # random bytes: for tests only (the system's clock and SecureRandom by default).
70
+ def initialize(key: nil, rate_source: Internal::Order::ABSENT, coingecko_api_key: nil, http_client: nil,
71
+ websocket_client: nil, relay_timeout_ms: nil, http_timeout_ms: nil, logger: nil, now: nil,
72
+ random: nil, **unknown)
73
+ unless unknown.empty?
74
+ raise InvalidOptionError.new("options", "unknown option #{unknown.keys.map(&:inspect).join(", ")}")
75
+ end
76
+
77
+ @key = Internal::IntegrationKey.parse(key)
78
+ @rate_sources = if rate_source.equal?(Internal::Order::ABSENT)
79
+ Internal::Rates::DEFAULT_SOURCES
80
+ else
81
+ Internal::Rates.source_list(rate_source)
82
+ end
83
+ raise InvalidOptionError.new("rate_source", Internal::Order::RATE_SOURCE_RULE) unless @rate_sources
84
+
85
+ @coingecko_api_key = coingecko_key_of(coingecko_api_key)
86
+ @http_client = object_with(http_client, :get, "http_client", "an object with get(url, headers:, timeout:, " \
87
+ "cancellation:)") || HttpClient.new
88
+ @relay_timeout_ms = milliseconds(relay_timeout_ms, "relay_timeout_ms")
89
+ @http_timeout_ms = milliseconds(http_timeout_ms, "http_timeout_ms")
90
+ @websocket_client = object_with(websocket_client, :connect, "websocket_client",
91
+ "an object with connect(url, timeout:, headers:, cancellation:)") ||
92
+ WebSocketClient.new
93
+ @logger = object_with(logger, :warn, "logger", "an object with warn(message)") || StandardErrorLogger.new
94
+ @now = object_with(now, :call, "now", "a callable giving Unix seconds") ||
95
+ -> { Process.clock_gettime(Process::CLOCK_REALTIME) }
96
+ @random = object_with(random, :call, "random", "a callable giving that many random bytes") ||
97
+ SecureRandom.method(:random_bytes)
98
+ # One invoice at a time per order, and one invoice of the rest at a time per invoice, in
99
+ # this process.
100
+ @orders = Internal::KeyedLocks.new
101
+ @rest_asks = Internal::KeyedLocks.new
102
+ end
103
+
104
+ # The integration key's public parts: its team and its relays, never the key.
105
+ def to_h
106
+ @key.to_h
107
+ end
108
+
109
+ # Its JSON, as ActiveSupport and the json gem ask it of any object: its public parts alone.
110
+ def as_json(*)
111
+ to_h
112
+ end
113
+
114
+ def to_json(*)
115
+ Internal::Json.generate(to_h)
116
+ end
117
+
118
+ def inspect
119
+ "#<#{self.class.name} team=#{@key.team_public_key}>"
120
+ end
121
+ alias to_s inspect
122
+
123
+ # The merchant: its business's name, the bounds of its Lightning address in sats, and how
124
+ # many deposit addresses the integration's lot holds. RevokedError when the merchant removed
125
+ # the integration. Never its Lightning address.
126
+ def merchant(cancellation: nil)
127
+ call(cancellation) do |stop|
128
+ with_relays(stop) do |pool|
129
+ channel = channel(pool, stop)
130
+ branches = stop.child
131
+ begin
132
+ pay = Internal::Future.spawn { Internal::Lnurl.pay_request(channel.lightning_address, http(branches)) }
133
+ lot = lot(pool, channel, stop)
134
+ min, max = pay.value(stop).sendable_sats
135
+ Merchant.new(business_name: channel.business_name, min_sats: min.to_s, max_sats: max.to_s,
136
+ onchain_addresses: lot.size)
137
+ ensure
138
+ branches.stop
139
+ end
140
+ end
141
+ end
142
+ end
143
+
144
+ # The invoice of an order (SPEC.md §17): a Lightning invoice asked to the merchant's Lightning
145
+ # address and checked, when its amount is within the address's bounds; a deposit address of
146
+ # the merchant's wallet leased from the integration's lot, from 1 000 sats (or both). Then the
147
+ # invoice is declared in the merchant's registry on a majority of its relays. Only then may it
148
+ # be shown. Store the result with the order (Invoice#to_json).
149
+ #
150
+ # The order: `ref:` (1 to 64 characters A–Z a–z 0–9 . _ : -: one order, one sale), `sats:` (an
151
+ # Integer or a String of digits) or `fiat:` ({ amount: "24.50", currency: "CHF" }), and
152
+ # optionally `rate_source:` (with `fiat:`), `duration_seconds:` (60 to 3600, 900 by default),
153
+ # `note:` (100 characters at most; the reference by default), `checkout:` (true for a checkout
154
+ # link) and `redirect_url:` (with `checkout: true`).
155
+ #
156
+ # One order, one invoice at a time: InvoicePendingError (with that invoice) while an earlier
157
+ # invoice of the same `ref` may still be paid (or its on-chain payment is being confirmed),
158
+ # OrderPaidError when one was paid. OnchainUnavailableError when the order can only be paid
159
+ # on-chain and no address could be leased; CheckoutUnavailableError when `checkout: true` and
160
+ # the merchant's app gives no web app for it.
161
+ def create_invoice(cancellation: nil, **order)
162
+ checked = Internal::Order.check(order, @rate_sources)
163
+ call(cancellation) do |stop|
164
+ # One at a time per order in this process: two calls for one `ref` would both pass the
165
+ # check of its earlier invoices.
166
+ @orders.synchronize(checked.ref, stop) { make_invoice(checked, stop) }
167
+ end
168
+ end
169
+
170
+ # Where the payment of an invoice is (SPEC.md §22), checked: its Lightning part from the
171
+ # merchant's Lightning address (LUD-21), its on-chain part from the explorer and the
172
+ # witnesses of its order, and the Lightning invoices of the rest of an on-chain underpayment,
173
+ # all at once. `invoice`: an Invoice, a DeclaredInvoice, its JSON or the Hash of its JSON.
174
+ # Underpaid on-chain, it asks the merchant's Lightning address for an invoice of the rest,
175
+ # declares it and publishes it for the order's checkout links (a failure is logged, the next
176
+ # check asks again). Never opens the explorer's WebSocket. NetworkError (retry) when a service
177
+ # does not answer, InvalidInvoiceError when an answer is not about this invoice or its
178
+ # preimage is wrong, InvalidOrderError (`invoice`) when it is no invoice of create_invoice.
179
+ def get_status(invoice, cancellation: nil)
180
+ stored = Internal::Order.check_stored_invoice(invoice)
181
+ call(cancellation) do |stop|
182
+ status_of(stored, check(stored, stop, nil, @logger), seconds)
183
+ end
184
+ end
185
+
186
+ # Checks the payment until it is `paid` or `expired` (SPEC.md §23): its Lightning part, and the
187
+ # invoices of the rest of an on-chain underpayment, every `interval_ms` (250 to 60 000, 2000 by
188
+ # default); its on-chain part (with an address) each time the explorer's WebSocket says
189
+ # something changed for the address, every 60 s at least, and at once when an invoice of the
190
+ # rest is paid. Each status goes to the block (or `on_status:`). Network errors are retried
191
+ # (one that each check meets again logged once, and again only after it stopped); any other
192
+ # error ends it. An on-chain payment takes about 30 minutes to be `paid` once `unconfirmed`:
193
+ # a server that cannot wait that long checks again later with get_status.
194
+ def wait_for_payment(invoice, interval_ms: nil, on_status: nil, cancellation: nil, &block)
195
+ interval = Internal::Order.check_milliseconds(interval_ms, Internal::Protocol::DEFAULT_INTERVAL_MS,
196
+ Internal::Protocol::MIN_INTERVAL_MS,
197
+ Internal::Protocol::MAX_INTERVAL_MS, "interval_ms")
198
+ listener = listener_of(on_status, block)
199
+ stored = Internal::Order.check_stored_invoice(invoice)
200
+ call(cancellation) do |stop|
201
+ warnings = OnceWarnings.new(@logger)
202
+ if stored.onchain_address
203
+ wait_with_address(stored, interval, listener, warnings, stop)
204
+ else
205
+ wait_lightning(stored, interval, listener, warnings, stop)
206
+ end
207
+ end
208
+ end
209
+
210
+ # The invoices declared for the order `ref` in the merchant's registry (SPEC.md §24), oldest
211
+ # first (DeclaredInvoice): to find an order's invoice again after a failure. Publishes
212
+ # nothing: to show an order's invoice again, call create_invoice, whose InvoicePendingError
213
+ # carries the pending invoice.
214
+ def find_invoices(ref, cancellation: nil)
215
+ checked = Internal::Order.check_ref(ref)
216
+ call(cancellation) do |stop|
217
+ with_relays(stop) do |pool|
218
+ channel = channel(pool, stop)
219
+ sale = Internal::Derive.sale(@key.key, channel.registry, checked)
220
+ declared(pool, sale, channel, stop).invoices.map(&:invoice)
221
+ end
222
+ end
223
+ end
224
+
225
+ private
226
+
227
+ def coingecko_key_of(value)
228
+ return nil if value.nil?
229
+
230
+ text = Internal::Text.caller_text(value)
231
+ # Visible ASCII: its HTTP header carries it as it is.
232
+ unless text&.match?(/\A[\x21-\x7e]+\z/)
233
+ raise InvalidOptionError.new("coingecko_api_key",
234
+ "1 or more visible ASCII characters")
235
+ end
236
+
237
+ text
238
+ end
239
+
240
+ def object_with(value, method, name, rule)
241
+ return nil if value.nil?
242
+ raise InvalidOptionError.new(name, rule) unless value.respond_to?(method)
243
+
244
+ value
245
+ end
246
+
247
+ def milliseconds(value, name)
248
+ Internal::Order.check_milliseconds(value, Internal::Protocol::DEFAULT_TIMEOUT_MS, Internal::Protocol::MIN_TIMEOUT_MS,
249
+ Internal::Protocol::MAX_TIMEOUT_MS, name)
250
+ end
251
+
252
+ def listener_of(on_status, block)
253
+ raise InvalidOptionError.new("on_status", "a block or on_status:, not both") if on_status && block
254
+ raise InvalidOptionError.new("on_status", "a callable") if on_status && !on_status.respond_to?(:call)
255
+
256
+ on_status || block
257
+ end
258
+
259
+ # Runs one call: its stop, from the caller's cancellation (Cancellation::NONE when nil).
260
+ def call(cancellation)
261
+ cancellation ||= Cancellation::NONE
262
+ unless cancellation.is_a?(Cancellation)
263
+ raise InvalidOptionError.new("cancellation",
264
+ "a Sattleme::Checkout::Cancellation")
265
+ end
266
+
267
+ cancellation.raise_if_cancelled
268
+ stop = Internal::Stop.new(cancellation)
269
+ threads = Internal::CallThreads.new
270
+ begin
271
+ result = Internal::CallThreads.within(threads) { yield stop }
272
+ rescue Cancelled
273
+ raise
274
+ rescue StandardError => e
275
+ # Cancelled while a step that does not stop at once ran (a clock, a logger, a listener
276
+ # of the caller's): the call fails with the cancellation all the same, never an error.
277
+ raise Cancelled.new(cancellation.reason), cause: e if cancellation.cancelled?
278
+
279
+ raise
280
+ ensure
281
+ # Once it returns, nothing it started runs on (SPEC.md §4, §13): what still runs (a read
282
+ # or a check it no longer needs, after an error) is stopped, then waited for until it
283
+ # ended. A publication's relays past its majority alone go on (Relay::Pool).
284
+ stop.stop
285
+ threads.wait
286
+ end
287
+ # Cancelled before it ended: a cancelled call fails (SPEC.md §4).
288
+ cancellation.raise_if_cancelled
289
+ result
290
+ end
291
+
292
+ # Runs the block with the relays of one call: one connection per relay, closed once the call
293
+ # is done (a write still running past the quorum first ends, bounded by its timeout).
294
+ def with_relays(stop)
295
+ pool = Internal::Relay::Pool.new(websocket: @websocket_client, timeout_ms: @relay_timeout_ms, stop: stop,
296
+ random: @random, now: -> { seconds })
297
+ begin
298
+ yield pool
299
+ ensure
300
+ pool.release
301
+ end
302
+ end
303
+
304
+ def http(stop)
305
+ Internal::Http::Context.new(client: @http_client, timeout_ms: @http_timeout_ms, stop: stop)
306
+ end
307
+
308
+ # "Now": the clock in Unix seconds, rounded down.
309
+ def seconds
310
+ time = @now.call
311
+ time.is_a?(Integer) ? time : time.to_f.floor
312
+ end
313
+
314
+ # The integration's channel, read on the connections of `pool`, with the explorer of the call:
315
+ # its node's failures those of `call` (an ExplorerCall; a new call's own by default), which
316
+ # hears the node the channel names.
317
+ def channel(pool, stop, logger = @logger, call = nil)
318
+ found = Internal::Channels.read(pool, @key, random: @random, logger: logger, stop: stop).channel
319
+ node = found.bitcoin_node
320
+ call&.on_node&.call(node)
321
+ explorer = Internal::CallExplorer.new(node, call&.failures || Internal::NodeFailures.new, @now)
322
+ MerchantChannel.new(business_name: found.business_name, lightning_address: found.lightning_address,
323
+ registry: Internal::Derive.registry(found.registry_key, found.registry_reader),
324
+ relays: Internal::Channels.merchant_relays(found, @key),
325
+ checkout_origin: found.checkout_origin, tolerance: found.tolerance,
326
+ bitcoin_node: node, explorer: explorer)
327
+ end
328
+
329
+ # The integration's lot of deposit addresses, read on the merchant's relays.
330
+ def lot(pool, merchant, stop)
331
+ Internal::Lot.read(pool, @key, merchant.relays, random: @random, logger: @logger, stop: stop)
332
+ end
333
+
334
+ def declared(pool, sale, merchant, stop, every_relay: false, logger: @logger)
335
+ Internal::Sales.read(pool, sale, merchant.relays, logger: logger, stop: stop, every_relay: every_relay)
336
+ end
337
+
338
+ # The steps of SPEC.md §17, from the checked order.
339
+ def make_invoice(order, stop)
340
+ with_relays(stop) do |pool|
341
+ merchant = channel(pool, stop)
342
+ raise CheckoutUnavailableError if order.checkout && merchant.checkout_origin.nil?
343
+
344
+ sale = Internal::Derive.sale(@key.key, merchant.registry, order.ref)
345
+ pay, sats, rate = pay_request_and_amount(pool, sale, merchant, order, stop)
346
+ make_with(pool, sale, merchant, order, pay, sats, rate, stop)
347
+ end
348
+ end
349
+
350
+ # Step 3 and 4: the earlier invoices checked while the pay request and the rate are asked (an
351
+ # error of the earlier invoices' check wins over the other two), then the amount.
352
+ def pay_request_and_amount(pool, sale, merchant, order, stop)
353
+ branches = stop.child
354
+ begin
355
+ context = http(branches)
356
+ pay = Internal::Future.spawn { Internal::Lnurl.pay_request(merchant.lightning_address, context) }
357
+ rates = Internal::Rates::Context.new(http: context, coingecko_api_key: @coingecko_api_key)
358
+ quote = if order.fiat
359
+ Internal::Future.spawn do
360
+ Internal::Rates.fetch_first_rate(order.rate_sources, order.fiat.currency, rates, -> { seconds },
361
+ @logger)
362
+ end
363
+ end
364
+ check_earlier_invoices(pool, sale, merchant, order, stop)
365
+ pay_request = pay.value(stop)
366
+ return [pay_request, order.sats, nil] unless order.fiat
367
+
368
+ price, rate = quote.value(stop)
369
+ sats = Internal::Rates.minor_to_sats(Integer(order.fiat.minor, 10), order.fiat.digits, price)
370
+ if sats > Internal::Protocol::MAX_SATS
371
+ raise InvalidOrderError.new("fiat", "#{sats} sats is more than 21 million bitcoins")
372
+ end
373
+
374
+ [pay_request, sats, rate]
375
+ ensure
376
+ branches.stop
377
+ end
378
+ end
379
+
380
+ # Steps 4 to 10 of SPEC.md §17, once the amount is known.
381
+ def make_with(pool, sale, merchant, order, pay, sats, rate, stop)
382
+ methods = Internal::Methods.of(sats, pay.sendable_sats, order.fiat ? "fiat" : "sats")
383
+ answer = nil
384
+ decoded = nil
385
+ if methods.lightning
386
+ answer = Internal::Lnurl.request_invoice(pay, sats: sats, expiry_seconds: order.duration_seconds,
387
+ comment: order.label, http: http(stop))
388
+ decoded = Internal::Lnurl.check_invoice(answer, pay: pay, sats: sats,
389
+ duration_seconds: order.duration_seconds, now: seconds)
390
+ end
391
+ leased_at = seconds
392
+ created_at = decoded ? decoded.timestamp : leased_at
393
+ expires_at = decoded ? decoded.expires_at : leased_at + order.duration_seconds
394
+ price = Internal::Declarations.price_of(order.fiat, sats)
395
+ event = (declaration_event(sale, answer, decoded, price, order.label, nil) if answer)
396
+
397
+ # The address before the link and the declaration: when the lease fails, nothing is
398
+ # published.
399
+ lease = nil
400
+ if methods.onchain
401
+ terms = Internal::Leases::Terms.new(address: nil, sats: sats, invoice: answer&.pr, verify_url: answer&.verify,
402
+ created_at: created_at, expires_at: expires_at, price: price,
403
+ note: order.label,
404
+ # The order's for good: every check judges its payment with it.
405
+ tolerance: merchant.tolerance, confirmed: nil)
406
+ check_lease_size(sale, terms, leased_at)
407
+ # Without an invoice, the lease's date is the Invoice's.
408
+ outcome = lease_address(pool, merchant, sale, terms, decoded ? nil : leased_at, stop)
409
+ Internal::Methods.with(methods, outcome.is_a?(Leased) ? :leased : outcome)
410
+ lease = outcome if outcome.is_a?(Leased)
411
+ if outcome.is_a?(Error)
412
+ @logger.warn("sattleme-checkout: no deposit address leased, the explorer did not answer " \
413
+ "(#{outcome.message}): Lightning only")
414
+ end
415
+ end
416
+ address = lease&.address
417
+
418
+ # On a failure below, the lease stays: it holds its address until its end, and was
419
+ # confirmed: §21 may hand it out. The link before the declaration: when the link fails,
420
+ # nothing is declared and the order gets a new invoice at once; when the declaration fails,
421
+ # the link's URL was never given and its keys are gone, so nobody can open it.
422
+ checkout_url = nil
423
+ if order.checkout
424
+ value = Internal::CheckoutLinks.value(
425
+ business_name: merchant.business_name, invoice: answer&.pr, verify_url: answer&.verify,
426
+ fiat: order.fiat ? price : nil, note: order.label, redirect_url: order.redirect_url,
427
+ onchain: address && link_onchain(merchant, order.ref, address, sats, created_at, expires_at)
428
+ )
429
+ checkout_url = publish_checkout(pool, merchant, value, expires_at, stop)
430
+ end
431
+ declare(pool, event, sale, merchant, stop) if event
432
+
433
+ Invoice.new(ref: order.ref, bolt11: answer&.pr, payment_hash: decoded&.payment_hash,
434
+ verify_url: answer&.verify, onchain_address: address,
435
+ payment_uri: Internal::Addresses.payment_uri(address, sats, answer&.pr), sats: sats.to_s,
436
+ fiat: order.fiat, rate: rate, note: order.label, created_at: created_at, expires_at: expires_at,
437
+ checkout_url: checkout_url, redirect_url: order.checkout ? order.redirect_url : nil)
438
+ end
439
+
440
+ # The declaration of an invoice the Lightning address answered, dated `created_at` (now by
441
+ # default); InvalidInvoiceError when it does not fit a NIP-44 plaintext (65 535 bytes).
442
+ def declaration_event(sale, answer, decoded, price, note, rest, created_at = seconds)
443
+ Internal::Declarations.event(sale: sale, invoice: answer.pr, verify_url: answer.verify,
444
+ payment_hash: decoded.payment_hash, price: price, note: note,
445
+ created_at: created_at, random: @random, rest: rest)
446
+ rescue Internal::Nip44::TooLong
447
+ raise InvalidInvoiceError, "The invoice is too large to be declared"
448
+ end
449
+
450
+ # A text of a deposit address's length (`bc1p` and 58 more): a lease's size before its address.
451
+ SIZED_ADDRESS = "bc1p#{"q" * (Internal::Addresses::LENGTH - 4)}".freeze
452
+ private_constant :SIZED_ADDRESS
453
+
454
+ # InvalidInvoiceError when the lease of an address cannot hold the order's `terms` (SPEC.md §17,
455
+ # step 6): it holds the invoice too, sealed twice as the declaration, with some 150 bytes more,
456
+ # and must fit a NIP-44 plaintext. Checked before anything is published, on a lease that
457
+ # differs from the real one by its address alone (every deposit address has one length), never
458
+ # published: its random bytes are zeros, the client's are left alone.
459
+ def check_lease_size(sale, terms, created_at)
460
+ Internal::Leases.event(sale: sale, terms: terms.with(address: SIZED_ADDRESS, confirmed: false),
461
+ created_at: created_at, random: ->(length) { "\x00".b * length })
462
+ nil
463
+ rescue Internal::Nip44::TooLong
464
+ raise InvalidInvoiceError, "The invoice is too large for the lease of an address"
465
+ end
466
+
467
+ # Leases a deposit address of the integration's lot for `sale` (SPEC.md §31, "Leasing an
468
+ # address"): the lot and its leases read; of its free addresses, in a random order, at most 3
469
+ # tried, one at a time: one the explorer shows paid already is skipped (its witness none
470
+ # published, so that the merchant's app takes it out of the lot), the explorer read with its
471
+ # fallback (SPEC.md §31: with "none" and the node down, no address); else the lease is published
472
+ # on a majority, the address's leases read again on every relay, and the lease confirmed then
473
+ # marked, or withdrawn when the read is not complete or another author's leases it too (the
474
+ # later of two servers sees both). A lease once confirmed is never withdrawn. `leased_at`: the
475
+ # lease's date when it is the Invoice's (an order paid on-chain only). A Leased, :none, or the
476
+ # explorer's NetworkError; raises NetworkError when the relays fail.
477
+ def lease_address(pool, merchant, sale, terms, leased_at, stop)
478
+ lot = lot(pool, merchant, stop)
479
+ return :none if lot.empty?
480
+
481
+ relays = merchant.relays
482
+ # The leases, complete or not (the confirmation decides), and the addresses a witness names.
483
+ leases_future = Internal::Future.spawn do
484
+ Internal::Leases.read(pool, merchant.registry.key, lot, relays, now: seconds, random: @random, stop: stop)
485
+ end
486
+ named_future = Internal::Future.spawn do
487
+ Internal::Witnesses.read_named_addresses(pool, Internal::Derive.seen_keys(@key.key), lot, relays,
488
+ random: @random, stop: stop)
489
+ end
490
+ leases, named = Internal.all([leases_future, named_future], stop)
491
+ raise NetworkError, "Fewer than a majority of the merchant's relays answered" unless leases.answered
492
+
493
+ # Its signature checked: a lease of a newer format holds its address (SPEC.md §12).
494
+ if leases.records.each_value.any? { |records| records.any? { |record| newer_lease?(record) } }
495
+ @logger.warn("sattleme-checkout: a lease of the integration's addresses has a newer format than this " \
496
+ "version reads; update the gem")
497
+ end
498
+ now = seconds
499
+ # Not where the read shows a record of the sale (its signature checked): an earlier call of
500
+ # the order tried it, and a new lease could be of the second of its withdrawal, and either
501
+ # replace the other.
502
+ free = lot.select do |address|
503
+ records = leases.records.fetch(address)
504
+ !named.key?(address) && !Internal::Leases.leased?(records, now) &&
505
+ records.none? { |record| record.event.pubkey == sale.author && record.signed? }
506
+ end
507
+ in_random_order(free).first(Internal::Protocol::MAX_ADDRESS_TRIES).each do |address|
508
+ outcome = try_address(pool, merchant, sale, terms.with(address: address), leased_at, stop)
509
+ return outcome unless outcome == :next
510
+ end
511
+ :none
512
+ end
513
+
514
+ # Whether `record`, at a lease's address, is of a newer format, its signature checked.
515
+ def newer_lease?(record)
516
+ record.hold == :newer && record.signed?
517
+ end
518
+
519
+ # Steps 3.1 to 3.5 of SPEC.md §31, "Leasing an address", for one free address: a Leased, the
520
+ # explorer's NetworkError, or :next.
521
+ def try_address(pool, merchant, sale, terms, leased_at, stop)
522
+ address = terms.address
523
+ relays = merchant.relays
524
+ begin
525
+ txs = merchant.explorer.read(http(stop)) do |base, context|
526
+ Internal::Explorer.address_transactions(base, address, context)
527
+ end
528
+ rescue NetworkError => e
529
+ return e
530
+ end
531
+ paid = txs.select { |tx| tx.pays_to(address).positive? }
532
+ unless paid.empty?
533
+ # Paid on-chain already: of no order, for good.
534
+ publish_witnesses_of_none(pool, merchant, address, paid, stop)
535
+ return :next
536
+ end
537
+ # Published unconfirmed: it holds the address, never gives the invoice one.
538
+ event = Internal::Leases.event(sale: sale, terms: terms.with(confirmed: false),
539
+ created_at: leased_at || seconds, random: @random)
540
+ again = begin
541
+ publish_lease_record(pool, relays, event, sale, stop)
542
+ # On every relay, each until its timeout: a relay that hides a lease cannot hide it while
543
+ # one that holds it answers in time (SPEC.md §13, §27).
544
+ Internal::Leases.read(pool, merchant.registry.key, [address], relays, now: seconds, random: @random,
545
+ stop: stop, every_relay: true)
546
+ rescue StandardError, Cancelled
547
+ # On some relays only (or the call cancelled): withdrawn, never the order's.
548
+ withdraw(pool, relays, sale, address, event, stop)
549
+ raise
550
+ end
551
+ records = again.records.fetch(address)
552
+ own = Internal::Leases::LeaseEvent.new(id: event.id, pubkey: event.pubkey, created_at: event.created_at,
553
+ sig: event.sig)
554
+ confirmed = again.answered && again.complete && Internal::Leases.confirmed?(records, own, seconds)
555
+ unless confirmed
556
+ # Another server leased it at once (the later reader sees both), the read could not be
557
+ # complete, or fewer than a majority answered: withdrawn (safe on some relays only: the
558
+ # address was never the order's), unless the read shows another record of the sale there
559
+ # whose signature checks out, even from fewer than a majority: another call of the order
560
+ # made it at once (its lock failed, SPEC.md §17), and it is not this call's to end.
561
+ another = records.any? do |record|
562
+ record.event.pubkey == sale.author && record.event.id != event.id && record.signed?
563
+ end
564
+ withdraw(pool, relays, sale, address, event, stop) unless another
565
+ raise NetworkError, "Fewer than a majority of the merchant's relays answered" unless again.answered
566
+
567
+ return :next
568
+ end
569
+ # Confirmed: never withdrawn from now on, whatever fails (a withdrawal on some relays only
570
+ # would leave them disagreeing on an address that may be the order's). Marked confirmed:
571
+ # from now on the address is the order's, its invoice's in §21 too.
572
+ marked = Internal::Leases.event(sale: sale, terms: terms.with(confirmed: true),
573
+ created_at: [seconds, event.created_at + 1].max, random: @random)
574
+ publish_lease_record(pool, relays, marked, sale, stop)
575
+ Leased.new(address: address, event: marked)
576
+ end
577
+
578
+ # Withdraws `lease`, the lease of `address` by `sale` that was not confirmed: its withdrawal, a
579
+ # second after it (so that it replaces the lease, and no later record of the sale), published
580
+ # on the merchant's `relays`; a failure only logged (the lease then holds its address until
581
+ # its end, and never gives its invoice one).
582
+ def withdraw(pool, relays, sale, address, lease, stop)
583
+ return if stop.cancelled?
584
+
585
+ event = Internal::Leases.withdrawal_event(sale: sale, address: address, created_at: lease.created_at + 1,
586
+ random: @random)
587
+ pool.publish_to_quorum(relays, event, sale.secret_key, Internal::Relay.majority(relays.size), stop: stop)
588
+ rescue Internal::Relay::Failure, Cancelled
589
+ return if stop.cancelled?
590
+
591
+ @logger.warn("sattleme-checkout: a lease that was not confirmed could not be withdrawn; it holds its " \
592
+ "deposit address until its end")
593
+ end
594
+
595
+ # Publishes a lease record on a majority of the merchant's `relays`, else NetworkError.
596
+ def publish_lease_record(pool, relays, event, sale, stop)
597
+ pool.publish_to_quorum(relays, event, sale.secret_key, Internal::Relay.majority(relays.size), stop: stop)
598
+ rescue Internal::Relay::Failure
599
+ raise NetworkError,
600
+ "Fewer than a majority of the merchant's relays took the lease of a deposit address: try again"
601
+ end
602
+
603
+ # Publishes a witness none of each transaction of `txs` paying `address`, failures logged.
604
+ def publish_witnesses_of_none(pool, merchant, address, txs, stop)
605
+ seen = Internal::Derive.seen_keys(@key.key)
606
+ futures = txs.map do |tx|
607
+ witness = Internal::Witnesses::Witness.new(
608
+ address: address, txid: tx.txid, sale: nil, sats: tx.pays_to(address),
609
+ inputs: tx.coins.first(Internal::Protocol::MAX_WITNESS_INPUTS), replacement: false, expires_at: nil
610
+ )
611
+ Internal::Future.spawn("sattleme-checkout witness") do
612
+ Internal::Witnesses.publish(pool, seen, witness, merchant.relays, created_at: seconds, random: @random,
613
+ stop: stop)
614
+ rescue NetworkError => e
615
+ @logger.warn("sattleme-checkout: the witness of a paid address was not published: #{e.message}")
616
+ end
617
+ end
618
+ Internal.all(futures, stop)
619
+ end
620
+
621
+ # Publishes a new checkout link holding `value` on a majority of the merchant's relays, and
622
+ # gives its URL. The author's secret answers the relays' authentication, then is dropped with
623
+ # the link: nobody can change it afterwards. NetworkError when fewer than a majority took it.
624
+ def publish_checkout(pool, merchant, value, expires_at, stop)
625
+ link = begin
626
+ Internal::CheckoutLinks.new_link(origin: merchant.checkout_origin, relays: merchant.relays, value: value,
627
+ expires_at: expires_at, created_at: seconds, random: @random)
628
+ rescue Internal::Nip44::TooLong
629
+ raise InvalidInvoiceError, "The invoice is too large for a checkout link"
630
+ end
631
+ begin
632
+ pool.publish_to_quorum(merchant.relays, link.event, link.secret_key,
633
+ Internal::Relay.majority(merchant.relays.size), stop: stop)
634
+ rescue Internal::Relay::Failure
635
+ raise NetworkError, "Fewer than a majority of the merchant's relays took the checkout link: try again"
636
+ end
637
+ link.url
638
+ end
639
+
640
+ # Publishes a declaration on a majority of the merchant's relays, else NetworkError.
641
+ def declare(pool, event, sale, merchant, stop)
642
+ pool.publish_to_quorum(merchant.relays, event, sale.secret_key, Internal::Relay.majority(merchant.relays.size),
643
+ stop: stop)
644
+ rescue Internal::Relay::Failure
645
+ raise NetworkError, "Fewer than a majority of the merchant's relays took the invoice's declaration: do not " \
646
+ "show this invoice, try again"
647
+ end
648
+
649
+ # Publishes a lease again on a majority of the merchant's relays, else NetworkError.
650
+ def publish_lease(pool, event, sale, merchant, stop)
651
+ pool.publish_to_quorum(merchant.relays, event, sale.secret_key, Internal::Relay.majority(merchant.relays.size),
652
+ stop: stop)
653
+ rescue Internal::Relay::Failure
654
+ raise NetworkError, "Fewer than a majority of the merchant's relays took the invoice's lease: do not show " \
655
+ "this invoice, try again"
656
+ end
657
+
658
+ # Refuses a new invoice for the sale while an earlier one may still be paid (until its end
659
+ # plus 120 s, or while its on-chain payment is being confirmed or undecided), or when one was
660
+ # paid (SPEC.md §21): read in the registry, so that it holds even when the shop lost what it
661
+ # stored.
662
+ def check_earlier_invoices(pool, sale, merchant, order, stop)
663
+ records = declared(pool, sale, merchant, stop)
664
+ earlier = records.invoices
665
+ may_be_paid = Internal::Sales.may_still_be_paid(earlier.map(&:invoice), seconds).map { |index| earlier[index] }
666
+ unless may_be_paid.empty?
667
+ hand_out_pending(pool, sale, merchant, order, records, may_be_paid, stop)
668
+ return
669
+ end
670
+ statuses = check_each(pool, merchant, records, earlier, stop)
671
+ statuses.each_with_index do |status, index|
672
+ raise OrderPaidError.new(earlier[index].invoice, status.value) if status.ok? && status.value.paid?
673
+ end
674
+ # An on-chain payment being confirmed, or a transaction undecided: its time to be paid is
675
+ # over, nothing is published again, and no new link (the shop keeps the one it got, whose
676
+ # page goes on following the payment).
677
+ pending = statuses.index { |status| status.ok? && (status.value.unconfirmed? || status.value.open?) }
678
+ raise InvoicePendingError.new(earlier[pending].invoice, nil) if pending
679
+
680
+ failed = statuses.find { |status| !status.ok? }
681
+ raise failed.error if failed
682
+ end
683
+
684
+ # Step 1 of SPEC.md §21: the invoices that may still be paid, their payments checked (even of
685
+ # one alone: an invoice already paid is never handed out again), and of several, the sale's
686
+ # records read on every relay at the same time: the one shown is the one a majority holds.
687
+ # Raises OrderPaidError, an error of a check, NetworkError, or InvoicePendingError.
688
+ def hand_out_pending(pool, sale, merchant, order, records, may_be_paid, stop)
689
+ everywhere = if may_be_paid.size > 1
690
+ Internal.settled { declared(pool, sale, merchant, stop, every_relay: true) }
691
+ end
692
+ statuses = check_each(pool, merchant, records, may_be_paid, stop)
693
+ everywhere = everywhere&.value(stop)
694
+ held = (Internal::Sales.held(may_be_paid, everywhere.value.sent_by, merchant.relays.size) if everywhere&.ok?)
695
+ kind, index = Internal::Sales.pending_outcome(statuses, held)
696
+ raise OrderPaidError.new(may_be_paid[index].invoice, statuses[index].value) if kind == :paid
697
+ raise statuses[index].error if kind == :failed
698
+
699
+ # Fewer than a majority answered the read again: after a payment and an error.
700
+ if kind == :unread
701
+ raise everywhere.error if everywhere && !everywhere.ok?
702
+
703
+ raise NetworkError, "Fewer than a majority of the merchant's relays answered"
704
+ end
705
+
706
+ open = may_be_paid[index]
707
+ # Its create_invoice may have failed with fewer than a majority of the relays holding its
708
+ # declaration or its lease ("do not show this invoice"): published again before it is
709
+ # handed out. Its lease, with an address, was confirmed: the address is the order's.
710
+ declare(pool, open.event, sale, merchant, stop) if open.event
711
+ publish_lease(pool, open.lease, sale, merchant, stop) if open.lease
712
+ invoice = open.invoice
713
+ # A new link to it, for a shop that lost the one it stored (or never got it): links only show
714
+ # the invoice, several of them change nothing.
715
+ checkout_url = nil
716
+ if order.checkout
717
+ link = pending_link_value(invoice, merchant, order)
718
+ checkout_url = publish_checkout(pool, merchant, link, invoice.expires_at, stop)
719
+ end
720
+ raise InvoicePendingError.new(invoice, checkout_url)
721
+ end
722
+
723
+ # A checkout link's record of a DeclaredInvoice, with this order's redirect URL.
724
+ def pending_link_value(invoice, merchant, order)
725
+ fiat = invoice.fiat
726
+ price = fiat && Internal::Declarations.price(minor: Integer(fiat.minor, 10), digits: fiat.digits,
727
+ currency: fiat.currency)
728
+ address = invoice.onchain_address
729
+ Internal::CheckoutLinks.value(
730
+ business_name: merchant.business_name, invoice: invoice.bolt11, verify_url: invoice.verify_url,
731
+ fiat: price, note: invoice.note, redirect_url: order.redirect_url,
732
+ onchain: address && link_onchain(merchant, order.ref, address, Integer(invoice.sats, 10),
733
+ invoice.created_at, invoice.expires_at)
734
+ )
735
+ end
736
+
737
+ # What a checkout link's record holds of the address of the order `ref` (version 2): its
738
+ # amount and dates, its rest keys, and the node its page reads (the channel's, with `payers`
739
+ # true: SPEC.md §30).
740
+ def link_onchain(merchant, ref, address, sats, created_at, expires_at)
741
+ Internal::CheckoutLinks::Onchain.new(
742
+ address: address, sats: sats, created_at: created_at, expires_at: expires_at,
743
+ rest: Internal::Derive.rest_keys(@key.key, ref, address, expires_at),
744
+ bitcoin_node: Internal::BitcoinNodes.record_node_for(merchant.bitcoin_node)
745
+ )
746
+ end
747
+
748
+ # The payment check of each of `invoices` (Sales::Declared), MAX_PARALLEL_PAYMENT_CHECKS at a
749
+ # time: their Settled statuses, in order. A paid invoice wins over a service that did not answer
750
+ # about another one.
751
+ def check_each(pool, merchant, records, invoices, stop)
752
+ outcomes = Internal.settle_each(invoices, Internal::Protocol::MAX_PARALLEL_PAYMENT_CHECKS, stop) do |declared|
753
+ stored = stored_of(declared.invoice)
754
+ status_of(stored, check(stored, stop, [pool, merchant, records], @logger), seconds)
755
+ end
756
+ outcomes.map do |state, result|
757
+ raise result if result.is_a?(Cancelled) || result.is_a?(Internal::Stopped)
758
+
759
+ state == :ok ? Internal::Settled.ok(result) : Internal::Settled.failed(result)
760
+ end
761
+ end
762
+
763
+ # What a payment check asks of a declared invoice.
764
+ def stored_of(invoice)
765
+ lightning = unless invoice.bolt11.nil?
766
+ Internal::Lnurl::LightningInvoice.new(bolt11: invoice.bolt11, payment_hash: invoice.payment_hash,
767
+ verify_url: invoice.verify_url,
768
+ expires_at: invoice.expires_at)
769
+ end
770
+ Internal::Order::Stored.new(ref: invoice.ref, lightning: lightning, onchain_address: invoice.onchain_address,
771
+ sats: Integer(invoice.sats, 10), expires_at: invoice.expires_at)
772
+ end
773
+
774
+ # The status of `stored` from its parts, at `now`; raises a part's error.
775
+ def status_of(stored, parts, now)
776
+ terms = Internal::Payments::Terms.new(sats: stored.sats, expires_at: stored.expires_at,
777
+ address: stored.onchain_address)
778
+ Internal::Payments.combine(terms, now, parts.lightning, parts.onchain, parts.rests)
779
+ end
780
+
781
+ # Every part of `stored` checked at once (SPEC.md §31, "The on-chain payment"): its Lightning
782
+ # part, and with an address its on-chain part and its rest part, read on the merchant's relays
783
+ # (over `scope`, [pool, merchant, records], when given; else over the connections of a call of
784
+ # its own, whose channel's explorer shares the node's failures of `call`, an ExplorerCall); an
785
+ # invoice of the rest asked when the status calls for one. A part that fails is its error,
786
+ # never raised; a cancellation is.
787
+ def check(stored, stop, scope, logger, call = nil)
788
+ lightning = if stored.lightning
789
+ Internal.settled { Internal::Lnurl.verify_payment(stored.lightning, http(stop), seconds) }
790
+ end
791
+ return Parts.new(lightning: lightning&.value(stop), onchain: nil, rests: nil) unless stored.onchain_address
792
+
793
+ begin
794
+ if scope
795
+ pool, merchant, records = scope
796
+ address_parts(stored, pool, merchant, records, lightning, stop, logger)
797
+ else
798
+ with_relays(stop) do |pool|
799
+ address_parts(stored, pool, channel(pool, stop, logger, call), nil, lightning, stop, logger)
800
+ end
801
+ end
802
+ rescue Cancelled, Internal::Stopped
803
+ raise
804
+ rescue StandardError => e
805
+ # The relays or the channel failed: the address's parts cannot be told.
806
+ Parts.new(lightning: lightning&.value(stop), onchain: Internal::Settled.failed(e), rests: nil)
807
+ end
808
+ end
809
+
810
+ # What the checks of the parts of one invoice with an address work with: the stored invoice,
811
+ # the call's relays (its pool) and channel (the merchant), the order's sale, the call's stop,
812
+ # where warnings go.
813
+ AddressCheck = Data.define(:stored, :pool, :merchant, :sale, :stop, :logger)
814
+ private_constant :AddressCheck
815
+
816
+ # The on-chain part and the rest part of `stored` (it has an address and a reference), at
817
+ # once: the sale's records (its rest invoices, its lease) read while the explorer is asked;
818
+ # then with_rest. `records`: the sale's records when the call read them already.
819
+ def address_parts(stored, pool, merchant, records, lightning_check, stop, logger)
820
+ sale = Internal::Derive.sale(@key.key, merchant.registry, stored.ref)
821
+ scope = AddressCheck.new(stored: stored, pool: pool, merchant: merchant, sale: sale, stop: stop, logger: logger)
822
+ read = if records
823
+ Internal::Future.resolved(records)
824
+ else
825
+ Internal::Future.spawn { declared(pool, sale, merchant, stop, logger: logger) }
826
+ end
827
+ rest_check = Internal.settled { rest_part(scope, read.value(stop)) }
828
+ tolerance = -> { tolerance_of(scope, read) }
829
+ # A rest invoice that failed counts as not paid: the on-chain part then needs more.
830
+ paid_by_rests = lambda do
831
+ rest = rest_check.value(stop)
832
+ rest.ok? ? Internal::Payments.rest_summary(rest.value).paid : 0
833
+ end
834
+ onchain_check = Internal.settled { check_onchain(scope, paid_by_rests, tolerance) }
835
+ lightning = lightning_check&.value(stop)
836
+ onchain = onchain_check.value(stop)
837
+ rest_result = rest_check.value(stop)
838
+ unless rest_result.ok?
839
+ # The sale's records unread: whether a rest invoice was paid cannot be told.
840
+ return Parts.new(lightning: lightning, onchain: onchain,
841
+ rests: Internal::Payments::RestPart.failed(rest_result.error))
842
+ end
843
+
844
+ parts = Parts.new(lightning: lightning, onchain: onchain, rests: rest_result.value)
845
+ parts = with_rest(scope, read.value(stop), parts, tolerance)
846
+ publish_acceptance(scope, parts)
847
+ parts
848
+ end
849
+
850
+ # The rest part of the invoice of `scope`, from the sale's records `found`: its rest invoices,
851
+ # each checked as a Lightning part. One whose declaration fewer than a majority of the relays
852
+ # sent (its publication failed) is published again on a majority first: else the rest part
853
+ # fails (network).
854
+ def rest_part(scope, found)
855
+ stored = scope.stored
856
+ context = http(scope.stop)
857
+ # This invoice's own: another invoice of the order may have leased the address before.
858
+ invoices = found.rests.fetch(Internal::Sales.rest_key_of(stored.onchain_address, stored.expires_at), [])
859
+ invoices.each do |invoice|
860
+ event = found.unsure_rests[invoice.payment_hash]
861
+ declare(scope.pool, event, scope.sale, scope.merchant, scope.stop) if event
862
+ end
863
+ checks = invoices.map do |invoice|
864
+ Internal.settled { Internal::Lnurl.verify_payment(invoice.lightning, context, seconds) }
865
+ end
866
+ Internal::Payments::RestPart.of(invoices, Internal.all(checks, scope.stop))
867
+ end
868
+
869
+ # The order's tolerance, its lease's (the invoice's own terms), once the sale's records `read`
870
+ # are: without them, or with another lease of the address, none.
871
+ def tolerance_of(scope, read)
872
+ stored = scope.stored
873
+ terms = read.value(scope.stop).leases[stored.onchain_address]&.terms
874
+ terms && terms.sats == stored.sats && terms.expires_at == stored.expires_at ? terms.tolerance : 0
875
+ rescue Cancelled, Internal::Stopped
876
+ raise
877
+ rescue StandardError
878
+ 0
879
+ end
880
+
881
+ # The parts of the invoice of `scope` once each answered (`found`: the sale's records): when
882
+ # the status is open with a rest and no invoice of it, one asked (ask_rest; one another check
883
+ # asked and that is paid already has the on-chain part checked again); then, before the end of
884
+ # the grace period, the records of its rest invoices published again where fewer than a
885
+ # majority hold them.
886
+ def with_rest(scope, found, parts, tolerance)
887
+ stored = scope.stored
888
+ rests = parts.rests
889
+ onchain = parts.onchain
890
+ lease = found.leases[stored.onchain_address]&.terms
891
+ # The rest invoices whose rest record a majority took in this check.
892
+ recorded = {}
893
+ asked = ask_rest(scope, parts, lease) if lease && rest_wanted?(stored, parts, lease)
894
+ if asked
895
+ invoice, result, taken = asked
896
+ recorded[invoice.payment_hash] = true if taken
897
+ rests = Internal::Payments::RestPart.of(rests.invoices + [invoice], rests.results + [result])
898
+ # Asked meanwhile by another check and paid already: less is due on-chain.
899
+ if result.ok? && result.value.paid?
900
+ paid = Internal::Payments.rest_summary(rests).paid
901
+ onchain = Internal.settled { check_onchain(scope, -> { paid }, tolerance) }.value(scope.stop)
902
+ end
903
+ end
904
+ now = seconds
905
+ if !rests.invoices.empty? && now < stored.expires_at + Internal::Protocol::GRACE_SECONDS
906
+ rests = rests.with(unrecorded: publish_missing_rests(scope, rests.invoices, recorded, now))
907
+ end
908
+ Parts.new(lightning: parts.lightning, onchain: onchain, rests: rests)
909
+ end
910
+
911
+ # The status of `parts` at `now`, nil when a part failed (the status is its error).
912
+ def status_or_nil(stored, parts, now)
913
+ status_of(stored, parts, now)
914
+ rescue Cancelled, Internal::Stopped
915
+ raise
916
+ rescue StandardError
917
+ nil
918
+ end
919
+
920
+ # Whether an invoice of the rest of `parts` would be asked now, with the sale's `lease` of the
921
+ # address (Rests.to_ask): worth the order's critical section, where ask_rest decides again.
922
+ def rest_wanted?(stored, parts, lease)
923
+ now = seconds
924
+ status = status_or_nil(stored, parts, now)
925
+ return false unless status&.open?
926
+
927
+ ask = Internal::Rests.to_ask(rest: status.rest, sats: stored.sats, expires_at: stored.expires_at, now: now,
928
+ lease: lease)
929
+ !ask.nil?
930
+ end
931
+
932
+ # The on-chain part of the invoice of `scope`, with what its rest invoices paid and the order's
933
+ # tolerance as they come (callables), and the merchant's acceptance of the invoice (the
934
+ # team's record, read on every relay).
935
+ def check_onchain(scope, paid_by_rests, tolerance)
936
+ stored = scope.stored
937
+ address = stored.onchain_address
938
+ author = scope.sale.author
939
+ relays = scope.merchant.relays
940
+ seen = Internal::Derive.seen_keys(@key.key)
941
+ accepted = Internal::MerchantAcceptances.keys(@key.key, @key.team_public_key, author, address,
942
+ stored.expires_at)
943
+ terms = Internal::MerchantAcceptances::Terms.new(sats: stored.sats, expires_at: stored.expires_at)
944
+ check = Internal::Payments::Check.new(
945
+ address: address, sats: stored.sats, expires_at: stored.expires_at, sale: author,
946
+ # Read once the explorer answered.
947
+ clock: -> { seconds }, http: http(scope.stop), explorer: scope.merchant.explorer,
948
+ read_witnesses: lambda do |every_relay|
949
+ Internal::Witnesses.read_of_order(scope.pool, seen, address, author, stored.expires_at, relays,
950
+ random: @random, stop: scope.stop, every_relay: every_relay)
951
+ end,
952
+ witness_address: ->(txid, of) { Internal::Witnesses.witness_address(seen.address_key, address, txid, of) },
953
+ publish: lambda do |witness|
954
+ Internal::Witnesses.publish(scope.pool, seen, witness, relays,
955
+ created_at: seconds, random: @random, stop: scope.stop)
956
+ end,
957
+ logger: scope.logger, paid_by_rests: paid_by_rests, tolerance: tolerance,
958
+ read_merchant_acceptance: lambda do
959
+ Internal::MerchantAcceptances.read(scope.pool, accepted, terms, relays, random: @random, stop: scope.stop)
960
+ end
961
+ )
962
+ Internal::Payments.check_onchain(check, scope.stop)
963
+ end
964
+
965
+ # When the order's tolerance or the merchant's acceptance accepted less than its amount (the
966
+ # status `parts` give is being confirmed, or paid on-chain), has the pages of its checkout
967
+ # links know it (SPEC.md §31, "Acceptance records"): unless a majority of the merchant's relays
968
+ # hold what it received, or less, publishes an acceptance record of it. A failure is logged,
969
+ # never the check's: the next check publishes it again. Never the tolerance itself.
970
+ def publish_acceptance(scope, parts)
971
+ stored = scope.stored
972
+ now = seconds
973
+ # A part failed: nothing is accepted.
974
+ status = status_or_nil(stored, parts, now)
975
+ return if status.nil?
976
+
977
+ keys = -> { Internal::Derive.rest_keys(@key.key, stored.ref, stored.onchain_address, stored.expires_at) }
978
+ Internal::Acceptances.publish(scope.pool, status, sats: stored.sats, expires_at: stored.expires_at, now: now,
979
+ keys: keys, relays: scope.merchant.relays,
980
+ clock: -> { seconds }, random: @random,
981
+ logger: scope.logger, stop: scope.stop)
982
+ rescue NetworkError => e
983
+ scope.logger.warn("sattleme-checkout: the acceptance record of a payment was not published (#{e.message}); " \
984
+ "published again at the next check")
985
+ end
986
+
987
+ # Asks the merchant's Lightning address for an invoice of the rest of the invoice of `scope`,
988
+ # declares it with `rest` (the price and note of the sale's `lease` of the address) on a
989
+ # majority of the merchant's relays, then publishes its rest record (SPEC.md §31, "Asking for
990
+ # a rest invoice"). One at a time per invoice in this process, each deciding (ask_rest_now)
991
+ # inside that critical section; another check's invoice of the same rest, declared meanwhile,
992
+ # is taken instead. [invoice, result (Settled), whether a majority took its rest record], or
993
+ # nil when none is asked or none could be made: outside the address's sendable sats, or a
994
+ # failure, logged as a warning (the next check asks again).
995
+ def ask_rest(scope, parts, lease)
996
+ @rest_asks.synchronize("#{scope.sale.ref}/#{scope.stored.onchain_address}", scope.stop) do
997
+ scope.stop.check!
998
+ ask_rest_now(scope, parts, lease)
999
+ rescue Error => e
1000
+ scope.logger.warn("sattleme-checkout: no Lightning invoice of the rest of an underpayment (#{e.message}); " \
1001
+ "asked again at the next check")
1002
+ nil
1003
+ end
1004
+ end
1005
+
1006
+ # ask_rest's steps, in the critical section: the rest invoices read again, then the clock,
1007
+ # which the decision to ask, the invoice's expiry, its checks and its records all use.
1008
+ def ask_rest_now(scope, parts, lease)
1009
+ stored = scope.stored
1010
+ # Another check may have asked for it meanwhile.
1011
+ again = declared(scope.pool, scope.sale, scope.merchant, scope.stop)
1012
+ now = seconds
1013
+ status = status_or_nil(stored, parts, now)
1014
+ ask = if status&.open?
1015
+ Internal::Rests.to_ask(rest: status.rest, sats: stored.sats, expires_at: stored.expires_at, now: now,
1016
+ lease: lease)
1017
+ end
1018
+ return nil unless ask
1019
+
1020
+ taken_meanwhile(scope, again, parts.rests.invoices, ask, now) || new_rest(scope, ask, lease, now)
1021
+ end
1022
+
1023
+ # A rest invoice of exactly `ask`'s sats that another check declared meanwhile (`again`: the
1024
+ # sale's records read again; `known`: the rest invoices this check read) and not ended at
1025
+ # `now`, checked as any rest invoice (it may have been paid already): [invoice, result, false],
1026
+ # else nil.
1027
+ def taken_meanwhile(scope, again, known, ask, now)
1028
+ stored = scope.stored
1029
+ before = known.to_h { |invoice| [invoice.payment_hash, true] }
1030
+ candidates = again.rests.fetch(Internal::Sales.rest_key_of(stored.onchain_address, stored.expires_at), [])
1031
+ meanwhile = candidates.find do |invoice|
1032
+ !before.key?(invoice.payment_hash) && invoice.sats == ask.sats && now < invoice.expires_at
1033
+ end
1034
+ return nil unless meanwhile
1035
+
1036
+ # On a majority, as any rest invoice found.
1037
+ event = again.unsure_rests[meanwhile.payment_hash]
1038
+ declare(scope.pool, event, scope.sale, scope.merchant, scope.stop) if event
1039
+ context = http(scope.stop)
1040
+ result = Internal.settled { Internal::Lnurl.verify_payment(meanwhile.lightning, context, now) }
1041
+ [meanwhile, result.value(scope.stop), false]
1042
+ end
1043
+
1044
+ # A new invoice of the rest `ask` gives, asked at `now` of the merchant's Lightning address (nil
1045
+ # outside its sendable sats), checked, declared with the price and note of the sale's `lease`
1046
+ # (dated `now`), its rest record published (dated `now`): [invoice, result, whether a majority
1047
+ # took its rest record].
1048
+ def new_rest(scope, ask, lease, now)
1049
+ stored = scope.stored
1050
+ context = http(scope.stop)
1051
+ pay = Internal::Lnurl.pay_request(scope.merchant.lightning_address, context)
1052
+ return nil unless Internal::Rests.sendable?(ask.sats, pay.sendable_sats)
1053
+
1054
+ expiry = ask.expiry_seconds
1055
+ answer = Internal::Lnurl.request_invoice(pay, sats: ask.sats, expiry_seconds: expiry, comment: lease.note,
1056
+ http: context)
1057
+ decoded = Internal::Lnurl.check_invoice(answer, pay: pay, sats: ask.sats, duration_seconds: expiry, now: now)
1058
+ rest_of = Internal::Declarations::RestOf.new(address: stored.onchain_address, expires_at: stored.expires_at)
1059
+ event = declaration_event(scope.sale, answer, decoded, lease.price, lease.note, rest_of, now)
1060
+ declare(scope.pool, event, scope.sale, scope.merchant, scope.stop)
1061
+ invoice = Internal::Rests::Invoice.new(bolt11: answer.pr, payment_hash: decoded.payment_hash,
1062
+ verify_url: answer.verify, sats: ask.sats, created_at: decoded.timestamp,
1063
+ expires_at: decoded.expires_at)
1064
+ # Declared: it may be shown. Its record, for the checkout links' pages.
1065
+ [invoice, Internal::Settled.ok(Internal::Lnurl::Part.open), publish_rest(scope, invoice, now)]
1066
+ end
1067
+
1068
+ # Publishes the rest record of `invoice`, dated `created_at`, on a majority: whether a majority
1069
+ # took it (a failure only logged).
1070
+ def publish_rest(scope, invoice, created_at)
1071
+ stored = scope.stored
1072
+ keys = Internal::Derive.rest_keys(@key.key, stored.ref, stored.onchain_address, stored.expires_at)
1073
+ event = Internal::Rests.record_event(keys: keys, invoice: invoice, expires_at: stored.expires_at,
1074
+ created_at: created_at, random: @random)
1075
+ Internal::Rests.publish_record(scope.pool, event, keys, scope.merchant.relays, stop: scope.stop)
1076
+ true
1077
+ rescue NetworkError => e
1078
+ scope.logger.warn("sattleme-checkout: the record of an invoice of the rest was not published (#{e.message}); " \
1079
+ "published again at the next check")
1080
+ false
1081
+ end
1082
+
1083
+ # Publishes again, dated `now`, the rest records of `invoices` that fewer than a majority of the
1084
+ # relays sent (their first publication may have failed), so that the checkout links' pages see
1085
+ # each of them; never over a record of a newer format at its address (logged: update the gem),
1086
+ # which holds it. Gives the payment hashes of those still not known on a majority: neither sent
1087
+ # by a majority, held by a newer record, nor taken by one in this check (`recorded`, or
1088
+ # published again here); when fewer than a majority answered, all of them but `recorded`.
1089
+ # Those are never the status's `bolt11`: the next check tries again.
1090
+ def publish_missing_rests(scope, invoices, recorded, now)
1091
+ stored = scope.stored
1092
+ keys = Internal::Derive.rest_keys(@key.key, stored.ref, stored.onchain_address, stored.expires_at)
1093
+ terms = Internal::Rests::LinkTerms.new(sats: stored.sats, created_at: -Internal::Json::MAX_SAFE_INTEGER,
1094
+ expires_at: stored.expires_at)
1095
+ read = Internal::Rests.read_records(scope.pool, keys, terms, scope.merchant.relays,
1096
+ random: @random, stop: scope.stop)
1097
+ unknown = invoices.reject { |invoice| recorded.key?(invoice.payment_hash) }
1098
+ # Not read: whether the page can see the others is not known.
1099
+ return unknown.to_h { |invoice| [invoice.payment_hash, true] } if read.nil?
1100
+
1101
+ unless read.newer.empty?
1102
+ scope.logger.warn("sattleme-checkout: a record of an invoice of the rest has a newer format than this " \
1103
+ "version reads; update the gem")
1104
+ end
1105
+ unrecorded = {}
1106
+ unknown.each do |invoice|
1107
+ next if read.held.key?(invoice.payment_hash)
1108
+ # A record of a newer format at its address: never written over (SPEC.md §12).
1109
+ next if read.newer.key?(Internal::Derive.rest_record_address(keys.key, invoice.payment_hash))
1110
+
1111
+ unrecorded[invoice.payment_hash] = true unless publish_rest(scope, invoice, now)
1112
+ end
1113
+ unrecorded
1114
+ end
1115
+
1116
+ # wait_for_payment of an invoice without an address: a check every `interval`.
1117
+ def wait_lightning(stored, interval, listener, warnings, stop)
1118
+ loop do
1119
+ stop.check!
1120
+ begin
1121
+ status = status_of(stored, check(stored, stop, nil, warnings), seconds)
1122
+ listener&.call(status)
1123
+ return status if status.final?
1124
+ rescue NetworkError => e
1125
+ warnings.failed(e)
1126
+ end
1127
+ warnings.checked
1128
+ stop.cancellation.wait(interval / 1000.0)
1129
+ end
1130
+ end
1131
+
1132
+ # wait_for_payment of an invoice with an address: each status combines the last result of each
1133
+ # part. A full check (every part, an invoice of the rest asked when needed) at each change the
1134
+ # explorer's WebSocket pushes and every 60 s; between them, the Lightning invoice and the rest
1135
+ # invoices the last full check found, every `interval`.
1136
+ def wait_with_address(stored, interval, listener, warnings, stop)
1137
+ waiter = AddressWait.new(self, stored, interval, listener, warnings, stop)
1138
+ waiter.run
1139
+ end
1140
+
1141
+ # The parts of one wait_for_payment of an invoice with an address, driven from the calling
1142
+ # thread: the checks run in threads of their own and hand their results to it.
1143
+ class AddressWait
1144
+ def initialize(client, stored, interval, listener, warnings, stop)
1145
+ @client = client
1146
+ @stored = stored
1147
+ @interval = interval / 1000.0
1148
+ @listener = listener
1149
+ @warnings = warnings
1150
+ @stop = stop
1151
+ @inbox = Internal::Inbox.new
1152
+ @checks = stop.child
1153
+ # The checks it started, each until it ended.
1154
+ @running = []
1155
+ # The last result of each part; :unknown until it was checked once.
1156
+ @lightning = stored.lightning ? :unknown : nil
1157
+ @onchain = :unknown
1158
+ @rests = nil
1159
+ @checking = false
1160
+ @again = false
1161
+ @lightning_checking = false
1162
+ # Full checks started, the last one that ended, and the first one a status must wait for.
1163
+ @started = 0
1164
+ @ended = 0
1165
+ @wait_for = 0
1166
+ @lightning_at = nil
1167
+ @onchain_at = nil
1168
+ # The explorer's WebSocket: of the node the last channel read names (SPEC.md §31), with its
1169
+ # fallback, opened once a check read the channel (before, whether mempool.space may be
1170
+ # asked is not known), and opened again when the channel names another node. The node's
1171
+ # failures are the call's, shared by its checks and its WebSocket.
1172
+ @call = ExplorerCall.new(failures: Internal::NodeFailures.new, on_node: ->(node) { @inbox << [:node, node] })
1173
+ @watcher = nil
1174
+ @watched = nil
1175
+ end
1176
+
1177
+ def run
1178
+ check_onchain
1179
+ loop do
1180
+ deadline = [@lightning_at, @onchain_at].compact.min
1181
+ message = @inbox.pop(@stop, deadline)
1182
+ outcome = handle(message)
1183
+ return outcome if outcome
1184
+ end
1185
+ ensure
1186
+ @watcher&.close
1187
+ # Nothing it started runs on once it returns (SPEC.md §23): each check is stopped, then
1188
+ # waited for until it ended.
1189
+ @checks.stop
1190
+ @running.each { |check| check.wait(nil) }
1191
+ end
1192
+
1193
+ private
1194
+
1195
+ # Handles one message: the final status once there is one.
1196
+ def handle(message)
1197
+ now = Internal::Clock.now
1198
+ if message.equal?(Internal::Inbox::TIMEOUT)
1199
+ if @onchain_at && now >= @onchain_at
1200
+ @onchain_at = nil
1201
+ check_onchain
1202
+ end
1203
+ if @lightning_at && now >= @lightning_at
1204
+ @lightning_at = nil
1205
+ check_lightning
1206
+ end
1207
+ return nil
1208
+ end
1209
+ case message
1210
+ in :change
1211
+ check_onchain
1212
+ nil
1213
+ in [:node, node] then watch(node)
1214
+ in [:full, mine, parts] then full_ended(mine, parts)
1215
+ in [:full_failed, error] then raise error
1216
+ in [:lightning, own, results, known] then lightning_ended(own, results, known)
1217
+ end
1218
+ end
1219
+
1220
+ # A check read the channel, which names `node` (nil: mempool.space): the WebSocket watched is
1221
+ # that explorer's, with its fallback.
1222
+ def watch(node)
1223
+ key = node ? "#{node.fallback} #{node.url}" : "mempool"
1224
+ return nil if key == @watched
1225
+
1226
+ @watcher&.close
1227
+ @watched = key
1228
+ explorer = Internal::CallExplorer.new(node, @call.failures, @client.send(:clock))
1229
+ @watcher = Internal::Watch.new(@client.send(:websocket_client), explorer, @stored.onchain_address,
1230
+ @client.send(:relay_timeout)) { @inbox << :change }
1231
+ nil
1232
+ end
1233
+
1234
+ def full_ended(mine, parts)
1235
+ @checking = false
1236
+ @ended = mine
1237
+ @onchain = parts.onchain
1238
+ @rests = parts.rests
1239
+ @lightning = parts.lightning unless parts.lightning.nil?
1240
+ status = report
1241
+ return status if status
1242
+
1243
+ # A full check ended: what it, and the checks of the Lightning invoices since the last one,
1244
+ # no longer met has stopped.
1245
+ @warnings.checked
1246
+ schedule_lightning
1247
+ if @again
1248
+ @again = false
1249
+ check_onchain
1250
+ end
1251
+ nil
1252
+ end
1253
+
1254
+ def lightning_ended(own, results, known)
1255
+ @lightning_checking = false
1256
+ @lightning = own unless own == :unknown
1257
+ paid = false
1258
+ # A full check may have found other rest invoices meanwhile: its results stand.
1259
+ if known && @rests.equal?(known)
1260
+ paid = results.each_with_index.any? { |result, index| paid?(result) && !paid?(known.results[index]) }
1261
+ @rests = known.with(results: results)
1262
+ end
1263
+ if paid
1264
+ # Paid by a rest invoice: what is due on-chain changed, a full check tells the status.
1265
+ @wait_for = @started + 1
1266
+ check_onchain
1267
+ else
1268
+ status = report
1269
+ return status if status
1270
+ end
1271
+ schedule_lightning
1272
+ nil
1273
+ end
1274
+
1275
+ # The status of the last results, given to the listener: itself once final, else nil.
1276
+ def report
1277
+ return nil if @lightning == :unknown || @onchain == :unknown
1278
+ # A rest invoice was paid after the last full check began: its on-chain part was judged
1279
+ # against what was due then, never combined with it (it might read underpaid for good).
1280
+ return nil if @ended < @wait_for
1281
+
1282
+ parts = Parts.new(lightning: @lightning, onchain: @onchain, rests: @rests)
1283
+ begin
1284
+ status = @client.send(:status_of, @stored, parts, @client.send(:seconds))
1285
+ rescue NetworkError => e
1286
+ @warnings.failed(e)
1287
+ return nil
1288
+ end
1289
+ @listener&.call(status)
1290
+ status.final? ? status : nil
1291
+ end
1292
+
1293
+ def paid?(result)
1294
+ result.ok? && result.value.paid?
1295
+ end
1296
+
1297
+ def final?(result)
1298
+ result.ok? && !result.value.open?
1299
+ end
1300
+
1301
+ # Whether a Lightning invoice (the order's, or one of the rest) may still change.
1302
+ def lightning_pending?
1303
+ own = @lightning == :unknown || (!@lightning.nil? && !final?(@lightning))
1304
+ own || (@rests&.results&.any? { |result| !final?(result) } || false)
1305
+ end
1306
+
1307
+ def schedule_lightning
1308
+ return if !@lightning_at.nil? || @lightning_checking || !lightning_pending?
1309
+
1310
+ @lightning_at = Internal::Clock.now + @interval
1311
+ end
1312
+
1313
+ def check_lightning
1314
+ @lightning_checking = true
1315
+ known = @rests
1316
+ lightning = @lightning
1317
+ stored = @stored
1318
+ client = @client
1319
+ checks = @checks
1320
+ started = Internal::Future.spawn("sattleme-checkout wait") do
1321
+ context = client.send(:http, checks)
1322
+ own = if stored.lightning && (lightning == :unknown || (!lightning.nil? && !final?(lightning)))
1323
+ Internal.settled do
1324
+ Internal::Lnurl.verify_payment(stored.lightning, context, client.send(:seconds))
1325
+ end.value(checks)
1326
+ else
1327
+ lightning
1328
+ end
1329
+ results = (known&.invoices || []).each_with_index.map do |invoice, index|
1330
+ result = known.results[index]
1331
+ next Internal::Future.resolved(result) if final?(result)
1332
+
1333
+ Internal.settled { Internal::Lnurl.verify_payment(invoice.lightning, context, client.send(:seconds)) }
1334
+ end
1335
+ @inbox << [:lightning, own, Internal.all(results, checks), known]
1336
+ rescue Internal::Stopped, Cancelled
1337
+ nil
1338
+ end
1339
+ track(started)
1340
+ end
1341
+
1342
+ # Keeps `check` until it ended, and forgets those that did.
1343
+ def track(check)
1344
+ @running.reject!(&:settled?)
1345
+ @running << check
1346
+ end
1347
+
1348
+ def check_onchain
1349
+ if @checking
1350
+ @again = true
1351
+ return
1352
+ end
1353
+ @checking = true
1354
+ @started += 1
1355
+ mine = @started
1356
+ # Every 60 s at least: a socket may go quiet without closing.
1357
+ @onchain_at = Internal::Clock.now + (Internal::Protocol::ONCHAIN_CHECK_INTERVAL_MS / 1000.0)
1358
+ client = @client
1359
+ stored = @stored
1360
+ checks = @checks
1361
+ warnings = @warnings
1362
+ started = Internal::Future.spawn("sattleme-checkout wait") do
1363
+ parts = client.send(:check, stored, checks, nil, warnings, @call)
1364
+ @inbox << [:full, mine, parts]
1365
+ rescue Internal::Stopped, Cancelled
1366
+ nil
1367
+ rescue StandardError => e
1368
+ @inbox << [:full_failed, e]
1369
+ end
1370
+ track(started)
1371
+ end
1372
+ end
1373
+ private_constant :AddressWait
1374
+
1375
+ attr_reader :websocket_client
1376
+
1377
+ # The client's clock (Unix seconds), as given.
1378
+ def clock = @now
1379
+
1380
+ def relay_timeout = @relay_timeout_ms / 1000.0
1381
+
1382
+ # The warnings of the checks of one wait_for_payment (SPEC.md §23): a warning each check meets
1383
+ # again (an explorer or a Lightning address that does not answer, a rest invoice that cannot
1384
+ # be asked, a witness that cannot be published) is logged once, and again only once a check
1385
+ # went without it. A logger itself (`warn`), for the checks.
1386
+ class OnceWarnings
1387
+ def initialize(logger)
1388
+ @logger = logger
1389
+ @mutex = Mutex.new
1390
+ @before = {}
1391
+ @now = {}
1392
+ end
1393
+
1394
+ def warn(message)
1395
+ fresh = @mutex.synchronize do
1396
+ seen = @before.key?(message) || @now.key?(message)
1397
+ @now[message] = true
1398
+ !seen
1399
+ end
1400
+ @logger.warn(message) if fresh
1401
+ end
1402
+
1403
+ # Warns of a check that failed (NetworkError): it is checked again.
1404
+ def failed(error)
1405
+ warn("sattleme-checkout: the payment check failed (#{error.message}); checked again")
1406
+ end
1407
+
1408
+ # A check ended: a warning it did not meet stopped.
1409
+ def checked
1410
+ @mutex.synchronize do
1411
+ @before = @now
1412
+ @now = {}
1413
+ end
1414
+ end
1415
+ end
1416
+ private_constant :OnceWarnings
1417
+
1418
+ # `items` in a random order, from the CSPRNG (so that two servers rarely try the same address
1419
+ # first): Fisher–Yates, each draw without bias.
1420
+ def in_random_order(items)
1421
+ shuffled = items.dup
1422
+ (shuffled.size - 1).downto(1) do |i|
1423
+ bound = i + 1
1424
+ # The largest multiple of `bound` within 2^32: draws at or above it are drawn again.
1425
+ limit = (2**32) - ((2**32) % bound)
1426
+ draw = nil
1427
+ loop do
1428
+ draw = @random.call(4).unpack1("N")
1429
+ break if draw < limit
1430
+ end
1431
+ j = draw % bound
1432
+ shuffled[i], shuffled[j] = shuffled[j], shuffled[i]
1433
+ end
1434
+ shuffled
1435
+ end
1436
+ end
1437
+ end
1438
+ end