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,238 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sattleme
4
+ module Checkout
5
+ module Internal
6
+ # The invoices declared for a sale, read back from the merchant's registry (SPEC.md §21): its
7
+ # declarations and its leases of deposit addresses. What create_invoice checks before a new
8
+ # invoice, and find_invoices gives.
9
+ module Sales
10
+ # A declared invoice (a DeclaredInvoice), with its signed declaration (nil for an order paid
11
+ # on-chain only) and its lease's event (nil without an address): published again when the
12
+ # invoice may still be paid.
13
+ Declared = Data.define(:invoice, :event, :lease)
14
+
15
+ # What the registry holds of a sale: the order's invoices, oldest first; the rest invoices of
16
+ # each invoice with an address, by rest_key_of of that invoice (its declarations with
17
+ # `rest`, by date then payment hash); the declarations of rest invoices fewer than a majority
18
+ # of the relays sent, by payment hash (published again on a majority before they are used);
19
+ # the sale's leases still held (not withdrawn), by address; how many relays sent each event,
20
+ # by id.
21
+ SaleRecords = Data.define(:invoices, :rests, :unsure_rests, :leases, :sent_by)
22
+
23
+ module_function
24
+
25
+ # The invoices of `sale` on `relays`, oldest first (by date, then payment hash, then address):
26
+ # read page after page as soon as a majority of the relays answered (each declaration and
27
+ # lease is on a majority of them), or on every relay (`every_relay`: which relays hold a
28
+ # record). One per payment hash, with the address of the sale's confirmed lease naming its
29
+ # invoice; and one per confirmed lease of an order paid on-chain only (invoices_of). A
30
+ # declaration with `rest` is no invoice of the order: one of the rest invoices of the invoice
31
+ # it names. NetworkError when fewer than a majority answered.
32
+ def read(pool, sale, relays, logger:, stop:, every_relay: false)
33
+ needed = Relay.majority(relays.size)
34
+ keep = Internal::Records.that_open do |d, author|
35
+ author == sale.author && d ? Derive.outer_key(sale.registry.key, d, author) : nil
36
+ end
37
+ filter = { "kinds" => [Protocol::RECORD_KIND], "authors" => [sale.author] }
38
+ result = pool.query_relays(relays, filter, sale.secret_key,
39
+ paged: true, every_relay: every_relay, keep: keep, stop: stop)
40
+ raise NetworkError, "Fewer than a majority of the merchant's relays answered" unless result.answered
41
+
42
+ declarations, records, sent_by, newer = open_answers(result.answers, sale)
43
+ if newer
44
+ logger.warn("sattleme-checkout: a declaration or a lease of this order has a newer format than this " \
45
+ "version reads; update the gem")
46
+ end
47
+ newest = newest_records(records)
48
+ rests = Hash.new { |hash, key| hash[key] = [] }
49
+ unsure = {}
50
+ invoices = []
51
+ declarations.each_value do |declaration|
52
+ if declaration.rest.nil?
53
+ invoices << declaration
54
+ next
55
+ end
56
+ hash = declaration.decoded.payment_hash
57
+ unsure[hash] = declaration.event if sent_by.fetch(declaration.event.id, 0) < needed
58
+ rests[rest_key_of(declaration.rest.address, declaration.rest.expires_at)] << Rests.invoice_of(declaration)
59
+ end
60
+ rests.each_value { |list| list.sort_by! { |invoice| Rests.order_key(invoice) } }
61
+ leases = newest.filter_map { |record| record[:lease] if record[:kind] == :lease }
62
+ SaleRecords.new(invoices: invoices_of(sale.ref, invoices, newest), rests: rests.to_h, unsure_rests: unsure,
63
+ leases: leases.to_h { |lease| [lease.terms.address, lease] }, sent_by: sent_by)
64
+ end
65
+
66
+ # Each event the relays sent, opened once per id that checked out: the declarations (one per
67
+ # payment hash), the sale's records at registry addresses, how many relays sent each event,
68
+ # and whether one was of a newer format.
69
+ def open_answers(answers, sale)
70
+ declarations = {}
71
+ records = []
72
+ checked = {}
73
+ sent_by = Hash.new(0)
74
+ newer = false
75
+ answers.each_value do |events|
76
+ # A relay counts for an event when it sent a copy whose id is its hash: it holds that event.
77
+ held = events.select { |value| Events.valid_id?(value) }.map { |value| value["id"] }
78
+ held.uniq.each { |id| sent_by[id] += 1 }
79
+ events.each do |value|
80
+ next if value.is_a?(Hash) && value["id"].is_a?(String) && checked.key?(value["id"])
81
+
82
+ declaration = nil
83
+ lease = nil
84
+ begin
85
+ declaration = Declarations.open(value, sale)
86
+ lease = Leases.open_sale_lease(value, sale) unless declaration
87
+ rescue Internal::Records::Newer
88
+ newer = true
89
+ # Authentic (its signature checked before its format), at a registry address: the
90
+ # newest there, it leaves no lease of the sale.
91
+ d = Internal::Records.d_tag_of(value)
92
+ unless d.nil?
93
+ event = Events.from(value)
94
+ checked[event.id] = true
95
+ records << { kind: :newer, event: event, d: d }
96
+ end
97
+ next
98
+ end
99
+ if declaration
100
+ checked[declaration.event.id] = true
101
+ declarations[declaration.decoded.payment_hash] ||= declaration
102
+ elsif lease
103
+ checked[event_of(lease).id] = true
104
+ records << lease
105
+ end
106
+ end
107
+ end
108
+ [declarations, records, sent_by.to_h, newer]
109
+ end
110
+
111
+ def event_of(record)
112
+ record[:kind] == :lease ? record[:lease].event : record[:event]
113
+ end
114
+
115
+ def d_of(record)
116
+ record[:kind] == :lease ? record[:lease].d : record[:d]
117
+ end
118
+
119
+ # Of the sale's records at registry addresses, the newest at each (the highest `created_at`,
120
+ # then the lowest id, as relays keep them): its lease there, or its withdrawal, which leaves
121
+ # none.
122
+ def newest_records(records)
123
+ newest = {}
124
+ records.each do |record|
125
+ d = d_of(record)
126
+ known = newest[d]
127
+ newest[d] = record if known.nil? || Internal::Records.replaces?(event_of(record), event_of(known))
128
+ end
129
+ newest.values
130
+ end
131
+
132
+ # The sale's invoices, oldest first (by date, then payment hash, none first, then address),
133
+ # from its declarations (one per payment hash; one with `rest` gives none) and its newest
134
+ # record at each registry address. Only a confirmed lease gives an address: one that is not
135
+ # was left by a create_invoice that failed before the address was the order's. One invoice
136
+ # per declaration, with the address of the newest confirmed lease naming its invoice; and one
137
+ # per confirmed lease of an order paid on-chain only. A lease naming an invoice without a
138
+ # declaration is left out: that invoice was never shown.
139
+ def invoices_of(ref, declarations, newest)
140
+ confirmed = newest.filter_map do |record|
141
+ record[:lease] if record[:kind] == :lease && record[:lease].terms.confirmed == true
142
+ end
143
+ found = declarations.reject(&:rest).map do |declaration|
144
+ decoded = declaration.decoded
145
+ invoice = Text.ascii_lower(declaration.invoice)
146
+ naming = confirmed.select do |opened|
147
+ opened.terms.invoice && Text.ascii_lower(opened.terms.invoice) == invoice
148
+ end
149
+ lease = naming.min { |a, b| Internal::Records.replaces?(a.event, b.event) ? -1 : 1 }
150
+ sats = decoded.amount_msat / 1000
151
+ address = lease&.terms&.address
152
+ Declared.new(invoice: DeclaredInvoice.new(
153
+ ref: ref, bolt11: declaration.invoice, payment_hash: decoded.payment_hash,
154
+ verify_url: declaration.verify_url, onchain_address: address,
155
+ payment_uri: Addresses.payment_uri(address, sats, declaration.invoice), sats: sats.to_s,
156
+ fiat: fiat_of(declaration.price), note: declaration.note, created_at: decoded.timestamp,
157
+ expires_at: decoded.expires_at, declared_at: declaration.declared_at
158
+ ), event: declaration.event, lease: lease&.event)
159
+ end
160
+ confirmed.each do |lease|
161
+ terms = lease.terms
162
+ next unless terms.invoice.nil?
163
+
164
+ found << Declared.new(invoice: DeclaredInvoice.new(
165
+ ref: ref, bolt11: nil, payment_hash: nil, verify_url: nil, onchain_address: terms.address,
166
+ payment_uri: Addresses.payment_uri(terms.address, terms.sats, nil), sats: terms.sats.to_s,
167
+ fiat: fiat_of(terms.price), note: terms.note, created_at: terms.created_at,
168
+ expires_at: terms.expires_at,
169
+ # Its mark's date.
170
+ declared_at: lease.event.created_at
171
+ ), event: nil, lease: lease.event)
172
+ end
173
+ found.sort_by do |declared|
174
+ invoice = declared.invoice
175
+ [invoice.created_at, invoice.payment_hash || "", invoice.onchain_address || ""]
176
+ end
177
+ end
178
+
179
+ # Step 1 of SPEC.md §21: the indices of the invoices (oldest first) that may still be paid at
180
+ # `now`, until their end and its grace period.
181
+ def may_still_be_paid(invoices, now)
182
+ invoices.each_index.select { |index| now < invoices[index].expires_at + Protocol::GRACE_SECONDS }
183
+ end
184
+
185
+ # An invoice's last record: its declaration, or for an invoice paid on-chain only its
186
+ # lease's event (its mark). The one shown has it on a majority of the relays.
187
+ def last_record_of(declared)
188
+ declared.event || declared.lease
189
+ end
190
+
191
+ # Of each invoice of `declared` (Declared), whether a majority of the `relays` relays of a
192
+ # read on every relay sent its last record (`sent_by`: how many relays sent each id).
193
+ def held(declared, sent_by, relays)
194
+ declared.map { |invoice| sent_by.fetch(last_record_of(invoice).id, 0) >= Relay.majority(relays) }
195
+ end
196
+
197
+ # Of the invoices that may still be paid (oldest first, one or more), from the payment check
198
+ # of each (Settled PaymentStatus) and, of several, whether a majority of the relays sent its
199
+ # last record (`held`, read on every relay; nil when fewer than a majority answered that
200
+ # read): the first paid gives [:paid, index], whatever the read (a payment proves itself);
201
+ # else the first error [:failed, index] (that invoice may have been paid); else, when the
202
+ # read was not answered by a majority, [:unread]. Else [:hand_out, index]: the only one; of
203
+ # several, the only one held (the one shown), else the newest that received something
204
+ # (unconfirmed, or open with received above 0), else the newest.
205
+ def pending_outcome(statuses, held)
206
+ paid = statuses.index { |status| status.ok? && status.value.paid? }
207
+ return [:paid, paid] if paid
208
+
209
+ failed = statuses.index { |status| !status.ok? }
210
+ return [:failed, failed] if failed
211
+ return [:hand_out, 0] if statuses.size == 1
212
+ return [:unread] if held.nil?
213
+
214
+ shown = held.each_index.select { |index| held[index] }
215
+ return [:hand_out, shown[0]] if shown.size == 1
216
+
217
+ received = statuses.rindex do |status|
218
+ status.value.unconfirmed? || (status.value.open? && Integer(status.value.received || "0", 10).positive?)
219
+ end
220
+ [:hand_out, received || (statuses.size - 1)]
221
+ end
222
+
223
+ # The key, in SaleRecords#rests, of the invoice with `address` and the end `expires_at`.
224
+ def rest_key_of(address, expires_at)
225
+ "#{address}/#{expires_at}"
226
+ end
227
+
228
+ # The price of a declared sale as a Fiat: nil for a sale in sats.
229
+ def fiat_of(price)
230
+ return nil if price["currency"] == Protocol::SATS_CURRENCY
231
+
232
+ Fiat.new(amount: Rates.format_decimal(Rates::Decimal.new(units: price["minor"], scale: price["digits"])),
233
+ currency: price["currency"], minor: price["minor"].to_s, digits: price["digits"])
234
+ end
235
+ end
236
+ end
237
+ end
238
+ end
@@ -0,0 +1,234 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ffi"
4
+ require "securerandom"
5
+
6
+ module Sattleme
7
+ module Checkout
8
+ # libsecp256k1 (https://github.com/bitcoin-core/secp256k1, Bitcoin Core's) is not found, or
9
+ # lacks a module the gem needs: raised when the gem is required, never by a call.
10
+ class LibraryNotFound < LoadError; end
11
+
12
+ module Internal
13
+ # secp256k1 (SPEC.md §11, §12): BIP-340 signatures, x-only public keys and `lift_x`, and the
14
+ # ECDH of NIP-44, from libsecp256k1, the library Bitcoin Core uses and audits, through FFI:
15
+ # never a curve of this gem's own. The system's library (0.2.0 or later, with its ecdh,
16
+ # extrakeys and schnorrsig modules, which its builds enable by default), or the one
17
+ # SATTLEME_SECP256K1_LIBRARY names (a path).
18
+ module Secp256k1
19
+ extend FFI::Library
20
+
21
+ # The environment variable that names the library's file, when it is not where the
22
+ # system's dynamic loader finds it.
23
+ LIBRARY_VARIABLE = "SATTLEME_SECP256K1_LIBRARY"
24
+ # Its names: the development link first, then each release's soname (0.2.0 is .so.1, 0.8.0
25
+ # .so.7), then Homebrew's prefixes, which macOS's loader does not search.
26
+ NAMES = [
27
+ "secp256k1",
28
+ *8.downto(0).map { |version| "libsecp256k1.so.#{version}" },
29
+ "/opt/homebrew/lib/libsecp256k1.dylib",
30
+ "/usr/local/lib/libsecp256k1.dylib"
31
+ ].freeze
32
+ INSTALL = "install libsecp256k1 0.2.0 or later (Debian, Ubuntu: apt install " \
33
+ "libsecp256k1-dev; Fedora: dnf install libsecp256k1; Alpine: apk add " \
34
+ "libsecp256k1; macOS: brew install secp256k1), or name its file in " \
35
+ "#{LIBRARY_VARIABLE}".freeze
36
+
37
+ begin
38
+ path = ENV.fetch(LIBRARY_VARIABLE, "")
39
+ ffi_lib(path.empty? ? NAMES : [path])
40
+ rescue LoadError
41
+ raise LibraryNotFound, "sattleme-checkout needs libsecp256k1: #{INSTALL}"
42
+ end
43
+
44
+ # SECP256K1_CONTEXT_NONE (secp256k1.h): every context can sign and verify since 0.2.0.
45
+ CONTEXT_NONE = 1
46
+ # The sizes of the library's opaque structures (secp256k1.h, secp256k1_extrakeys.h).
47
+ PUBKEY_BYTES = 64
48
+ KEYPAIR_BYTES = 96
49
+
50
+ # The ECDH output function (secp256k1_ecdh.h): it gets the shared point's coordinates.
51
+ callback :ecdh_hash, %i[pointer pointer pointer pointer], :int
52
+
53
+ {
54
+ "the library itself" => [
55
+ [:secp256k1_context_create, [:uint], :pointer],
56
+ [:secp256k1_context_randomize, %i[pointer pointer], :int],
57
+ [:secp256k1_ec_seckey_verify, %i[pointer pointer], :int],
58
+ [:secp256k1_ec_pubkey_parse, %i[pointer pointer pointer size_t], :int]
59
+ ],
60
+ "its extrakeys module" => [
61
+ [:secp256k1_keypair_create, %i[pointer pointer pointer], :int],
62
+ [:secp256k1_keypair_xonly_pub, %i[pointer pointer pointer pointer], :int],
63
+ [:secp256k1_xonly_pubkey_parse, %i[pointer pointer pointer], :int],
64
+ [:secp256k1_xonly_pubkey_serialize, %i[pointer pointer pointer], :int]
65
+ ],
66
+ "its schnorrsig module" => [
67
+ [:secp256k1_schnorrsig_sign32, %i[pointer pointer pointer pointer pointer], :int],
68
+ [:secp256k1_schnorrsig_verify, %i[pointer pointer pointer size_t pointer], :int]
69
+ ],
70
+ "its ecdh module" => [
71
+ [:secp256k1_ecdh, %i[pointer pointer pointer pointer ecdh_hash pointer], :int]
72
+ ]
73
+ }.each do |part, functions|
74
+ functions.each { |name, arguments, result| attach_function(name, arguments, result) }
75
+ rescue FFI::NotFoundError
76
+ raise LibraryNotFound, "sattleme-checkout needs libsecp256k1 with #{part} " \
77
+ "(#{ffi_libraries.map(&:name).join(", ")} has not): #{INSTALL}"
78
+ end
79
+
80
+ # NIP-44's shared secret is the x coordinate of the ECDH point, unhashed: the library hashes
81
+ # it by default, this output function copies it as it is.
82
+ X_ONLY = FFI::Function.new(:int, %i[pointer pointer pointer pointer]) do |output, x, _y, _data|
83
+ output.put_bytes(0, x.get_bytes(0, 32))
84
+ 1
85
+ end
86
+
87
+ # One context for every call: its API is thread-safe but for its randomization, done here
88
+ # once (a blinding of the signing tables against side channels).
89
+ CONTEXT = secp256k1_context_create(CONTEXT_NONE)
90
+ raise LibraryNotFound, "libsecp256k1 made no context" if CONTEXT.null?
91
+
92
+ FFI::MemoryPointer.new(:uchar, 32) do |seed|
93
+ seed.put_bytes(0, SecureRandom.random_bytes(32))
94
+ secp256k1_context_randomize(CONTEXT, seed)
95
+ seed.clear
96
+ end
97
+
98
+ module_function
99
+
100
+ # Whether `secret` (32 bytes) is a secret key: from 1 to the curve's order minus 1.
101
+ def valid_secret?(secret)
102
+ return false unless secret.is_a?(String) && secret.bytesize == 32
103
+
104
+ with_bytes(secret) { |pointer| secp256k1_ec_seckey_verify(CONTEXT, pointer) == 1 }
105
+ end
106
+
107
+ # The x-only public key (32 bytes) of the secret key `secret` (BIP-340). Raises ArgumentError
108
+ # for a value that is not a secret key.
109
+ def public_key(secret)
110
+ with_keypair(secret) do |keypair|
111
+ FFI::MemoryPointer.new(:uchar, PUBKEY_BYTES) do |xonly|
112
+ raise ArgumentError, "Invalid secret key" if secp256k1_keypair_xonly_pub(CONTEXT, xonly, nil,
113
+ keypair) != 1
114
+
115
+ FFI::MemoryPointer.new(:uchar, 32) do |output|
116
+ secp256k1_xonly_pubkey_serialize(CONTEXT, output, xonly)
117
+ return output.get_bytes(0, 32)
118
+ end
119
+ end
120
+ end
121
+ end
122
+
123
+ # Whether `x` (32 bytes) is the x coordinate of a point of the curve (BIP-340 `lift_x`).
124
+ def xonly?(x)
125
+ return false unless x.is_a?(String) && x.bytesize == 32
126
+
127
+ FFI::MemoryPointer.new(:uchar, PUBKEY_BYTES) do |xonly|
128
+ with_bytes(x) { |input| return secp256k1_xonly_pubkey_parse(CONTEXT, xonly, input) == 1 }
129
+ end
130
+ end
131
+
132
+ # The BIP-340 signature (64 bytes) of `message` (32 bytes) by `secret`, with the 32 bytes
133
+ # `aux` of auxiliary random data.
134
+ def sign(message, secret, aux)
135
+ raise ArgumentError, "A message of 32 bytes" unless message.bytesize == 32
136
+ raise ArgumentError, "32 bytes of auxiliary data" unless aux.bytesize == 32
137
+
138
+ with_keypair(secret) do |keypair|
139
+ FFI::MemoryPointer.new(:uchar, 64) do |signature|
140
+ with_bytes(message) do |digest|
141
+ with_bytes(aux) do |random|
142
+ ok = secp256k1_schnorrsig_sign32(CONTEXT, signature, digest, keypair, random)
143
+ raise ArgumentError, "Signing failed" unless ok == 1
144
+ end
145
+ end
146
+ return signature.get_bytes(0, 64)
147
+ end
148
+ end
149
+ end
150
+
151
+ # Whether `signature` (64 bytes) is a BIP-340 signature of `message` (32 bytes) by the
152
+ # x-only public key `x` (32 bytes). False for anything malformed.
153
+ def verify(signature, message, x)
154
+ return false unless [signature, message, x].all?(String)
155
+ return false unless signature.bytesize == 64 && message.bytesize == 32 && x.bytesize == 32
156
+
157
+ Verifications.increment
158
+ FFI::MemoryPointer.new(:uchar, PUBKEY_BYTES) do |xonly|
159
+ with_bytes(x) { |input| return false unless secp256k1_xonly_pubkey_parse(CONTEXT, xonly, input) == 1 }
160
+ with_bytes(signature) do |sig|
161
+ with_bytes(message) do |digest|
162
+ return secp256k1_schnorrsig_verify(CONTEXT, sig, digest, 32, xonly) == 1
163
+ end
164
+ end
165
+ end
166
+ end
167
+
168
+ # The x coordinate (32 bytes) of the ECDH point of `secret` and the x-only public key `x`
169
+ # (its even point: either has the same product's x), as NIP-44 v2 takes it. Constant time
170
+ # in the secret (secp256k1_ecdh). Raises ArgumentError for an invalid key.
171
+ def shared_x(secret, x)
172
+ raise ArgumentError, "Invalid public key" unless x.is_a?(String) && x.bytesize == 32
173
+ raise ArgumentError, "Invalid secret key" unless valid_secret?(secret)
174
+
175
+ FFI::MemoryPointer.new(:uchar, PUBKEY_BYTES) do |point|
176
+ with_bytes("\x02".b + x) do |input|
177
+ raise ArgumentError, "Invalid public key" if secp256k1_ec_pubkey_parse(CONTEXT, point, input, 33) != 1
178
+ end
179
+ FFI::MemoryPointer.new(:uchar, 32) do |output|
180
+ with_bytes(secret) do |scalar|
181
+ raise ArgumentError, "Invalid secret key" if secp256k1_ecdh(CONTEXT, output, point, scalar, X_ONLY,
182
+ nil) != 1
183
+ end
184
+ shared = output.get_bytes(0, 32)
185
+ output.clear
186
+ return shared
187
+ end
188
+ end
189
+ end
190
+
191
+ # `bytes` copied into memory of the library's, cleared once `block` returned.
192
+ def with_bytes(bytes)
193
+ FFI::MemoryPointer.new(:uchar, bytes.bytesize) do |pointer|
194
+ pointer.put_bytes(0, bytes)
195
+ return yield pointer
196
+ ensure
197
+ pointer.clear
198
+ end
199
+ end
200
+
201
+ # The key pair of `secret`, cleared once `block` returned. ArgumentError for an invalid key.
202
+ def with_keypair(secret)
203
+ raise ArgumentError, "Invalid secret key" unless secret.is_a?(String) && secret.bytesize == 32
204
+
205
+ FFI::MemoryPointer.new(:uchar, KEYPAIR_BYTES) do |keypair|
206
+ with_bytes(secret) do |seckey|
207
+ raise ArgumentError, "Invalid secret key" unless secp256k1_keypair_create(CONTEXT, keypair, seckey) == 1
208
+ end
209
+ return yield keypair
210
+ ensure
211
+ keypair.clear
212
+ end
213
+ end
214
+
215
+ # How many signatures were verified: a test counts those a read checks (each costs a
216
+ # fraction of a millisecond, and a relay decides how many records it sends).
217
+ module Verifications
218
+ @count = 0
219
+ @mutex = Mutex.new
220
+
221
+ class << self
222
+ def increment
223
+ @mutex.synchronize { @count += 1 }
224
+ end
225
+
226
+ def count
227
+ @mutex.synchronize { @count }
228
+ end
229
+ end
230
+ end
231
+ end
232
+ end
233
+ end
234
+ end
@@ -0,0 +1,144 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sattleme
4
+ module Checkout
5
+ module Internal
6
+ # Text rules every implementation applies alike (SPEC.md §6): lengths in Unicode code
7
+ # points, trimming and case of ASCII only, strict UTF-8, lone surrogates refused. Ruby's own
8
+ # `strip`, `downcase` and regular expressions follow other rules, or raise on a string whose
9
+ # UTF-8 is broken (as a lone surrogate from Json.parse leaves it): every check here takes any
10
+ # value and answers false for anything but a well-formed text.
11
+ module Text
12
+ UTF_8 = Encoding::UTF_8
13
+
14
+ module_function
15
+
16
+ # Whether `value` is a String of well-formed UTF-8: no invalid byte, no lone surrogate (US-ASCII,
17
+ # which Ruby gives what it packs and prints, is UTF-8 too).
18
+ def well_formed?(value)
19
+ value.is_a?(String) && [UTF_8, Encoding::US_ASCII].include?(value.encoding) &&
20
+ value.valid_encoding?
21
+ end
22
+
23
+ # A caller's String as well-formed UTF-8, whatever its encoding says: UTF-8 as it is,
24
+ # US-ASCII (`42.to_s`, a variable of the environment under the C locale) or binary bytes
25
+ # decoded strictly as UTF-8, any other encoding transcoded from it. Nil when it is no String,
26
+ # or its bytes are not valid in its encoding (a lone surrogate included): never repaired.
27
+ def caller_text(value)
28
+ return nil unless value.is_a?(String)
29
+ return (value.valid_encoding? ? value : nil) if value.encoding == UTF_8
30
+ return decode_utf8(value) if [Encoding::US_ASCII, Encoding::BINARY].include?(value.encoding)
31
+ return nil unless value.valid_encoding?
32
+
33
+ value.encode(UTF_8)
34
+ rescue EncodingError
35
+ nil
36
+ end
37
+
38
+ # Whether `value` is a well-formed text that `pattern` matches.
39
+ def match?(value, pattern)
40
+ well_formed?(value) && value.match?(pattern)
41
+ end
42
+
43
+ # The text of UTF-8 `bytes`, decoded strictly (a byte order mark kept, as U+FEFF); nil when
44
+ # they are not valid UTF-8 (never repaired).
45
+ def decode_utf8(bytes)
46
+ text = bytes.dup.force_encoding(UTF_8)
47
+ text.valid_encoding? ? text : nil
48
+ end
49
+
50
+ # The UTF-8 bytes of a well-formed text.
51
+ def utf8(text)
52
+ text.b
53
+ end
54
+
55
+ # Unicode code points of a well-formed text.
56
+ def code_point_length(text)
57
+ text.length
58
+ end
59
+
60
+ # Bytes of a well-formed text in UTF-8.
61
+ def utf8_length(text)
62
+ text.bytesize
63
+ end
64
+
65
+ # A well-formed text with A–Z lowered to a–z, and nothing else changed.
66
+ def ascii_lower(text)
67
+ text.tr("A-Z", "a-z")
68
+ end
69
+
70
+ # A well-formed text without its leading and trailing ASCII whitespace (space, tab, line
71
+ # feed, carriage return).
72
+ def trim_ascii(text)
73
+ text.sub(/\A[ \t\n\r]+/, "").sub(/[ \t\n\r]+\z/, "")
74
+ end
75
+
76
+ # Whether a well-formed text holds a C0 control character (U+0000 to U+001F) or DEL.
77
+ def control_character?(text)
78
+ text.match?(/[\x00-\x1F\x7F]/)
79
+ end
80
+
81
+ # Lowercase hex of 32 bytes.
82
+ def hex32?(value)
83
+ match?(value, /\A[0-9a-f]{64}\z/)
84
+ end
85
+
86
+ # Lowercase hex of 64 bytes.
87
+ def hex64?(value)
88
+ match?(value, /\A[0-9a-f]{128}\z/)
89
+ end
90
+
91
+ # The bytes of lowercase (or any case) hex text.
92
+ def hex_bytes(text)
93
+ [text].pack("H*")
94
+ end
95
+
96
+ # Lowercase hex of `bytes`.
97
+ def hex(bytes)
98
+ bytes.unpack1("H*").force_encoding(UTF_8)
99
+ end
100
+ end
101
+
102
+ # Base64 (RFC 4648), as the merchant's app writes it (SPEC.md §2): decoding is strict, one
103
+ # value has one spelling (the alphabet's characters only, padding exactly where §4 puts it,
104
+ # unused trailing bits zero); anything else is refused (nil), never repaired.
105
+ module Base64
106
+ STANDARD = %r{\A(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?\z}
107
+ URL_SAFE = /\A[A-Za-z0-9_-]*\z/
108
+
109
+ module_function
110
+
111
+ # Standard base64 with "=" padding (RFC 4648 §4), as NIP-44 payloads use it.
112
+ def encode(bytes)
113
+ [bytes].pack("m0").force_encoding(Text::UTF_8)
114
+ end
115
+
116
+ # The bytes of padded standard base64 text, or nil when it is not canonical.
117
+ def decode(text)
118
+ return nil unless Text.match?(text, STANDARD)
119
+
120
+ bytes = text.unpack1("m0")
121
+ encode(bytes) == text ? bytes : nil
122
+ rescue ArgumentError
123
+ nil
124
+ end
125
+
126
+ # Base64url without padding (RFC 4648 §5).
127
+ def encode_url(bytes)
128
+ encode(bytes).tr("+/", "-_").delete("=")
129
+ end
130
+
131
+ # The bytes of unpadded base64url text, or nil when it is not canonical.
132
+ def decode_url(text)
133
+ return nil unless Text.match?(text, URL_SAFE) && text.length % 4 != 1
134
+
135
+ padded = text.tr("-_", "+/") + ("=" * ((4 - (text.length % 4)) % 4))
136
+ bytes = padded.unpack1("m0")
137
+ encode_url(bytes) == text ? bytes : nil
138
+ rescue ArgumentError
139
+ nil
140
+ end
141
+ end
142
+ end
143
+ end
144
+ end