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,345 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sattleme
4
+ module Checkout
5
+ module Internal
6
+ # The payment of an invoice (SPEC.md §31, "The on-chain payment"): its on-chain part, from the
7
+ # explorer and the witnesses of its order, its rest part (the Lightning invoices of the rest
8
+ # of an underpayment), and how they combine with its Lightning part.
9
+ module Payments
10
+ # The on-chain part of an invoice with an address: :underpaid (less than the amount came in
11
+ # time; `final` once the lease ended and nothing is undecided), :unconfirmed (enough, not 3
12
+ # confirmations deep yet on the explorer read), or :paid.
13
+ OnchainPart = Data.define(:kind, :received, :final, :confirmations, :txids) do
14
+ def self.underpaid(received, final)
15
+ new(kind: :underpaid, received: received, final: final,
16
+ confirmations: nil, txids: [].freeze)
17
+ end
18
+
19
+ def self.unconfirmed(received, confirmations, txids)
20
+ new(kind: :unconfirmed, received: received, final: false,
21
+ confirmations: confirmations, txids: txids)
22
+ end
23
+
24
+ def self.paid(received, txids)
25
+ new(kind: :paid, received: received, final: true, confirmations: nil,
26
+ txids: txids)
27
+ end
28
+ end
29
+
30
+ # What the on-chain part of an invoice needs: its address, amount and end; the order's sale
31
+ # (its author); the clock (`clock.call`: Unix seconds, read once the explorer answered); the
32
+ # HTTP context (for BlockCypher); the explorer of the call (CallExplorer: mempool.space, or
33
+ # the merchant's Bitcoin node with its fallback); and, as callables, the read of the order's witnesses
34
+ # (`read_witnesses.call(every_relay)`), a witness address (`witness_address.call(txid, sale)`),
35
+ # the publication of a witness on a majority (`publish.call(witness)`); the logger; what the
36
+ # rest invoices paid and the order's tolerance, each a callable that gives it once known (read
37
+ # at the same time); the read of the merchant's acceptance of the invoice
38
+ # (`read_merchant_acceptance.call`: a MerchantAcceptances::Acceptance, read on every relay at
39
+ # the same time as the witnesses, when some transaction pays the address; NetworkError when
40
+ # fewer than a majority answered).
41
+ Check = Data.define(:address, :sats, :expires_at, :sale, :clock, :http, :explorer, :read_witnesses,
42
+ :witness_address, :publish, :logger, :paid_by_rests, :tolerance,
43
+ :read_merchant_acceptance)
44
+
45
+ # The rest part of an invoice: its rest invoices and the Lightning part of each (Settled), in
46
+ # order; the error of the read of the sale's records (whether a rest invoice was paid cannot
47
+ # be told), nil without one; the payment hashes of the rest invoices whose rest record is not
48
+ # known on a majority of the relays (never the status's `bolt11`).
49
+ RestPart = Data.define(:invoices, :results, :error, :unrecorded) do
50
+ def self.of(invoices, results) = new(invoices: invoices, results: results, error: nil, unrecorded: {}.freeze)
51
+ def self.failed(error) = new(invoices: [].freeze, results: [].freeze, error: error, unrecorded: {}.freeze)
52
+ end
53
+
54
+ # What the rest invoices paid (each payment hash once), their preimages in order, the hashes
55
+ # paid, whether each is final, and the first error (nil without one).
56
+ Summary = Data.define(:paid, :preimages, :hashes, :final, :error)
57
+
58
+ # What an invoice is, for its status: its amount, its end, its address (nil without one).
59
+ Terms = Data.define(:sats, :expires_at, :address)
60
+
61
+ module_function
62
+
63
+ # The on-chain part of an invoice, checked at `now`, the clock once the explorer answered:
64
+ # each transaction paying its address in time (while the lease ran, as a witness of the sale
65
+ # or BlockCypher's time says), a replacement of payments in time, late, or undecided; what
66
+ # counts of them; and, once enough counts, the confirmations on the explorer read: paid at 3.
67
+ # Publishes the witnesses it finds (of the sale on a majority, else NetworkError; of none for
68
+ # the merchant's app only, a failure logged). What is due on-chain is the least the order's
69
+ # tolerance accepts of the amount, or the `received` of the merchant's acceptance a majority
70
+ # of the relays sent when less, less what its rest invoices paid, a sat at least
71
+ # (Tolerance.due_onchain): when they pay the amount, the part is :paid without transactions.
72
+ # A witness or a merchant's acceptance of a newer format is logged. NetworkError when the
73
+ # explorer (with its fallback), BlockCypher or the relays fail.
74
+ def check_onchain(check, stop)
75
+ address = check.address
76
+ ending = check.expires_at + Protocol::GRACE_SECONDS
77
+ # One read, of one explorer: a transaction's confirmations compare its block's height with
78
+ # that explorer's height. Either failing, both are asked of the next explorer (SPEC.md §31).
79
+ txs, height = check.explorer.read(check.http) do |base, http|
80
+ listing = Future.spawn { Explorer.address_transactions(base, address, http) }
81
+ tip = Future.spawn { Explorer.chain_height(base, http) }
82
+ Internal.all([listing, tip], http.stop)
83
+ end
84
+ # After the explorer's answer, never before: listed now, a transaction was broadcast by now.
85
+ now = check.clock.call
86
+ paying = []
87
+ txs.each do |tx|
88
+ pays = tx.pays_to(address)
89
+ paying << [tx, pays] if pays.positive? && paying.none? { |other, _| other.txid == tx.txid }
90
+ end
91
+ # The witnesses, and the merchant's acceptance at the same time (on every relay), when some
92
+ # transaction pays the address.
93
+ accepting = Future.spawn { check.read_merchant_acceptance.call } unless paying.empty?
94
+ witnesses = paying.empty? ? Witnesses::NONE : check.read_witnesses.call(false)
95
+ accepted = accepting ? accepting.value(stop) : MerchantAcceptances::NONE
96
+ check.logger.warn(MerchantAcceptances::NEWER_FORMAT) if accepted.newer
97
+ listed = paying.to_h { |tx, _| [tx.txid, true] }
98
+ parts = parts_of(witnesses, paying, listed)
99
+ kinds, of_sale, of_none = judge(check, paying, witnesses, parts, ending, now)
100
+ publish_witnesses(check, of_sale, of_none, stop)
101
+ newer = !witnesses.newer.empty?
102
+ # Its witnesses on a majority, read again on every relay: of two checks that publish
103
+ # witnesses of one transaction at once, the later reader sees both, whatever one relay hides.
104
+ unless of_sale.empty?
105
+ again = check.read_witnesses.call(true)
106
+ newer ||= !again.newer.empty?
107
+ parts_again = parts_of(again, paying, listed)
108
+ paying.map(&:first).each { |tx| kinds[tx.txid] = :anothers if anothers?(again, parts_again, tx.txid) }
109
+ end
110
+ if newer
111
+ check.logger.warn("sattleme-checkout: a witness of this address has a newer format than this version " \
112
+ "reads; update the gem")
113
+ end
114
+ count(check, paying, witnesses, parts, kinds, listed, height, ending, now, accepted)
115
+ end
116
+
117
+ # The parts of the transactions paying the address (Replacements.parts), from the witnesses of
118
+ # this invoice and of other invoices (in the order they were seen), then the transactions no
119
+ # such witness names (their order unknown): a replacement of another invoice's payment stands
120
+ # for it.
121
+ def parts_of(witnesses, paying, listed)
122
+ known = witnesses.sale.merge(witnesses.others) { |_, mine, _| mine }
123
+ entries = witnesses.sale.to_a + witnesses.others.to_a
124
+ from_witnesses = entries.map do |txid, witness|
125
+ Replacements::PaymentTx.new(txid: txid, sats: witness.sats, inputs: witness.inputs, order: witness.seen_at,
126
+ listed: listed.key?(txid))
127
+ end
128
+ unnamed = paying.reject { |tx, _| known.key?(tx.txid) }.map do |tx, pays|
129
+ Replacements::PaymentTx.new(txid: tx.txid, sats: pays, inputs: tx.coins, order: nil, listed: true)
130
+ end
131
+ Replacements.parts(from_witnesses + unnamed)
132
+ end
133
+
134
+ # Another invoice's: a witness of another invoice names it, or the root of one of its parts.
135
+ def anothers?(witnesses, parts, txid)
136
+ witnesses.others.key?(txid) || parts.fetch(txid).any? { |part| witnesses.others.key?(part.root) }
137
+ end
138
+
139
+ # Step 3 of SPEC.md §31, "The on-chain payment": the kind of each transaction paying the
140
+ # address (:in_time, :replacement, :late, :undecided or :anothers), and the witnesses to
141
+ # publish, of the sale and of none.
142
+ def judge(check, paying, witnesses, parts, ending, now)
143
+ sale = check.sale
144
+ newer_names = ->(txid, of) { witnesses.newer.key?(check.witness_address.call(txid, of)) }
145
+ # A witness of a newer format that names no transaction listed may be of a payment replaced.
146
+ newer_elsewhere = witnesses.newer.keys.any? do |d|
147
+ paying.none? do |tx, _|
148
+ d == check.witness_address.call(tx.txid, sale) || d == check.witness_address.call(tx.txid, nil)
149
+ end
150
+ end
151
+ kinds = {}
152
+ of_sale = []
153
+ of_none = []
154
+ witness_of = lambda do |tx, pays, for_sale, replacement|
155
+ Witnesses::Witness.new(address: check.address, txid: tx.txid, sale: for_sale ? sale : nil, sats: pays,
156
+ inputs: tx.coins.first(Protocol::MAX_WITNESS_INPUTS), replacement: replacement,
157
+ expires_at: for_sale ? check.expires_at : nil)
158
+ end
159
+ paying.each do |tx, pays|
160
+ txid = tx.txid
161
+ # Another invoice's: a transaction counts for one invoice at most.
162
+ if anothers?(witnesses, parts, txid)
163
+ kinds[txid] = :anothers
164
+ next
165
+ end
166
+ witness = witnesses.sale[txid]
167
+ if witness && !witness.replacement
168
+ kinds[txid] = :in_time
169
+ next
170
+ end
171
+ if newer_names.call(txid, sale)
172
+ kinds[txid] = :undecided
173
+ next
174
+ end
175
+ if now <= ending
176
+ # Listed now, it was broadcast by now: while the lease runs.
177
+ kinds[txid] = :in_time
178
+ of_sale << witness_of.call(tx, pays, true, false)
179
+ next
180
+ end
181
+ if witness
182
+ # An earlier check found it a replacement, and BlockCypher's time of it late.
183
+ kinds[txid] = :replacement
184
+ next
185
+ end
186
+ # No check saw it in time.
187
+ own = parts.fetch(txid)
188
+ replaces = own.any? { |part| part.root != txid }
189
+ if own.any? { |part| part.root == txid }
190
+ time = Explorer.received_at(txid, check.http)
191
+ if time && time <= ending * 1000
192
+ kinds[txid] = :in_time
193
+ of_sale << witness_of.call(tx, pays, true, false)
194
+ next
195
+ end
196
+ end
197
+ if newer_elsewhere
198
+ kinds[txid] = :undecided
199
+ elsif replaces
200
+ kinds[txid] = :replacement
201
+ of_sale << witness_of.call(tx, pays, true, true)
202
+ else
203
+ # Its payment reaches the merchant's wallet, but no order. A witness none names it
204
+ # already, or one of a newer format holds that witness's address: never written over.
205
+ kinds[txid] = :late
206
+ unless witnesses.none.key?(txid) || newer_names.call(txid, nil)
207
+ of_none << witness_of.call(tx, pays, false, false)
208
+ end
209
+ end
210
+ end
211
+ [kinds, of_sale, of_none]
212
+ end
213
+
214
+ # Publishes the witnesses of the sale (on a majority, else NetworkError) and of none (a
215
+ # failure logged), all at once.
216
+ def publish_witnesses(check, of_sale, of_none, stop)
217
+ futures = of_sale.map { |witness| Future.spawn("sattleme-checkout witness") { check.publish.call(witness) } }
218
+ futures += of_none.map do |witness|
219
+ Future.spawn("sattleme-checkout witness") do
220
+ check.publish.call(witness)
221
+ rescue NetworkError => e
222
+ check.logger.warn("sattleme-checkout: the witness of a late payment was not published: #{e.message}")
223
+ end
224
+ end
225
+ Internal.all(futures, stop)
226
+ end
227
+
228
+ # Step 4 of SPEC.md §31, "The on-chain payment": what counts, what is due, and the part.
229
+ def count(check, paying, witnesses, parts, kinds, listed, height, ending, now, accepted)
230
+ in_time = lambda do |root|
231
+ listed.key?(root) ? kinds[root] == :in_time : witnesses.sale[root]&.replacement == false
232
+ end
233
+ counted = {}
234
+ paying.map(&:first).each do |tx|
235
+ next if %i[undecided anothers].include?(kinds[tx.txid])
236
+
237
+ sum = parts.fetch(tx.txid).select { |part| in_time.call(part.root) }.sum(&:sats)
238
+ counted[tx.txid] = sum if sum.positive?
239
+ end
240
+ received = counted.values.sum
241
+ # Nothing due when the rest invoices paid it all; else the least the order's tolerance
242
+ # accepts, or what the merchant accepted when less, less what they paid, at least a sat.
243
+ due = Tolerance.due_onchain(check.sats, check.tolerance.call, check.paid_by_rests.call, accepted.received)
244
+ return OnchainPart.paid(received, []) if due.zero?
245
+ return OnchainPart.underpaid(received, now > ending && !kinds.value?(:undecided)) if received < due
246
+
247
+ order = paying.filter_map { |tx, _| tx if counted.key?(tx.txid) }
248
+ txids = order.map(&:txid)
249
+ confirmations = order.map { |tx| tx.confirmations(height) }.min
250
+ # 3 confirmations on the explorer read: what it alone shows makes the payment count as made.
251
+ return OnchainPart.paid(received, txids) if confirmations >= Protocol::CONFIRMATIONS
252
+
253
+ OnchainPart.unconfirmed(received, confirmations, txids)
254
+ end
255
+
256
+ # What the rest invoices of `rests` paid (each payment hash once; one that failed counts as
257
+ # not paid), their preimages in order, whether each is final, and the first error.
258
+ def rest_summary(rests)
259
+ paid = 0
260
+ preimages = []
261
+ hashes = {}
262
+ final = true
263
+ error = nil
264
+ if rests&.error
265
+ final = false
266
+ error = rests.error
267
+ end
268
+ # In the order of the rest invoices (by date, then payment hash), whatever the order given.
269
+ order = (rests&.invoices || []).each_with_index.map { |invoice, index| [invoice, rests.results[index]] }
270
+ order = order.sort_by { |invoice, _| Rests.order_key(invoice) }
271
+ order.each do |invoice, result|
272
+ unless result.ok?
273
+ final = false
274
+ error ||= result.error
275
+ next
276
+ end
277
+ if result.value.paid?
278
+ next if hashes.key?(invoice.payment_hash)
279
+
280
+ hashes[invoice.payment_hash] = true
281
+ paid += invoice.sats
282
+ preimages << result.value.preimage
283
+ elsif result.value.open?
284
+ final = false
285
+ end
286
+ end
287
+ Summary.new(paid: paid, preimages: preimages, hashes: hashes, final: final, error: error)
288
+ end
289
+
290
+ # The status of an invoice from its parts (SPEC.md §31): paid in Lightning, else paid by its
291
+ # rest invoices alone, else paid on-chain (mixed when rest invoices paid part of it), else
292
+ # unconfirmed on-chain, else an error of a part (the Lightning part's first, then the rest
293
+ # part's, then the on-chain part's, raised), else expired once every part is final, else
294
+ # open, with its rest. A part is nil when the invoice has none (no Lightning invoice, no
295
+ # address); `lightning` and `onchain` are Settled. `received` counts what the rest invoices
296
+ # paid.
297
+ def combine(terms, now, lightning, onchain, rests = nil)
298
+ return PaymentStatus.paid_lightning(lightning.value.preimage) if lightning&.ok? && lightning.value.paid?
299
+
300
+ summary = rest_summary(rests)
301
+ onchain_value = onchain&.ok? ? onchain.value : nil
302
+ if summary.paid >= terms.sats
303
+ # What came on-chain in time counts too (0 when the on-chain part failed).
304
+ received = (onchain_value&.received || 0) + summary.paid
305
+ return PaymentStatus.paid_mixed(received: received.to_s, txids: [], preimages: summary.preimages)
306
+ end
307
+ if onchain_value&.kind == :paid
308
+ received = (onchain_value.received + summary.paid).to_s
309
+ if summary.paid.positive?
310
+ return PaymentStatus.paid_mixed(received: received, txids: onchain_value.txids,
311
+ preimages: summary.preimages)
312
+ end
313
+
314
+ return PaymentStatus.paid_onchain(received: received, txids: onchain_value.txids)
315
+ end
316
+ if onchain_value&.kind == :unconfirmed
317
+ return PaymentStatus.unconfirmed(received: (onchain_value.received + summary.paid).to_s,
318
+ confirmations: onchain_value.confirmations, txids: onchain_value.txids)
319
+ end
320
+ raise lightning.error if lightning && !lightning.ok?
321
+ raise summary.error if summary.error
322
+ raise onchain.error if onchain && !onchain.ok?
323
+
324
+ underpaid = onchain_value&.kind == :underpaid ? onchain_value : nil
325
+ received = (underpaid&.received || 0) + summary.paid
326
+ lightning_final = lightning.nil? || lightning.value.expired?
327
+ onchain_final = onchain.nil? || underpaid&.final == true
328
+ return PaymentStatus.expired(received: received.to_s) if lightning_final && onchain_final && summary.final
329
+
330
+ PaymentStatus.open(expires_at: terms.expires_at, received: received.to_s,
331
+ rest: open_rest(terms, now, received, rests, summary))
332
+ end
333
+
334
+ def open_rest(terms, now, received, rests, summary)
335
+ return nil if terms.address.nil?
336
+
337
+ unrecorded = rests&.unrecorded || {}
338
+ recorded = (rests&.invoices || []).reject { |invoice| unrecorded.key?(invoice.payment_hash) }
339
+ Rests.rest_of(sats: terms.sats, expires_at: terms.expires_at, address: terms.address, received: received,
340
+ now: now, rests: recorded, paid: summary.hashes)
341
+ end
342
+ end
343
+ end
344
+ end
345
+ end
@@ -0,0 +1,323 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sattleme
4
+ module Checkout
5
+ module Internal
6
+ # The rest of an on-chain underpayment (SPEC.md §31, "The rest of an underpayment"): when less
7
+ # than the amount came on-chain in time, a payment check asks the merchant's Lightning address
8
+ # for an invoice of the rest, declares it for the order's sale with `rest` (the address), and
9
+ # publishes a rest record, which the pages of the order's checkout links read (they cannot read
10
+ # the registry). From ONCHAIN_FLOOR_SATS, the rest is payable on-chain to the same address
11
+ # too; below, in Lightning only.
12
+ module Rests
13
+ # A rest invoice: a declaration of the sale with `rest`, its invoice decoded: its amount, its
14
+ # BOLT11 timestamp and that + its expiry (Unix seconds).
15
+ Invoice = Data.define(:bolt11, :payment_hash, :verify_url, :sats, :created_at, :expires_at) do
16
+ # What the Lightning part of a payment check needs of it.
17
+ def lightning
18
+ Lnurl::LightningInvoice.new(bolt11: bolt11, payment_hash: payment_hash, verify_url: verify_url,
19
+ expires_at: expires_at)
20
+ end
21
+ end
22
+
23
+ # What a check asks for: an invoice of `sats`, lasting `expiry_seconds`.
24
+ Ask = Data.define(:sats, :expiry_seconds)
25
+
26
+ # The invoice of the order a rest record belongs to: its amount and dates, as its link holds
27
+ # them.
28
+ LinkTerms = Data.define(:sats, :created_at, :expires_at)
29
+
30
+ # A rest record, opened as the page reads it: its invoice, decoded.
31
+ OpenedRest = Data.define(:invoice, :event)
32
+
33
+ # What a read of the rest records of an invoice tells: the payment hashes of the rest invoices
34
+ # whose record a majority of the relays sent, and the addresses (`d` tags) of the records of a
35
+ # newer format any relay sent: such a record holds its address, never written over.
36
+ RecordsRead = Data.define(:held, :newer)
37
+
38
+ module_function
39
+
40
+ # The rest invoice of a declaration with `rest` (opened: its invoice decodes, in whole sats).
41
+ def invoice_of(declaration)
42
+ decoded = declaration.decoded
43
+ Invoice.new(bolt11: declaration.invoice, payment_hash: decoded.payment_hash,
44
+ verify_url: declaration.verify_url, sats: decoded.amount_msat / 1000,
45
+ created_at: decoded.timestamp, expires_at: decoded.expires_at)
46
+ end
47
+
48
+ # The order of the rest invoices: by date, then payment hash.
49
+ def order_key(invoice)
50
+ [invoice.created_at, invoice.payment_hash]
51
+ end
52
+
53
+ # The `rest` of an open status (SPEC.md §31, "The status's rest"): nil unless `received` is
54
+ # above 0 before the invoice's end; else what is left, the latest rest invoice of exactly that
55
+ # amount neither paid nor ended (`paid`: the payment hashes paid), and its QR code: on-chain
56
+ # to `address` too from ONCHAIN_FLOOR_SATS, in Lightning only below.
57
+ def rest_of(sats:, expires_at:, address:, received:, now:, rests:, paid:)
58
+ return nil if received <= 0 || received >= sats || now >= expires_at
59
+
60
+ rest = sats - received
61
+ invoice = rests.sort_by { |candidate| order_key(candidate) }.reverse.find do |candidate|
62
+ candidate.sats == rest && !paid.key?(candidate.payment_hash) && now < candidate.expires_at
63
+ end
64
+ bolt11 = invoice&.bolt11
65
+ uri = if rest >= Protocol::ONCHAIN_FLOOR_SATS
66
+ Addresses.payment_uri(address, rest, bolt11)
67
+ elsif bolt11
68
+ "lightning:#{bolt11}"
69
+ end
70
+ Rest.new(sats: rest.to_s, bolt11: bolt11, payment_uri: uri)
71
+ end
72
+
73
+ # Whether a check whose status gave `rest` asks for an invoice of it (SPEC.md §31, "Asking
74
+ # for a rest invoice"), and which: none when it has one, with less than MIN_REST_SECONDS
75
+ # left, or when the sale's lease of the address is not the invoice's (`lease`: its terms, nil
76
+ # without one). The Lightning address's sendable sats are checked after: its pay request is
77
+ # asked only then.
78
+ def to_ask(rest:, sats:, expires_at:, now:, lease:)
79
+ return nil if rest.nil? || !rest.bolt11.nil?
80
+ return nil if now + Protocol::MIN_REST_SECONDS > expires_at
81
+ return nil if lease.nil? || lease.sats != sats || lease.expires_at != expires_at
82
+
83
+ Ask.new(sats: Integer(rest.sats, 10), expiry_seconds: expires_at - now)
84
+ end
85
+
86
+ # Whether `sats` is within the Lightning address's sendable sats ([min, max]).
87
+ def sendable?(sats, bounds)
88
+ sats.between?(bounds[0], bounds[1])
89
+ end
90
+
91
+ # The rest record of `invoice` (SPEC.md §31, "Rest records"): its invoice and verify URL,
92
+ # sealed with the rest encryption key at the rest record address of its payment hash, signed
93
+ # by the rest secret at `created_at`, dropped by the relays a week after the end of the
94
+ # order's invoice (`expires_at`), as its checkout links.
95
+ def record_event(keys:, invoice:, expires_at:, created_at:, random:)
96
+ Internal::Records.seal(
97
+ type: Protocol::REST_RECORD_TYPE,
98
+ value: { "version" => Protocol::REST_VERSION, "invoice" => invoice.bolt11,
99
+ "verifyUrl" => invoice.verify_url },
100
+ signer: keys.secret_key, encryption_key: keys.encryption_key,
101
+ address: Derive.rest_record_address(keys.key, invoice.payment_hash), created_at: created_at, random: random,
102
+ tags: [["expiration", (expires_at + Protocol::CHECKOUT_LIFE_SECONDS).to_s]]
103
+ )
104
+ end
105
+
106
+ # What a relay sent, if it is a rest record of the rest author and rest key of a checkout link
107
+ # of an invoice `terms` describes (SPEC.md §31, "Reading a rest record"): nil when it is not
108
+ # one; :newer for one of a newer format, which the page leaves aside. An event at the link's
109
+ # acceptance record address (same author) is no rest record, of a newer format or not.
110
+ def open_record(value, keys, terms)
111
+ d = Internal::Records.d_tag_of(value)
112
+ return nil if d.nil? || d == Derive.acceptance_record_address(keys.key)
113
+
114
+ opened = Internal::Records.open(value, type: Protocol::REST_RECORD_TYPE, encryption_key: keys.encryption_key,
115
+ address: d, author: keys.author) do |record, _|
116
+ parse_record(record, keys, terms, d)
117
+ end
118
+ return nil unless opened
119
+ return :newer if opened.newer?
120
+
121
+ OpenedRest.new(invoice: opened.value, event: opened.event)
122
+ end
123
+
124
+ def parse_record(value, keys, terms, d)
125
+ return nil unless value.is_a?(Hash)
126
+
127
+ version = value["version"]
128
+ raise Internal::Records::Newer if Json.number?(version) && version > Protocol::REST_VERSION
129
+ return nil unless version == Protocol::REST_VERSION && Text.well_formed?(value["invoice"])
130
+ return nil unless Urls.https_url(value["verifyUrl"])
131
+
132
+ decoded = Bolt11.decode(value["invoice"])
133
+ return nil unless decoded && decoded.network == "bc" && decoded.amount_msat
134
+ return nil unless decoded.amount_msat.positive? && (decoded.amount_msat % 1000).zero?
135
+
136
+ sats = decoded.amount_msat / 1000
137
+ if sats >= terms.sats || decoded.timestamp < terms.created_at - Protocol::CLOCK_TOLERANCE_SECONDS ||
138
+ decoded.expires_at > terms.expires_at + Protocol::CLOCK_TOLERANCE_SECONDS
139
+ return nil
140
+ end
141
+ return nil unless d == Derive.rest_record_address(keys.key, decoded.payment_hash)
142
+
143
+ Invoice.new(bolt11: value["invoice"], payment_hash: decoded.payment_hash, verify_url: value["verifyUrl"],
144
+ sats: sats, created_at: decoded.timestamp, expires_at: decoded.expires_at)
145
+ end
146
+
147
+ # What a read of the records of `keys` (their rest author) keeps: those that open with their
148
+ # encryption key (Records.that_open).
149
+ def keep_of(keys)
150
+ Internal::Records.that_open { |_, author| author == keys.author ? keys.encryption_key : nil }
151
+ end
152
+
153
+ # The rest records of `keys` on the merchant's `relays`, as the page would read them
154
+ # (RecordsRead): the payment hashes of those a majority sent (a page reading a majority meets
155
+ # each of them), and the addresses of those of a newer format; nil when fewer than a majority
156
+ # answered. Read with a key of this read alone, not paged (a rest record per rest invoice: a
157
+ # few).
158
+ def read_records(pool, keys, terms, relays, random:, stop:)
159
+ needed = Relay.majority(relays.size)
160
+ filter = { "kinds" => [Protocol::RECORD_KIND], "authors" => [keys.author] }
161
+ result = pool.query_relays(relays, filter, random.call(32),
162
+ paged: false, stop: stop, keep: Rests.keep_of(keys))
163
+ return nil unless result.answered
164
+
165
+ # How many relays sent a valid record of each payment hash.
166
+ sent_by = Hash.new(0)
167
+ newer = {}
168
+ result.answers.each_value do |events|
169
+ hashes = events.filter_map do |value|
170
+ opened = open_record(value, keys, terms)
171
+ newer[Internal::Records.d_tag_of(value)] = true if opened == :newer
172
+ opened.invoice.payment_hash if opened.is_a?(OpenedRest)
173
+ end
174
+ hashes.uniq.each { |hash| sent_by[hash] += 1 }
175
+ end
176
+ RecordsRead.new(held: sent_by.select { |_, count| count >= needed }.to_h { |hash, _| [hash, true] },
177
+ newer: newer)
178
+ end
179
+
180
+ # Publishes a rest record on the merchant's `relays`, signed and authenticated with the rest
181
+ # secret: once a majority took it, else NetworkError.
182
+ def publish_record(pool, event, keys, relays, stop:)
183
+ pool.publish_to_quorum(relays, event, keys.secret_key, Relay.majority(relays.size), stop: stop)
184
+ rescue Relay::Failure
185
+ raise NetworkError, "Fewer than a majority of the merchant's relays took the record of an invoice of the rest"
186
+ end
187
+ end
188
+
189
+ # Acceptance records (SPEC.md §31, "Acceptance records"): the page of a checkout link cannot
190
+ # know the merchant's tolerance nor read the merchant's acceptance (MerchantAcceptances), so
191
+ # an order either accepted would read underpaid there, its customer asked for the rest and
192
+ # never sent back to the shop. A check whose status is paid (or being confirmed) with less
193
+ # than the amount publishes what it received then, signed by the rest secret, for the pages
194
+ # of the order's checkout links: they count the payment as enough from that on. Never the
195
+ # tolerance itself.
196
+ module Acceptances
197
+ # An acceptance record, opened as the page reads it.
198
+ Opened = Data.define(:received, :event)
199
+
200
+ module_function
201
+
202
+ # What a check whose status is `status` must have the pages of the order's checkout links
203
+ # know (SPEC.md §31, "Publishing it"): the status's `received`, when the order's tolerance
204
+ # or the merchant's acceptance accepted less than its amount (`unconfirmed`, or `paid` with
205
+ # transactions) before the links' life ends; nil otherwise.
206
+ def to_publish(status, sats, expires_at, now)
207
+ return nil if now >= expires_at + Protocol::CHECKOUT_LIFE_SECONDS
208
+
209
+ accepted = status.unconfirmed? ||
210
+ (status.paid? && status.payment_method != "lightning" && !status.txids.empty?)
211
+ return nil unless accepted
212
+
213
+ received = Integer(status.received, 10)
214
+ received < sats ? received : nil
215
+ end
216
+
217
+ # The acceptance record of the invoice of `keys` (its rest keys): `received`, sealed with the
218
+ # rest encryption key at its acceptance record address, signed by the rest secret at
219
+ # `created_at`, dropped by the relays a week after the invoice's end, as its checkout links.
220
+ def record_event(keys:, received:, expires_at:, created_at:, random:)
221
+ Internal::Records.seal(
222
+ type: Protocol::ACCEPTANCE_RECORD_TYPE,
223
+ value: { "version" => Protocol::ACCEPTANCE_VERSION, "received" => received },
224
+ signer: keys.secret_key, encryption_key: keys.encryption_key,
225
+ address: Derive.acceptance_record_address(keys.key), created_at: created_at, random: random,
226
+ tags: [["expiration", (expires_at + Protocol::CHECKOUT_LIFE_SECONDS).to_s]]
227
+ )
228
+ end
229
+
230
+ # `value` opened as an acceptance record of `keys` for an invoice of `sats` (a
231
+ # Records::Opened of its `received`), else nil.
232
+ def open_opened(value, keys, sats)
233
+ address = Derive.acceptance_record_address(keys.key)
234
+ return nil unless Internal::Records.d_tag_of(value) == address
235
+
236
+ Internal::Records.open(value, type: Protocol::ACCEPTANCE_RECORD_TYPE, encryption_key: keys.encryption_key,
237
+ address: address, author: keys.author) do |record, _|
238
+ next nil unless record.is_a?(Hash)
239
+
240
+ version = record["version"]
241
+ raise Internal::Records::Newer if Json.number?(version) && version > Protocol::ACCEPTANCE_VERSION
242
+ next nil unless version == Protocol::ACCEPTANCE_VERSION
243
+
244
+ received = record["received"]
245
+ next nil unless Json.safe_integer?(received) && received >= 1
246
+
247
+ received.to_i < sats ? received.to_i : nil
248
+ end
249
+ end
250
+
251
+ # What a relay sent, if it is an acceptance record of the rest author and rest key of a
252
+ # checkout link of an invoice of `sats` (SPEC.md §31, "Reading an acceptance record"): its
253
+ # `received`, from 1, below `sats`; nil when it is not one; :newer for one of a newer format,
254
+ # left aside.
255
+ def open_record(value, keys, sats)
256
+ opened = open_opened(value, keys, sats)
257
+ return nil unless opened
258
+ return :newer if opened.newer?
259
+
260
+ Opened.new(received: opened.value, event: opened.event)
261
+ end
262
+
263
+ # Whether the pages already know `received` (SPEC.md §31, "Publishing it"): a majority of the
264
+ # merchant's `relays` each sent a valid acceptance record of the invoice of `keys` (of `sats`)
265
+ # whose `received`, the newest it sent, is at most `received`. Read with a key of this read
266
+ # alone, not paged (one record per invoice). True when a relay sent one of a newer format,
267
+ # never written over (logged: update the gem). NetworkError when fewer than a majority
268
+ # answered: nothing is published, the next check reads again.
269
+ def known?(pool, keys, sats, received, relays, random:, logger:, stop:)
270
+ needed = Relay.majority(relays.size)
271
+ filter = { "kinds" => [Protocol::RECORD_KIND], "authors" => [keys.author],
272
+ "#d" => [Derive.acceptance_record_address(keys.key)] }
273
+ result = pool.query_relays(relays, filter, random.call(32),
274
+ paged: false, stop: stop, keep: Rests.keep_of(keys))
275
+ holders = 0
276
+ result.answers.each do |relay, events|
277
+ found = Internal::Records.newest({ relay => events }) { |value| open_opened(value, keys, sats) }
278
+ unless found.newest_unreadable.nil?
279
+ logger.warn("sattleme-checkout: an acceptance record of this order has a newer format than this " \
280
+ "version reads; update the gem")
281
+ return true
282
+ end
283
+
284
+ holders += 1 if !found.value.nil? && found.value <= received
285
+ end
286
+ # Fewer than a majority answered: what the others hold (of a newer format, perhaps) cannot
287
+ # be told, so nothing is written over it; the next check reads again (SPEC.md §13, §12).
288
+ raise NetworkError, "Fewer than a majority of the merchant's relays answered" unless result.answered
289
+
290
+ holders >= needed
291
+ end
292
+
293
+ # Lets the pages of the order's checkout links know what its tolerance or the merchant's
294
+ # acceptance accepted (SPEC.md §31, "Acceptance records"), from `status`, the status a check
295
+ # gave at `now` of the invoice of `sats` and `expires_at`: when to_publish gives what it
296
+ # received, publishes an acceptance record of it with the rest keys `keys` gives (asked only
297
+ # then), dated `clock.call`, unless a majority of the merchant's `relays` hold one of it or
298
+ # less (known?). What it published (its `received`), or nil. NetworkError when fewer than a
299
+ # majority answered the read, or took the record.
300
+ def publish(pool, status, sats:, expires_at:, now:, keys:, relays:, clock:, random:, logger:, stop:)
301
+ received = to_publish(status, sats, expires_at, now)
302
+ return nil if received.nil?
303
+
304
+ rest = keys.call
305
+ return nil if known?(pool, rest, sats, received, relays, random: random, logger: logger, stop: stop)
306
+
307
+ event = record_event(keys: rest, received: received, expires_at: expires_at, created_at: clock.call,
308
+ random: random)
309
+ publish_record(pool, event, rest, relays, stop: stop)
310
+ received
311
+ end
312
+
313
+ # Publishes an acceptance record on the merchant's `relays`, signed and authenticated with the
314
+ # rest secret: once a majority took it, else NetworkError.
315
+ def publish_record(pool, event, keys, relays, stop:)
316
+ pool.publish_to_quorum(relays, event, keys.secret_key, Relay.majority(relays.size), stop: stop)
317
+ rescue Relay::Failure
318
+ raise NetworkError, "Fewer than a majority of the merchant's relays took the acceptance record of a payment"
319
+ end
320
+ end
321
+ end
322
+ end
323
+ end