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,165 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sattleme
4
+ module Checkout
5
+ # What every error of this gem is (SPEC.md §5), but for a cancelled call, which raises
6
+ # Cancelled: a stable `code` for programs, and whether the same call may succeed later,
7
+ # unchanged (`retryable?`). A message never holds a secret: neither the integration's key, nor
8
+ # a sale's key, nor any key derived from them.
9
+ class Error < StandardError
10
+ # A stable code: "invalid_key", "network"…
11
+ attr_reader :code
12
+
13
+ def initialize(code, message, retryable: false)
14
+ super(message)
15
+ @code = code
16
+ @retryable = retryable
17
+ end
18
+
19
+ # Whether the same call may succeed later, unchanged (a relay or a service down).
20
+ def retryable?
21
+ @retryable
22
+ end
23
+ end
24
+
25
+ # Not an integration's secret key (`sattleme_ck_…`), or a damaged one.
26
+ class InvalidKeyError < Error
27
+ def initialize(message = "Not a sattle.me integration key")
28
+ super("invalid_key", message)
29
+ end
30
+ end
31
+
32
+ # An option of the client or of a call is invalid (a programming error, found before any
33
+ # request): `param` names it.
34
+ class InvalidOptionError < Error
35
+ attr_reader :param
36
+
37
+ def initialize(param, message)
38
+ super("invalid_option", "#{param}: #{message}")
39
+ @param = param
40
+ end
41
+ end
42
+
43
+ # A parameter of the order, or a stored invoice, is invalid: `param` names it.
44
+ class InvalidOrderError < Error
45
+ attr_reader :param
46
+
47
+ def initialize(param, message)
48
+ super("invalid_order", "#{param}: #{message}")
49
+ @param = param
50
+ end
51
+ end
52
+
53
+ # The merchant removed the integration: no invoice can be made with this key any more.
54
+ class RevokedError < Error
55
+ def initialize(message = "The merchant removed this integration")
56
+ super("revoked", message)
57
+ end
58
+ end
59
+
60
+ # The relays answered, but none holds the integration's channel (or only one of a newer format
61
+ # than this version of the gem reads: `newer_format?`, then not retryable: update the gem).
62
+ class ChannelNotFoundError < Error
63
+ def initialize(newer_format: false)
64
+ super(
65
+ "channel_not_found",
66
+ if newer_format
67
+ "The integration's channel is of a newer format: update sattleme-checkout"
68
+ else
69
+ "The integration's channel was not found on its relays"
70
+ end,
71
+ retryable: !newer_format
72
+ )
73
+ @newer_format = newer_format
74
+ end
75
+
76
+ def newer_format?
77
+ @newer_format
78
+ end
79
+ alias newer_format newer_format?
80
+ end
81
+
82
+ # A relay, the Lightning address's server, a rate source or an explorer did not answer (in
83
+ # time), or fewer relays than needed did. Retry later.
84
+ class NetworkError < Error
85
+ def initialize(message = "No answer")
86
+ super("network", message, retryable: true)
87
+ end
88
+ end
89
+
90
+ # An invoice, a pay request or a payment answer that fails the checks: another network, amount,
91
+ # merchant, duration or date, a verify answer about another invoice, a preimage that does not
92
+ # match. Never show such an invoice.
93
+ class InvalidInvoiceError < Error
94
+ def initialize(message = "The invoice failed the checks")
95
+ super("invalid_invoice", message)
96
+ end
97
+ end
98
+
99
+ # The order still has an invoice that may be paid (not expired, or in the 120 s after its end,
100
+ # or its on-chain payment being confirmed): show that one (`invoice`, a DeclaredInvoice)
101
+ # instead of making another. With `checkout: true`, `checkout_url` is a new link to it, else nil.
102
+ class InvoicePendingError < Error
103
+ attr_reader :invoice, :checkout_url
104
+
105
+ def initialize(invoice, checkout_url = nil)
106
+ super("invoice_pending", "This order still has an invoice that may be paid")
107
+ @invoice = invoice
108
+ @checkout_url = checkout_url
109
+ end
110
+ end
111
+
112
+ # The order was already paid, with `invoice`: `status` is its `paid` PaymentStatus, `preimage`
113
+ # the proof of its own Lightning payment (nil when it was paid on-chain, or mixed). Never charge
114
+ # it again.
115
+ class OrderPaidError < Error
116
+ attr_reader :invoice, :status, :preimage
117
+
118
+ def initialize(invoice, status)
119
+ super("order_paid", "This order was already paid")
120
+ @invoice = invoice
121
+ @status = status
122
+ @preimage = status.payment_method == "lightning" ? status.preimage : nil
123
+ end
124
+ end
125
+
126
+ # The rate source has no price in this currency (`currency`).
127
+ class UnsupportedCurrencyError < Error
128
+ attr_reader :currency
129
+
130
+ def initialize(currency, source = "The rate source", message = nil)
131
+ super("unsupported_currency", message || "#{source} has no price in #{currency}")
132
+ @currency = currency
133
+ end
134
+ end
135
+
136
+ # No usable rate: a source answered something that is not a price, a price too old, or a custom
137
+ # source failed (`cause`). Retry later, or with another source.
138
+ class RateError < Error
139
+ def initialize(message = "No usable price")
140
+ super("rate", message, retryable: true)
141
+ end
142
+ end
143
+
144
+ # A checkout link was asked, and the merchant's app gives no web app for it. Make the invoice
145
+ # without `checkout`, and show it on the shop's page.
146
+ class CheckoutUnavailableError < Error
147
+ def initialize
148
+ super("checkout_unavailable",
149
+ "The merchant's app gives no web app for checkout links: show the invoice on the " \
150
+ "shop's page")
151
+ end
152
+ end
153
+
154
+ # The order can only be paid on-chain (its amount is outside the Lightning address's bounds),
155
+ # and no deposit address of the integration's lot could be leased. Retry later: the merchant's
156
+ # app fills the lot again whenever it is opened.
157
+ class OnchainUnavailableError < Error
158
+ def initialize
159
+ super("onchain_unavailable",
160
+ "No deposit address of the integration's lot could be leased: try again later",
161
+ retryable: true)
162
+ end
163
+ end
164
+ end
165
+ end
@@ -0,0 +1,294 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+
5
+ module Sattleme
6
+ module Checkout
7
+ # The platform's HTTP client, the gem's own, for the Lightning address, the rate sources and the
8
+ # explorer (SPEC.md §15): a GET over TLS (TlsConnector: the certificate and the host name
9
+ # verified, TLS 1.2 at least) in HTTP/1.1, no redirect followed (a 3xx is an answer as any
10
+ # other), no compression asked, the whole request bounded by `timeout`. Every part of an answer
11
+ # is bounded as it comes: its head (status line and headers) at MAX_HEAD_BYTES, what it holds
12
+ # besides its body (its heads, a chunked body's size lines and trailers) at MAX_FRAMING_BYTES in
13
+ # all, and its body is given chunk by chunk (the gem stops reading at 1 MiB): a server cannot
14
+ # make the process hold more than that. No proxy, not even one of the environment: give one
15
+ # (`proxy: URI("http://proxy:3128")`, an HTTP proxy that tunnels with CONNECT), or inject a
16
+ # client of your own. The certificates it trusts are the system's, or those of `cert_store:`
17
+ # (an OpenSSL::X509::Store: a company's CA). It asks https URLs, and those of the merchant's
18
+ # Bitcoin node (SPEC.md §31), whose URL follows a rule of its own: `https` to an IPv4 address
19
+ # too, and `http`, in clear (no TLS), to a host of a local network alone (10.0.0.0/8,
20
+ # 172.16.0.0/12, 192.168.0.0/16, 100.64.0.0/10, names under `.local`); every other rule holds.
21
+ #
22
+ # Inject another as `http_client:` of a Client: anything that answers
23
+ # `get(url, headers:, timeout:, cancellation:) { |chunk| … }`, yields the body's chunks
24
+ # (Strings) as they come and returns the HTTP status (an Integer). `timeout` is in seconds;
25
+ # `cancellation` is cancelled when the gem gives up the request (its time ran out, its call was
26
+ # cancelled): stop then. Keep it bounded as this one is. It gets an `http://` URL only to read a
27
+ # merchant's node on a local network: ask it in clear HTTP, or fail (raise), and the node's
28
+ # fallback applies.
29
+ class HttpClient
30
+ # The longest head of an answer read: its status line, its headers and the blank line after
31
+ # them (as undici's, and the WebSocket client's handshake answer).
32
+ MAX_HEAD_BYTES = 16_384
33
+ # What an answer may hold besides its body, in all: its heads (an interim answer's too) and a
34
+ # chunked body's size lines, line ends and trailers (SPEC.md §15: 10 MiB at most).
35
+ MAX_FRAMING_BYTES = 10 * 1024 * 1024
36
+ # What is read at a time.
37
+ READ_BYTES = 16_384
38
+ STATUS_LINE = %r{\AHTTP/1\.[01] ([0-9]{3})(?: .*)?\z}n
39
+ CHUNK_SIZE = /\A([0-9a-fA-F]{1,15})[ \t]*(?:;.*)?\z/n
40
+
41
+ # The answer is not HTTP/1.1, or goes beyond a bound.
42
+ class ProtocolError < StandardError; end
43
+
44
+ # Where a URL is asked: its host, its port, and whether over TLS.
45
+ Target = Data.define(:host, :port, :tls) do
46
+ def default_port = tls ? 443 : 80
47
+ end
48
+ private_constant :Target
49
+
50
+ def initialize(proxy: nil, cert_store: nil)
51
+ raise ArgumentError, "proxy: a URI with a host and a port" unless proxy.nil? || proxy.respond_to?(:host)
52
+ unless cert_store.nil? || cert_store.is_a?(OpenSSL::X509::Store)
53
+ raise ArgumentError, "cert_store: an OpenSSL::X509::Store"
54
+ end
55
+
56
+ @proxy = proxy
57
+ context = OpenSSL::SSL::SSLContext.new
58
+ params = { verify_mode: OpenSSL::SSL::VERIFY_PEER, verify_hostname: true }
59
+ params[:cert_store] = cert_store if cert_store
60
+ context.set_params(params)
61
+ context.min_version = OpenSSL::SSL::TLS1_2_VERSION
62
+ context.alpn_protocols = ["http/1.1"]
63
+ @tls = TlsConnector.new(ssl_context: context)
64
+ end
65
+
66
+ def get(url, headers:, timeout:, cancellation: Cancellation::NONE, &)
67
+ target = target_of(url)
68
+ unless target
69
+ raise ArgumentError, "Not an https URL, nor one of a merchant's Bitcoin node (http: on a local network)"
70
+ end
71
+
72
+ request = request(url, target, headers)
73
+ deadline = Internal::Clock.now + timeout
74
+ opened = []
75
+ handle = cancellation.on_cancel { opened.each { |io| close_quietly(io) } }
76
+ begin
77
+ cancellation.raise_if_cancelled
78
+ io = connect(target, deadline, opened)
79
+ cancellation.raise_if_cancelled
80
+ WebSocketClient.write_all(io, request, deadline)
81
+ Answer.new(io, deadline).read(&)
82
+ ensure
83
+ cancellation.remove(handle)
84
+ opened.each { |io| close_quietly(io) }
85
+ end
86
+ end
87
+
88
+ private
89
+
90
+ # Where `url` is asked: its host, its port and whether over TLS. An https URL (Urls.https_url);
91
+ # or a URL under a merchant's Bitcoin node (SPEC.md §31), its scheme and authority a node
92
+ # URL's (NodeUrl): `https`, an IPv4 address too, or `http` to a host of a local network alone.
93
+ # Nil for any other URL.
94
+ def target_of(url)
95
+ https = Internal::Urls.https_url(url)
96
+ return Target.new(host: https.host, port: https.port, tls: true) if https
97
+ return nil unless url.is_a?(String) && url.match?(%r{\Ahttps?://})
98
+
99
+ node = Internal::NodeUrl.origin_of(url)
100
+ node && Target.new(host: node.host, port: node.port, tls: node.tls?)
101
+ end
102
+
103
+ def request(url, target, headers)
104
+ host = target.port == target.default_port ? target.host : "#{target.host}:#{target.port}"
105
+ path = Internal::Urls.request_target(url.sub(%r{\Ahttps?://[^/?#]*}, ""))
106
+ lines = ["GET #{path} HTTP/1.1", "Host: #{host}"]
107
+ headers.merge("Accept-Encoding" => "identity", "Connection" => "close").each do |name, value|
108
+ unless name.to_s.match?(WebSocketClient::HEADER_NAME) && value.to_s.match?(WebSocketClient::HEADER_VALUE)
109
+ raise ArgumentError, "Not an HTTP header: #{name}"
110
+ end
111
+
112
+ lines << "#{name}: #{value}"
113
+ end
114
+ "#{lines.join("\r\n")}\r\n\r\n"
115
+ end
116
+
117
+ # TLS to the host of `target` (a TCP connection alone to a local node asked over `http`),
118
+ # through the proxy's tunnel when there is one: each socket opened is added to `opened`, which
119
+ # the call's cancellation closes.
120
+ def connect(target, deadline, opened)
121
+ tcp = @tls.connect_tcp(@proxy ? @proxy.host : target.host, @proxy ? @proxy.port : target.port, deadline)
122
+ opened << tcp
123
+ tunnel(tcp, target, deadline) if @proxy
124
+ return tcp unless target.tls
125
+
126
+ ssl = @tls.handshake(tcp, target.host, deadline)
127
+ opened << ssl
128
+ ssl
129
+ end
130
+
131
+ # Asks the proxy for a tunnel to the host and port of `target` (CONNECT): it answers a head
132
+ # alone, 2xx when it opened it.
133
+ def tunnel(io, target, deadline)
134
+ authority = "#{target.host}:#{target.port}"
135
+ lines = ["CONNECT #{authority} HTTP/1.1", "Host: #{authority}"]
136
+ lines << "Proxy-Authorization: Basic #{["#{@proxy.user}:#{@proxy.password}"].pack("m0")}" if @proxy.user
137
+ WebSocketClient.write_all(io, "#{lines.join("\r\n")}\r\n\r\n", deadline)
138
+ answer = Answer.new(io, deadline)
139
+ status, = answer.head
140
+ raise ProtocolError, "The proxy refused the tunnel (HTTP #{status})" unless status.between?(200, 299)
141
+ raise ProtocolError, "The proxy sent more than its answer" unless answer.drained?
142
+ end
143
+
144
+ def close_quietly(io)
145
+ io.close
146
+ rescue StandardError
147
+ nil
148
+ end
149
+
150
+ # One answer, read from `io` by `deadline`, each part bounded as it comes.
151
+ class Answer
152
+ def initialize(io, deadline)
153
+ @io = io
154
+ @deadline = deadline
155
+ @buffer = +"".b
156
+ # The bytes read besides the body.
157
+ @framing = 0
158
+ end
159
+
160
+ # The final answer's status, its body given to the block chunk by chunk.
161
+ def read(&)
162
+ status, fields = head
163
+ # Interim answers (100 Continue, 103 Early Hints), a head each: the final one follows.
164
+ status, fields = head while status.between?(100, 199) && status != 101
165
+ raise ProtocolError, "The answer switched protocols, which was not asked" if status == 101
166
+
167
+ body(status, fields, &) unless [204, 304].include?(status)
168
+ status
169
+ end
170
+
171
+ # The next head: [status, its fields by lower-case name].
172
+ def head
173
+ started = @framing
174
+ left = -> { MAX_HEAD_BYTES - (@framing - started) }
175
+ status = STATUS_LINE.match(line(left.call))&.[](1)
176
+ raise ProtocolError, "Not an HTTP/1.1 answer" unless status
177
+
178
+ fields = Hash.new { |hash, name| hash[name] = [] }
179
+ until (text = line(left.call)).empty?
180
+ name, value = text.split(":", 2)
181
+ raise ProtocolError, "A malformed header" if value.nil? || !name.match?(WebSocketClient::HEADER_NAME)
182
+
183
+ fields[name.downcase] << value.sub(/\A[ \t]+/, "").sub(/[ \t]+\z/, "")
184
+ end
185
+ [Integer(status, 10), fields]
186
+ end
187
+
188
+ # Whether nothing was read past what was read so far.
189
+ def drained?
190
+ @buffer.empty?
191
+ end
192
+
193
+ private
194
+
195
+ # RFC 9112 §6.3: chunked, else as long as its length, else until the connection ends.
196
+ def body(_status, fields, &)
197
+ codings = fields.fetch("transfer-encoding", []).flat_map { |value| value.split(",") }
198
+ .map { |coding| coding.strip.downcase }
199
+ return (codings.last == "chunked" ? chunked(&) : to_end(&)) unless codings.empty?
200
+
201
+ length = content_length(fields.fetch("content-length", []))
202
+ length ? exactly(length, &) : to_end(&)
203
+ end
204
+
205
+ # The length its Content-Length headers say (one value, written once or repeated); nil
206
+ # without one.
207
+ def content_length(values)
208
+ lengths = values.flat_map { |value| value.split(",") }.map(&:strip).uniq
209
+ return nil if lengths.empty?
210
+ unless lengths.size == 1 && lengths[0].match?(/\A[0-9]{1,15}\z/)
211
+ raise ProtocolError, "An invalid Content-Length"
212
+ end
213
+
214
+ Integer(lengths[0], 10)
215
+ end
216
+
217
+ def chunked(&)
218
+ loop do
219
+ size = CHUNK_SIZE.match(line(MAX_HEAD_BYTES))&.[](1)
220
+ raise ProtocolError, "Not a chunk's size" unless size
221
+ break if size.to_i(16).zero?
222
+
223
+ exactly(size.to_i(16), &)
224
+ raise ProtocolError, "A chunk without its line end" unless line(2).empty?
225
+ end
226
+ # Its trailers, up to a blank line.
227
+ nil until line(MAX_HEAD_BYTES).empty?
228
+ end
229
+
230
+ # `count` bytes of the body, given as they come.
231
+ def exactly(count)
232
+ until count.zero?
233
+ raise EOFError, "The connection ended within the answer's body" if @buffer.empty? && !fill
234
+
235
+ taken = [count, @buffer.bytesize].min
236
+ yield @buffer.byteslice(0, taken)
237
+ @buffer = @buffer.byteslice(taken..)
238
+ count -= taken
239
+ end
240
+ end
241
+
242
+ # The body, until the connection ends.
243
+ def to_end
244
+ loop do
245
+ yield @buffer unless @buffer.empty?
246
+ @buffer = +"".b
247
+ break unless fill
248
+ end
249
+ end
250
+
251
+ # The next line, without its line end (CR LF, or LF), of `limit` bytes at most with it: a
252
+ # longer one fails before more of it is read.
253
+ def line(limit)
254
+ scanned = 0
255
+ until (index = @buffer.index("\n", scanned))
256
+ scanned = @buffer.bytesize
257
+ raise ProtocolError, "A line of the answer longer than #{limit} bytes" if scanned >= limit
258
+ raise EOFError, "The connection ended within a line of the answer" unless fill
259
+ end
260
+ length = index + 1
261
+ raise ProtocolError, "A line of the answer longer than #{limit} bytes" if length > limit
262
+
263
+ @framing += length
264
+ raise ProtocolError, "More than #{MAX_FRAMING_BYTES} bytes besides the body" if @framing > MAX_FRAMING_BYTES
265
+
266
+ text = @buffer.byteslice(0, index)
267
+ @buffer = @buffer.byteslice(length..)
268
+ text.delete_suffix("\r")
269
+ end
270
+
271
+ # Reads what came into the buffer, waiting for it until the deadline: false once the
272
+ # connection ended.
273
+ def fill
274
+ loop do
275
+ left = Internal::Clock.left(@deadline)
276
+ raise IO::TimeoutError, "The answer took longer than its timeout" if left.zero?
277
+
278
+ chunk = @io.read_nonblock(READ_BYTES, exception: false)
279
+ case chunk
280
+ when nil then return false
281
+ when :wait_readable, :wait_writable
282
+ ready = @io.to_io.public_send(chunk, left)
283
+ raise IO::TimeoutError, "The answer took longer than its timeout" unless ready
284
+ else
285
+ @buffer << chunk
286
+ return true
287
+ end
288
+ end
289
+ end
290
+ end
291
+ private_constant :Answer
292
+ end
293
+ end
294
+ end
@@ -0,0 +1,187 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sattleme
4
+ module Checkout
5
+ module Internal
6
+ # Bech32 decoding (BIP-173), without its 90-character limit: BOLT11 invoices are longer.
7
+ # Bech32m (BIP-350), for taproot addresses, differs by its checksum's constant alone.
8
+ module Bech32
9
+ CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
10
+ VALUES = CHARSET.each_char.with_index.to_h.freeze
11
+ GENERATOR = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3].freeze
12
+ # The checksum's constant: BIP-173's bech32, BIP-350's bech32m.
13
+ BECH32 = 1
14
+ BECH32M = 0x2bc830a3
15
+
16
+ # A decoded string: its human-readable part (lower case) and its 5-bit words, checksum
17
+ # removed.
18
+ Decoded = Data.define(:hrp, :words)
19
+
20
+ module_function
21
+
22
+ def polymod(values)
23
+ checksum = 1
24
+ values.each do |value|
25
+ top = checksum >> 25
26
+ checksum = ((checksum & 0x1ffffff) << 5) ^ value
27
+ 5.times { |i| checksum ^= GENERATOR[i] if top[i] == 1 }
28
+ end
29
+ checksum
30
+ end
31
+
32
+ def expand_hrp(hrp)
33
+ codes = hrp.bytes
34
+ codes.map { |code| code >> 5 } + [0] + codes.map { |code| code & 31 }
35
+ end
36
+
37
+ # A bech32 string (either case, never mixed), or nil when it is not valid bech32 (bech32m
38
+ # with `constant` BECH32M).
39
+ def decode(input, constant = BECH32)
40
+ return nil unless Text.well_formed?(input) && input.ascii_only?
41
+
42
+ text = Text.ascii_lower(input)
43
+ return nil unless input == text || input == input.tr("a-z", "A-Z")
44
+
45
+ separator = text.rindex("1")
46
+ return nil if separator.nil? || separator < 1 || separator + 7 > text.length
47
+
48
+ hrp = text[0, separator]
49
+ return nil unless hrp.bytes.all? { |code| code.between?(33, 126) }
50
+
51
+ values = text[(separator + 1)..].each_char.map { |char| VALUES[char] }
52
+ return nil if values.include?(nil)
53
+ return nil unless polymod(expand_hrp(hrp) + values) == constant
54
+
55
+ Decoded.new(hrp: hrp, words: values[0...-6])
56
+ end
57
+
58
+ # 5-bit words regrouped into bytes; the trailing padding bits (fewer than 8) dropped.
59
+ def words_to_bytes(words)
60
+ bytes = []
61
+ accumulator = 0
62
+ bits = 0
63
+ words.each do |word|
64
+ accumulator = ((accumulator << 5) | word) & 0xfff
65
+ bits += 5
66
+ next unless bits >= 8
67
+
68
+ bits -= 8
69
+ bytes << ((accumulator >> bits) & 0xff)
70
+ end
71
+ bytes.pack("C*")
72
+ end
73
+
74
+ # The big-endian unsigned integer of 5-bit words.
75
+ def words_to_integer(words)
76
+ words.reduce(0) { |value, word| (value * 32) + word }
77
+ end
78
+ end
79
+
80
+ # The fields of a BOLT11 invoice the gem checks (SPEC.md §19): network, amount, payment hash,
81
+ # description hash, date and expiry. The signature is not verified: the payee is the LNURL
82
+ # server's node, which nothing here can check it against; the description hash ties the
83
+ # invoice to the merchant's Lightning address instead. The first `p` and `h` fields count and
84
+ # the last `x`, as in the merchant's app; an `x` field of more than 7 words or an amount above
85
+ # 21 million bitcoins makes the invoice invalid.
86
+ module Bolt11
87
+ # A decoded invoice. `amount_msat` is nil for an invoice without an amount; `expiry_seconds`
88
+ # 3600 when the invoice does not say; `description_hash` nil with a plain description.
89
+ Invoice = Data.define(:network, :amount_msat, :timestamp, :expiry_seconds, :payment_hash,
90
+ :description_hash) do
91
+ # The end of the invoice: its timestamp and its expiry.
92
+ def expires_at = timestamp + expiry_seconds
93
+ end
94
+
95
+ HRP = /\Aln(bcrt|bc|tbs|tb)([0-9]+)?([munp])?\z/
96
+ # Millisatoshis per unit of the amount, by multiplier (1 BTC = 10^11 msat).
97
+ MSAT_PER_UNIT = { nil => 100_000_000_000, "m" => 100_000_000, "u" => 100_000, "n" => 100 }.freeze
98
+ TIMESTAMP_WORDS = 7
99
+ # A 65-byte signature, as 5-bit words.
100
+ SIGNATURE_WORDS = 104
101
+ TAG_PAYMENT_HASH = 1
102
+ TAG_DESCRIPTION_HASH = 23
103
+ TAG_EXPIRY = 6
104
+ # 256 bits as 5-bit words.
105
+ HASH_WORDS = 52
106
+ DEFAULT_EXPIRY_SECONDS = 3600
107
+
108
+ module_function
109
+
110
+ # A BOLT11 invoice, decoded; nil when it is not a valid one.
111
+ def decode(input)
112
+ decoded = Bech32.decode(input)
113
+ return nil unless decoded
114
+
115
+ hrp = HRP.match(decoded.hrp)
116
+ return nil unless hrp
117
+
118
+ valid, amount = amount_msat(hrp[2], hrp[3])
119
+ return nil unless valid
120
+
121
+ words = decoded.words
122
+ return nil if words.size < TIMESTAMP_WORDS + SIGNATURE_WORDS
123
+
124
+ fields = words[TIMESTAMP_WORDS...(words.size - SIGNATURE_WORDS)]
125
+ payment_hash, description_hash, expiry = read_fields(fields)
126
+ return nil if payment_hash.nil? || payment_hash == :invalid
127
+
128
+ Invoice.new(network: hrp[1], amount_msat: amount,
129
+ timestamp: Bech32.words_to_integer(words[0, TIMESTAMP_WORDS]),
130
+ expiry_seconds: expiry || DEFAULT_EXPIRY_SECONDS, payment_hash: payment_hash,
131
+ description_hash: description_hash)
132
+ end
133
+
134
+ # The payment hash, the description hash and the expiry of the tagged fields; the payment
135
+ # hash :invalid when a field runs past the signature or an expiry field is too long.
136
+ def read_fields(fields)
137
+ payment_hash = nil
138
+ description_hash = nil
139
+ expiry = nil
140
+ index = 0
141
+ while index < fields.size
142
+ return [:invalid] if index + 3 > fields.size
143
+
144
+ tag = fields[index]
145
+ length = (fields[index + 1] * 32) + fields[index + 2]
146
+ data = fields[index + 3, length]
147
+ return [:invalid] unless data && data.size == length
148
+
149
+ # Fields of an unexpected length are skipped, as BOLT11 requires for p and h; the first
150
+ # of each counts, and the last x.
151
+ if tag == TAG_PAYMENT_HASH && length == HASH_WORDS && payment_hash.nil?
152
+ payment_hash = Text.hex(Bech32.words_to_bytes(data))
153
+ elsif tag == TAG_DESCRIPTION_HASH && length == HASH_WORDS && description_hash.nil?
154
+ description_hash = Text.hex(Bech32.words_to_bytes(data))
155
+ elsif tag == TAG_EXPIRY
156
+ return [:invalid] if length > Protocol::MAX_BOLT11_EXPIRY_WORDS
157
+
158
+ expiry = Bech32.words_to_integer(data)
159
+ end
160
+ index += 3 + length
161
+ end
162
+ [payment_hash, description_hash, expiry]
163
+ end
164
+
165
+ # [valid, millisatoshis] of the amount's digits and multiplier: digits without a leading
166
+ # zero, an optional multiplier (a pico-bitcoin is a tenth of a millisatoshi: only whole
167
+ # ones), 21 million bitcoins at most; no digits, no amount (a multiplier alone is invalid).
168
+ def amount_msat(digits, multiplier)
169
+ return [multiplier.nil?, nil] if digits.nil?
170
+ return [false, nil] if digits.length > 1 && digits.start_with?("0")
171
+ # Longer than any amount up to 21 million bitcoins, whatever the multiplier.
172
+ return [false, nil] if digits.length > 22
173
+
174
+ value = digits.to_i
175
+ msat = if multiplier == "p"
176
+ return [false, nil] unless (value % 10).zero?
177
+
178
+ value / 10
179
+ else
180
+ value * MSAT_PER_UNIT.fetch(multiplier)
181
+ end
182
+ msat > Protocol::MAX_BOLT11_AMOUNT_MSAT ? [false, nil] : [true, msat]
183
+ end
184
+ end
185
+ end
186
+ end
187
+ end