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,352 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sattleme
4
+ module Checkout
5
+ module Internal
6
+ # The merchant's tolerance of on-chain underpayments (SPEC.md §31, "The merchant's
7
+ # tolerance"): the share of an order's amount its payment in time may miss and still pay it,
8
+ # in basis points. The channel gives it, an order's lease keeps the one of its creation: every
9
+ # check of the order judges its payment with that one, as the merchant's app does. It is never
10
+ # written where the shop's page or the customer reads (the Invoice, the PaymentStatus, a
11
+ # checkout link's record, an error, a log): a customer who knew it could pay that much less.
12
+ module Tolerance
13
+ module_function
14
+
15
+ # A tolerance as a channel or a lease writes it: an integer from 0 to MAX_TOLERANCE, else 0.
16
+ def of(value)
17
+ Json.integer?(value) && value.between?(0, Protocol::MAX_TOLERANCE) ? value.to_i : 0
18
+ end
19
+
20
+ # The least accepted of `sats` with `tolerance` (basis points): `sats` less the share the
21
+ # tolerance allows, rounded down to the whole sat. On integers.
22
+ def least_accepted(sats, tolerance)
23
+ sats - ((sats * of(tolerance)) / Protocol::TOLERANCE_SCALE)
24
+ end
25
+
26
+ # What is due on-chain of an invoice of `sats` with `tolerance`, its rest invoices having paid
27
+ # `paid_by_rests`, with the `received` of the merchant's acceptance that counts,
28
+ # `merchant_accepted` (nil without one: MerchantAcceptances) (SPEC.md §31, "The on-chain
29
+ # payment", step 4): nothing (0) when they paid `sats` or more; else max(1, min(L, M) − R),
30
+ # L the least accepted, M the merchant's acceptance's `received` (`sats` without one), R
31
+ # what they paid. R is taken once from the lesser: M counts the rest invoices paid when the
32
+ # merchant accepted, as L counts every payment. At least 1 sat: something must count
33
+ # on-chain for the tolerance or the merchant's acceptance to apply.
34
+ def due_onchain(sats, tolerance, paid_by_rests, merchant_accepted = nil)
35
+ return 0 if paid_by_rests >= sats
36
+
37
+ least = least_accepted(sats, tolerance)
38
+ accepted = merchant_accepted && merchant_accepted < least ? merchant_accepted : least
39
+ due = accepted - paid_by_rests
40
+ due.positive? ? due : 1
41
+ end
42
+ end
43
+
44
+ # The methods of an order by its amount (SPEC.md §31, "Methods by amount"): Lightning when the
45
+ # amount is within the Lightning address's sendable sats, on-chain from 1 000 sats when an
46
+ # address can be leased. Nothing is repaired: an amount is never split between the two, nor
47
+ # moved into the sendable sats.
48
+ module Methods
49
+ Chosen = Data.define(:lightning, :onchain)
50
+
51
+ module_function
52
+
53
+ # The methods `sats` may be paid with, before an address is leased. InvalidOrderError
54
+ # (`param`: "sats" or "fiat") below 1 000 sats and outside the sendable sats ([min, max]).
55
+ def of(sats, sendable, param)
56
+ min, max = sendable
57
+ lightning = sats.between?(min, max)
58
+ onchain = sats >= Protocol::ONCHAIN_FLOOR_SATS
59
+ unless lightning || onchain
60
+ raise InvalidOrderError.new(param, "#{sats} sats is outside the merchant's bounds (#{min} to #{max} sats)")
61
+ end
62
+
63
+ Chosen.new(lightning: lightning, onchain: onchain)
64
+ end
65
+
66
+ # The methods once leasing an address gave `outcome` (:leased, :none, or the explorer's
67
+ # NetworkError): without an address, Lightning only; an order that can only be paid on-chain
68
+ # then fails with OnchainUnavailableError, or the explorer's NetworkError.
69
+ def with(methods, outcome)
70
+ return methods if !methods.onchain || outcome == :leased
71
+ raise(outcome.is_a?(Error) ? outcome : OnchainUnavailableError.new) unless methods.lightning
72
+
73
+ Chosen.new(lightning: true, onchain: false)
74
+ end
75
+ end
76
+
77
+ # The integration's lot (SPEC.md §31, "The lot"): deposit addresses of the merchant's wallet,
78
+ # which the merchant's app gives the integration and fills again whenever the merchant opens
79
+ # it. One record signed by the team, sealed with the channel's key, at an address the
80
+ # integration key derives. The gem only reads it: it never makes an address, nor writes a lot.
81
+ module Lot
82
+ module_function
83
+
84
+ # A lot's value: version 1, `updatedAt` its event's `created_at`, 0 to 100 deposit
85
+ # addresses, none twice. Nil when it is not valid; raises Records::Newer for a newer version.
86
+ def parse(value, created_at)
87
+ return nil unless value.is_a?(Hash)
88
+
89
+ version = value["version"]
90
+ raise Records::Newer if Json.number?(version) && version > Protocol::LOT_VERSION
91
+ return nil unless version == Protocol::LOT_VERSION && value["updatedAt"] == created_at
92
+
93
+ addresses = value["addresses"]
94
+ return nil unless addresses.is_a?(Array) && addresses.size <= Protocol::MAX_LOT_ADDRESSES
95
+
96
+ lot = []
97
+ addresses.each do |address|
98
+ return nil unless Addresses.deposit?(address) && !lot.include?(address)
99
+
100
+ lot << address
101
+ end
102
+ lot
103
+ end
104
+
105
+ # The addresses of the integration's lot, read on the merchant's `relays` as soon as a
106
+ # majority answered: the newest valid copy. Empty when there is none, or when a copy of a
107
+ # newer format is newer than it (logged: update the gem). The order means nothing.
108
+ # NetworkError when fewer than a majority answered.
109
+ def read(pool, key, relays, random:, logger:, stop:)
110
+ address = Derive.lot_address(key.key)
111
+ encryption_key = Derive.channel_keys(key.key)[1]
112
+ team = key.team_public_key
113
+ filter = { "kinds" => [Protocol::RECORD_KIND], "authors" => [team], "#d" => [address] }
114
+ keep = Records.that_open { |_, author| author == team ? encryption_key : nil }
115
+ # A relay that asks to authenticate (NIP-42) gets a key of this read alone.
116
+ result = pool.query_relays(relays, filter, random.call(32), paged: false, stop: stop, keep: keep)
117
+ raise NetworkError, "Fewer than a majority of the merchant's relays answered" unless result.answered
118
+
119
+ found = Records.newest(result.answers) do |value|
120
+ Records.open(value, type: Protocol::LOT_RECORD_TYPE, encryption_key: encryption_key, address: address,
121
+ author: team) { |lot, event| parse(lot, event.created_at) }
122
+ end
123
+ if found.newest_unreadable && found.newest_unreadable >= (found.event&.created_at || -1)
124
+ logger.warn("sattleme-checkout: the integration's lot of addresses has a newer format than this " \
125
+ "version reads; update the gem (no on-chain payment until then)")
126
+ return []
127
+ end
128
+
129
+ found.value || []
130
+ end
131
+ end
132
+
133
+ # Replacements (SPEC.md §31, "Replacements"): a payer whose transaction is slow to confirm may
134
+ # broadcast another one in its place (RBF), which spends a coin of the same. A replacement
135
+ # keeps the time of the payment it replaces, for at most what that payment paid the address:
136
+ # what it pays more counts at its own time, as any other payment would.
137
+ module Replacements
138
+ # A transaction paying the address, as the parts are made of it: what it pays the address,
139
+ # the coins it spends (or those recorded of it), when it was seen (a witness's `created_at`;
140
+ # nil: unknown, after every known one), whether the explorer lists it now.
141
+ PaymentTx = Data.define(:txid, :sats, :inputs, :order, :listed)
142
+
143
+ # A part of a listed transaction: sats it pays as its `root` (itself, for a part of its own).
144
+ Part = Data.define(:sats, :root)
145
+
146
+ module_function
147
+
148
+ # The parts of each listed transaction, by txid: a txid given twice is taken once (its first
149
+ # entry); the transactions in order (unknown last, then by txid); the roots of each are those
150
+ # before it that spend one of its coins (their roots, put together), else itself; each root
151
+ # gives at most its sats, in that order, then what a transaction still pays is a part of its
152
+ # own.
153
+ def parts(txs)
154
+ unique = {}
155
+ txs.each { |tx| unique[tx.txid] ||= tx }
156
+ sorted = unique.values.sort_by { |tx| [tx.order.nil? ? 1 : 0, tx.order || 0, tx.txid] }
157
+ position = sorted.each_with_index.to_h { |tx, index| [tx.txid, index] }
158
+ roots = {}
159
+ sorted.each_with_index do |tx, index|
160
+ coins = tx.inputs.to_h { |coin| [coin, true] }
161
+ before = sorted.first(index).select { |other| other.inputs.any? { |coin| coins.key?(coin) } }
162
+ roots[tx.txid] = if before.empty?
163
+ [tx.txid]
164
+ else
165
+ before.flat_map { |other| roots[other.txid] }.uniq.sort_by { |root| position[root] }
166
+ end
167
+ end
168
+ to_give = sorted.to_h { |tx| [tx.txid, tx.sats] }
169
+ result = {}
170
+ sorted.each do |tx|
171
+ next unless tx.listed
172
+
173
+ own = roots[tx.txid]
174
+ owed = tx.sats
175
+ list = []
176
+ if own == [tx.txid]
177
+ # A payment of its own: all its sats, which it no longer has to give.
178
+ to_give[tx.txid] = 0
179
+ else
180
+ own.each do |root|
181
+ left = to_give[root]
182
+ take = [owed, left].min
183
+ next unless take.positive?
184
+
185
+ list << Part.new(sats: take, root: root)
186
+ to_give[root] = left - take
187
+ owed -= take
188
+ end
189
+ end
190
+ list << Part.new(sats: owed, root: tx.txid) if owed.positive?
191
+ result[tx.txid] = list
192
+ end
193
+ result
194
+ end
195
+ end
196
+
197
+ # What the blockchain shows (SPEC.md §31, "Explorers"): one explorer of the Esplora API, the
198
+ # explorer, asked over HTTP; and BlockCypher, for when a transaction was received, asked only
199
+ # about a transaction no check saw while its lease ran. Third parties: they see the server's
200
+ # IP address and what it asks about, never a key. Their answers are checked as strictly as a
201
+ # relay's: anything else is a failure (NetworkError). A payment counts as made on what the
202
+ # explorer read alone shows.
203
+ module Explorer
204
+ # A transaction, as an explorer gives it, checked: the coins it spends (`<txid>:<vout>`,
205
+ # coinbase inputs left out, in their order), its outputs ([sats, address or nil]), the
206
+ # height of its block (nil while it is not confirmed).
207
+ Tx = Data.define(:txid, :coins, :outputs, :block_height) do
208
+ # What it pays `address`: the sum of its outputs to it.
209
+ def pays_to(address)
210
+ outputs.sum { |sats, to| to == address ? sats : 0 }
211
+ end
212
+
213
+ # Its confirmations at the chain's `height`: 0 unconfirmed, else height − its block's + 1,
214
+ # 1 at least.
215
+ def confirmations(height)
216
+ block_height.nil? ? 0 : [1, height - block_height + 1].max
217
+ end
218
+ end
219
+
220
+ MAX_VOUT = 4_294_967_295
221
+ BLOCKCYPHER_TIME = /\A([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.([0-9]{1,9}))?Z\z/
222
+ MONTH_DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31].freeze
223
+
224
+ module_function
225
+
226
+ def natural?(value)
227
+ Json.safe_integer?(value) && value >= 0
228
+ end
229
+
230
+ # An Esplora transaction, checked; nil when it is not one.
231
+ def parse_transaction(value)
232
+ return nil unless value.is_a?(Hash) && Text.hex32?(value["txid"])
233
+
234
+ vin, vout, status = value.values_at("vin", "vout", "status")
235
+ return nil unless vin.is_a?(Array) && vout.is_a?(Array) && status.is_a?(Hash)
236
+
237
+ coins = []
238
+ vin.each do |input|
239
+ return nil unless input.is_a?(Hash)
240
+ next if input["is_coinbase"] == true
241
+
242
+ txid, index = input.values_at("txid", "vout")
243
+ return nil unless Text.hex32?(txid) && natural?(index) && index <= MAX_VOUT
244
+
245
+ coins << "#{txid}:#{index.to_i}"
246
+ end
247
+ outputs = []
248
+ vout.each do |output|
249
+ return nil unless output.is_a?(Hash) && natural?(output["value"])
250
+
251
+ # A string when it is there (`null` is no string); absent, the output pays no address.
252
+ address = output["scriptpubkey_address"]
253
+ return nil if output.key?("scriptpubkey_address") && !address.is_a?(String)
254
+
255
+ outputs << [output["value"].to_i, address]
256
+ end
257
+ # More than every bitcoin there will ever be (SPEC.md §31, Explorers): no transaction,
258
+ # whatever an explorer says.
259
+ return nil if outputs.sum(&:first) > Protocol::MAX_SATS
260
+
261
+ confirmed = status["confirmed"]
262
+ return nil unless [true, false].include?(confirmed)
263
+
264
+ height = nil
265
+ if confirmed
266
+ return nil unless natural?(status["block_height"])
267
+
268
+ height = status["block_height"].to_i
269
+ end
270
+ Tx.new(txid: value["txid"], coins: coins, outputs: outputs, block_height: height)
271
+ end
272
+
273
+ # The transactions of `address` on the explorer at `base`: its first answer (a deposit
274
+ # address is paid a few times at most), in the explorer's order.
275
+ def address_transactions(base, address, http)
276
+ url = "#{base}/address/#{address}/txs"
277
+ answer = Http.get_json(url, http)
278
+ raise NetworkError, "#{Urls.host_of(url)} answered HTTP #{answer.status}" unless answer.ok?
279
+ raise NetworkError, "#{Urls.host_of(url)} gave no transactions" unless answer.body.is_a?(Array)
280
+
281
+ answer.body.map do |value|
282
+ parse_transaction(value) ||
283
+ raise(NetworkError, "#{Urls.host_of(url)} gave a transaction that is not one")
284
+ end
285
+ end
286
+
287
+ # The chain's height on the explorer at `base`: a body of 1 to 9 digits (plain text).
288
+ def chain_height(base, http)
289
+ url = "#{base}/blocks/tip/height"
290
+ answer = Http.get_text(url, http)
291
+ raise NetworkError, "#{Urls.host_of(url)} answered HTTP #{answer.status}" unless answer.ok?
292
+ raise NetworkError, "#{Urls.host_of(url)} gave no height" unless Text.match?(answer.text, /\A[0-9]{1,9}\z/)
293
+
294
+ Integer(answer.text, 10)
295
+ end
296
+
297
+ # Unix milliseconds of a time as BlockCypher writes it (UTC, a fraction of 1 to 9 digits or
298
+ # none, `Z`), the fraction past milliseconds dropped (never rounded); nil when it is not
299
+ # one, or not a real date and time (no leap second). Another spelling of RFC 3339 is not
300
+ # BlockCypher's.
301
+ def blockcypher_milliseconds(text)
302
+ match = Text.well_formed?(text) && BLOCKCYPHER_TIME.match(text)
303
+ return nil unless match
304
+
305
+ year, month, day, hour, minute, second = match.captures.first(6).map { |part| Integer(part, 10) }
306
+ return nil unless month.between?(1, 12) && hour <= 23 && minute <= 59 && second <= 59
307
+ return nil unless day.between?(1, days_in_month(year, month))
308
+
309
+ milliseconds = Integer((match[7] || "")[0, 3].ljust(3, "0"), 10)
310
+ seconds = (days_from_civil(year, month, day) * 86_400) + (hour * 3600) + (minute * 60) + second
311
+ (seconds * 1000) + milliseconds
312
+ end
313
+
314
+ def days_in_month(year, month)
315
+ leap = (year % 4).zero? && (!(year % 100).zero? || (year % 400).zero?)
316
+ month == 2 && leap ? 29 : MONTH_DAYS[month - 1]
317
+ end
318
+
319
+ # Days from 1970-01-01 to a date of the proleptic Gregorian calendar.
320
+ def days_from_civil(year, month, day)
321
+ year -= 1 if month <= 2
322
+ era = year.div(400)
323
+ year_of_era = year - (era * 400)
324
+ day_of_year = (((153 * ((month + 9) % 12)) + 2) / 5) + day - 1
325
+ day_of_era = (year_of_era * 365) + (year_of_era / 4) - (year_of_era / 100) + day_of_year
326
+ (era * 146_097) + day_of_era - 719_468
327
+ end
328
+
329
+ # When BlockCypher first received `txid`, in Unix milliseconds (it never changes); nil when
330
+ # it does not know it yet (HTTP 404: it receives it later). Without a token, BlockCypher
331
+ # takes 100 requests an hour from an IP address: it is asked only about a transaction no
332
+ # check saw in time.
333
+ def received_at(txid, http)
334
+ url = "#{Protocol::BLOCKCYPHER_URL}/txs/#{txid}?limit=1&includeHex=false"
335
+ answer = Http.get_json(url, http)
336
+ return nil if answer.status == 404
337
+ raise NetworkError, "#{Urls.host_of(url)} answered HTTP #{answer.status}" unless answer.ok?
338
+
339
+ body = answer.body
340
+ unless body.is_a?(Hash) && body["hash"] == txid && body["received"].is_a?(String)
341
+ raise NetworkError, "#{Urls.host_of(url)} gave no time for the transaction"
342
+ end
343
+
344
+ time = blockcypher_milliseconds(body["received"])
345
+ raise NetworkError, "#{Urls.host_of(url)} gave no time for the transaction" unless time&.positive?
346
+
347
+ time
348
+ end
349
+ end
350
+ end
351
+ end
352
+ end
@@ -0,0 +1,326 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sattleme
4
+ module Checkout
5
+ module Internal
6
+ # Leases (SPEC.md §31, "Leases"): an order holds a deposit address of the lot for the time of
7
+ # its invoice with a record in the merchant's registry, signed by the order's sale, at the
8
+ # address's registry address. Outside, what anyone holding the registry key reads (when the
9
+ # lease ends, or its withdrawal); inside, sealed to the merchant's reading key as a
10
+ # declaration's, the order's terms. Like a declaration, a lease stays: a payment of its address
11
+ # in its time is the order's for good.
12
+ module Leases
13
+ # What a lease holds of its order (the lease's JSON, inside): the order's Lightning invoice
14
+ # and its verify URL (nil for an order paid on-chain only), the Invoice's dates, the price as
15
+ # declared, the label, the order's tolerance (0: none, absent from the lease), and whether
16
+ # it is marked confirmed (nil when absent, which is not confirmed either).
17
+ Terms = Data.define(:address, :sats, :invoice, :verify_url, :created_at, :expires_at, :price, :note,
18
+ :tolerance, :confirmed) do
19
+ def confirmed? = confirmed == true
20
+ end
21
+
22
+ # A lease of the sale, opened by the sale (or the merchant): its event, its `d` tag, its
23
+ # terms, and the lease's JSON as it was sealed.
24
+ Opened = Data.define(:event, :d, :terms, :inside)
25
+
26
+ # What a read of leases keeps of a record's event, its id checked: what the walk of its
27
+ # address and a lease's confirmation need, and its signature (SPEC.md §13, Limits).
28
+ LeaseEvent = Data.define(:id, :pubkey, :created_at, :sig)
29
+
30
+ # A record of the registry at a deposit address's registry address `d`, by any author: its id
31
+ # checked, its signature not yet (SPEC.md §31, "Opening a lease"); `hold` is :withdrawn,
32
+ # :newer, or the lease's `end` (an Integer). #signed? checks the signature once, with the
33
+ # copies other relays sent (#add_copy): a relay's copy with a damaged signature never hides
34
+ # the valid one another relay sent.
35
+ class Record
36
+ attr_reader :event, :d, :hold
37
+
38
+ def initialize(event, d, hold)
39
+ @event = event
40
+ @d = d
41
+ @hold = hold
42
+ @signatures = [event.sig]
43
+ @signed = nil
44
+ end
45
+
46
+ def signed?
47
+ @signed = @signatures.any? { |sig| signature_checks?(sig) } if @signed.nil?
48
+ @signed
49
+ end
50
+
51
+ # The same event (its id is its hash) with another signature: one more to try.
52
+ def add_copy(sig)
53
+ return if @signatures.include?(sig)
54
+
55
+ @signatures << sig
56
+ @signed = nil if @signed == false
57
+ end
58
+
59
+ # Whether it holds its address at `t`: a lease whose end is at most the clock tolerance
60
+ # before `t` (another server's clock may be behind), or of a newer format.
61
+ def holds?(time)
62
+ hold == :newer || (hold.is_a?(Integer) && hold >= time - Protocol::CLOCK_TOLERANCE_SECONDS)
63
+ end
64
+
65
+ private
66
+
67
+ def signature_checks?(sig)
68
+ Text.hex64?(sig) && Secp256k1.verify(Text.hex_bytes(sig), Text.hex_bytes(event.id),
69
+ Text.hex_bytes(event.pubkey))
70
+ end
71
+ end
72
+
73
+ # The records of the registry at the registry addresses of deposit addresses, by address;
74
+ # whether a majority of the relays answered (else the read is no answer); whether a majority
75
+ # read them completely.
76
+ Read = Data.define(:records, :answered, :complete)
77
+
78
+ module_function
79
+
80
+ # The lease of `terms.address` for `sale`, signed at `created_at`; it ends at expiresAt + 120.
81
+ # Its tolerance follows `taker` when it is above 0, and is absent otherwise.
82
+ def event(sale:, terms:, created_at:, random:)
83
+ inside = { "version" => Protocol::LEASE_VERSION, "address" => terms.address, "sats" => terms.sats,
84
+ "invoice" => terms.invoice, "verifyUrl" => terms.verify_url, "createdAt" => terms.created_at,
85
+ "expiresAt" => terms.expires_at,
86
+ "sale" => { "key" => Text.hex(sale.key), "fiat" => terms.price, "note" => terms.note },
87
+ "taker" => sale.taker }
88
+ inside["tolerance"] = terms.tolerance if terms.tolerance.positive?
89
+ inside["confirmed"] = terms.confirmed unless terms.confirmed.nil?
90
+ seal(sale, terms.address, { "version" => Protocol::LEASE_VERSION,
91
+ "end" => terms.expires_at + Protocol::GRACE_SECONDS,
92
+ "sealed" => Nip44.encrypt(Json.generate(inside), sale.inner_key, random) },
93
+ created_at, random)
94
+ end
95
+
96
+ # The withdrawal of `sale`'s lease of `address`, which replaces it (same author and `d` tag):
97
+ # its `created_at` is strictly after the lease's.
98
+ def withdrawal_event(sale:, address:, created_at:, random:)
99
+ seal(sale, address, { "version" => Protocol::LEASE_VERSION, "withdrawn" => true }, created_at, random)
100
+ end
101
+
102
+ def seal(sale, address, value, created_at, random)
103
+ d = Addresses.lease_address(sale.registry.key, address)
104
+ Internal::Records.seal(type: Protocol::LEASE_RECORD_TYPE, value: value, signer: sale.secret_key,
105
+ encryption_key: Derive.outer_key(sale.registry.key, d, sale.author), address: d,
106
+ created_at: created_at, random: random)
107
+ end
108
+
109
+ # A record's outside, as anyone holding the registry key reads it: [:lease, end, sealed],
110
+ # [:withdrawn], or nil; raises Records::Newer for a newer version.
111
+ def parse_outside(value)
112
+ return nil unless value.is_a?(Hash)
113
+
114
+ version = value["version"]
115
+ raise Internal::Records::Newer if Json.number?(version) && version > Protocol::LEASE_VERSION
116
+ return nil unless version == Protocol::LEASE_VERSION
117
+ return [:withdrawn] if value["withdrawn"] == true
118
+
119
+ ending, sealed = value.values_at("end", "sealed")
120
+ return nil unless Json.safe_integer?(ending) && sealed.is_a?(String)
121
+
122
+ [:lease, ending.to_i, sealed]
123
+ end
124
+
125
+ # What a relay sent, opened as a record of type `registry-onchain` at the registry address
126
+ # `d`, with the outer key of `d` and of the event's own author (SPEC.md §31, "Opening a
127
+ # lease"): its id first; a content of a newer NIP-44 version is no record here (anybody can
128
+ # write one at `d`); its signature is left to leased?, which checks it only where it
129
+ # decides. Nil when it is not one.
130
+ def open_record(value, registry_key, d)
131
+ opened = open_outside(value, registry_key, d)
132
+ return nil unless opened
133
+
134
+ event, outside = opened
135
+ Record.new(event, d, outside[0] == :lease ? outside[1] : outside[0])
136
+ end
137
+
138
+ # open_record's opening, with the whole outside: [LeaseEvent, outside] ([:newer] for a newer
139
+ # format), or nil.
140
+ def open_outside(value, registry_key, d)
141
+ return nil unless value.is_a?(Hash) && value["kind"] == Protocol::RECORD_KIND && Text.hex32?(value["pubkey"])
142
+ return nil unless Internal::Records.d_tag_of(value) == d
143
+
144
+ # The content before the id, the cheap check first (SPEC.md §12): what anybody writes at
145
+ # `d` is dropped before its id is computed, which costs time in its content's size, and
146
+ # escapes cost the most there. Both are checked, in either order: what opens is the same.
147
+ begin
148
+ plaintext = Nip44.decrypt(value["content"], Derive.outer_key(registry_key, d, value["pubkey"]))
149
+ rescue Nip44::Invalid, Nip44::UnknownVersion
150
+ # A content of a newer NIP-44 version included: only the outer key seals a newer lease.
151
+ return nil
152
+ end
153
+ return nil unless Events.valid_id?(value)
154
+
155
+ envelope = Json.parse_or(plaintext)
156
+ return nil unless envelope.is_a?(Hash) && envelope.key?("v") && envelope["t"] == Protocol::LEASE_RECORD_TYPE
157
+
158
+ outside = begin
159
+ parse_outside(envelope["v"])
160
+ rescue Internal::Records::Newer
161
+ [:newer]
162
+ end
163
+ return nil unless outside
164
+
165
+ [LeaseEvent.new(id: value["id"], pubkey: value["pubkey"], created_at: value["created_at"].to_i,
166
+ sig: value["sig"]), outside]
167
+ end
168
+
169
+ # Whether the records of one address lease it at `t` (SPEC.md §31, "Leases"): of each author,
170
+ # its records from the newest (a withdrawal replaces its author's lease): one that holds the
171
+ # address leases it; one that holds nothing ends the author's records, unless an older one
172
+ # of them holds and its signature does not check out. A record that holds is never checked
173
+ # for its signature: only a holder of the registry key seals one, and it may lease. Every
174
+ # author is walked (the vectors count the signatures checked).
175
+ def leased?(records, time)
176
+ leased = false
177
+ records.group_by { |record| record.event.pubkey }.each_value do |list|
178
+ walk = list.sort { |a, b| Internal::Records.replaces?(a.event, b.event) ? -1 : 1 }
179
+ walk.each_with_index do |record, index|
180
+ if record.holds?(time)
181
+ leased = true
182
+ break
183
+ end
184
+ break unless walk[(index + 1)..].any? { |older| older.holds?(time) }
185
+ break if record.signed?
186
+ end
187
+ end
188
+ leased
189
+ end
190
+
191
+ # Whether the lease `own` (an event of the sale) is confirmed by `records`, a complete read of
192
+ # its address's records (SPEC.md §31, "Leasing an address", step 3.3): it is among them, no
193
+ # record of another author holds the address at `t`, and `own` is the newest record of its
194
+ # author there.
195
+ def confirmed?(records, own, time)
196
+ return false unless records.any? { |record| record.event.id == own.id }
197
+ return false if leased?(records.reject { |record| record.event.pubkey == own.pubkey }, time)
198
+
199
+ records.none? do |record|
200
+ record.event.pubkey == own.pubkey && record.event.id != own.id &&
201
+ Internal::Records.replaces?(record.event, own)
202
+ end
203
+ end
204
+
205
+ # The records of the registry at the registry addresses of `addresses`, by address: a complete
206
+ # read on the merchant's `relays`, since LEASE_LOOKBACK before `now` (older leases have
207
+ # ended), with a key of this read alone (leases are signed by sales the integration does not
208
+ # know). Each relay's first copy of an event counts, its signature tried with the other
209
+ # relays' (Record#add_copy).
210
+ def read(pool, registry_key, addresses, relays, now:, random:, stop:, every_relay: false)
211
+ by_d = addresses.to_h { |address| [Addresses.lease_address(registry_key, address), address] }
212
+ found = addresses.to_h { |address| [address, []] }
213
+ return Read.new(records: found, answered: true, complete: true) if addresses.empty?
214
+
215
+ # At a lease's address, by any author: the record each event opens to, as it comes.
216
+ keep = lambda do |value|
217
+ d = Internal::Records.d_tag_of(value)
218
+ d && by_d.key?(d) ? open_record(value, registry_key, d) : nil
219
+ end
220
+ filter = { "kinds" => [Protocol::RECORD_KIND], "#d" => by_d.keys,
221
+ "since" => now - Protocol::LEASE_LOOKBACK_SECONDS }
222
+ result = pool.query_complete(relays, filter, random.call(32), keep: keep, every_relay: every_relay,
223
+ stop: stop)
224
+ # Ids that checked out: another copy of one is the same event, its signature one more to try.
225
+ checked = {}
226
+ result.answers.each_value do |records|
227
+ # A relay's first copy of each id: at most one signature per relay to try.
228
+ of_relay = {}
229
+ records.each do |record|
230
+ id = record.event.id
231
+ next if of_relay.key?(id)
232
+
233
+ of_relay[id] = true
234
+ known = checked[id]
235
+ if known
236
+ known.add_copy(record.event.sig)
237
+ next
238
+ end
239
+ checked[id] = record
240
+ found[by_d[record.d]] << record
241
+ end
242
+ end
243
+ Read.new(records: found, answered: result.answered, complete: result.complete)
244
+ end
245
+
246
+ # The inside of a lease's outside (its `sealed`), opened with the sale's inner key (SPEC.md
247
+ # §31, "Opening it as the sale"): [terms, inside], nil when they are not valid (its tolerance
248
+ # read as 0 when it is absent or not one). Raises Records::Newer for a newer version.
249
+ def open_inside(ending, sealed, d, sale)
250
+ inside = begin
251
+ Json.parse_or(Nip44.decrypt(sealed, sale.inner_key))
252
+ rescue Nip44::Invalid, Nip44::UnknownVersion
253
+ nil
254
+ end
255
+ return nil unless inside.is_a?(Hash)
256
+
257
+ version = inside["version"]
258
+ raise Internal::Records::Newer if Json.number?(version) && version > Protocol::LEASE_VERSION
259
+ return nil unless version == Protocol::LEASE_VERSION
260
+
261
+ terms = terms_of(inside, ending, d, sale)
262
+ terms && [terms, inside]
263
+ end
264
+
265
+ def terms_of(inside, ending, d, sale)
266
+ address, sats, invoice, verify_url, created_at, expires_at =
267
+ inside.values_at("address", "sats", "invoice", "verifyUrl", "createdAt", "expiresAt")
268
+ return nil unless Addresses.deposit?(address) && Addresses.lease_address(sale.registry.key, address) == d
269
+ return nil unless Json.safe_integer?(sats) && sats.to_i.between?(1, Protocol::MAX_SATS)
270
+ return nil unless Json.safe_integer?(created_at) && Json.safe_integer?(expires_at) && created_at < expires_at
271
+ return nil unless ending == expires_at + Protocol::GRACE_SECONDS
272
+ return nil unless lightning_valid?(inside, sats.to_i, created_at, expires_at)
273
+
274
+ sale_value = inside["sale"]
275
+ return nil unless sale_value.is_a?(Hash) && sale_value["key"] == Text.hex(sale.key)
276
+ return nil unless sale_value["note"].is_a?(String)
277
+
278
+ price = Declarations.parse_price(sale_value["fiat"])
279
+ return nil unless price
280
+
281
+ Terms.new(address: address, sats: sats.to_i, invoice: invoice, verify_url: verify_url,
282
+ created_at: created_at.to_i, expires_at: expires_at.to_i, price: price, note: sale_value["note"],
283
+ # Absent (a lease without tolerance) or invalid: none.
284
+ tolerance: Tolerance.of(inside["tolerance"]),
285
+ # Absent, or anything but true: not confirmed.
286
+ confirmed: inside.key?("confirmed") ? inside["confirmed"] == true : nil)
287
+ end
288
+
289
+ # A lease's invoice and verify URL: both null (absent is neither), or a mainnet invoice of
290
+ # exactly `sats`, its timestamp `created_at` and its end `expires_at`, and an https verify
291
+ # URL.
292
+ def lightning_valid?(inside, sats, created_at, expires_at)
293
+ return Json.null_member?(inside, "verifyUrl") if Json.null_member?(inside, "invoice")
294
+
295
+ invoice, verify_url = inside.values_at("invoice", "verifyUrl")
296
+ return false unless Text.well_formed?(invoice) && Urls.https_url(verify_url)
297
+
298
+ decoded = Bolt11.decode(invoice)
299
+ !decoded.nil? && decoded.network == "bc" && decoded.amount_msat == sats * 1000 &&
300
+ decoded.timestamp == created_at && decoded.expires_at == expires_at
301
+ end
302
+
303
+ # What a relay sent, if it is a lease (or a withdrawal) of `sale`: at a registry address (its
304
+ # `d` tag, hex32), signed by the sale, with valid terms inside. A Hash ({kind: :lease, lease:}
305
+ # or {kind: :withdrawn, event:, d:}), nil otherwise; raises Records::Newer for one of a newer
306
+ # format.
307
+ def open_sale_lease(value, sale)
308
+ d = Internal::Records.d_tag_of(value)
309
+ return nil if d.nil? || !value.is_a?(Hash) || value["pubkey"] != sale.author
310
+
311
+ key = Derive.outer_key(sale.registry.key, d, sale.author)
312
+ opened = Internal::Records.open(value, type: Protocol::LEASE_RECORD_TYPE, encryption_key: key, address: d,
313
+ author: sale.author) { |outside, _| parse_outside(outside) }
314
+ return nil unless opened
315
+ raise Internal::Records::Newer if opened.newer?
316
+
317
+ kind, ending, sealed = opened.value
318
+ return { kind: :withdrawn, event: opened.event, d: d } if kind == :withdrawn
319
+
320
+ inside = open_inside(ending, sealed, d, sale)
321
+ inside && { kind: :lease, lease: Opened.new(event: opened.event, d: d, terms: inside[0], inside: inside[1]) }
322
+ end
323
+ end
324
+ end
325
+ end
326
+ end