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
data/README.md ADDED
@@ -0,0 +1,754 @@
1
+ # sattleme-checkout
2
+
3
+ Take Lightning and on-chain payments for a sattle.me merchant from an online shop's **server**,
4
+ in Ruby: the invoice of each order (a Lightning invoice, a deposit address of the merchant's
5
+ wallet, or both), its declaration in the merchant's registry, and the check of its payment.
6
+
7
+ - Everything runs on your server, which holds the integration's secret key. The customer's
8
+ browser only ever gets the invoice and its address: on your page, or on the merchant's web app
9
+ through a [checkout link](#checkout-links), if you ask for one.
10
+ - Payments go straight to the merchant's wallet. sattle.me runs no server and no API for
11
+ integrations: this gem talks to the merchant's Lightning address (breez.tips), to the merchant's
12
+ Nostr relays and, for [on-chain payments](#on-chain-payments), to one block explorer
13
+ (mempool.space, or [the merchant's own Bitcoin node](#the-merchants-bitcoin-node) when it names
14
+ one) and BlockCypher; nothing else (and to the rate source you choose, for prices in a
15
+ currency).
16
+ - Amounts are exact: strings of digits (sats, a currency's minor units), never floating-point.
17
+
18
+ The protocol is specified, for implementations in other languages, in
19
+ [sattleme/checkout-spec](https://github.com/sattleme/checkout-spec) (`SPEC.md`), with conformance
20
+ vectors every implementation passes. This version implements its version 1.0.0 (`spec/PIN.json`).
21
+
22
+ ## Requirements
23
+
24
+ - Ruby 3.3 or later (CRuby), on a **server**.
25
+ - [libsecp256k1](https://github.com/bitcoin-core/secp256k1) 0.2.0 or later, Bitcoin Core's
26
+ library, installed on the system (see [Installing](#installing)).
27
+ - A clock synchronized by NTP: invoices more than 5 minutes off the server's clock are refused.
28
+ - An integration's secret key: the merchant creates the integration in the sattle.me app
29
+ ("Integrations") and gives you its key, `sattleme_ck_…`.
30
+
31
+ ## Installing
32
+
33
+ ```ruby
34
+ # Gemfile
35
+ gem "sattleme-checkout", "1.0.0"
36
+ ```
37
+
38
+ ```sh
39
+ bundle install
40
+ ```
41
+
42
+ The gem signs and checks Nostr events with libsecp256k1, the system's (it builds nothing):
43
+
44
+ | System | Install |
45
+ | --------------- | ---------------------------------------------------------- |
46
+ | Debian, Ubuntu | `apt install libsecp256k1-1` (Ubuntu 24.04, Debian 12 on) |
47
+ | Fedora | `dnf install libsecp256k1` |
48
+ | Alpine | `apk add libsecp256k1` |
49
+ | macOS | `brew install secp256k1` |
50
+
51
+ Elsewhere, build it from Bitcoin Core's release (its `ecdh`, `extrakeys` and `schnorrsig` modules,
52
+ which its builds enable by default) and name the file in the environment:
53
+ `SATTLEME_SECP256K1_LIBRARY=/opt/secp256k1/lib/libsecp256k1.so`. Without it,
54
+ `require "sattleme/checkout"` raises `Sattleme::Checkout::LibraryNotFound`, which says how to
55
+ install it: never a call, later.
56
+
57
+ ## The key is a secret
58
+
59
+ Keep the integration's key on the server only: in an environment variable or a secrets vault,
60
+ never in a web page, an app, a code repository or a log. With it, anyone can make invoices that
61
+ pay the merchant and mark sales as the integration's. It can never spend the merchant's funds nor
62
+ read their wallet. The gem never writes it anywhere: not in an error, a log, `inspect` nor
63
+ `to_h`.
64
+
65
+ If it leaks, the merchant removes the integration in the app ("Remove the integration") and
66
+ creates another one: the old key then makes no invoice, finds none and reads no merchant
67
+ (`RevokedError`). A check of an invoice it made still finds its Lightning payment: an invoice
68
+ without an address is checked as before, and one with an address is `RevokedError` unless its
69
+ Lightning invoice was paid (SPEC.md §14). The merchant settles by hand the orders still being paid
70
+ on-chain.
71
+
72
+ **One key, one shop.** The merchant creates one integration for each shop (each system with its
73
+ own orders' references), and two shops never share a key: the sale of an order is derived from the
74
+ key and the order's reference, so two shops with one key would share their references, and an
75
+ order of one would be found paid, or pending, with an invoice of the other. The servers of one
76
+ shop share its key.
77
+
78
+ ## Quick start
79
+
80
+ ```ruby
81
+ require "sattleme/checkout"
82
+
83
+ # Nothing to connect nor to close: each call reads the merchant, opens one connection per relay
84
+ # and closes it when it is done. One client for the whole process: it is safe to share between
85
+ # threads (Puma, Sidekiq).
86
+ SATTLEME = Sattleme::Checkout::Client.new(key: ENV.fetch("SATTLEME_INTEGRATION_KEY"))
87
+
88
+ # When the customer checks out, or when the payment page asks again:
89
+ def invoice_of(order)
90
+ return order.invoice if order.invoice # one order, one invoice at a time
91
+
92
+ begin
93
+ invoice = SATTLEME.create_invoice(
94
+ ref: order.ref, # "ORD-1042": the order's reference, its sale in the merchant's app
95
+ sats: 49_000, # or "49000"; or: fiat: { amount: "24.50", currency: "CHF" }
96
+ duration_seconds: 900, # 60 to 3600
97
+ note: "Order #{order.number}" # shown to the merchant, 100 characters at most
98
+ )
99
+ order.update!(invoice: invoice.to_json) # a JSON column, or text
100
+ rescue Sattleme::Checkout::InvoicePendingError => e
101
+ # An invoice of this order may still be paid (say, after a crash): keep that one. It is the
102
+ # registry's copy (a DeclaredInvoice): the same fields, without `rate`.
103
+ order.update!(invoice: e.invoice.to_json)
104
+ end
105
+ order.invoice
106
+ end
107
+
108
+ # The payment page gets the invoice alone: its paymentUri ("bitcoin:bc1p…?amount=…&lightning=lnbc…")
109
+ # and expiresAt. When it asks for the order's status (every 1 to 2 seconds):
110
+ def status_of(order)
111
+ status = SATTLEME.get_status(order.invoice) # the stored JSON as it is
112
+ if status.paid?
113
+ # In Lightning: keep the preimage, the proof of payment. On-chain: the transactions. Mixed
114
+ # (on-chain, its rest in Lightning): both.
115
+ order.mark_paid!(status.to_json)
116
+ elsif status.expired?
117
+ # Never paid: the order may get a new invoice. `received` above "0": an on-chain
118
+ # underpayment the merchant received, to settle with the customer.
119
+ order.update!(invoice: nil)
120
+ end
121
+ status.state # "open", "unconfirmed", "paid" or "expired"
122
+ end
123
+ ```
124
+
125
+ `create_invoice` gives a `Sattleme::Checkout::Invoice`, whose JSON (`invoice.to_json`) you store
126
+ with the order:
127
+
128
+ ```ruby
129
+ {
130
+ "ref" => "ORD-1042",
131
+ "bolt11" => "lnbc490u1p…", # the BOLT11 invoice; nil for an order paid on-chain only
132
+ "paymentHash" => "9c41…",
133
+ "verifyUrl" => "https://breez.tips/lnurlp/verify/9c41…",
134
+ "onchainAddress" => "bc1p…", # the deposit address it leased, or nil (Lightning only)
135
+ "paymentUri" => "bitcoin:bc1p…?amount=0.00049&lightning=lnbc490u1p…", # one QR code for both
136
+ "sats" => "49000",
137
+ "fiat" => nil, # or { "amount" => "24.50", "currency" => "CHF", "minor" => "2450", "digits" => 2 }
138
+ "rate" => nil, # or { "source" => "coingecko", "currency" => "CHF", "price" => "69012", "fetchedAt", "time" }
139
+ "note" => "Order 1042",
140
+ "createdAt" => 1791378000, # Unix seconds
141
+ "expiresAt" => 1791378900,
142
+ "checkoutUrl" => nil, # a checkout link, with checkout: true
143
+ "redirectUrl" => nil
144
+ }
145
+ ```
146
+
147
+ Every amount is a string of digits, every date an integer of Unix seconds, an absent value `null`:
148
+ the JSON is the same in every implementation of the specification, which reads what this gem
149
+ stores, and the other way round. Its members are the Invoice's in snake case
150
+ (`invoice.onchain_address`, `invoice.expires_at`…); `Sattleme::Checkout::Invoice.from_json(text)`
151
+ reads it back, every member there (a member left out is not `null`: `ArgumentError`), but
152
+ `onchainAddress`, which an invoice stored without an address may leave out. `get_status` and
153
+ `wait_for_payment` take the Invoice, its JSON text, or the Hash of its JSON.
154
+
155
+ **Stored invoices are your shop's.** Check only the invoices your shop stored itself with their
156
+ orders, where only it writes (its database), never one that comes from the customer (a form field,
157
+ a URL, a cookie): `get_status` checks that a stored invoice is well formed (SPEC.md §22), never that
158
+ this integration made it. An invoice someone else wrote, with a Lightning invoice of their own that
159
+ they paid, reads as `paid` (SPEC.md §27).
160
+
161
+ Instead of polling from your page's requests, a background job may wait for the payment:
162
+
163
+ ```ruby
164
+ final = SATTLEME.wait_for_payment(order.invoice, interval_ms: 2000,
165
+ cancellation: Sattleme::Checkout::Cancellation.after(3600)) do |status|
166
+ Rails.logger.info("#{order.ref}: #{status.state}")
167
+ end
168
+ # final.paid? (final.payment_method: "lightning", "onchain" or "mixed"), or final.expired?
169
+ ```
170
+
171
+ A network failure only delays the next check. One that each check meets again (an explorer or the
172
+ Lightning address that does not answer…) is reported to your `logger` once, and again only after
173
+ it stopped.
174
+
175
+ ### One order, one invoice at a time
176
+
177
+ - An order keeps its invoice until it has **expired**: `get_status` says `expired` 120 seconds
178
+ after the invoice's end (a payment of its last seconds may be reported that late). Only then may
179
+ the order get a new invoice. `create_invoice` checks it in the merchant's registry and raises
180
+ `InvoicePendingError` (with that invoice) while an earlier invoice of the same `ref` may still be
181
+ paid (or its on-chain payment is being confirmed), or `OrderPaidError` (with its `status`, and
182
+ the `preimage` of a Lightning payment) when one was paid.
183
+ - Only the order that holds an invoice is marked paid with it, in the database transaction that
184
+ marks it paid. Keep the `preimage` (the proof of a Lightning payment) or the `txids` (of an
185
+ on-chain one) and the `rate` the amount was converted at, to answer a customer or an audit.
186
+ - Invoices of the same `ref` are one sale in the merchant's app. One order, one `ref`: never
187
+ reused for another order by anything that holds the key (a test copy of the shop, a restored
188
+ database included), and never taken from what the customer sends (make it on your server).
189
+ - After a failure, `find_invoices(ref)` lists the invoices declared for an order, from the
190
+ merchant's registry.
191
+ - "One at a time" holds within one `Client` and against the registry: when several processes may
192
+ make the invoice of the same order at once, lock the order (in your database:
193
+ `order.with_lock { invoice_of(order) }`) around `create_invoice`.
194
+
195
+ ### Showing the invoice
196
+
197
+ This gem is for servers only. The shop's page shows the invoice with its own code:
198
+
199
+ - a QR code of `payment_uri`, with any QR library (`rqrcode`, a JavaScript one):
200
+ `bitcoin:<address>?amount=…&lightning=<bolt11>` with an address (BIP-21, the "unified QR" wallets
201
+ read: they pay in Lightning or on-chain), `lightning:<bolt11>` without one;
202
+ - an "Open in wallet" link to the same URI;
203
+ - the time left until `expires_at`, then the status your server gives (`open`, `unconfirmed`,
204
+ `paid`, `expired`). With an on-chain underpayment, `open` carries what was `received` and its
205
+ `rest`: show its `payment_uri` as the QR code (the rest in Lightning, and on-chain to the same
206
+ address from 1 000 sats), until `expires_at`.
207
+
208
+ The page talks to your server only: never give it the key, nor ask it to reach breez.tips or the
209
+ relays. Or send the customer to a checkout link instead (below).
210
+
211
+ ## Checkout links
212
+
213
+ Instead of showing the invoice on your page, you may send the customer to a page of the merchant's
214
+ sattle.me web app made for this invoice: its QR code, a button that opens the customer's wallet,
215
+ the time left, then "Paid" or "Expired". Once the invoice is paid, the page sends the customer
216
+ back to your `redirect_url`, 7 seconds later or at once with a tap.
217
+
218
+ ```ruby
219
+ invoice = SATTLEME.create_invoice(
220
+ ref: "ORD-1042",
221
+ fiat: { amount: "24.50", currency: "CHF" },
222
+ note: "Order 1042", # shown to the customer too
223
+ checkout: true,
224
+ redirect_url: "https://shop.example/orders/1042/thanks" # or "myshop://orders/1042"
225
+ )
226
+ # Store it with the order, then redirect the customer's browser to invoice.checkout_url:
227
+ # "https://…/pay#c.…" (nothing after "#" is ever sent to the web app's host).
228
+ ```
229
+
230
+ - **Optional, per order.** Without `checkout: true`, nothing changes. `redirect_url:` alone is
231
+ refused (`InvalidOrderError`, `param` `"redirect_url"`); without one, the page shows the receipt
232
+ and sends the customer nowhere.
233
+ - **Not a proof of payment.** Anyone can open your redirect URL. When the customer arrives there,
234
+ check the order with `get_status(invoice)` (or `wait_for_payment`) on your server, and mark it
235
+ paid only then, as without checkout.
236
+ - **What the page gets**: a record the gem publishes on a majority of the merchant's relays, before
237
+ the invoice is declared: the invoice, its verify URL, its deposit address (with its amount and
238
+ dates), the business's name, the price, the note and your redirect URL; and, when the merchant
239
+ lets the pages read [its Bitcoin node](#the-merchants-bitcoin-node) (`payers`), that node's URL
240
+ and fallback. Never the key, the merchant's Lightning address nor its registry. It is signed by
241
+ a key of that link alone, forgotten once it is published: nobody, you included, can change a
242
+ link afterwards. Relays that honor NIP-40 drop it a week after the invoice's end.
243
+ - **The rest of an underpayment**: with an address, the record also carries the key and the public
244
+ key with which the page reads the invoices of the rest your server asks for
245
+ ([On-chain payments](#on-chain-payments)): the page shows the rest's invoice as soon as a check of
246
+ your server published it, so keep checking the payment while the customer pays
247
+ (`wait_for_payment`, or `get_status` from your page's polling). Only the integration key signs
248
+ them.
249
+ - **Who sees the customer**: the customer's browser loads the web app, reads the record from the
250
+ merchant's relays and checks the payment with the merchant's Lightning address (breez.tips) and,
251
+ with an address, the explorer (mempool.space, or the merchant's node with `payers`): they see
252
+ its IP address, which they never do when your page shows the invoice.
253
+ - **Redirect URLs**: `https://` with a lowercase host name (no IP address, no `localhost` nor a
254
+ name under it, no `user:password@`), or an app's link (`myshop://…`), 2048 characters at most,
255
+ every character of RFC 3986 (anything else percent-encoded, host names in punycode). Refused:
256
+ `http:`, browser and file schemes, other browsers' schemes (`x-safari-https:`, `googlechrome:`,
257
+ `firefox:`…, which would open a web page whose host the page cannot show: a web page is an
258
+ `https` URL), `intent:`, payment schemes (`lightning:`, `bitcoin:`…), calls and messages. The
259
+ page shows "Redirecting to shop.example" (or "myshop://") on its button. Prefer universal links
260
+ (iOS) and App Links (Android), which are `https` URLs: browsers do not open an app on their own
261
+ after a delay (Chrome on Android refuses it), so for an app's link the customer taps the button.
262
+ - **One order, one invoice at a time** holds with checkout links too. When an invoice of the order
263
+ may still be paid, `InvoicePendingError` carries, with `checkout: true`, a new link to it:
264
+ `error.checkout_url`. Send the customer there.
265
+ - **Availability**: the merchant's app says in the integration's channel where its web app is. An
266
+ app without a web app gives none: `create_invoice` with `checkout: true` raises
267
+ `CheckoutUnavailableError`; show the invoice on your page instead.
268
+
269
+ ## On-chain payments
270
+
271
+ From 1 000 sats, an order may also be paid on-chain, to a deposit address of the merchant's
272
+ wallet. Nothing to ask for: `create_invoice` leases an address when the amount allows it, and the
273
+ Invoice's `payment_uri` shows both methods in one QR code.
274
+
275
+ | Amount | Methods |
276
+ | ----------------------------------------------- | ------------------------------------------------------------ |
277
+ | below 1 000 sats | Lightning (outside its bounds: `InvalidOrderError`) |
278
+ | 1 000 sats or more, within the Lightning bounds | Lightning and on-chain (Lightning only without an address) |
279
+ | 1 000 sats or more, outside them | on-chain only (`OnchainUnavailableError` without an address) |
280
+
281
+ - **The lot**: your server has no wallet and makes no address. The merchant's app gives the
282
+ integration a lot of up to 100 taproot addresses (`bc1p…`) of its wallet, and fills it again
283
+ whenever the merchant opens the app. `merchant.onchain_addresses` says how many it holds (0: no
284
+ on-chain payment yet).
285
+ - **One address, one order**: an order leases an address in the merchant's registry until its
286
+ invoice's end plus 120 seconds; two servers never keep the same one. The lease is published, read
287
+ again on every relay of the merchant (it is confirmed when no other order holds the address),
288
+ then marked confirmed: only then is the address the order's. An address the explorer shows paid
289
+ already, or that a witness (below) names, is skipped.
290
+ - **Unconfirmed, then paid**: `get_status` says `unconfirmed` once enough was sent in time, then
291
+ `paid` (`payment_method` `"onchain"`) at 3 confirmations on the explorer read (mempool.space, or
292
+ the merchant's node): about 30 minutes. Ship the order only once it is `paid`.
293
+ `wait_for_payment` watches the address on the explorer's WebSocket meanwhile; a server that
294
+ cannot wait that long checks again later with `get_status` (`create_invoice` for the same `ref`
295
+ raises `InvoicePendingError` while it is being confirmed).
296
+ - **In time**: a transaction counts for the order when it came while the lease ran. The gem records
297
+ each transaction it sees in the merchant's registry (a witness), so that the merchant's app tells
298
+ the same order paid: check the payment while the customer pays (your page's polling, or
299
+ `wait_for_payment`), until the invoice's end and its 120 seconds. A transaction no check saw by
300
+ then is told by BlockCypher's time; one received after the end is late: it reaches the merchant,
301
+ but pays no order. A replacement (RBF, a fee bump) of a payment in time counts for it. A
302
+ transaction counts for one invoice at most: one that a witness of another invoice names counts
303
+ for nothing here.
304
+ - **Underpaid**: `received` is what came in time. Below the amount (and unless the merchant's
305
+ tolerance or acceptance, below, accepted it), the invoice stays `open` until its end, then
306
+ `expired` with `received` above "0": the merchant received it, settle it with the customer. An
307
+ overpayment is `paid`.
308
+ - **The merchant's tolerance**: the merchant may accept, in its app, an on-chain payment a little
309
+ short of the amount (up to 10 %) as paying the order in full. An order keeps the tolerance of its
310
+ creation, whatever the merchant sets later. A payment short by no more than it is
311
+ `unconfirmed`, then `paid`, with `received` below the amount: ship the order as for any `paid`
312
+ status. One short by more is underpaid: its whole rest is asked. The tolerance is the merchant's:
313
+ the gem never gives it to your server, nor to your customer; the page of a checkout link learns
314
+ only that this payment counts (an acceptance record), and sends the customer back to your shop.
315
+ - **The merchant's acceptance**: the merchant may also accept, by hand in its app, what an order
316
+ underpaid on-chain received as paying it in full: one short by more than its tolerance, which
317
+ the merchant would rather settle at what came. Nothing to configure, nothing to call: every check
318
+ (`get_status`, `wait_for_payment`, and `create_invoice`'s check of an order's earlier invoices)
319
+ reads it on every relay of the merchant with the order's witnesses, and counts it only when a
320
+ majority of those relays hold it. The order is then `unconfirmed`, then `paid` (`payment_method`
321
+ `"onchain"`, or `"mixed"` with invoices of the rest), with `received` below the amount, as with
322
+ the tolerance: ship it as for any `paid` status. `wait_for_payment` sees it at its next check of
323
+ the on-chain part (within 60 s), the `rest` still given until then. Only the merchant's team can
324
+ make one: neither your server's key nor a customer can. The page of a checkout link learns of it
325
+ as of the tolerance, through an acceptance record.
326
+ - **The rest, in Lightning**: the check that sees an underpayment (`get_status`,
327
+ `wait_for_payment`) asks the merchant's Lightning address for an invoice of the rest, until the
328
+ invoice's end, declares it in the merchant's registry and publishes it for the order's checkout
329
+ links, whose page shows it at once. `open` carries it in `rest`:
330
+
331
+ ```ruby
332
+ status.to_h
333
+ # {
334
+ # "state" => "open",
335
+ # "expiresAt" => 1791378900,
336
+ # "received" => "20000", # what came in time
337
+ # "rest" => {
338
+ # "sats" => "29000", # what is left
339
+ # "bolt11" => "lnbc290u1p…", # its invoice; nil while there is none (asked at the next check)
340
+ # "paymentUri" => "bitcoin:bc1p…?amount=0.00029&lightning=lnbc290u1p…" # one QR code
341
+ # }
342
+ # }
343
+ ```
344
+
345
+ From 1 000 sats the rest is payable on-chain to the same address too; below, in Lightning only
346
+ (`payment_uri` is `lightning:…`, or nil while its invoice is asked). No invoice of the rest is
347
+ asked with less than a minute left, nor outside the Lightning address's bounds; a failure is
348
+ logged as a warning, never raised: the next check asks again. Once the rest is paid, the order
349
+ is `unconfirmed` until its on-chain part is 3 confirmations deep, then `paid` with
350
+ `payment_method` `"mixed"`: keep its `txids` and the `preimages` of the invoices of the rest.
351
+
352
+ - **Who sees what**: the explorer (mempool.space, or the merchant's node, and mempool.space too
353
+ when the node fails and its fallback is `"mempool"`) sees your server's IP address and the
354
+ addresses and transactions it asks about; BlockCypher, a transaction no check saw in time. Never
355
+ a key. Trust rests on that one explorer: what it alone shows makes a payment count as made.
356
+
357
+ ### The merchant's Bitcoin node
358
+
359
+ The merchant may have the blockchain read from a node of its own that serves mempool.space's API
360
+ (an Umbrel, a server of its own) rather than from mempool.space. It sets it in its app, which
361
+ writes it in the integration's channel (`bitcoinNode`): nothing to configure on your server. Every
362
+ call reads it with the channel; every read of an address and of the chain's height (when an
363
+ address is leased, at each check), and `wait_for_payment`'s WebSocket, then go to the node:
364
+ `http://192.168.1.10:3006` is read at `http://192.168.1.10:3006/api` and
365
+ `ws://192.168.1.10:3006/api/v1/ws` (`wss://` for an `https://` node). BlockCypher and the
366
+ `"mempool"` rate source stay BlockCypher's and mempool.space's.
367
+
368
+ - **Its URL** follows a rule of its own (SPEC.md §31): `https`, or `http` for a host of a local
369
+ network only (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 100.64.0.0/10, a name under `.local`);
370
+ an IPv4 address or a lowercase name, never `localhost`, 127.0.0.0/8 nor 0.0.0.0/8; an optional
371
+ port and path (not ending with `/` nor `/api`); no user name, query nor fragment; 200 characters
372
+ at most. A node the channel names in any other way, or with an invalid `fallback` or `payers`,
373
+ is none: mempool.space is read, and the channel stays valid.
374
+ - **Its `fallback`**, when the node does not answer a read (no answer, an error status, a
375
+ redirect, an answer out of format):
376
+ - `"mempool"`: the same read of mempool.space, `NetworkError` when both fail. A node that failed
377
+ less than 60 s ago in the same call (`create_invoice`, `get_status`, one `wait_for_payment`) is
378
+ asked after mempool.space, so that a node that is down does not make each read wait for its
379
+ timeout. The WebSocket goes to mempool.space's when the node's fails, or is lost before any
380
+ message.
381
+ - `"none"`: mempool.space is never asked. While the node does not answer, no address is leased
382
+ (`create_invoice` gives a Lightning invoice only, or `NetworkError` for an order paid on-chain
383
+ only) and every check of an order with an address is `NetworkError`: never `expired` nor
384
+ final underpaid for want of an answer, however long it lasts. The order waits until the node
385
+ answers again; `wait_for_payment` goes on meanwhile.
386
+
387
+ A check's two reads (the address's transactions and the chain's height) always come from one
388
+ explorer: when the node fails either, both are asked of mempool.space.
389
+
390
+ - **A node on the merchant's network** (`http://192.168.1.10:3006`, `http://umbrel.local`) is
391
+ reachable only by a server on that network: a shop the merchant hosts itself, or one that joined
392
+ it (by Tailscale, for one). Any other server fails every read of it, and its fallback applies:
393
+ with `"none"`, no on-chain payment at all. The gem's `HttpClient` and `WebSocketClient` ask such
394
+ a node in clear (`http://`, `ws://`), and no other host: every other URL stays `https` or `wss`
395
+ to a name. An `http_client:` or `websocket_client:` of yours gets an `http://` or `ws://` URL
396
+ only for such a node: reach it in clear HTTP (through your proxy, if it allows that host), or
397
+ raise, and the fallback applies.
398
+ - **`payers`**: with `true` (only for a node of the Internet: `https` and a name, not under
399
+ `.local`), the checkout links' records name the node (its `url` and `fallback`, never `payers`),
400
+ and their page reads the chain from it too, with the same fallback; the node then sees the
401
+ customer's IP address and the address the page follows, and whoever holds a link reads the
402
+ node's URL. With `false`, only your server reads the node, and the page reads mempool.space.
403
+ - **Security**: a node's URL is the merchant's choice, and the gem follows a valid one: GET
404
+ requests at the paths of mempool.space's API under `/api`, and the WebSocket's two messages, in
405
+ clear HTTP too to a host of a local network, and to an IPv4 address. Nothing is sent but
406
+ deposit addresses, no redirect is followed, and every answer is bounded and checked. But if your
407
+ server holds the keys of several merchants (a shared host), one merchant could so have it ask
408
+ machines of your own network: restrict what your server can reach to public addresses (see
409
+ [Outbound requests](#outbound-requests)); such a merchant's node is then unreachable, and its
410
+ fallback applies. The node is trusted as mempool.space is: what it shows decides whether an
411
+ order is paid. Over `http`, whoever is on the network between your server and the node can
412
+ change its answers: it is as safe as that network.
413
+
414
+ ## Prices in a currency
415
+
416
+ Give `fiat:` instead of `sats:`: the gem converts the price to sats on your server, at the rate of
417
+ a price source, and declares the price to the merchant's app, which shows it. Nothing to set up:
418
+ without `rate_source`, it asks the default list of sources (below).
419
+
420
+ ```ruby
421
+ invoice = SATTLEME.create_invoice(
422
+ ref: "ORD-1043",
423
+ fiat: { amount: "24.50", currency: "CHF" } # a String: never a Float
424
+ )
425
+ # 24.50 CHF at 69 012 CHF/BTC: ⌈2450 × 10^8 / 6 901 200⌉ = 35 502 sats
426
+ ```
427
+
428
+ - `currency` is an ISO 4217 code in upper case, of the ISO 4217 currencies (List One, without
429
+ funds, metals and test codes). `amount` is a string of digits with at most the currency's
430
+ decimals (2 for CHF, 0 for JPY, 3 for KWD): those the merchant's app uses, from the gem's own
431
+ table, never from the platform's locale data. `Sattleme::Checkout.currency_digits(code)` gives
432
+ them, with no key and nothing asked: `2` for `"CHF"`, nil for any text that is not exactly one of
433
+ these codes (`"chf"`, `" CHF"`, `"XAU"`, `"BTC"`). Ask it, for one, whether your shop may offer
434
+ its customers to pay in its currency, and in how many decimals its prices go to `create_invoice`.
435
+ - The conversion is exact, on integers: the price of one bitcoin is read as the decimal its source
436
+ wrote, and the sats are **rounded up** to the next whole sat, so that the merchant never receives
437
+ less than the price. `Sattleme::Checkout.fiat_to_sats(fiat, price)` gives what an order asks at a
438
+ price.
439
+ - The sats must fit the bounds of the merchant's Lightning address (`merchant`), as for an amount
440
+ in sats.
441
+
442
+ ### Rate sources
443
+
444
+ `rate_source` is optional. Without it, the gem asks these sources **one after the other**, the next
445
+ one only when the previous one does not answer, gives no usable price, or has no price in the
446
+ currency (`Sattleme::Checkout::DEFAULT_RATE_SOURCES`):
447
+
448
+ `"coingecko"`, then `"mempool"`, `"coinbase"`, `"kraken"` and `"opennode"`.
449
+
450
+ The dated sources come first (a dated price is checked for its age), then the undated ones. The
451
+ first usable price is the rate, and `invoice.rate.source` names the source that gave it. Each
452
+ source that failed before it is reported to your `logger` as a warning.
453
+
454
+ To choose, give `rate_source:` to the client or to an order (an order's wins):
455
+
456
+ ```ruby
457
+ Sattleme::Checkout::Client.new(key: key, rate_source: "kraken") # this source only: no other is asked
458
+ Sattleme::Checkout::Client.new(key: key, rate_source: %w[kraken coingecko]) # asked in this order
459
+ SATTLEME.create_invoice(ref: ref, fiat: fiat, rate_source: %i[mempool coinbase]) # this order only
460
+ ```
461
+
462
+ A list holds sources (names, as Strings or Symbols, or callables), at least one, no name twice;
463
+ anything else raises `InvalidOptionError` (`InvalidOrderError` for an order). `rate_source: nil` is
464
+ no source either: leave the keyword out for the default list. Each source asked may take up to
465
+ `http_timeout_ms`: a list of 5 sources that all fail to answer may take 5 times as long.
466
+
467
+ | Source | Currencies | Dated | Notes |
468
+ | ------------- | --------------------------- | ----- | --------------------------------------------------------------------------------------------------------------------- |
469
+ | `"coingecko"` | many | yes | No key needed. Optional: a Demo key (`coingecko_api_key:`), sent to CoinGecko only. Without one, limited by IP. |
470
+ | `"mempool"` | USD EUR GBP CAD CHF AUD JPY | yes | |
471
+ | `"coinbase"` | many | no | Prices are decimal strings, read as written. |
472
+ | `"kraken"` | Kraken's pairs | no | The last trade's price. |
473
+ | `"opennode"` | ~140 | no | |
474
+ | a callable | yours | maybe | `->(currency) { "69012.5" }`, or `{ price:, time: }`. Never a number. `rate.source` is then `"custom"`. |
475
+
476
+ Any other source (a CoinGecko Pro key, your own mempool instance, several sources checked against
477
+ each other) is a callable. It gives the price as a **String**, as its source wrote it: a number may
478
+ already have lost digits. With two parameters, it gets a `Cancellation` too, cancelled when the call
479
+ is, or once the call no longer needs the price (another of its steps failed meanwhile): stop then,
480
+ the call waits for your callable to return.
481
+
482
+ ```ruby
483
+ require "net/http"
484
+ require "json"
485
+
486
+ rates = lambda do |currency, cancellation|
487
+ # Your service answers { "price": "69012.50", "time": 1791378000 }: the price as a string.
488
+ response = Net::HTTP.get_response(URI("https://rates.example.ch/btc/#{currency}"))
489
+ raise Sattleme::Checkout::UnsupportedCurrencyError.new(currency, "rates.example.ch") if response.code == "404"
490
+
491
+ cancellation.raise_if_cancelled
492
+ body = JSON.parse(response.body)
493
+ { price: body.fetch("price"), time: body["time"] }
494
+ end
495
+ SATTLEME = Sattleme::Checkout::Client.new(key: ENV.fetch("SATTLEME_INTEGRATION_KEY"), rate_source: rates)
496
+ ```
497
+
498
+ A price its source dates is refused when it is more than an hour old, or more than 5 minutes
499
+ ahead: the next source of the list is then asked. When no source gives a price, `create_invoice`
500
+ raises `UnsupportedCurrencyError` if none of them has the currency, else the last `RateError` (no
501
+ usable price) or `NetworkError` (no answer), both retryable. Your callable raises
502
+ `UnsupportedCurrencyError` when it has no price in a currency, `NetworkError` or `RateError` when
503
+ it cannot give one now: the next source is then asked. Any other error of yours becomes a
504
+ `RateError` (your error as its `cause`); an error of this gem of another kind stops the list and
505
+ goes through as it is.
506
+
507
+ ## Errors
508
+
509
+ Every error is a `Sattleme::Checkout::Error` with a stable `code` and `retryable?`, but for a
510
+ cancelled call, which raises `Sattleme::Checkout::Cancelled` (never an `Error`). None ever holds a
511
+ secret: neither the key, nor a sale's key, nor any key derived from them.
512
+
513
+ | Error | Code | When | Retry? |
514
+ | -------------------------- | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- |
515
+ | `InvalidKeyError` | `invalid_key` | The key is not an integration key (another prefix, damaged, an old `https://…/pay#…` link). | no |
516
+ | `InvalidOptionError` | `invalid_option` | An option of the client or of `wait_for_payment` is invalid: `error.param` names it. | no |
517
+ | `InvalidOrderError` | `invalid_order` | A parameter is invalid: `error.param` names it (`ref`, `sats`, `fiat`, `rate_source`, `duration_seconds`, `note`, `checkout`, `redirect_url`, `invoice`, `order`). | no |
518
+ | `RevokedError` | `revoked` | The merchant removed the integration. | no |
519
+ | `ChannelNotFoundError` | `channel_not_found` | The relays answered without the integration's channel (`newer_format?`: update the gem). | when not newer |
520
+ | `NetworkError` | `network` | A relay, breez.tips, a rate source or an explorer did not answer, or fewer than a majority of the merchant's relays took a record. | yes |
521
+ | `InvalidInvoiceError` | `invalid_invoice` | An invoice or a payment answer failed the checks. Never show such an invoice. | no |
522
+ | `InvoicePendingError` | `invoice_pending` | An earlier invoice of this order may still be paid, or is being confirmed on-chain: `error.invoice` (and `error.checkout_url` with `checkout: true`). | after it expires |
523
+ | `OrderPaidError` | `order_paid` | An earlier invoice of this order was paid: `error.invoice`, `error.status`, `error.preimage` (nil on-chain). | no |
524
+ | `UnsupportedCurrencyError` | `unsupported_currency` | The rate source has no price in this currency (`error.currency`). | no |
525
+ | `RateError` | `rate` | No usable price: invalid, too old, or your rate callable failed. | yes |
526
+ | `CheckoutUnavailableError` | `checkout_unavailable` | `checkout: true`, and the merchant's app gives no web app for checkout links. | no |
527
+ | `OnchainUnavailableError` | `onchain_unavailable` | The order can only be paid on-chain, and no address of the integration's lot could be leased. | yes |
528
+
529
+ `error.invoice` is a `DeclaredInvoice`, `error.status` a `PaymentStatus`: both have `to_json`.
530
+ Every value the gem gives (`Invoice`, `DeclaredInvoice`, `PaymentStatus` of each state, `Rest`,
531
+ `Fiat`, `RateInfo`, `Merchant`) writes the JSON of SPEC.md §3 with `to_json`, and gives it as a
532
+ Hash with `as_json` and `to_h`: the json gem (`JSON.generate`) and Rails (`render json:`, a log)
533
+ write it so too, alone or in a document. An option or a parameter given as `nil` is one not given
534
+ (its default), but for `rate_source: nil`, which is invalid (no source).
535
+
536
+ ## Cancellation
537
+
538
+ Every method takes `cancellation:`, a `Sattleme::Checkout::Cancellation`:
539
+
540
+ ```ruby
541
+ cancellation = Sattleme::Checkout::Cancellation.new
542
+ Thread.new { sleep 5; cancellation.cancel("the customer left") }
543
+ SATTLEME.wait_for_payment(invoice, cancellation: cancellation) # raises Cancelled after 5 s
544
+
545
+ # Or bounded in time:
546
+ SATTLEME.wait_for_payment(invoice, cancellation: Sattleme::Checkout::Cancellation.after(600))
547
+ ```
548
+
549
+ A cancelled call stops its requests, closes its connections and raises `Cancelled` (its `reason`,
550
+ and its message when the reason is a String), even when a step that cannot stop at once (a name's
551
+ resolution, a callable of yours) delayed it: never an error of the table above, never a result.
552
+
553
+ ## What `create_invoice` does
554
+
555
+ 1. Reads the integration's channel on the Nostr relays of the key (signed by the merchant's team,
556
+ following up to 3 moves of the merchant's relays): the merchant's Lightning address, registry
557
+ and relays, or `removed`. At every call: a removal stops the next invoice.
558
+ 2. Checks that no earlier invoice of the order may still be paid (its payment checked: one already
559
+ paid is never handed out again, `OrderPaidError`; one underpaid on-chain gets the invoice of its
560
+ rest, as with `get_status`, before `InvoicePendingError`). Meanwhile, reads the Lightning
561
+ address and, for a price in a currency, the rate.
562
+ 3. Converts the price to sats, when it is in a currency; its methods follow from the amount.
563
+ 4. With Lightning, asks the merchant's Lightning address for the invoice (LUD-06/16), and checks
564
+ it: Bitcoin mainnet, exactly the amount, the merchant's description hash, a verify URL (LUD-21)
565
+ on the same host and port, no longer than asked, dated within 5 minutes.
566
+ 5. With on-chain, leases an address of the integration's lot: publishes the lease on a majority of
567
+ the merchant's relays, reads the address's leases again on every relay to confirm it, then marks
568
+ it confirmed. A lease that was not confirmed is withdrawn, and the next address is tried.
569
+ Without an address, Lightning only (or `OnchainUnavailableError`).
570
+ 6. With `checkout: true`, publishes its checkout link on a majority of the merchant's relays.
571
+ Without a majority, no invoice (nothing is declared).
572
+ 7. With Lightning, declares it in the merchant's registry, on a majority of the merchant's relays:
573
+ so that its payment counts for this order's sale and for no other. Without a majority, no
574
+ invoice.
575
+
576
+ A confirmed lease is never withdrawn, whatever fails after it (its mark, the link, the
577
+ declaration): it holds its address until its end, and the order's next `create_invoice` may hand
578
+ its invoice out (`InvoicePendingError`).
579
+
580
+ `get_status` asks the invoice's verify URL (LUD-21) and accepts a Lightning payment only with the
581
+ preimage of its payment hash, in an answer about this very invoice; with an address, it asks the
582
+ explorer at the same time and reads the witnesses of the order (see
583
+ [On-chain payments](#on-chain-payments)).
584
+
585
+ A call opens one connection per relay, used for all it reads and writes there, and closes them
586
+ when it is done. Every relay is asked at once, each in a thread of its own, and reads and writes go
587
+ on as soon as a majority of the relays answered (each declaration is on a majority of them, and
588
+ any two majorities share a relay): a slow or down relay slows nothing. Three reads decide that a
589
+ record is nobody else's and wait for every relay instead, up to `relay_timeout_ms` after a
590
+ majority answered: a lease's confirmation, the witnesses read again after one is published, and
591
+ the choice among several invoices of an order that may still be paid. A relay that failed earlier
592
+ in the call is not waited for again. A write to the relays past the majority goes on in a
593
+ background thread, for `relay_timeout_ms` at most, then its connection closes.
594
+
595
+ HTTP requests follow no redirect, read at most 1 MiB of an answer's body, 16 KiB of its head
596
+ (status line and headers) and 10 MiB of all it holds besides its body (a chunked body's size lines
597
+ included), and carry `User-Agent: sattleme-Checkout/1`, the same in every implementation of the specification. The
598
+ relays' WebSocket handshake follows no redirect either, carries the same User-Agent (relays behind
599
+ a bot protection refuse a handshake without one), and offers no compression; a message larger than
600
+ 1 MiB fails its connection before it is read. Of what a relay sends, a read keeps only what opens
601
+ with its keys and, for a signed record, whose signature checks out (of a lease, only its id,
602
+ author, date, signature and end; of any other event, its id and its date): a relay cannot make the
603
+ server's memory grow. A JSON text in which more than 64 arrays and objects nest is no JSON.
604
+
605
+ ## Outbound requests
606
+
607
+ Besides fixed hosts (the rate sources, mempool.space, BlockCypher), your server asks hosts that
608
+ others choose: the merchant's Lightning address and its provider (breez.tips), the merchant's
609
+ relays and [its Bitcoin node](#the-merchants-bitcoin-node). Their URLs are checked first: `https`
610
+ or `wss` only, no IP address, no `localhost` nor a name under it, no redirect followed; but for
611
+ the merchant's node, whose URL follows its own rule (`http` and `ws` to a host of a local network,
612
+ an IPv4 address). A name may still lead into your own network (an internal name, a public name
613
+ resolving to a private address), and the gem does not resolve names itself (a name that resolves
614
+ again would bypass such a check). If your server holds the keys of several merchants, or sits in a
615
+ network with services of its own, restrict what it can reach to public addresses: in your network
616
+ (an egress proxy, a firewall), or in the HTTP and WebSocket clients you give the client (below).
617
+
618
+ The time a request takes counts from its start, the resolution of the host's name and the
619
+ connection included: `http_timeout_ms` bounds an HTTP request, its body included,
620
+ `relay_timeout_ms` each request to a relay.
621
+
622
+ ## Security
623
+
624
+ - **Constant time.** What handles a secret key on the curve is libsecp256k1's, Bitcoin Core's
625
+ library (see [Dependencies](#dependencies)): signing (BIP-340, `secp256k1_schnorrsig_sign32`),
626
+ a key's public point (`secp256k1_keypair_create`) and the ECDH of NIP-44 (`secp256k1_ecdh`) run
627
+ in constant time and with constant memory access in the secret: its README says so of signing
628
+ and key generation ("Constant time, constant memory access signing and public key generation"),
629
+ and its ECDH multiplies by the secret with `secp256k1_ecmult_const` ("in constant-time for q",
630
+ `src/ecmult_const.h`). Its context is randomized once loaded (`secp256k1_context_randomize`), a
631
+ blinding against side channels. HKDF, HMAC-SHA256 and ChaCha20 are OpenSSL's, and MACs are
632
+ compared with `OpenSSL.fixed_length_secure_compare`. The Ruby code around them (a key copied,
633
+ a sale's key written in hex into its records) is not constant time, and Ruby cannot erase a
634
+ String from memory: the key lives in the server's memory as long as the client does.
635
+ - **Reports**: [SECURITY.md](SECURITY.md).
636
+
637
+ ## Limits
638
+
639
+ - One hour at most per invoice; on-chain, about 30 minutes more to be `paid` (3 confirmations).
640
+ - Not measured: the limits of breez.tips, of mempool.space and of the relays for a shop that makes
641
+ many invoices from one IP address. BlockCypher takes 100 requests an hour from an IP address
642
+ without a token: it is asked only about a transaction no check saw while its lease ran.
643
+ - Each call runs a thread per relay, and a few for the HTTP requests it makes at once: a server
644
+ that makes many calls at once runs that many more threads.
645
+
646
+ Not in this version: refunds, webhooks, and showing open (unpaid) invoices in the merchant's app.
647
+
648
+ ## Options
649
+
650
+ ```ruby
651
+ Sattleme::Checkout::Client.new(
652
+ key: ENV.fetch("SATTLEME_INTEGRATION_KEY"), # required
653
+ # A source or a list of them (names or callables); without it, the default list.
654
+ rate_source: Sattleme::Checkout::DEFAULT_RATE_SOURCES,
655
+ coingecko_api_key: nil, # optional: CoinGecko's Demo key (visible ASCII), sent to CoinGecko only
656
+ # Anything with get(url, headers:, timeout:, cancellation:) { |chunk| … } giving the HTTP status.
657
+ http_client: Sattleme::Checkout::HttpClient.new,
658
+ # Anything with connect(url, timeout:, headers:, cancellation:) giving a socket.
659
+ websocket_client: Sattleme::Checkout::WebSocketClient.new,
660
+ relay_timeout_ms: 10_000, # per relay request, connection included: 100 to 60 000
661
+ http_timeout_ms: 10_000, # per HTTP request, body included: 100 to 60 000
662
+ # Anything with warn(message), never given a secret: Rails.logger, a Logger (require "logger").
663
+ logger: nil # nil: standard error, a line each
664
+ )
665
+ ```
666
+
667
+ An invalid option, or one the client does not know, raises `InvalidOptionError` at once, before any
668
+ request. `now:` (a callable giving Unix seconds) and `random:` (a callable giving that many random
669
+ bytes) are for tests only.
670
+
671
+ **Threads.** A call runs its requests in threads of its own (one per relay, one per HTTP request,
672
+ its checks at once): what you give the client (`http_client`, `websocket_client`, `logger`, `now`,
673
+ `random`, a rate source of yours) is called from several threads within one call, so it must be
674
+ safe to call so. Once a call returned, nothing it started runs on, but the relays of a publication
675
+ past its majority: each may still finish its own request (with NIP-42's one authentication and the
676
+ one write again), up to `relay_timeout_ms`, and so use your `websocket_client`, `now` and `random`
677
+ after the call returned (SPEC.md §4, §13). A request the gem gives up (its time ran out, its call is
678
+ cancelled or failed meanwhile) is told so through its `cancellation`, or its socket is closed, and
679
+ the call waits half a second for it to stop: a client that does not is left behind, never the call.
680
+
681
+ - **Behind an HTTP proxy**: `Sattleme::Checkout::HttpClient.new(proxy: URI("http://proxy:3128"))`
682
+ (a proxy that tunnels with CONNECT). It never reads the proxy of the environment.
683
+ - **A company's certificate authority**: `HttpClient.new(cert_store: store)`, an
684
+ `OpenSSL::X509::Store`; for the relays,
685
+ `WebSocketClient.new(connector: TlsConnector.new(ssl_context: context))`.
686
+ - **The merchant's node on a local network**: `HttpClient` and `WebSocketClient` reach it in clear
687
+ (`WebSocketClient.new(plain_connector: …)`, a `PlainConnector` by default), and no other host
688
+ (see [The merchant's Bitcoin node](#the-merchants-bitcoin-node)).
689
+ - **Your own WebSocket client**: its `connect` gives a socket with `send_text(text)`, `receive` (the
690
+ next text message, nil once closed) and `close`. Keep it bounded as the gem's is: no redirect
691
+ followed, no compression offered, the headers it is given (the User-Agent) sent, a message capped
692
+ at 1 MiB, the handshake within `timeout`.
693
+
694
+ ## Dependencies
695
+
696
+ | Dependency | Version | Why |
697
+ | ------------------------------------------------------------- | --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
698
+ | [libsecp256k1](https://github.com/bitcoin-core/secp256k1) | 0.2.0 or later (the system) | BIP-340 Schnorr signatures, x-only keys and the ECDH of NIP-44: the library Bitcoin Core uses and audits. Never a curve of this gem's own. 0.2.0 is the oldest supported. |
699
+ | [ffi](https://github.com/ffi/ffi) | 1.17.4 (`>= 1.17.4, < 2`) | Calls libsecp256k1 without a C extension of this gem's own: ffi ships prebuilt for Linux and macOS, where installing compiles nothing. |
700
+ | Ruby's own `openssl` | Ruby's | SHA-256, HMAC-SHA256, HKDF-SHA256 and ChaCha20 (NIP-44, key derivations), TLS 1.2 or later for HTTP and the relays, the certificates' checks. |
701
+ | Ruby's own `socket` | Ruby's | The TCP connections of the gem's HTTP client (HTTP/1.1, its own: no redirect, every part of an answer bounded) and WebSocket client (RFC 6455, its own: no compression). |
702
+
703
+ Nothing else at run time. Development only, pinned exactly in `Gemfile.lock` (with their
704
+ checksums): minitest 5.27.0 (the tests), rake 13.4.2 (the checks), RuboCop 1.92.2 with
705
+ rubocop-minitest 0.41.0 (format and lint), and RuboCop's own json 2.18.0, parser 3.3.13.0, prism
706
+ 1.8.2 and racc 1.8.1, held at the versions Ruby 4.0.9 ships so that the CI compiles nothing.
707
+
708
+ ## Development
709
+
710
+ ```sh
711
+ bundle install
712
+ bundle exec rake # the pinned specification, RuboCop (format and lint), the tests, the package
713
+ ```
714
+
715
+ `bundle exec rake test` runs the tests alone, `bundle exec rubocop -a` corrects what RuboCop can.
716
+ Without a system libsecp256k1, `bundle exec rake secp256k1` builds Bitcoin Core's v0.8.0 (its commit
717
+ checked; git, cmake and a C compiler) into `tmp/secp256k1`, which the tests find.
718
+
719
+ The tests run local Nostr relays (in-process WebSocket servers) and fakes of breez.tips, of the
720
+ rate sources, of mempool.space and of a merchant's Bitcoin node (REST and WebSocket) and of
721
+ BlockCypher, reached through the injected HTTP and WebSocket clients: no network.
722
+
723
+ `spec/` is a copy of [sattleme/checkout-spec](https://github.com/sattleme/checkout-spec) pinned to
724
+ one commit (`spec/PIN.json`, checked file by file by `bundle exec rake spec:check` and the tests),
725
+ never edited here. Its vectors are what the tests check the gem against: the conformance vectors,
726
+ the official NIP-44 vectors, the merchant's app's vectors (`spec/vectors/app/app.json`) and the
727
+ vectors an implementation makes for the app to read (`spec/vectors/app/implementation-declaration.json`,
728
+ `spec/vectors/app/checkout-link.json`, `spec/vectors/app/checkout-rest.json`). A disagreement with
729
+ the specification, or a wrong vector, is reported to checkout-spec. To take a newer version: clone
730
+ checkout-spec at that commit (of its default branch, a tagged version when there is one), then
731
+ `bundle exec rake "spec:import[../checkout-spec]"`: it replaces `spec/` and `spec/PIN.json`
732
+ together, from the clone's `manifest.json`, and refuses a clone with changes of its own. Commit the
733
+ copy with the code that passes the new vectors, in one pull request.
734
+
735
+ ## Releasing
736
+
737
+ Releases are the maintainers': never from a development or agent session. A maintainer writes the
738
+ version's entry in `CHANGELOG.md` and sets `Sattleme::Checkout::VERSION`
739
+ (`lib/sattleme/checkout/version.rb`), then pushes a tag `vX.Y.Z` of that version on a commit of
740
+ `main`.
741
+ `.github/workflows/release.yml` then runs the CI again, checks that the tag is the gem's version and
742
+ that its commit is on `main`, and publishes the gem to RubyGems.org in a job bound to the protected
743
+ environment `rubygems` (required reviewers: a maintainer approves each release). It publishes by
744
+ trusted publishing: RubyGems.org exchanges that job's OIDC token for a short-lived key, and no key
745
+ is stored anywhere. To set it up once: on RubyGems.org, the gem's trusted publisher
746
+ `sattleme/checkout-ruby`, workflow `release.yml`, environment `rubygems`; on GitHub, the environment
747
+ `rubygems` with its required reviewers, and a ruleset that lets only maintainers create `v*` tags.
748
+ The exchange names the RubyGems.org account that owns the gem, by its immutable ID
749
+ (`RUBYGEMS_OWNER` in `release.yml`): RubyGems.org creates the gem, at its first release, only from
750
+ that account's pending trusted publisher, which expires if no release uses it in time.
751
+
752
+ ## License
753
+
754
+ [MIT](LICENSE)