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,260 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sattleme
4
+ module Checkout
5
+ module Internal
6
+ # Every constant of the protocol (SPEC.md §28), in one place. Those marked "never changes" are
7
+ # fixed by data already published (keys, channels, declarations): changing one loses
8
+ # merchants' sales or stops their integrations.
9
+ module Protocol
10
+ # The beginning of every integration key (`sattleme` sattle.me, `ck` checkout key). Never
11
+ # changes: a later format of the key takes another prefix (`sattleme_ck2_`).
12
+ INTEGRATION_KEY_PREFIX = "sattleme_ck_"
13
+ # Bytes of the team's public key and of the integration's key.
14
+ KEY_BYTES = 32
15
+
16
+ # HKDF-SHA256 salts (UTF-8). Never change.
17
+ INTEGRATION_SALT = "sattle.me/integration"
18
+ SALE_SALT = "sattle.me/sale"
19
+ DECLARATION_SALT = "sattle.me/registry-declaration"
20
+
21
+ # HKDF-SHA256 `info` strings (UTF-8). Never change.
22
+ CHANNEL_ADDRESS_INFO = "channel/address/v1"
23
+ CHANNEL_ENCRYPTION_INFO = "channel/encryption-key/v1"
24
+ TAKER_INFO = "taker/v1"
25
+ SALE_NOSTR_SECRET_INFO = "nostr-secret-key/v1"
26
+ # Bytes of HMAC-SHA256(taker key, author) kept as the taker tag.
27
+ TAKER_TAG_BYTES = 16
28
+
29
+ # NIP-78 application data: every record of the app. NIP-42 authentication.
30
+ RECORD_KIND = 30_078
31
+ AUTH_KIND = 22_242
32
+ # A record's plaintext is padded with spaces to a multiple of this many bytes.
33
+ RECORD_BLOCK_BYTES = 256
34
+
35
+ CHANNEL_RECORD_TYPE = "team-channel"
36
+ CHANNEL_VERSION = 1
37
+ # At most this many moves of the merchant's relays are followed.
38
+ MAX_RELAY_MOVES = 3
39
+ # Longest business name, in Unicode code points.
40
+ MAX_BUSINESS_NAME_LENGTH = 200
41
+
42
+ DECLARATION_RECORD_TYPE = "registry-declaration"
43
+ DECLARATION_VERSION = 1
44
+ # The currency of a sale declared in sats: its `minor` is the sats, its `digits` 0.
45
+ SATS_CURRENCY = "SAT"
46
+ # Most decimals a declared price may have.
47
+ MAX_DECLARED_DIGITS = 8
48
+ # Largest amount in minor units (2^53 − 1: a JSON number every reader holds exactly).
49
+ MAX_MINOR_UNITS = 9_007_199_254_740_991
50
+
51
+ # Checkout links (SPEC.md §30). The salt and `info` strings never change: the merchant's web
52
+ # app derives the same keys.
53
+ CHECKOUT_SALT = "sattle.me/checkout"
54
+ CHECKOUT_ADDRESS_INFO = "address/v1"
55
+ CHECKOUT_ENCRYPTION_INFO = "encryption-key/v1"
56
+ CHECKOUT_RECORD_TYPE = "checkout"
57
+ CHECKOUT_VERSION = 1
58
+ # The version of a checkout link's record for an invoice with an address.
59
+ CHECKOUT_ONCHAIN_VERSION = 2
60
+ # The first part of a checkout link's fragment: a link of this version. Never changes.
61
+ CHECKOUT_MARKER = "c"
62
+ # The page of the merchant's web app that reads checkout links.
63
+ CHECKOUT_PATH = "/pay"
64
+ # A checkout link's record lives this long after its invoice's end (NIP-40): a week.
65
+ CHECKOUT_LIFE_SECONDS = 604_800
66
+ # Longest redirect URL, in characters (ASCII only), and longest scheme of an app's link.
67
+ MAX_REDIRECT_URL_LENGTH = 2048
68
+ MAX_REDIRECT_SCHEME_LENGTH = 32
69
+ # Schemes a redirect URL never has: the browser's own, files and scripts; other browsers
70
+ # (they open any web page given in the rest of the link, whose host the page would not show:
71
+ # a web page is an https URL); other transports; any Android activity; payments (a second
72
+ # invoice right after the first); calls and messages; installing software or running system
73
+ # tools. `https` follows its own rule.
74
+ REFUSED_REDIRECT_SCHEMES = %w[
75
+ about blob chrome chrome-extension content data file filesystem javascript moz-extension
76
+ resource safari-extension vbscript view-source
77
+ brave com-apple-mobilesafari-tab ddgquicklink firefox firefox-focus googlechrome
78
+ googlechrome-x-callback googlechromes microsoft-edge microsoft-edge-http
79
+ microsoft-edge-https onionbrowser onionbrowsers opera-http opera-https x-safari-http
80
+ x-safari-https
81
+ ftp http ws wss
82
+ android-app intent
83
+ bitcoin keyauth lightning liquidnetwork lnurl lnurlc lnurlp lnurlw
84
+ callto facetime facetime-audio mailto sip sms tel
85
+ itms-services ms-msdt search-ms
86
+ ].to_set.freeze
87
+
88
+ # Most relays a list holds, and the longest relay address (`wss://` included).
89
+ MAX_RELAYS = 10
90
+ MAX_RELAY_URL_LENGTH = 120
91
+ # Longest host of a relay address, a checkout origin, a redirect URL or an https URL.
92
+ MAX_HOST_LENGTH = 253
93
+ # Longest https URL (a pay URL, a callback, a verify URL), in characters (ASCII only).
94
+ MAX_HTTPS_URL_LENGTH = 2048
95
+
96
+ # An order's reference: one order, one sale.
97
+ REF_PATTERN = /\A[A-Za-z0-9._:-]{1,64}\z/
98
+ REF_RULE = "1 to 64 characters A-Z a-z 0-9 . _ : -"
99
+ # Invoice durations, in seconds.
100
+ MIN_DURATION_SECONDS = 60
101
+ MAX_DURATION_SECONDS = 3600
102
+ DEFAULT_DURATION_SECONDS = 900
103
+ # Longest note, in Unicode code points.
104
+ MAX_NOTE_LENGTH = 100
105
+
106
+ # After an invoice's end, a payment of its last seconds may still be reported: until then,
107
+ # "not paid" is not final.
108
+ GRACE_SECONDS = 120
109
+ # An invoice's date may be this far from the server's clock (synchronized by NTP).
110
+ CLOCK_TOLERANCE_SECONDS = 300
111
+ # The LUD-21 refusal that means "never paid" once the grace period is over.
112
+ NOT_FOUND_REASON = "Not found"
113
+
114
+ # A dated price older than this is refused; one dated further than the clock tolerance
115
+ # ahead too.
116
+ MAX_RATE_AGE_SECONDS = 3600
117
+ # Longest price text a rate source may give, and largest exponent (either sign) in it.
118
+ MAX_PRICE_LENGTH = 64
119
+ MAX_PRICE_EXPONENT = 64
120
+
121
+ # Most events read from one relay for one query, and most pages of a paged read.
122
+ MAX_EVENTS_PER_QUERY = 1000
123
+ MAX_PAGES = 20
124
+ # The `limit` of each page of a complete read: a page of fewer events is the relay's last.
125
+ COMPLETE_READ_LIMIT = 100
126
+ # The User-Agent of every HTTP request and WebSocket handshake: the same in every
127
+ # implementation and version (CoinGecko refuses a request without one; one naming a language
128
+ # or a version would help single it out).
129
+ USER_AGENT = "sattleme-Checkout/1"
130
+ # Largest message read from a relay, and largest HTTP answer body read.
131
+ MAX_RELAY_MESSAGE_BYTES = 1 << 20
132
+ MAX_HTTP_BODY_BYTES = 1 << 20
133
+ # Earlier invoices of an order checked at once (createInvoice).
134
+ MAX_PARALLEL_PAYMENT_CHECKS = 4
135
+
136
+ # Per request timeouts, in milliseconds: the default and the bounds a caller may choose.
137
+ DEFAULT_TIMEOUT_MS = 10_000
138
+ MIN_TIMEOUT_MS = 100
139
+ MAX_TIMEOUT_MS = 60_000
140
+ # waitForPayment's interval, in milliseconds.
141
+ DEFAULT_INTERVAL_MS = 2000
142
+ MIN_INTERVAL_MS = 250
143
+ MAX_INTERVAL_MS = 60_000
144
+
145
+ # Longest `x` (expiry) field of a BOLT11 invoice, in 5-bit words (35 bits, as its date).
146
+ MAX_BOLT11_EXPIRY_WORDS = 7
147
+ # Largest BOLT11 amount: 21 million bitcoins, in millisatoshis.
148
+ MAX_BOLT11_AMOUNT_MSAT = 2_100_000_000_000_000_000
149
+
150
+ # On-chain payments (SPEC.md §31). The types, salts and `info` strings never change: the
151
+ # merchant's app reads the same records.
152
+ # Below this amount, an order is Lightning only.
153
+ ONCHAIN_FLOOR_SATS = 1000
154
+ # The largest amount of an order: 21 million bitcoins, in sats.
155
+ MAX_SATS = 2_100_000_000_000_000
156
+ SATS_PER_BTC = 100_000_000
157
+
158
+ LOT_RECORD_TYPE = "integration-onchain-lot"
159
+ LOT_VERSION = 1
160
+ LOT_ADDRESS_INFO = "onchain-lot/address/v1"
161
+ # Most addresses a lot holds.
162
+ MAX_LOT_ADDRESSES = 100
163
+
164
+ LEASE_RECORD_TYPE = "registry-onchain"
165
+ LEASE_VERSION = 1
166
+ # What a deposit address's registry address is the HMAC of: this, then the address (UTF-8).
167
+ LEASE_ADDRESS_PREFIX = "onchain/v1/"
168
+ # Leases read back this far: a lease ends at most 4 320 s after its `created_at` (a BOLT11
169
+ # date up to 300 s ahead, 3600 s, the grace period, the clock tolerance).
170
+ LEASE_LOOKBACK_SECONDS = 7200
171
+ # Free addresses tried for one order.
172
+ MAX_ADDRESS_TRIES = 3
173
+
174
+ WITNESS_RECORD_TYPE = "integration-onchain-seen"
175
+ WITNESS_VERSION = 1
176
+ SEEN_SECRET_INFO = "onchain-seen/nostr-secret-key/v1"
177
+ SEEN_ADDRESS_KEY_INFO = "onchain-seen/address-key/v1"
178
+ # The tag of a witness that names its order (its address and sale), and its address.
179
+ ORDER_TAG = "o"
180
+ # The coins of a transaction a witness keeps: its first 100.
181
+ MAX_WITNESS_INPUTS = 100
182
+ # The `sale` a witness names when the transaction came at no lease's time.
183
+ NO_SALE = "none"
184
+
185
+ # mempool.space (Esplora REST): the explorer, unless the channel names the merchant's Bitcoin
186
+ # node (BitcoinNodes), and the node's fallback when it says "mempool".
187
+ MEMPOOL_URL = "https://mempool.space/api"
188
+ # mempool.space's WebSocket, which wait_for_payment watches an address on without a node.
189
+ MEMPOOL_WEBSOCKET_URL = "wss://mempool.space/api/v1/ws"
190
+ # A node URL (SPEC.md §31, "A node URL"): 200 characters at most.
191
+ MAX_NODE_URL_LENGTH = 200
192
+ # A node that failed a read less than this long ago, in the same call, is asked after
193
+ # mempool.space (`fallback` "mempool"): a node that does not answer does not make each read
194
+ # wait for its timeout.
195
+ NODE_FAILED_RECENTLY_SECONDS = 60
196
+ # When a transaction was received, asked only for one no check saw while its lease ran.
197
+ BLOCKCYPHER_URL = "https://api.blockcypher.com/v1/btc/main"
198
+ # Confirmations of an on-chain payment, on the explorer read.
199
+ CONFIRMATIONS = 3
200
+ # The on-chain part is checked at least this often while waitForPayment waits.
201
+ ONCHAIN_CHECK_INTERVAL_MS = 60_000
202
+ # The explorer's WebSocket, lost: connected again after this, doubled at each failure, up
203
+ # to RECONNECT_MAX_MS.
204
+ RECONNECT_FIRST_MS = 1000
205
+ RECONNECT_MAX_MS = 30_000
206
+
207
+ # The rest of an on-chain underpayment (SPEC.md §31). The type, the salts and the `info`
208
+ # strings never change: the merchant's web app reads the same records.
209
+ REST_RECORD_TYPE = "checkout-rest"
210
+ REST_VERSION = 1
211
+ # HKDF `info` (salt CHECKOUT_SALT) of a rest record's encryption key.
212
+ REST_ENCRYPTION_INFO = "rest/encryption-key/v1"
213
+ # A rest invoice is asked only with this long left before the invoice's end.
214
+ MIN_REST_SECONDS = 60
215
+
216
+ # The merchant's tolerance of on-chain underpayments: an integer of basis points, from 0 to
217
+ # MAX_TOLERANCE (10 %); anything else is 0.
218
+ MAX_TOLERANCE = 1000
219
+ # Basis points in a whole.
220
+ TOLERANCE_SCALE = 10_000
221
+
222
+ # Acceptance records (SPEC.md §31). The type and the `info` string never change.
223
+ ACCEPTANCE_RECORD_TYPE = "checkout-accepted"
224
+ ACCEPTANCE_VERSION = 1
225
+ ACCEPTANCE_ADDRESS_INFO = "rest/accepted/v1"
226
+
227
+ # The merchant's acceptance (SPEC.md §31, "The merchant's acceptance"): the merchant accepts
228
+ # by hand, in its app, what an order underpaid on-chain received as paying it. A record of
229
+ # the team (never the integration's: it opens one but cannot make one), sealed with the
230
+ # channel's key, at an address the integration key derives (salt INTEGRATION_SALT) from the
231
+ # order's sale author, the invoice's deposit address and its `expiresAt`. The type and the
232
+ # `info` string never change: the merchant's app writes the same records.
233
+ MERCHANT_ACCEPTANCE_RECORD_TYPE = "integration-onchain-accepted"
234
+ MERCHANT_ACCEPTANCE_VERSION = 1
235
+
236
+ module_function
237
+
238
+ def sale_info(ref) = "sale/#{ref}/v1"
239
+
240
+ def outer_info(address, author) = "outer/v1/#{address}/#{author}"
241
+
242
+ # HKDF `info` of the rest key and the rest secret of the invoice of the order `ref` with the
243
+ # deposit address `address` and the end `expires_at` (Unix seconds, decimal).
244
+ def rest_key_info(ref, address, expires_at) = "checkout-rest/#{ref}/#{address}/#{expires_at}/key/v1"
245
+
246
+ def rest_secret_info(ref, address, expires_at)
247
+ "checkout-rest/#{ref}/#{address}/#{expires_at}/nostr-secret-key/v1"
248
+ end
249
+
250
+ # HKDF `info` (salt CHECKOUT_SALT) of a rest record's address, of the payment hash `hash`.
251
+ def rest_address_info(hash) = "rest/address/#{hash}/v1"
252
+
253
+ # HKDF `info` (salt INTEGRATION_SALT) of the merchant's acceptance address of the invoice of
254
+ # the sale `sale` (its author, hex) with the deposit address `address` and the end
255
+ # `expires_at` (Unix seconds, decimal).
256
+ def merchant_acceptance_info(sale, address, expires_at) = "onchain-accepted/#{sale}/#{address}/#{expires_at}/v1"
257
+ end
258
+ end
259
+ end
260
+ end
@@ -0,0 +1,373 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sattleme
4
+ module Checkout
5
+ module Internal
6
+ # Amounts in a currency, converted to sats on the integrator's server at the rate of the
7
+ # source it chooses (SPEC.md §25, §26). Exact integers end to end: the price of one bitcoin is
8
+ # read as the exact decimal its source wrote, and the sats are rounded up to the next whole
9
+ # sat: the merchant never receives less than the price.
10
+ module Rates
11
+ # An exact positive decimal: `units` × 10^-`scale`.
12
+ Decimal = Data.define(:units, :scale)
13
+
14
+ # A price of one bitcoin as a source gave it: a decimal string, and when it was set (Unix
15
+ # seconds, nil when the source does not say).
16
+ Quote = Data.define(:price, :time)
17
+
18
+ # What a source may use: the HTTP context (the call's stop included) and CoinGecko's key.
19
+ Context = Data.define(:http, :coingecko_api_key) do
20
+ include Redacted
21
+
22
+ def stop = http.stop
23
+
24
+ def inspect = "#<Rates::Context>"
25
+ alias_method :to_s, :inspect
26
+ end
27
+
28
+ DECIMAL = /\A([0-9]+)(?:\.([0-9]+))?(?:[eE]([+-]?[0-9]+))?\z/
29
+ FIAT_AMOUNT = /\A([0-9]{1,15})(?:\.([0-9]{1,15}))?\z/
30
+ # The sources the gem knows, by name.
31
+ NAMES = %w[coingecko mempool opennode coinbase kraken].freeze
32
+ # The sources asked when the client is given none, in this order: the dated ones first
33
+ # (their price's age is checked), CoinGecko for its currencies, then mempool.space for its
34
+ # 7; then the undated ones, Coinbase and Kraken (two exchanges), and OpenNode.
35
+ DEFAULT_SOURCES = %w[coingecko mempool coinbase kraken opennode].freeze
36
+ # The currencies of mempool.space's `/api/v1/prices`.
37
+ MEMPOOL_CURRENCIES = %w[USD EUR GBP CAD CHF AUD JPY].freeze
38
+ # A member a source's answer does not hold.
39
+ ABSENT = Object.new.freeze
40
+
41
+ module_function
42
+
43
+ # A price as an exact decimal: digits, an optional fraction and an optional exponent
44
+ # (`"69025.1084416666694295"`, `"8e-8"`), 64 characters at most, an exponent of 64 at most
45
+ # either way, nothing around it. Nil unless it is strictly positive.
46
+ def parse_decimal(value)
47
+ return nil unless Text.well_formed?(value) && value.length <= Protocol::MAX_PRICE_LENGTH
48
+
49
+ match = DECIMAL.match(value)
50
+ return nil unless match
51
+
52
+ fraction = match[2] || ""
53
+ exponent = (match[3] || "0").to_i
54
+ return nil if exponent.abs > Protocol::MAX_PRICE_EXPONENT
55
+
56
+ units = Integer(match[1] + fraction, 10)
57
+ scale = fraction.length - exponent
58
+ if scale.negative?
59
+ units *= 10**-scale
60
+ scale = 0
61
+ end
62
+ # The shortest exact writing: 69012.50 is 69012.5.
63
+ while scale.positive? && (units % 10).zero?
64
+ units /= 10
65
+ scale -= 1
66
+ end
67
+ units.positive? ? Decimal.new(units: units, scale: scale) : nil
68
+ end
69
+
70
+ # The text of a JSON number a source answered: the shortest decimal that reads back as the
71
+ # same double (ECMAScript's Number::toString). Nil when it is not a finite number.
72
+ def number_text(value)
73
+ return nil unless value.is_a?(Float) || value.is_a?(Integer)
74
+ return nil if value.is_a?(Float) && !value.finite?
75
+
76
+ Json.number_text(value.is_a?(Integer) ? value.to_f : value)
77
+ end
78
+
79
+ # The plain decimal writing of an exact decimal: `69012.5`, `0.00000008`.
80
+ def format_decimal(decimal)
81
+ return decimal.units.to_s if decimal.scale.zero?
82
+
83
+ digits = decimal.units.to_s.rjust(decimal.scale + 1, "0")
84
+ "#{digits[0...-decimal.scale]}.#{digits[-decimal.scale..]}"
85
+ end
86
+
87
+ # A price given as `{ amount: "24.50", currency: "CHF" }`, as integer minor units of its
88
+ # currency: the currency an ISO 4217 code of the table (upper case); the amount a string of
89
+ # digits with at most the currency's decimals (trailing zeros aside), nothing around it:
90
+ # never a float, never rounded. Raises InvalidOrderError (`fiat`).
91
+ def parse_fiat(fiat)
92
+ raise InvalidOrderError.new("fiat", "expected { amount:, currency: }") unless fiat.is_a?(Hash)
93
+
94
+ # Strings in any encoding, read as text (Text.caller_text): never repaired.
95
+ currency = Text.caller_text(member(fiat, "currency"))
96
+ amount = member(fiat, "amount")
97
+ digits = Currencies.digits(currency)
98
+ raise InvalidOrderError.new("fiat", "currency: an ISO 4217 code in upper case, as CHF") if digits.nil?
99
+ unless amount.is_a?(String)
100
+ raise InvalidOrderError.new("fiat", 'amount: a string of digits, as "24.50" (never a float)')
101
+ end
102
+
103
+ amount = Text.caller_text(amount)
104
+ match = amount && FIAT_AMOUNT.match(amount)
105
+ raise InvalidOrderError.new("fiat", 'amount: digits, as "24.50"') unless match
106
+
107
+ fraction = (match[2] || "").sub(/0+\z/, "")
108
+ if fraction.length > digits
109
+ raise InvalidOrderError.new("fiat", "amount: #{currency} has #{digits} decimals at most")
110
+ end
111
+
112
+ padded = fraction.ljust(digits, "0")
113
+ minor = (Integer(match[1], 10) * (10**digits)) + (padded.empty? ? 0 : Integer(padded, 10))
114
+ unless minor.between?(1, Protocol::MAX_MINOR_UNITS)
115
+ raise InvalidOrderError.new("fiat", "amount: more than 0, and not that large")
116
+ end
117
+
118
+ Fiat.new(amount: format_decimal(Decimal.new(units: minor, scale: digits)), currency: currency,
119
+ minor: minor.to_s, digits: digits)
120
+ end
121
+
122
+ # A member of a Hash given by the caller, by its name as a String or a Symbol.
123
+ def member(hash, name)
124
+ hash.key?(name) ? hash[name] : hash[name.to_sym]
125
+ end
126
+
127
+ # Sats for `minor` units of a currency with `digits` decimals, at `price` (one bitcoin in
128
+ # that currency), rounded up to the next whole sat, on integers:
129
+ # ⌈minor × 10^8 × 10^scale / (units × 10^digits)⌉.
130
+ def minor_to_sats(minor, digits, price)
131
+ dividend = minor * Protocol::SATS_PER_BTC * (10**price.scale)
132
+ divisor = price.units * (10**digits)
133
+ (dividend + divisor - 1) / divisor
134
+ end
135
+
136
+ # Sats for a price in a currency at the price of one bitcoin (a decimal string): exact,
137
+ # rounded up. InvalidOrderError for an invalid price in a currency, RateError for an
138
+ # invalid price of one bitcoin.
139
+ def fiat_to_sats(fiat, price)
140
+ parsed = parse_fiat(fiat)
141
+ decimal = parse_decimal(price)
142
+ raise RateError, "A price must be a decimal string above 0" unless decimal
143
+
144
+ minor_to_sats(Integer(parsed.minor, 10), parsed.digits, decimal)
145
+ end
146
+
147
+ # A rate source as the gem keeps it: a name it knows (a String, or a Symbol of that name), as
148
+ # a String, or a callable of the integrator's (a custom source); nil for anything else (a
149
+ # name in another case, `custom`, a list).
150
+ def source_of(value)
151
+ if value.is_a?(String) || value.is_a?(Symbol)
152
+ name = Text.caller_text(value.to_s)
153
+ NAMES.include?(name) ? name.dup.freeze : nil
154
+ elsif value.respond_to?(:call) && !value.is_a?(Array)
155
+ value
156
+ end
157
+ end
158
+
159
+ # The sources `value` names, in the order they are asked: a source alone, or a non-empty
160
+ # list of sources without the same name twice (and no list inside it). Nil when it is
161
+ # neither.
162
+ def source_list(value)
163
+ single = source_of(value)
164
+ return [single].freeze if single
165
+ return nil unless value.is_a?(Array) && !value.empty?
166
+
167
+ list = value.map { |source| source_of(source) }
168
+ return nil if list.include?(nil)
169
+
170
+ names = list.grep(String)
171
+ names.uniq.size == names.size ? list.freeze : nil
172
+ end
173
+
174
+ def source_name(source)
175
+ source.is_a?(String) ? source : "custom"
176
+ end
177
+
178
+ # The price of one bitcoin in `currency` from `source`, checked: an exact positive decimal,
179
+ # not older than an hour, not further ahead than 5 minutes. Undated sources cannot be
180
+ # checked for age. UnsupportedCurrencyError when the source has no price in the currency,
181
+ # NetworkError when it does not answer, RateError for anything else. [price, RateInfo].
182
+ def fetch_rate(source, currency, context, now)
183
+ name = source_name(source)
184
+ quote = if source.is_a?(String)
185
+ named_quote(source, currency, context)
186
+ else
187
+ custom_quote(source, currency, context)
188
+ end
189
+ price = parse_decimal(quote.price)
190
+ raise RateError, "#{name} gave no valid price in #{currency}" unless price
191
+
192
+ time = quote.time
193
+ unless time.nil?
194
+ if !Json.safe_integer?(time) || time > now + Protocol::CLOCK_TOLERANCE_SECONDS
195
+ raise RateError, "#{name} gave an invalid date for its price"
196
+ end
197
+ raise RateError, "#{name}'s price in #{currency} is too old" if now - time > Protocol::MAX_RATE_AGE_SECONDS
198
+
199
+ time = time.to_i
200
+ end
201
+ [price,
202
+ RateInfo.new(source: name, currency: currency, price: format_decimal(price), fetched_at: now, time: time)]
203
+ end
204
+
205
+ # The first usable price of `sources`, asked one at a time in their order (SPEC.md §26):
206
+ # the next source only when the previous one gives no usable price (NetworkError, RateError
207
+ # or UnsupportedCurrencyError, each logged but the last). A cancellation, or any other error
208
+ # a custom source raises, stops the list. With no price: UnsupportedCurrencyError when no
209
+ # source has the currency, else the last NetworkError or RateError.
210
+ def fetch_first_rate(sources, currency, context, now, logger, ask: method(:fetch_rate))
211
+ failure = nil
212
+ unsupported = nil
213
+ sources.each_with_index do |source, index|
214
+ return ask.call(source, currency, context, now.call)
215
+ rescue UnsupportedCurrencyError, NetworkError, RateError => e
216
+ context.stop.check!
217
+ e.is_a?(UnsupportedCurrencyError) ? unsupported = e : failure = e
218
+ following = sources[index + 1]
219
+ unless following.nil?
220
+ logger.warn("Rate source #{source_name(source)} failed (#{e.code}): #{e.message}; " \
221
+ "trying #{source_name(following)}")
222
+ end
223
+ end
224
+ raise failure if failure
225
+
226
+ if sources.size > 1
227
+ names = sources.map { |source| source_name(source) }.join(", ")
228
+ raise UnsupportedCurrencyError.new(currency, names, "None of #{names} has a price in #{currency}")
229
+ end
230
+ raise unsupported
231
+ end
232
+
233
+ # A custom source's quote: it takes the currency (and, when it takes two arguments, a
234
+ # Cancellation, cancelled with the call's or once the call no longer needs the price: the
235
+ # call waits for the source to return) and gives a decimal string or `{ price:, time: }`,
236
+ # never a number. An error of the gem it raises goes through as it is; any other becomes a
237
+ # RateError (its `cause`).
238
+ def custom_quote(source, currency, context)
239
+ answer = begin
240
+ arity = source.respond_to?(:arity) ? source.arity : source.method(:call).arity
241
+ arity == 1 ? source.call(currency) : context.stop.as_cancellation { |given| source.call(currency, given) }
242
+ rescue Error, Cancelled
243
+ context.stop.check!
244
+ raise
245
+ rescue StandardError
246
+ context.stop.check!
247
+ raise RateError, "The custom rate source failed"
248
+ end
249
+ context.stop.check!
250
+ return Quote.new(price: answer, time: nil) if answer.is_a?(String)
251
+ raise RateError, "The custom rate source gave no price" unless answer.is_a?(Hash)
252
+
253
+ time = member(answer, "time")
254
+ Quote.new(price: member(answer, "price"), time: time)
255
+ end
256
+
257
+ def named_quote(name, currency, context)
258
+ case name
259
+ when "coingecko" then coingecko(currency, context)
260
+ when "mempool" then mempool(currency, context)
261
+ when "opennode" then opennode(currency, context)
262
+ when "coinbase" then coinbase(currency, context)
263
+ when "kraken" then kraken(currency, context)
264
+ else raise RateError, "No rate source named #{name}"
265
+ end
266
+ end
267
+
268
+ # A source's JSON object: NetworkError without an answer (5xx, 408, 429), RateError for any
269
+ # other status or a body that is not a JSON object.
270
+ def source_json(name, url, context, headers = {})
271
+ answer = Http.get_json(url, context.http, headers)
272
+ unless answer.ok?
273
+ status = answer.status
274
+ # Only 5xx (500 to 599), 408 and 429 say "try again" (a redirect never comes here: §15).
275
+ again = status.between?(500, 599) || [408, 429].include?(status)
276
+ raise NetworkError, "#{name} answered HTTP #{status}" if again
277
+
278
+ raise RateError, "#{name} answered HTTP #{status}"
279
+ end
280
+ raise RateError, "#{name} gave no JSON object" unless answer.body.is_a?(Hash)
281
+
282
+ answer.body
283
+ end
284
+
285
+ def object_at(value, name)
286
+ raise RateError, "#{name}: unexpected answer" unless value.is_a?(Hash)
287
+
288
+ value
289
+ end
290
+
291
+ # A member of a source's JSON object, or ABSENT.
292
+ def at(object, name)
293
+ object.key?(name) ? object[name] : ABSENT
294
+ end
295
+
296
+ # A source's price: a string as written, a JSON number as its shortest decimal.
297
+ def price_of(value, name, currency)
298
+ raise UnsupportedCurrencyError.new(currency, name) if value.equal?(ABSENT)
299
+
300
+ text = value.is_a?(String) ? value : number_text(value)
301
+ raise RateError, "#{name}: unexpected price" if text.nil?
302
+
303
+ text
304
+ end
305
+
306
+ # CoinGecko (`/simple/price`, dated with `include_last_updated_at`); with the Demo key, its
307
+ # header, sent to CoinGecko only.
308
+ def coingecko(currency, context)
309
+ code = Text.ascii_lower(currency)
310
+ url = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=#{code}" \
311
+ "&include_last_updated_at=true"
312
+ headers = context.coingecko_api_key ? { "x-cg-demo-api-key" => context.coingecko_api_key } : {}
313
+ bitcoin = object_at(at(source_json("coingecko", url, context, headers), "bitcoin"), "coingecko")
314
+ time = at(bitcoin, "last_updated_at")
315
+ Quote.new(price: price_of(at(bitcoin, code), "coingecko", currency), time: Json.number?(time) ? time : nil)
316
+ end
317
+
318
+ # mempool.space (`/api/v1/prices`, dated): 7 currencies.
319
+ def mempool(currency, context)
320
+ raise UnsupportedCurrencyError.new(currency, "mempool") unless MEMPOOL_CURRENCIES.include?(currency)
321
+
322
+ body = source_json("mempool", "https://mempool.space/api/v1/prices", context)
323
+ time = at(body, "time")
324
+ raise RateError, "mempool: no time" unless Json.number?(time)
325
+
326
+ Quote.new(price: price_of(at(body, currency), "mempool", currency), time: time)
327
+ end
328
+
329
+ # OpenNode (`/v1/rates`): some 140 currencies, undated.
330
+ def opennode(currency, context)
331
+ data = object_at(at(source_json("opennode", "https://api.opennode.com/v1/rates", context), "data"),
332
+ "opennode")
333
+ pair = at(data, "BTC#{currency}")
334
+ raise UnsupportedCurrencyError.new(currency, "opennode") if pair.equal?(ABSENT)
335
+
336
+ Quote.new(price: price_of(at(object_at(pair, "opennode"), currency), "opennode", currency), time: nil)
337
+ end
338
+
339
+ # Coinbase (`/v2/exchange-rates?currency=BTC`): prices as decimal strings, read as written.
340
+ def coinbase(currency, context)
341
+ body = source_json("coinbase", "https://api.coinbase.com/v2/exchange-rates?currency=BTC", context)
342
+ data = object_at(at(body, "data"), "coinbase")
343
+ raise RateError, "coinbase: not the rates of BTC" unless at(data, "currency") == "BTC"
344
+
345
+ rates = object_at(at(data, "rates"), "coinbase")
346
+ Quote.new(price: price_of(at(rates, currency), "coinbase", currency), time: nil)
347
+ end
348
+
349
+ # Kraken (`/0/public/Ticker?pair=XBT<currency>`): the last trade's price (`c[0]`). The
350
+ # result's key is not always the pair asked (XBTUSD gives XXBTZUSD): its only entry is read.
351
+ def kraken(currency, context)
352
+ body = source_json("kraken", "https://api.kraken.com/0/public/Ticker?pair=XBT#{currency}", context)
353
+ errors = at(body, "error")
354
+ raise RateError, "kraken: unexpected answer" unless errors.is_a?(Array)
355
+ if errors.any? { |error| Text.well_formed?(error) && error.start_with?("EQuery:Unknown asset pair") }
356
+ raise UnsupportedCurrencyError.new(currency, "kraken")
357
+ end
358
+ unless errors.empty?
359
+ raise RateError, "kraken: #{Text.well_formed?(errors[0]) ? errors[0] : "an error"}"
360
+ end
361
+
362
+ entries = object_at(at(body, "result"), "kraken").values
363
+ raise RateError, "kraken: unexpected answer" unless entries.size == 1
364
+
365
+ last = at(object_at(entries[0], "kraken"), "c")
366
+ raise RateError, "kraken: unexpected answer" unless last.is_a?(Array)
367
+
368
+ Quote.new(price: price_of(last.empty? ? ABSENT : last[0], "kraken", currency), time: nil)
369
+ end
370
+ end
371
+ end
372
+ end
373
+ end