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,119 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sattleme
4
+ module Checkout
5
+ module Internal
6
+ # The explorer's WebSocket (SPEC.md §31, "Waiting for an on-chain payment"): while
7
+ # wait_for_payment waits, the explorer (mempool.space, or the merchant's Bitcoin node) pushes
8
+ # what changes for the address (a transaction entering the mempool, confirmed, or leaving it)
9
+ # and each new block (one more confirmation).
10
+ # Only a signal to check the on-chain part again: what it pushes is never trusted, the check
11
+ # asks the explorer.
12
+ class Watch
13
+ # The messages that say something changed for the address, or for its confirmations.
14
+ CHANGES = %w[address-transactions block-transactions address-removed-transactions block].freeze
15
+
16
+ # Watches `address` on the explorer's WebSocket (through `websocket`, the handshake bounded
17
+ # by `timeout` seconds) until #close, in a thread of its own: `on_change` is called (in that
18
+ # thread: quick) at each connection (what happened before was not pushed) and at each
19
+ # message about the address or a new block. Each connection tries the WebSockets of
20
+ # `explorer`'s sources in order (CallExplorer#sources): one that fails, or is lost before
21
+ # any message, goes to the next at once (the node's to mempool.space's with `fallback`
22
+ # "mempool", SPEC.md §31), a node's failure told to `explorer` (CallExplorer#node_failed).
23
+ # A lost socket connects again after 1 s, doubled at each failure (of the last one tried)
24
+ # up to 30 s; a connection lost before it received a message is a failure, so that a server
25
+ # that accepts and drops each connection (each one starts a check) is connected to less and
26
+ # less often. `wait` (seconds → whether it was closed meanwhile) waits between two
27
+ # connections: for tests.
28
+ def initialize(websocket, explorer, address, timeout, wait: nil, &on_change)
29
+ @websocket = websocket
30
+ @explorer = explorer
31
+ @address = address
32
+ @timeout = timeout
33
+ @on_change = on_change
34
+ @closed = Cancellation.new
35
+ @wait = wait || ->(seconds) { @closed.wait(seconds) }
36
+ @mutex = Mutex.new
37
+ @socket = nil
38
+ @thread = Thread.new { run }
39
+ @thread.name = "sattleme-checkout explorer socket"
40
+ @thread.report_on_exception = false
41
+ end
42
+
43
+ # Closes the socket, for good, and waits until the thread ended (STOP_GRACE_SECONDS at most:
44
+ # a WebSocket client of the integrator's may not stop when it is told).
45
+ def close
46
+ @closed.cancel
47
+ socket = @mutex.synchronize { @socket.tap { @socket = nil } }
48
+ begin
49
+ socket&.close
50
+ rescue StandardError
51
+ nil
52
+ end
53
+ Internal.join(@thread, STOP_GRACE_SECONDS)
54
+ nil
55
+ end
56
+
57
+ private
58
+
59
+ def run
60
+ delay = Protocol::RECONNECT_FIRST_MS
61
+ until @closed.cancelled?
62
+ # The explorer answered: the next loss waits 1 s again.
63
+ delay = Protocol::RECONNECT_FIRST_MS if heard_from_sources?
64
+ break if @closed.cancelled? || @wait.call(delay / 1000.0)
65
+
66
+ delay = [delay * 2, Protocol::RECONNECT_MAX_MS].min
67
+ end
68
+ end
69
+
70
+ # One connection to each of the explorer's sources in turn, until one received a message
71
+ # (then lost) or every one failed: whether one received a message.
72
+ def heard_from_sources?
73
+ @explorer.sources.each do |source|
74
+ return false if @closed.cancelled?
75
+ return true if watch_once(source)
76
+
77
+ # Failed, or lost before any message: the next one at once.
78
+ @explorer.node_failed if source.node? && !@closed.cancelled?
79
+ end
80
+ false
81
+ end
82
+
83
+ # One connection to `source`'s WebSocket, until it is lost: whether it received a message.
84
+ def watch_once(source)
85
+ heard = false
86
+ socket = @websocket.connect(source.web_socket,
87
+ timeout: @timeout, headers: { "User-Agent" => Protocol::USER_AGENT },
88
+ cancellation: @closed)
89
+ kept = @mutex.synchronize { @closed.cancelled? ? false : (@socket = socket) }
90
+ return false unless kept
91
+
92
+ begin
93
+ socket.send_text(Json.generate({ "action" => "want", "data" => ["blocks"] }))
94
+ socket.send_text(Json.generate({ "track-address" => @address }))
95
+ rescue StandardError
96
+ return false
97
+ end
98
+ @on_change.call
99
+ while (text = socket.receive)
100
+ heard = true
101
+ text = Text.decode_utf8(text) unless Text.well_formed?(text)
102
+ message = text && Json.parse_or(text)
103
+ @on_change.call if message.is_a?(Hash) && CHANGES.any? { |key| message.key?(key) }
104
+ end
105
+ heard
106
+ rescue StandardError
107
+ heard
108
+ ensure
109
+ @mutex.synchronize { @socket = nil if @socket.equal?(socket) }
110
+ begin
111
+ socket&.close
112
+ rescue StandardError
113
+ nil
114
+ end
115
+ end
116
+ end
117
+ end
118
+ end
119
+ end
@@ -0,0 +1,260 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sattleme
4
+ module Checkout
5
+ module Internal
6
+ # Witnesses (SPEC.md §31, "Witnesses"): the integration records each transaction it sees
7
+ # paying an address of its lot, and when: during the lease of an order (that order's sale), or
8
+ # at no lease's time (`none`). So that every reader, the merchant's app included, tells the
9
+ # same order paid. Only the integration writes them (signed by its seen secret, sealed with
10
+ # its channel's key); the merchant's app reads them to attribute deposits and to take paid
11
+ # addresses out of the lot.
12
+ module Witnesses
13
+ COIN = /\A[0-9a-f]{64}:(?:0|[1-9][0-9]{0,9})\z/
14
+
15
+ # What a witness says: the sale author (hex), or nil (none); what `txid` pays `address`; the
16
+ # coins `txid` spends (its first 100, in their order); whether it holds `txid` for the sale
17
+ # only as a replacement of payments in time; the `expires_at` of the invoice whose lease it
18
+ # came in (or stands for), nil for none.
19
+ Witness = Data.define(:address, :txid, :sale, :sats, :inputs, :replacement, :expires_at)
20
+
21
+ # A witness a relay sent, opened: :ok with its witness, or :newer (authentic, of a newer
22
+ # format: what it names cannot be read, its `d` tag can).
23
+ Opened = Data.define(:status, :event, :witness, :d)
24
+
25
+ # A witness of the order's sale, as a check uses it: `seen_at` its `created_at`.
26
+ SaleWitness = Data.define(:sats, :inputs, :replacement, :seen_at)
27
+
28
+ # The witnesses of an invoice: of this invoice (its sale and its `expires_at`), by txid; of
29
+ # other invoices (another sale, or another `expires_at` of its sale), by txid: what they name
30
+ # counts for nothing here; the txids a witness none names; the witness addresses (`d` tags)
31
+ # of the witnesses of a newer format.
32
+ OfOrder = Data.define(:sale, :others, :none, :newer)
33
+
34
+ NONE = OfOrder.new(sale: {}.freeze, others: {}.freeze, none: {}.freeze, newer: {}.freeze)
35
+
36
+ module_function
37
+
38
+ def mac(key, text)
39
+ Text.hex(Crypto.hmac(key, text.b))
40
+ end
41
+
42
+ # Where the witness of `txid` paying `address` for `sale` (a sale author, or nil: none) is.
43
+ def witness_address(address_key, address, txid, sale)
44
+ mac(address_key, "#{address}/#{txid}/#{sale || Protocol::NO_SALE}")
45
+ end
46
+
47
+ # The `o` tag of the witnesses of `address` for `sale` (nil: none): how a check reads them.
48
+ def order_tag(address_key, address, sale)
49
+ mac(address_key, "order/#{address}/#{sale || Protocol::NO_SALE}")
50
+ end
51
+
52
+ # The address tag of `address`: a witness's second `o` tag, which finds every witness of the
53
+ # address, whatever its sale.
54
+ def address_tag(address_key, address)
55
+ mac(address_key, "address/#{address}")
56
+ end
57
+
58
+ # A coin, as a witness writes it: `<txid>:<vout>`, the vout a u32 in decimal without leading
59
+ # zeros.
60
+ def coin?(value)
61
+ Text.match?(value, COIN) && Integer(value[65..], 10) <= Explorer::MAX_VOUT
62
+ end
63
+
64
+ # The signed event of a witness, `created_at` when it was seen.
65
+ def event(seen, witness, created_at, random)
66
+ Internal::Records.seal(
67
+ type: Protocol::WITNESS_RECORD_TYPE,
68
+ value: { "version" => Protocol::WITNESS_VERSION, "address" => witness.address, "txid" => witness.txid,
69
+ "sale" => witness.sale, "sats" => witness.sats,
70
+ "inputs" => witness.inputs.first(Protocol::MAX_WITNESS_INPUTS),
71
+ "replacement" => witness.replacement,
72
+ "expiresAt" => witness.sale.nil? ? nil : witness.expires_at },
73
+ signer: seen.secret_key, encryption_key: seen.encryption_key,
74
+ address: witness_address(seen.address_key, witness.address, witness.txid, witness.sale),
75
+ created_at: created_at, random: random,
76
+ tags: [[Protocol::ORDER_TAG, order_tag(seen.address_key, witness.address, witness.sale)],
77
+ [Protocol::ORDER_TAG, address_tag(seen.address_key, witness.address)]]
78
+ )
79
+ end
80
+
81
+ # A witness's value, checked against its event's tags: its `d` tag is the witness address of
82
+ # what it names, an `o` tag its order tag and an `o` tag its address's tag. Nil when it is not
83
+ # valid; raises Records::Newer for a newer version.
84
+ def parse(value, event, address_key)
85
+ return nil unless value.is_a?(Hash)
86
+
87
+ version = value["version"]
88
+ raise Internal::Records::Newer if Json.number?(version) && version > Protocol::WITNESS_VERSION
89
+ return nil unless version == Protocol::WITNESS_VERSION
90
+
91
+ address, txid, sale, sats, inputs, replacement = value.values_at("address", "txid", "sale", "sats", "inputs",
92
+ "replacement")
93
+ # `sale` null for none (absent is neither), else hex32.
94
+ return nil unless value.key?("sale") && (sale.nil? || Text.hex32?(sale))
95
+ return nil unless Addresses.deposit?(address) && Text.hex32?(txid)
96
+ return nil unless Json.safe_integer?(sats) && sats.to_i.between?(1, Protocol::MAX_SATS)
97
+ return nil unless inputs?(inputs)
98
+ return nil unless [true, false].include?(replacement) && !(sale.nil? && replacement)
99
+
100
+ # Null for none, the invoice's end for a sale; absent, it is no witness.
101
+ expires_at = value.key?("expiresAt") ? value["expiresAt"] : Order::ABSENT
102
+ return nil unless sale.nil? ? expires_at.nil? : Json.safe_integer?(expires_at)
103
+ return nil unless tagged?(event, address_key, address, txid, sale)
104
+
105
+ Witness.new(address: address, txid: txid, sale: sale, sats: sats.to_i, inputs: inputs.dup,
106
+ replacement: replacement, expires_at: sale.nil? ? nil : expires_at.to_i)
107
+ end
108
+
109
+ def inputs?(inputs)
110
+ inputs.is_a?(Array) && inputs.size <= Protocol::MAX_WITNESS_INPUTS && inputs.all? { |coin| coin?(coin) } &&
111
+ inputs.uniq.size == inputs.size
112
+ end
113
+
114
+ def tagged?(event, address_key, address, txid, sale)
115
+ d = event.tags.find { |tag| tag[0] == "d" }&.[](1)
116
+ o_tags = event.tags.filter_map { |tag| tag[1] if tag[0] == Protocol::ORDER_TAG }
117
+ d == witness_address(address_key, address, txid, sale) &&
118
+ o_tags.include?(order_tag(address_key, address, sale)) && o_tags.include?(address_tag(address_key, address))
119
+ end
120
+
121
+ # What a relay sent, if it is a witness of this integration; nil otherwise.
122
+ def open(value, seen)
123
+ d = Internal::Records.d_tag_of(value)
124
+ return nil if d.nil?
125
+
126
+ opened = Internal::Records.open(value, type: Protocol::WITNESS_RECORD_TYPE,
127
+ encryption_key: seen.encryption_key, address: d,
128
+ author: seen.author) do |witness, event|
129
+ parse(witness, event, seen.address_key)
130
+ end
131
+ return nil unless opened
132
+ return Opened.new(status: :newer, event: opened.event, witness: nil, d: d) if opened.newer?
133
+
134
+ Opened.new(status: :ok, event: opened.event, witness: opened.value, d: d)
135
+ end
136
+
137
+ # The `o` tags of the read of an invoice's witnesses: of the sale, of none, of the address.
138
+ def read_tags(seen, address, sale_author)
139
+ [order_tag(seen.address_key, address, sale_author), order_tag(seen.address_key, address, nil),
140
+ address_tag(seen.address_key, address)]
141
+ end
142
+
143
+ # The witnesses of the invoice with the address `address` and the end `expires_at`, for the
144
+ # sale `sale_author`: read on the merchant's `relays` by their order tags (of the sale and of
145
+ # none) and the address tag (every sale's), as soon as a majority answered (or on every
146
+ # relay), with a key of this read alone. NetworkError when fewer than a majority answered.
147
+ def read_of_order(pool, seen, address, sale_author, expires_at, relays, random:, stop:, every_relay: false)
148
+ filter = { "kinds" => [Protocol::RECORD_KIND], "authors" => [seen.author],
149
+ "#o" => read_tags(seen, address, sale_author) }
150
+ keep = Internal::Records.that_open { |_, author| author == seen.author ? seen.encryption_key : nil }
151
+ result = pool.query_relays(relays, filter, random.call(32),
152
+ paged: false, every_relay: every_relay, stop: stop, keep: keep)
153
+ raise NetworkError, "Fewer than a majority of the merchant's relays answered" unless result.answered
154
+
155
+ of_order(result.answers.values.flatten(1), seen, address, sale_author, expires_at)
156
+ end
157
+
158
+ # The witnesses of the invoice with the address `address` and the end `expires_at`, for the
159
+ # sale `sale_author`, from what the relays sent to its read: of each witness address, the
160
+ # newest event that opens (one of a newer format, its event checked, is kept as such). A
161
+ # witness that holds none of the read's `o` tags, or whose `address` is not `address`, is of
162
+ # no invoice of this read and is ignored, of a newer format or not.
163
+ def of_order(events, seen, address, sale_author, expires_at)
164
+ tags = read_tags(seen, address, sale_author)
165
+ newest = {}
166
+ checked = {}
167
+ events.each do |value|
168
+ next if value.is_a?(Hash) && value["id"].is_a?(String) && checked.key?(value["id"])
169
+
170
+ opened = Witnesses.open(value, seen)
171
+ next unless opened
172
+
173
+ checked[opened.event.id] = true
174
+ next unless opened.event.tags.any? { |tag| tag[0] == Protocol::ORDER_TAG && tags.include?(tag[1]) }
175
+ next if opened.status == :ok && opened.witness.address != address
176
+
177
+ known = newest[opened.d]
178
+ newest[opened.d] = opened if known.nil? || Internal::Records.replaces?(opened.event, known.event)
179
+ end
180
+ witnesses = OfOrder.new(sale: {}, others: {}, none: {}, newer: {})
181
+ newest.each do |d, opened|
182
+ if opened.status == :newer
183
+ witnesses.newer[d] = true
184
+ next
185
+ end
186
+ witness = opened.witness
187
+ of = SaleWitness.new(sats: witness.sats, inputs: witness.inputs, replacement: witness.replacement,
188
+ seen_at: opened.event.created_at)
189
+ if witness.sale.nil?
190
+ witnesses.none[witness.txid] = true
191
+ elsif witness.sale == sale_author && witness.expires_at == expires_at
192
+ witnesses.sale[witness.txid] = of
193
+ else
194
+ witnesses.others[witness.txid] = of
195
+ end
196
+ end
197
+ witnesses
198
+ end
199
+
200
+ # The addresses of `by_tag` (an address tag → its address) that `value`, an event a relay
201
+ # sent, names (SPEC.md §31, "Leasing an address", step 3): when it is of the seen author and
202
+ # checks out (`checks_out`: its id and signature, §11), each address whose address tag it
203
+ # holds as an `o` tag, whatever its content (one that does not open as a witness, or of a
204
+ # newer format, names it all the same); none otherwise.
205
+ def names(value, seen, by_tag, checks_out: ->(event) { Events.valid?(event) })
206
+ return [] unless value.is_a?(Hash) && value["pubkey"] == seen.author && value["tags"].is_a?(Array)
207
+
208
+ named = value["tags"].filter_map do |tag|
209
+ by_tag[tag[1]] if tag.is_a?(Array) && tag[0] == Protocol::ORDER_TAG && by_tag.key?(tag[1])
210
+ end
211
+ named.empty? || !checks_out.call(value) ? [] : named.uniq
212
+ end
213
+
214
+ # The addresses of `addresses` an event of the seen author names (names; SPEC.md §31,
215
+ # "Leasing an address", steps 2 and 3): read on the merchant's `relays` by their address
216
+ # tags, not paged, as soon as a majority answered, with a key of this read alone; of each
217
+ # event, the read keeps only the addresses it names. NetworkError when fewer than a majority
218
+ # answered.
219
+ def read_named_addresses(pool, seen, addresses, relays, random:, stop:)
220
+ return {} if addresses.empty?
221
+
222
+ by_tag = addresses.to_h { |address| [address_tag(seen.address_key, address), address] }
223
+ # Whether each event checks out: its id of each copy, its signature once per id and
224
+ # signature, whatever relays send copies.
225
+ signatures = {}
226
+ mutex = Mutex.new
227
+ checks_out = lambda do |value|
228
+ next false unless Events.valid_id?(value)
229
+
230
+ copy = "#{value["id"]}/#{value["sig"]}"
231
+ valid = mutex.synchronize { signatures[copy] }
232
+ if valid.nil?
233
+ valid = Events.signature_checks?(value)
234
+ mutex.synchronize { signatures[copy] = valid }
235
+ end
236
+ valid
237
+ end
238
+ keep = lambda do |value|
239
+ named = names(value, seen, by_tag, checks_out: checks_out)
240
+ named.empty? ? nil : named
241
+ end
242
+ filter = { "kinds" => [Protocol::RECORD_KIND], "authors" => [seen.author], "#o" => by_tag.keys }
243
+ result = pool.query_relays(relays, filter, random.call(32), paged: false, keep: keep, stop: stop)
244
+ raise NetworkError, "Fewer than a majority of the merchant's relays answered" unless result.answered
245
+
246
+ result.answers.values.flatten.to_h { |address| [address, true] }
247
+ end
248
+
249
+ # Publishes a witness on the merchant's `relays`, signed and authenticated with the seen
250
+ # secret: once a majority took it, else NetworkError.
251
+ def publish(pool, seen, witness, relays, created_at:, random:, stop:)
252
+ event = event(seen, witness, created_at, random)
253
+ pool.publish_to_quorum(relays, event, seen.secret_key, Relay.majority(relays.size), stop: stop)
254
+ rescue Relay::Failure
255
+ raise NetworkError, "Fewer than a majority of the merchant's relays took the witness of a payment"
256
+ end
257
+ end
258
+ end
259
+ end
260
+ end
@@ -0,0 +1,228 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sattleme
4
+ module Checkout
5
+ module Internal
6
+ # What a caller gives, checked before any request (SPEC.md §17, §22, §23): an order, a stored
7
+ # invoice, an option. Refused, never repaired. Each refusal names the parameter as the caller
8
+ # wrote it (`duration_seconds`, `redirect_url`).
9
+ module Order
10
+ # An order, checked: exactly one of `sats` (Integer) and `fiat` (Fiat); the rate sources of
11
+ # an order in a currency (nil in sats); the label (the note, else the reference); `checkout`;
12
+ # its redirect URL (nil without one).
13
+ Checked = Data.define(:ref, :sats, :fiat, :rate_sources, :duration_seconds, :label, :checkout,
14
+ :redirect_url)
15
+
16
+ # A stored invoice, checked: what its payment check asks. `ref` with an address only (its
17
+ # witnesses are its order's), `lightning` nil for an order paid on-chain only.
18
+ Stored = Data.define(:ref, :lightning, :onchain_address, :sats, :expires_at)
19
+
20
+ PARAMETERS = %i[ref sats fiat rate_source duration_seconds note checkout redirect_url].freeze
21
+ RATE_SOURCE_RULE = "#{Rates::NAMES.map { |name| "\"#{name}\"" }.join(", ")} or a callable, or a " \
22
+ "non-empty list of them without the same name twice".freeze
23
+ NOT_STORED = "not an invoice made by create_invoice"
24
+ INVOICE_MEMBERS = %w[ref bolt11 paymentHash verifyUrl onchainAddress sats expiresAt].freeze
25
+ ABSENT = Object.new.freeze
26
+
27
+ module_function
28
+
29
+ # `ref`, checked: InvalidOrderError (`ref`) unless it is 1 to 64 characters of REF_PATTERN.
30
+ # A String only: every order without one would otherwise be one sale (`sale//v1`).
31
+ def check_ref(value)
32
+ ref = Text.caller_text(value)
33
+ raise InvalidOrderError.new("ref", Protocol::REF_RULE) unless ref&.match?(Protocol::REF_PATTERN)
34
+
35
+ ref
36
+ end
37
+
38
+ # The order's parameters (`order`: a Hash of PARAMETERS, nil for absent), checked.
39
+ # `client_rate_sources` are the client's: an order in a currency without its own
40
+ # `rate_source` uses them.
41
+ def check(order, client_rate_sources)
42
+ unknown = order.keys - PARAMETERS
43
+ unless unknown.empty?
44
+ raise InvalidOrderError.new("order", "unknown parameter #{unknown.map(&:inspect).join(", ")}; " \
45
+ "expected ref:, sats: or fiat:, and optionally " \
46
+ "#{PARAMETERS.drop(3).map { |name| "#{name}:" }.join(", ")}")
47
+ end
48
+ ref = check_ref(order[:ref])
49
+ raise InvalidOrderError.new("sats", "give either sats or fiat") if order[:sats].nil? == order[:fiat].nil?
50
+
51
+ sats = order[:sats].nil? ? nil : check_sats(order[:sats])
52
+ fiat = order[:fiat].nil? ? nil : Rates.parse_fiat(order[:fiat])
53
+ # Given, nil included, it is checked: only absent does it take the client's (SPEC.md §26).
54
+ rate_sources = rate_sources_of(order.fetch(:rate_source, ABSENT), fiat, client_rate_sources)
55
+ Checked.new(ref: ref, sats: sats, fiat: fiat, rate_sources: rate_sources,
56
+ duration_seconds: duration_of(order[:duration_seconds]), label: label_of(order[:note], ref),
57
+ checkout: checkout_of(order[:checkout]), redirect_url: redirect_url_of(order))
58
+ end
59
+
60
+ def rate_sources_of(value, fiat, client_rate_sources)
61
+ return fiat ? client_rate_sources : nil if value.equal?(ABSENT)
62
+ raise InvalidOrderError.new("rate_source", "only for an order priced in a currency (fiat)") unless fiat
63
+
64
+ Rates.source_list(value) || raise(InvalidOrderError.new("rate_source", RATE_SOURCE_RULE))
65
+ end
66
+
67
+ def duration_of(value)
68
+ return Protocol::DEFAULT_DURATION_SECONDS if value.nil?
69
+
70
+ least = Protocol::MIN_DURATION_SECONDS
71
+ most = Protocol::MAX_DURATION_SECONDS
72
+ return value if value.is_a?(Integer) && value.between?(least, most)
73
+
74
+ raise InvalidOrderError.new("duration_seconds", "#{least} to #{most} seconds")
75
+ end
76
+
77
+ def checkout_of(value)
78
+ return false if value.nil?
79
+ raise InvalidOrderError.new("checkout", "true or false") unless [true, false].include?(value)
80
+
81
+ value
82
+ end
83
+
84
+ # The redirect URL: with `checkout` true only, a redirect URL (SPEC.md §30).
85
+ def redirect_url_of(order)
86
+ return nil if order[:redirect_url].nil?
87
+ raise InvalidOrderError.new("redirect_url", "only with checkout: true") unless order[:checkout] == true
88
+
89
+ url = Text.caller_text(order[:redirect_url])
90
+ if url.nil? || CheckoutLinks.redirect_shown(url).nil?
91
+ raise InvalidOrderError.new("redirect_url",
92
+ "an https URL (lowercase host, no user name nor password) or an app's " \
93
+ "link (scheme://…), 2048 characters at most, without spaces nor other " \
94
+ "characters to escape")
95
+ end
96
+
97
+ url
98
+ end
99
+
100
+ # Sats: an Integer, or a String of 1 to 18 digits, from 1 to 21 million BTC.
101
+ def check_sats(value)
102
+ text = value.is_a?(String) ? Text.caller_text(value) : nil
103
+ sats = if value.is_a?(Integer)
104
+ value
105
+ elsif text&.match?(/\A[0-9]{1,18}\z/)
106
+ Integer(text, 10)
107
+ end
108
+ unless sats&.between?(1, Protocol::MAX_SATS)
109
+ raise InvalidOrderError.new("sats", "a whole number of sats, from 1 to #{Protocol::MAX_SATS}")
110
+ end
111
+
112
+ sats
113
+ end
114
+
115
+ # The note, without the spaces (U+0020) around it, else the reference: 100 code points at
116
+ # most, well-formed, without control characters.
117
+ def label_of(value, ref)
118
+ return ref if value.nil?
119
+ raise InvalidOrderError.new("note", "a string") unless value.is_a?(String)
120
+ # Control characters are ASCII bytes, the same in every ASCII-compatible encoding.
121
+ if value.encoding.ascii_compatible? && value.b.match?(/[\x00-\x1F\x7F]/n)
122
+ raise InvalidOrderError.new("note", "no control characters")
123
+ end
124
+
125
+ note = Text.caller_text(value)
126
+ raise InvalidOrderError.new("note", "well-formed Unicode") if note.nil?
127
+ raise InvalidOrderError.new("note", "no control characters") if Text.control_character?(note)
128
+
129
+ label = note.sub(/\A +/, "").sub(/ +\z/, "")
130
+ label = ref if label.empty?
131
+ if Text.code_point_length(label) > Protocol::MAX_NOTE_LENGTH
132
+ raise InvalidOrderError.new("note", "#{Protocol::MAX_NOTE_LENGTH} characters at most")
133
+ end
134
+
135
+ label
136
+ end
137
+
138
+ # A stored invoice (an Invoice, a DeclaredInvoice, a Hash of its JSON members, String or
139
+ # Symbol names, or its JSON text), checked (SPEC.md §22): its sats and end; a mainnet invoice
140
+ # of exactly its sats, its own payment hash and end, an https verify URL, or none of the
141
+ # three; a deposit address, or none (absent: none); at least one of the two. With an address,
142
+ # its reference: the witnesses of its payment are its order's. InvalidOrderError (`invoice`).
143
+ def check_stored_invoice(invoice)
144
+ fields = invoice_fields(invoice)
145
+ raise InvalidOrderError.new("invoice", NOT_STORED) unless fields
146
+
147
+ sats_text = Text.caller_text(fields["sats"])
148
+ sats = sats_text&.match?(/\A[0-9]{1,16}\z/) ? Integer(sats_text, 10) : nil
149
+ expires_at = fields["expiresAt"]
150
+ unless sats&.between?(1, Protocol::MAX_SATS) && Json.safe_integer?(expires_at)
151
+ raise InvalidOrderError.new("invoice", NOT_STORED)
152
+ end
153
+
154
+ expires_at = expires_at.to_i
155
+ lightning = stored_lightning(fields, sats, expires_at)
156
+ address = fields["onchainAddress"]
157
+ address = nil if address.equal?(ABSENT)
158
+ address = Text.caller_text(address) unless address.nil?
159
+ raise InvalidOrderError.new("invoice", NOT_STORED) unless address.nil? || Addresses.deposit?(address)
160
+ raise InvalidOrderError.new("invoice", NOT_STORED) if lightning.nil? && address.nil?
161
+
162
+ ref = nil
163
+ unless address.nil?
164
+ ref = Text.caller_text(fields["ref"])
165
+ unless ref&.match?(Protocol::REF_PATTERN)
166
+ raise InvalidOrderError.new("invoice", "#{NOT_STORED}: with an address, its ref (#{Protocol::REF_RULE})")
167
+ end
168
+ end
169
+ Stored.new(ref: ref, lightning: lightning, onchain_address: address, sats: sats, expires_at: expires_at)
170
+ end
171
+
172
+ # The Lightning invoice of a stored invoice: nil, with its payment hash and verify URL nil
173
+ # too, or a mainnet invoice of exactly its sats, its payment hash and end, an https verify URL.
174
+ def stored_lightning(fields, sats, expires_at)
175
+ bolt11, payment_hash, verify_url = fields.values_at("bolt11", "paymentHash", "verifyUrl")
176
+ if bolt11.nil?
177
+ raise InvalidOrderError.new("invoice", NOT_STORED) unless payment_hash.nil? && verify_url.nil?
178
+
179
+ return nil
180
+ end
181
+
182
+ bolt11 = Text.caller_text(bolt11)
183
+ decoded = bolt11 && Bolt11.decode(bolt11)
184
+ payment_hash = Text.caller_text(payment_hash)
185
+ verify_url = Text.caller_text(verify_url)
186
+ unless decoded && decoded.network == "bc" && decoded.amount_msat == sats * 1000 &&
187
+ Text.hex32?(payment_hash) && decoded.payment_hash == payment_hash &&
188
+ decoded.expires_at == expires_at && Urls.https_url(verify_url)
189
+ raise InvalidOrderError.new("invoice", NOT_STORED)
190
+ end
191
+
192
+ Lnurl::LightningInvoice.new(bolt11: bolt11, payment_hash: payment_hash, verify_url: verify_url,
193
+ expires_at: expires_at)
194
+ end
195
+
196
+ # The members of a stored invoice by their JSON names (ABSENT for one it lacks), nil when it
197
+ # is none of the forms taken.
198
+ def invoice_fields(invoice)
199
+ hash = case invoice
200
+ when Invoice, DeclaredInvoice then invoice.to_h
201
+ when Hash then invoice
202
+ when String then Json.parse_or(Text.caller_text(invoice) || "")
203
+ end
204
+ return nil unless hash.is_a?(Hash)
205
+
206
+ INVOICE_MEMBERS.to_h do |name|
207
+ [name, if hash.key?(name)
208
+ hash[name]
209
+ else
210
+ (hash.key?(name.to_sym) ? hash[name.to_sym] : ABSENT)
211
+ end]
212
+ end
213
+ end
214
+
215
+ # A whole number of milliseconds within [min, max], `fallback` when nil. InvalidOptionError
216
+ # naming `name`.
217
+ def check_milliseconds(value, fallback, min, max, name)
218
+ return fallback if value.nil?
219
+ unless value.is_a?(Integer) && value.between?(min, max)
220
+ raise InvalidOptionError.new(name, "a whole number of milliseconds, #{min} to #{max}")
221
+ end
222
+
223
+ value
224
+ end
225
+ end
226
+ end
227
+ end
228
+ end