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,450 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sattleme
4
+ module Checkout
5
+ # The gem's own workings: none of it is API, any of it may change in any version.
6
+ module Internal
7
+ # A wait ended by an internal stop: a read that went on without this relay, a part that is no
8
+ # longer needed. Never escapes a call. An Exception, not a StandardError, so that no
9
+ # `rescue StandardError` takes it for a failure.
10
+ class Stopped < Exception # rubocop:disable Lint/InheritException
11
+ end
12
+
13
+ # How long, once it stopped what a client runs for it (an HTTP request, a WebSocket), the gem
14
+ # waits for that thread to end: a client that stops when it is told (its cancellation, its
15
+ # socket closed), as the gem's own do, has ended by then; one that does not is left behind,
16
+ # never the call.
17
+ STOP_GRACE_SECONDS = 0.5
18
+
19
+ # The monotonic clock, in seconds: every timeout (never the injected `now`, the protocol's
20
+ # dates).
21
+ module Clock
22
+ module_function
23
+
24
+ def now
25
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
26
+ end
27
+
28
+ # Seconds left until `deadline` (nil: no deadline), never below 0.
29
+ def left(deadline)
30
+ deadline && [deadline - now, 0.0].max
31
+ end
32
+ end
33
+
34
+ # What stops a task: the cancellation of its call (the caller's, which makes every wait raise
35
+ # Cancelled), and the stops of the tasks it runs within (which make it raise Stopped). Each
36
+ # wait of the gem watches one; a task's own work ends with #release.
37
+ class Stop
38
+ attr_reader :cancellation
39
+
40
+ def initialize(cancellation, parent = nil)
41
+ @cancellation = cancellation
42
+ @own = Cancellation.new
43
+ @links = []
44
+ link(cancellation)
45
+ link(parent.token) if parent
46
+ end
47
+
48
+ # A stop that stops with this one, and on its own.
49
+ def child
50
+ Stop.new(@cancellation, self)
51
+ end
52
+
53
+ # Stops what waits on it (and its children).
54
+ def stop
55
+ @own.cancel
56
+ release
57
+ end
58
+
59
+ def stopped?
60
+ @own.cancelled?
61
+ end
62
+
63
+ # Whether the call was cancelled (a wait then raises Cancelled).
64
+ def cancelled?
65
+ @cancellation.cancelled?
66
+ end
67
+
68
+ def on_stop(&)
69
+ @own.on_cancel(&)
70
+ end
71
+
72
+ def remove(handle)
73
+ @own.remove(handle)
74
+ end
75
+
76
+ # Runs the block with a Cancellation that is cancelled once this stops (with the call's
77
+ # reason, when the call was cancelled): what code of the integrator's knows of a stop.
78
+ def as_cancellation
79
+ cancellation = Cancellation.new
80
+ handle = on_stop { cancellation.cancel(@cancellation.reason) }
81
+ begin
82
+ yield cancellation
83
+ ensure
84
+ remove(handle)
85
+ end
86
+ end
87
+
88
+ # Raises Cancelled when the call was cancelled, else Stopped.
89
+ def raise!
90
+ raise Cancelled, @cancellation.reason if @cancellation.cancelled?
91
+
92
+ raise Stopped
93
+ end
94
+
95
+ # Raises as #raise! does when it is stopped.
96
+ def check!
97
+ raise! if stopped? || cancelled?
98
+ end
99
+
100
+ # Forgets its links to its parents (its work is done): a long-lived cancellation of the
101
+ # caller never piles up callbacks.
102
+ def release
103
+ links = @links
104
+ @links = []
105
+ links.each { |token, handle| token.remove(handle) }
106
+ end
107
+
108
+ protected
109
+
110
+ def token
111
+ @own
112
+ end
113
+
114
+ private
115
+
116
+ def link(token)
117
+ handle = token.on_cancel { @own.cancel }
118
+ @links << [token, handle] if handle
119
+ end
120
+ end
121
+
122
+ # The threads of one call (SPEC.md §4, §13): every thread the gem starts while the call runs,
123
+ # from any thread of the call (Internal.thread), is one of them, and the call waits for each
124
+ # to end before it returns: once it returned, nothing it started runs on. Only the relays of a
125
+ # publication past its majority (Relay::Pool, the publication's tail) may finish their own
126
+ # request after it, each within its timeout: their threads are no call's.
127
+ class CallThreads
128
+ KEY = :sattleme_checkout_call_threads
129
+ private_constant :KEY
130
+
131
+ # The threads of the call this thread runs for; nil outside a call.
132
+ def self.current
133
+ Thread.current[KEY]
134
+ end
135
+
136
+ # Runs the block for the call whose threads are `threads` (nil: for none).
137
+ def self.within(threads)
138
+ previous = Thread.current[KEY]
139
+ Thread.current[KEY] = threads
140
+ begin
141
+ yield
142
+ ensure
143
+ Thread.current[KEY] = previous
144
+ end
145
+ end
146
+
147
+ def initialize
148
+ @mutex = Mutex.new
149
+ @threads = []
150
+ end
151
+
152
+ def <<(thread)
153
+ @mutex.synchronize { @threads << thread }
154
+ self
155
+ end
156
+
157
+ # Waits until each of its threads ended, those they start meanwhile too.
158
+ def wait
159
+ loop do
160
+ running = @mutex.synchronize { @threads = @threads.select(&:alive?) }
161
+ return if running.empty?
162
+
163
+ running.each { |thread| Internal.join(thread) }
164
+ end
165
+ end
166
+ end
167
+
168
+ # The result of a task running in a thread of its own, settled once: its value or its error,
169
+ # which #value raises in the thread that waits.
170
+ class Future
171
+ # Runs `block` in a new thread (Internal.thread: one of its call's, unless `call` is false);
172
+ # its value, or the exception it raised, settles the future.
173
+ def self.spawn(name = "sattleme-checkout", call: true, &block)
174
+ future = new
175
+ future.thread = Internal.thread(name, call: call) do
176
+ future.fulfill(block.call)
177
+ rescue Exception => e # rubocop:disable Lint/RescueException -- carried to the waiter
178
+ future.reject(e)
179
+ end
180
+ future
181
+ end
182
+
183
+ # A future already settled with `value`.
184
+ def self.resolved(value)
185
+ new.tap { |future| future.fulfill(value) }
186
+ end
187
+
188
+ attr_accessor :thread
189
+
190
+ def initialize
191
+ @mutex = Mutex.new
192
+ @condition = ConditionVariable.new
193
+ @state = :pending
194
+ @result = nil
195
+ @waiters = []
196
+ end
197
+
198
+ def fulfill(value)
199
+ settle(:ok, value)
200
+ end
201
+
202
+ def reject(error)
203
+ settle(:error, error)
204
+ end
205
+
206
+ def settled?
207
+ @mutex.synchronize { @state != :pending }
208
+ end
209
+
210
+ # Waits until it is settled, `deadline` (Clock) passed, or `stop` stopped (then raises as
211
+ # Stop#raise! does): whether it is settled.
212
+ def wait(stop, deadline = nil)
213
+ handle = stop&.on_stop { @mutex.synchronize { @condition.broadcast } }
214
+ @mutex.synchronize do
215
+ while @state == :pending
216
+ stop&.raise! if stop&.stopped?
217
+ left = Clock.left(deadline)
218
+ return false if left&.zero?
219
+
220
+ @condition.wait(@mutex, left)
221
+ end
222
+ true
223
+ end
224
+ ensure
225
+ stop&.remove(handle)
226
+ end
227
+
228
+ # Its value, once settled; raises its error.
229
+ def value(stop)
230
+ wait(stop)
231
+ state, result = outcome
232
+ raise result if state == :error
233
+
234
+ result
235
+ end
236
+
237
+ # [:ok, value] or [:error, error]; nil while pending.
238
+ def outcome
239
+ @mutex.synchronize { @state == :pending ? nil : [@state, @result] }
240
+ end
241
+
242
+ # Calls `block` with the outcome once settled (at once when it is), in the settling thread.
243
+ def on_settle(&block)
244
+ now = @mutex.synchronize do
245
+ next true unless @state == :pending
246
+
247
+ @waiters << block
248
+ false
249
+ end
250
+ block.call(*outcome) if now
251
+ end
252
+
253
+ private
254
+
255
+ # Settles it once: a later outcome is dropped.
256
+ def settle(state, result)
257
+ waiters = @mutex.synchronize do
258
+ next [] unless @state == :pending
259
+
260
+ @state = state
261
+ @result = result
262
+ @condition.broadcast
263
+ @waiters.tap { @waiters = [] }
264
+ end
265
+ waiters.each { |waiter| waiter.call(state, result) }
266
+ nil
267
+ end
268
+ end
269
+
270
+ # A queue of messages between threads, popped with a deadline and a stop.
271
+ class Inbox
272
+ # Pushed when a stop wakes the waiter.
273
+ WAKE = Object.new.freeze
274
+ # What #pop gives when the deadline passed.
275
+ TIMEOUT = Object.new.freeze
276
+
277
+ def initialize
278
+ @queue = Thread::Queue.new
279
+ end
280
+
281
+ def push(message)
282
+ @queue << message
283
+ end
284
+ alias << push
285
+
286
+ # The next message; TIMEOUT once `deadline` (Clock, nil: none) passed; raises as Stop#raise!
287
+ # does once `stop` stopped (nil: none).
288
+ def pop(stop, deadline = nil)
289
+ handle = stop&.on_stop { @queue << WAKE }
290
+ loop do
291
+ stop&.raise! if stop&.stopped?
292
+ left = Clock.left(deadline)
293
+ return TIMEOUT if left&.zero?
294
+
295
+ message = @queue.pop(timeout: left)
296
+ return TIMEOUT if message.nil? && deadline
297
+ next if message.equal?(WAKE) || message.nil?
298
+
299
+ return message
300
+ end
301
+ ensure
302
+ stop&.remove(handle)
303
+ end
304
+ end
305
+
306
+ # One holder at a time per key (an order's reference…), within one client; the wait for it
307
+ # ends with the caller's cancellation.
308
+ class KeyedLocks
309
+ def initialize
310
+ @mutex = Mutex.new
311
+ @condition = ConditionVariable.new
312
+ @held = {}
313
+ end
314
+
315
+ # Runs `block` holding the lock of `key`.
316
+ def synchronize(key, stop)
317
+ acquire(key, stop)
318
+ begin
319
+ yield
320
+ ensure
321
+ release(key)
322
+ end
323
+ end
324
+
325
+ private
326
+
327
+ def acquire(key, stop)
328
+ handle = stop.on_stop { @mutex.synchronize { @condition.broadcast } }
329
+ @mutex.synchronize do
330
+ while @held.key?(key)
331
+ stop.raise! if stop.stopped?
332
+ @condition.wait(@mutex)
333
+ end
334
+ stop.raise! if stop.stopped?
335
+ @held[key] = true
336
+ end
337
+ ensure
338
+ stop.remove(handle)
339
+ end
340
+
341
+ def release(key)
342
+ @mutex.synchronize do
343
+ @held.delete(key)
344
+ @condition.broadcast
345
+ end
346
+ end
347
+ end
348
+
349
+ # The outcome of a part (SPEC.md §31: a part that fails is its error, never the check's): its
350
+ # value, or the error it failed with.
351
+ Settled = Data.define(:value, :error) do
352
+ def self.ok(value) = new(value: value, error: nil)
353
+ def self.failed(error) = new(value: nil, error: error)
354
+ def ok? = error.nil?
355
+ end
356
+
357
+ module_function
358
+
359
+ # Runs `block` in a thread named `name`: a thread of the call this thread runs for
360
+ # (CallThreads), which waits for it to end before it returns; with `call` false, of no call
361
+ # (one whose end is waited for otherwise, or a publication's tail), nor are the threads it
362
+ # starts.
363
+ def thread(name, call: true, &block)
364
+ threads = call ? CallThreads.current : nil
365
+ thread = Thread.new { CallThreads.within(threads, &block) }
366
+ thread.name = name
367
+ thread.report_on_exception = false
368
+ threads&.<<(thread)
369
+ thread
370
+ end
371
+
372
+ # Waits until `thread` ended, `seconds` at most (nil: for as long as it runs); what it raised
373
+ # is for whoever waits for its outcome, never for this.
374
+ def join(thread, seconds = nil)
375
+ thread.join(seconds)
376
+ rescue Exception # rubocop:disable Lint/RescueException -- its outcome is not the joiner's
377
+ nil
378
+ end
379
+
380
+ # The outcome of `future`, waited for with `stop`, as a Settled; a cancellation (Cancelled) or
381
+ # an internal stop (Stopped) is raised, never settled.
382
+ def settle(future, stop)
383
+ future.wait(stop)
384
+ state, result = future.outcome
385
+ return Settled.ok(result) if state == :ok
386
+ raise result if result.is_a?(Cancelled) || result.is_a?(Stopped)
387
+
388
+ Settled.failed(result)
389
+ end
390
+
391
+ # Runs `block` in a thread of its own, its outcome settled: the Future of a Settled.
392
+ def settled(name = "sattleme-checkout part", &block)
393
+ Future.spawn(name) do
394
+ Settled.ok(block.call)
395
+ rescue Cancelled, Stopped
396
+ raise
397
+ rescue StandardError => e
398
+ Settled.failed(e)
399
+ end
400
+ end
401
+
402
+ # The values of `futures`, as Promise.all gives them: raises the first error (the first in
403
+ # time), as soon as one fails.
404
+ def all(futures, stop)
405
+ inbox = Inbox.new
406
+ futures.each_with_index do |future, index|
407
+ future.on_settle { |state, result| inbox << [index, state, result] }
408
+ end
409
+ values = Array.new(futures.size)
410
+ futures.size.times do
411
+ index, state, result = inbox.pop(stop)
412
+ raise result if state == :error
413
+
414
+ values[index] = result
415
+ end
416
+ values
417
+ end
418
+
419
+ # The results of `futures`, each waited for with `stop`: [:ok, value] or [:error, error].
420
+ def settle_all(futures, stop)
421
+ futures.map do |future|
422
+ future.wait(stop)
423
+ future.outcome
424
+ end
425
+ end
426
+
427
+ # `run` on each of `items`, `limit` at a time, each in a thread: their outcomes, in order.
428
+ def settle_each(items, limit, stop, &run)
429
+ outcomes = Array.new(items.size)
430
+ queue = Thread::Queue.new
431
+ items.each_with_index { |item, index| queue << [item, index] }
432
+ queue.close
433
+ workers = Array.new([limit, items.size].min) do
434
+ Future.spawn("sattleme-checkout check") do
435
+ while (job = queue.pop)
436
+ item, index = job
437
+ outcomes[index] = begin
438
+ [:ok, run.call(item)]
439
+ rescue StandardError, Cancelled => e
440
+ [:error, e]
441
+ end
442
+ end
443
+ end
444
+ end
445
+ workers.each { |worker| worker.value(stop) }
446
+ outcomes
447
+ end
448
+ end
449
+ end
450
+ end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+
5
+ module Sattleme
6
+ module Checkout
7
+ module Internal
8
+ # SHA-256, HMAC-SHA256, HKDF-SHA256 (RFC 5869) and ChaCha20 (RFC 8439), from OpenSSL (Ruby's
9
+ # standard library): SPEC.md §2, §10, §12.
10
+ module Crypto
11
+ module_function
12
+
13
+ def sha256(data)
14
+ OpenSSL::Digest.digest("SHA256", data)
15
+ end
16
+
17
+ def hmac(key, data)
18
+ OpenSSL::HMAC.digest("SHA256", key, data)
19
+ end
20
+
21
+ # HKDF-SHA256 of `secret` with `salt` and `info` (texts, as their UTF-8), `length` bytes.
22
+ def hkdf(secret, salt, info, length = 32)
23
+ OpenSSL::KDF.hkdf(secret, salt: salt.b, info: info.b, length: length, hash: "SHA256")
24
+ end
25
+
26
+ # HKDF-Extract (RFC 5869 §2.2).
27
+ def hkdf_extract(salt, secret)
28
+ hmac(salt.b, secret)
29
+ end
30
+
31
+ # HKDF-Expand (RFC 5869 §2.3) of the pseudorandom key `prk`.
32
+ def hkdf_expand(prk, info, length)
33
+ out = "".b
34
+ block = "".b
35
+ counter = 1
36
+ while out.bytesize < length
37
+ block = hmac(prk, block + info.b + counter.chr)
38
+ out << block
39
+ counter += 1
40
+ end
41
+ out.byteslice(0, length)
42
+ end
43
+
44
+ # ChaCha20 of `data` with the 32-byte `key` and the 12-byte `nonce`, its block counter
45
+ # from 0. OpenSSL's IV is the counter (32 bits, little-endian), then the nonce.
46
+ def chacha20(key, nonce, data)
47
+ cipher = OpenSSL::Cipher.new("chacha20")
48
+ cipher.encrypt
49
+ cipher.key = key
50
+ cipher.iv = "\x00\x00\x00\x00".b + nonce
51
+ return "".b if data.empty?
52
+
53
+ cipher.update(data) + cipher.final
54
+ end
55
+
56
+ # Whether `a` and `b` are the same bytes, compared in constant time.
57
+ def same?(a, b)
58
+ a.bytesize == b.bytesize && OpenSSL.fixed_length_secure_compare(a, b)
59
+ end
60
+ end
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sattleme
4
+ module Checkout
5
+ module Internal
6
+ # The currencies an order may be priced in, with their decimals (SPEC.md §25): ISO 4217 List
7
+ # One (SIX Group, published 2026-09-17), without funds codes, precious metals, SDR, test and
8
+ # "no currency" codes; the decimals those the merchant's app uses (CLDR, through ECMAScript
9
+ # Intl), which the app compares with a sale's declared decimals, leaving out the sales that
10
+ # differ: ISO 4217 gives 13 of them other decimals (AFN, ALL, IQD, IRR, KPW, LAK, LBP, MGA,
11
+ # MMK, RSD, SOS, SYP, YER, where the app uses 0). The table of spec/currencies.json (a test
12
+ # checks it): every implementation uses it, never its platform's locale data.
13
+ module Currencies
14
+ DIGITS = {
15
+ "AED" => 2, "AFN" => 0, "ALL" => 0, "AMD" => 2, "AOA" => 2, "ARS" => 2, "AUD" => 2, "AWG" => 2,
16
+ "AZN" => 2, "BAM" => 2, "BBD" => 2, "BDT" => 2, "BHD" => 3, "BIF" => 0, "BMD" => 2, "BND" => 2,
17
+ "BOB" => 2, "BRL" => 2, "BSD" => 2, "BTN" => 2, "BWP" => 2, "BYN" => 2, "BZD" => 2, "CAD" => 2,
18
+ "CDF" => 2, "CHF" => 2, "CLP" => 0, "CNY" => 2, "COP" => 2, "CRC" => 2, "CUP" => 2, "CVE" => 2,
19
+ "CZK" => 2, "DJF" => 0, "DKK" => 2, "DOP" => 2, "DZD" => 2, "EGP" => 2, "ERN" => 2, "ETB" => 2,
20
+ "EUR" => 2, "FJD" => 2, "FKP" => 2, "GBP" => 2, "GEL" => 2, "GHS" => 2, "GIP" => 2, "GMD" => 2,
21
+ "GNF" => 0, "GTQ" => 2, "GYD" => 2, "HKD" => 2, "HNL" => 2, "HTG" => 2, "HUF" => 2, "IDR" => 2,
22
+ "ILS" => 2, "INR" => 2, "IQD" => 0, "IRR" => 0, "ISK" => 0, "JMD" => 2, "JOD" => 3, "JPY" => 0,
23
+ "KES" => 2, "KGS" => 2, "KHR" => 2, "KMF" => 0, "KPW" => 0, "KRW" => 0, "KWD" => 3, "KYD" => 2,
24
+ "KZT" => 2, "LAK" => 0, "LBP" => 0, "LKR" => 2, "LRD" => 2, "LSL" => 2, "LYD" => 3, "MAD" => 2,
25
+ "MDL" => 2, "MGA" => 0, "MKD" => 2, "MMK" => 0, "MNT" => 2, "MOP" => 2, "MRU" => 2, "MUR" => 2,
26
+ "MVR" => 2, "MWK" => 2, "MXN" => 2, "MYR" => 2, "MZN" => 2, "NAD" => 2, "NGN" => 2, "NIO" => 2,
27
+ "NOK" => 2, "NPR" => 2, "NZD" => 2, "OMR" => 3, "PAB" => 2, "PEN" => 2, "PGK" => 2, "PHP" => 2,
28
+ "PKR" => 2, "PLN" => 2, "PYG" => 0, "QAR" => 2, "RON" => 2, "RSD" => 0, "RUB" => 2, "RWF" => 0,
29
+ "SAR" => 2, "SBD" => 2, "SCR" => 2, "SDG" => 2, "SEK" => 2, "SGD" => 2, "SHP" => 2, "SLE" => 2,
30
+ "SOS" => 0, "SRD" => 2, "SSP" => 2, "STN" => 2, "SVC" => 2, "SYP" => 0, "SZL" => 2, "THB" => 2,
31
+ "TJS" => 2, "TMT" => 2, "TND" => 3, "TOP" => 2, "TRY" => 2, "TTD" => 2, "TWD" => 2, "TZS" => 2,
32
+ "UAH" => 2, "UGX" => 0, "USD" => 2, "UYU" => 2, "UZS" => 2, "VED" => 2, "VES" => 2, "VND" => 0,
33
+ "VUV" => 0, "WST" => 2, "XAF" => 0, "XCD" => 2, "XCG" => 2, "XOF" => 0, "XPF" => 0, "YER" => 0,
34
+ "ZAR" => 2, "ZMW" => 2, "ZWG" => 2
35
+ }.freeze
36
+
37
+ module_function
38
+
39
+ # The decimals of the currency `code` (ISO 4217, upper case), nil for a code that is not
40
+ # one of the table's.
41
+ def digits(code)
42
+ code.is_a?(String) ? DIGITS[code] : nil
43
+ end
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,135 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sattleme
4
+ module Checkout
5
+ module Internal
6
+ # The declaration of an invoice in the merchant's registry of payments (SPEC.md §20), as the
7
+ # merchant's app reads it: published on a majority of the merchant's relays before the invoice
8
+ # is shown, so that its payment counts for this order's sale and for no other. Its format is
9
+ # the app's, version 1: changing it needs a new version there first, but for an optional field
10
+ # the app ignores (as `taker`): `rest`, in a rest invoice's.
11
+ module Declarations
12
+ # The invoice an invoice of the rest is of: its deposit address and its end (Unix seconds).
13
+ RestOf = Data.define(:address, :expires_at)
14
+
15
+ # A declaration of the sale, opened by its holder: `price` as the declaration holds it
16
+ # ({"minor", "digits", "currency"}), `declared_at` its event's `created_at`, `rest` the
17
+ # invoice whose rest it is (nil for an invoice of the order).
18
+ Opened = Data.define(:event, :invoice, :decoded, :verify_url, :price, :note, :declared_at, :rest)
19
+
20
+ module_function
21
+
22
+ # The price a sale is declared with, as the declaration's JSON holds it: `minor` a JSON
23
+ # number (at most 2^53 − 1); for a sale in sats, `{minor: <sats>, digits: 0, currency: SAT}`.
24
+ def price(minor:, digits:, currency:)
25
+ { "minor" => minor, "digits" => digits, "currency" => currency }
26
+ end
27
+
28
+ # The price of an order: its Fiat's, else its sats.
29
+ def price_of(fiat, sats)
30
+ return price(minor: sats, digits: 0, currency: Protocol::SATS_CURRENCY) if fiat.nil?
31
+
32
+ price(minor: Integer(fiat.minor, 10), digits: fiat.digits, currency: fiat.currency)
33
+ end
34
+
35
+ # The signed declaration of an invoice for `sale`: the declaration (inside, NIP-44 with the
36
+ # ECDH conversation key of the sale's secret and the merchant's reading key), then
37
+ # `{"t": "registry-declaration", "v": {"sealed": …}}` padded to a multiple of 256 bytes
38
+ # (outside, NIP-44 with the outer key), kind 30078, `d` the registry address, signed by the
39
+ # sale's secret. Nip44::TooLong when it does not fit a NIP-44 plaintext.
40
+ def event(sale:, invoice:, verify_url:, payment_hash:, price:, note:, created_at:, random:, rest: nil)
41
+ declaration = { "version" => Protocol::DECLARATION_VERSION, "invoice" => invoice, "verifyUrl" => verify_url,
42
+ "sale" => { "key" => Text.hex(sale.key), "fiat" => price, "note" => note },
43
+ # "By" in the app: this integration.
44
+ "taker" => sale.taker }
45
+ # Only in a rest invoice's: the app ignores it, and counts the payment for the sale.
46
+ declaration["rest"] = { "address" => rest.address, "expiresAt" => rest.expires_at } if rest
47
+ address = Derive.registry_address(sale.registry.key, payment_hash)
48
+ sealed = Nip44.encrypt(Json.generate(declaration), sale.inner_key, random)
49
+ Records.seal(type: Protocol::DECLARATION_RECORD_TYPE, value: { "sealed" => sealed }, signer: sale.secret_key,
50
+ encryption_key: Derive.outer_key(sale.registry.key, address, sale.author), address: address,
51
+ created_at: created_at, random: random)
52
+ end
53
+
54
+ # A declared price, checked: `minor` a safe integer from 0, `digits` 0 to 8, `currency` three
55
+ # letters A–Z. Nil when it is not one.
56
+ def parse_price(value)
57
+ return nil unless value.is_a?(Hash)
58
+
59
+ minor, digits, currency = value.values_at("minor", "digits", "currency")
60
+ return nil unless Json.safe_integer?(minor) && minor >= 0
61
+ return nil unless Json.integer?(digits) && digits.between?(0, Protocol::MAX_DECLARED_DIGITS)
62
+ return nil unless Text.match?(currency, /\A[A-Z]{3}\z/)
63
+
64
+ price(minor: minor.to_i, digits: digits.to_i, currency: currency)
65
+ end
66
+
67
+ # A declaration's `rest`: absent (nil), or the invoice it names; Order::ABSENT when invalid.
68
+ def rest_of(value, present)
69
+ return nil unless present
70
+ return Order::ABSENT unless value.is_a?(Hash)
71
+
72
+ address, expires_at = value.values_at("address", "expiresAt")
73
+ return Order::ABSENT unless Addresses.deposit?(address) && Json.safe_integer?(expires_at) && expires_at >= 0
74
+
75
+ RestOf.new(address: address, expires_at: expires_at.to_i)
76
+ end
77
+
78
+ # What a relay sent, if it is a declaration of `sale`: author, `d` tag (the address of its
79
+ # own invoice), outer and inner encryption, signature, and the sale's own key inside. Nil
80
+ # otherwise; raises Records::Newer for one of a newer format.
81
+ def open(value, sale)
82
+ d = Records.d_tag_of(value)
83
+ return nil if d.nil?
84
+
85
+ opened = Records.open(value, type: Protocol::DECLARATION_RECORD_TYPE,
86
+ encryption_key: Derive.outer_key(sale.registry.key, d, sale.author),
87
+ address: d, author: sale.author) do |outside, event|
88
+ parse(outside, event, sale, d)
89
+ end
90
+ raise Records::Newer if opened&.newer?
91
+
92
+ opened&.value
93
+ end
94
+
95
+ def parse(outside, event, sale, d)
96
+ sealed = outside.is_a?(Hash) ? outside["sealed"] : nil
97
+ return nil unless sealed.is_a?(String)
98
+
99
+ inside = inside_of(sealed, sale)
100
+ return nil unless inside.is_a?(Hash)
101
+
102
+ version = inside["version"]
103
+ raise Records::Newer if Json.number?(version) && version > Protocol::DECLARATION_VERSION
104
+ return nil unless version == Protocol::DECLARATION_VERSION && inside["invoice"].is_a?(String)
105
+ return nil unless Urls.https_url(inside["verifyUrl"])
106
+
107
+ sale_value = inside["sale"]
108
+ return nil unless sale_value.is_a?(Hash) && sale_value["key"] == Text.hex(sale.key)
109
+ return nil unless sale_value["note"].is_a?(String)
110
+
111
+ price = parse_price(sale_value["fiat"])
112
+ return nil unless price
113
+
114
+ rest = rest_of(inside["rest"], inside.key?("rest"))
115
+ return nil if rest.equal?(Order::ABSENT)
116
+
117
+ decoded = Text.well_formed?(inside["invoice"]) ? Bolt11.decode(inside["invoice"]) : nil
118
+ return nil unless decoded && decoded.network == "bc" && decoded.amount_msat
119
+ return nil unless decoded.amount_msat.positive? && (decoded.amount_msat % 1000).zero?
120
+ return nil unless d == Derive.registry_address(sale.registry.key, decoded.payment_hash)
121
+
122
+ Opened.new(event: event, invoice: inside["invoice"], decoded: decoded, verify_url: inside["verifyUrl"],
123
+ price: price, note: sale_value["note"], declared_at: event.created_at, rest: rest)
124
+ end
125
+
126
+ # The JSON inside a declaration's `sealed`, nil when it does not open or is not JSON.
127
+ def inside_of(sealed, sale)
128
+ Json.parse_or(Nip44.decrypt(sealed, sale.inner_key))
129
+ rescue Nip44::Invalid, Nip44::UnknownVersion
130
+ nil
131
+ end
132
+ end
133
+ end
134
+ end
135
+ end