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,168 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sattleme
4
+ module Checkout
5
+ module Internal
6
+ # The merchant's acceptance (SPEC.md §31, "The merchant's acceptance"): the merchant may
7
+ # accept by hand, in its app, what an order underpaid on-chain received as paying it in full.
8
+ # The app publishes a record of the team (the integration key opens it but cannot make one)
9
+ # holding what the order had received then; a check judges the payment against that amount
10
+ # when it is less than the least the order's tolerance accepts (Tolerance.due_onchain). The
11
+ # majority of the merchant's relays holds the truth: a check reads it on every relay and
12
+ # counts a record only when a majority of the relays sent it. A check never publishes one,
13
+ # nor publishes one again: the pages of the order's checkout links learn of it only through
14
+ # an acceptance record (Acceptances).
15
+ module MerchantAcceptances
16
+ # What a check opens the merchant's acceptance of an invoice with: the team's public key
17
+ # (hex, its only author), the channel's encryption key (its NIP-44 conversation key) and its
18
+ # `d` tag (Derive.merchant_acceptance_address). Secret but `team` and `address`.
19
+ Keys = Data.define(:team, :encryption_key, :address) do
20
+ include Redacted
21
+
22
+ def inspect = "#<MerchantAcceptances::Keys team=#{team} address=#{address}>"
23
+ alias_method :to_s, :inspect
24
+ end
25
+
26
+ # The invoice a merchant's acceptance is read for: its amount and its end.
27
+ Terms = Data.define(:sats, :expires_at)
28
+
29
+ # A merchant's acceptance a relay sent, opened (MerchantAcceptances.open): :ok, with what
30
+ # the order had received when the merchant accepted it; :newer, of a newer format (logged;
31
+ # the newest a majority sent, it leaves the order without one); :newer_set_aside, of a
32
+ # newer format dated after the lease's end (set aside as any record dated so, logged).
33
+ Opened = Data.define(:status, :event, :received)
34
+
35
+ # The merchant's acceptance of an invoice, as a check counts it: the `received` of the one
36
+ # that counts (nil without one), and whether a relay sent one of a newer format, whatever
37
+ # its date and however many relays sent it.
38
+ Acceptance = Data.define(:received, :newer)
39
+
40
+ NONE = Acceptance.new(received: nil, newer: false)
41
+
42
+ # What a check logs when a relay sent a merchant's acceptance of a newer format.
43
+ NEWER_FORMAT = "sattleme-checkout: a merchant's acceptance of this order has a newer format than this " \
44
+ "version reads; update the gem"
45
+
46
+ module_function
47
+
48
+ # The keys of the merchant's acceptance of the invoice of the sale `sale_author` with the
49
+ # deposit address `address` and the end `expires_at`, for the integration `integration_key`
50
+ # of `team`.
51
+ def keys(integration_key, team, sale_author, address, expires_at)
52
+ Keys.new(team: team, encryption_key: Derive.channel_keys(integration_key)[1],
53
+ address: Derive.merchant_acceptance_address(integration_key, sale_author, address, expires_at))
54
+ end
55
+
56
+ # What a relay sent, read as the merchant's acceptance of the invoice of `terms` (SPEC.md
57
+ # §31, "Reading it"): a record of type `integration-onchain-accepted`, author the team,
58
+ # sealed with the channel's key, at the address of `keys`, that checks out (its id, its
59
+ # signature); valid when its value is an object whose `version` is 1 and whose `received`
60
+ # is a safe integer from 1, below the invoice's `sats` (more fields ignored), of a newer
61
+ # format when its `version` is above 1 or its content of a newer NIP-44 version. Nil for
62
+ # anything else, and for a record dated after the lease's end (`expires_at` + 120), which
63
+ # is set aside whatever its format: one of a newer format is still told, for the warning
64
+ # (:newer_set_aside). Its `created_at` is never compared with now.
65
+ def open(value, keys, terms)
66
+ opened = Internal::Records.open(value, type: Protocol::MERCHANT_ACCEPTANCE_RECORD_TYPE,
67
+ encryption_key: keys.encryption_key, address: keys.address,
68
+ author: keys.team) do |record, _|
69
+ parse(record, terms.sats)
70
+ end
71
+ return nil unless opened
72
+
73
+ # After the lease's end: set aside, of a newer format or not (SPEC.md §31, "Reading it").
74
+ late = opened.event.created_at > terms.expires_at + Protocol::GRACE_SECONDS
75
+ if opened.newer?
76
+ return Opened.new(status: late ? :newer_set_aside : :newer, event: opened.event, received: nil)
77
+ end
78
+
79
+ late ? nil : Opened.new(status: :ok, event: opened.event, received: opened.value)
80
+ end
81
+
82
+ # The `received` of a merchant's acceptance's value for an invoice of `sats`, nil when it
83
+ # is not valid; raises Records::Newer for a newer version.
84
+ def parse(record, sats)
85
+ return nil unless record.is_a?(Hash)
86
+
87
+ version = record["version"]
88
+ raise Internal::Records::Newer if Json.number?(version) && version > Protocol::MERCHANT_ACCEPTANCE_VERSION
89
+ return nil unless version == Protocol::MERCHANT_ACCEPTANCE_VERSION
90
+
91
+ received = record["received"]
92
+ return nil unless Json.safe_integer?(received) && received >= 1
93
+
94
+ received.to_i < sats ? received.to_i : nil
95
+ end
96
+
97
+ # The merchant's acceptance of the invoice of `terms` (SPEC.md §31, "Counting it"), from
98
+ # what each relay of the merchant's list (`relay_count` relays) sent to its read on every
99
+ # relay (`answers`: relay → values): every copy opened (MerchantAcceptances.open), once per
100
+ # id and signature; a relay sent a record when it sent a copy of it that opens. Of the
101
+ # records valid or of a newer format that a majority of the list sent, the newest (the
102
+ # highest `created_at`, then the lowest id, as relays keep them) decides: a valid one is
103
+ # the merchant's acceptance, one of a newer format leaves the order without one. One that
104
+ # fewer than a majority sent never counts, whichever relays sent it.
105
+ def of(answers, keys, terms, relay_count)
106
+ # Each copy opened once, by id and signature, whatever relays send it.
107
+ copies = {}
108
+ open_copy = lambda do |value|
109
+ fields = Events.fields(value)
110
+ unless fields.is_a?(Hash) && fields["id"].is_a?(String) && fields["sig"].is_a?(String)
111
+ next MerchantAcceptances.open(value, keys, terms)
112
+ end
113
+
114
+ copy = "#{fields["id"]}/#{fields["sig"]}"
115
+ copies[copy] = MerchantAcceptances.open(value, keys, terms) unless copies.key?(copy)
116
+ copies[copy]
117
+ end
118
+ # The records that count if enough relays sent them, by id, and how many relays sent each.
119
+ records = {}
120
+ sent_by = Hash.new(0)
121
+ newer = false
122
+ answers.each_value do |values|
123
+ sent = {}
124
+ values.each do |value|
125
+ opened = open_copy.call(value)
126
+ next if opened.nil?
127
+
128
+ newer = true unless opened.status == :ok
129
+ next if opened.status == :newer_set_aside
130
+
131
+ id = opened.event.id
132
+ # One relay counts once for a record, whatever copies of it it sent.
133
+ next if sent.key?(id)
134
+
135
+ sent[id] = true
136
+ records[id] ||= opened
137
+ sent_by[id] += 1
138
+ end
139
+ end
140
+ needed = Relay.majority(relay_count)
141
+ newest = nil
142
+ records.each do |id, opened|
143
+ next if sent_by[id] < needed
144
+
145
+ newest = opened if newest.nil? || Internal::Records.replaces?(opened.event, newest.event)
146
+ end
147
+ Acceptance.new(received: newest&.status == :ok ? newest.received : nil, newer: newer)
148
+ end
149
+
150
+ # The merchant's acceptance of the invoice of `terms` (MerchantAcceptances.of), read on
151
+ # every relay of the merchant's `relays` (SPEC.md §13: once every relay answered or failed,
152
+ # or one timeout after a majority answered), not paged, with a key of this read alone.
153
+ # NetworkError when fewer than a majority answered. Publishes nothing.
154
+ def read(pool, keys, terms, relays, random:, stop:)
155
+ filter = { "kinds" => [Protocol::RECORD_KIND], "authors" => [keys.team], "#d" => [keys.address] }
156
+ keep = Internal::Records.that_open do |d, author|
157
+ author == keys.team && d == keys.address ? keys.encryption_key : nil
158
+ end
159
+ result = pool.query_relays(relays, filter, random.call(32),
160
+ paged: false, every_relay: true, stop: stop, keep: keep)
161
+ raise NetworkError, "Fewer than a majority of the merchant's relays answered" unless result.answered
162
+
163
+ of(result.answers, keys, terms, relays.size)
164
+ end
165
+ end
166
+ end
167
+ end
168
+ end
@@ -0,0 +1,285 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sattleme
4
+ module Checkout
5
+ module Internal
6
+ # The merchant's Bitcoin node (SPEC.md §31, "The merchant's Bitcoin node"): a node of its own
7
+ # that serves mempool.space's API (an Umbrel, a server of its own), which the channel names
8
+ # (`bitcoinNode`, §14) and the server then reads the blockchain from, rather than from
9
+ # mempool.space. Its URL follows a rule of its own (NodeUrl), not the https URL's (§15):
10
+ # `http` is allowed for a host of a local network, and so is an IPv4 address. Nothing is
11
+ # repaired: a URL that is not in its one spelling is no node URL, and the channel then names
12
+ # no node.
13
+ module BitcoinNodes
14
+ # What the server does when the node does not answer a read: "mempool", the same read of
15
+ # mempool.space; "none", never mempool.space.
16
+ FALLBACKS = %w[mempool none].freeze
17
+
18
+ # The channel's `bitcoinNode`, valid: its URL (a node URL, as the channel writes it), its
19
+ # fallback, and whether the pages of checkout links read it too (`payers`, a node of the
20
+ # Internet only).
21
+ Node = Data.define(:url, :fallback, :payers)
22
+
23
+ # The node a checkout link's record names (SPEC.md §30): its URL and its fallback.
24
+ RecordNode = Data.define(:url, :fallback) do
25
+ def to_h = { "url" => url, "fallback" => fallback }
26
+ end
27
+
28
+ module_function
29
+
30
+ # The channel's `bitcoinNode` (SPEC.md §14, §31): an object (a Hash, never an array) whose
31
+ # `url` is a node URL, whose `fallback` is exactly "mempool" or "none" and whose `payers` is
32
+ # a JSON boolean, true only for a node of the Internet; its other members ignored. Nil when
33
+ # it is absent or invalid in any way: there is none, the server reads mempool.space, and the
34
+ # channel stays valid.
35
+ def of(value)
36
+ return nil unless value.is_a?(Hash)
37
+
38
+ url, fallback, payers = value.values_at("url", "fallback", "payers")
39
+ node = NodeUrl.parse(url)
40
+ return nil unless node && fallback?(fallback) && [true, false].include?(payers)
41
+ # A link must never make each customer's browser probe its own local network.
42
+ return nil if payers && !node.internet?
43
+
44
+ Node.new(url: node.url, fallback: fallback, payers: payers)
45
+ end
46
+
47
+ # What a checkout link's record of version 2 holds of `node` (SPEC.md §30): its `url` and
48
+ # `fallback`, copied as they are, never `payers`; nil (the field absent) when the channel
49
+ # names no node or its `payers` is false.
50
+ def record_node_for(node)
51
+ node&.payers ? RecordNode.new(url: node.url, fallback: node.fallback) : nil
52
+ end
53
+
54
+ # The node a page reads from a record of version 2's `bitcoinNode` (SPEC.md §30, "Reading a
55
+ # record"): an object whose `url` is a node URL of a node of the Internet and whose
56
+ # `fallback` is exactly "mempool" or "none" (its other members ignored); anything else (null
57
+ # included) is set aside, the page reading mempool.space, and leaves the record valid.
58
+ def record_node_of(value)
59
+ return nil unless value.is_a?(Hash)
60
+
61
+ url, fallback = value.values_at("url", "fallback")
62
+ node = NodeUrl.parse(url)
63
+ return nil unless node&.internet? && fallback?(fallback)
64
+
65
+ RecordNode.new(url: node.url, fallback: fallback)
66
+ end
67
+
68
+ # Whether `value` is "mempool" or "none", exactly.
69
+ def fallback?(value)
70
+ value.is_a?(String) && FALLBACKS.include?(value)
71
+ end
72
+
73
+ # The explorers one read asks, in order (SPEC.md §31, `fallback`): without a node
74
+ # (`fallback` nil), mempool.space; with "none", the node alone; with "mempool", the node
75
+ # then mempool.space, or mempool.space first when the node failed a read less than 60 s ago
76
+ # in the same call (`failed_recently`). The next one is asked only when the one before
77
+ # failed.
78
+ def explorers_to_ask(fallback, failed_recently)
79
+ return [:mempool] if fallback.nil?
80
+ return [:node] if fallback == "none"
81
+
82
+ failed_recently ? %i[mempool node] : %i[node mempool]
83
+ end
84
+ end
85
+
86
+ # A node URL (SPEC.md §31, "A node URL"), checked, with where the node is read: in its one
87
+ # spelling `<scheme>://<host>[:<port>][<path>]`, 200 characters at most. `https`, or `http` for
88
+ # a local host; a host in lowercase, an IPv4 address (never in 0.0.0.0/8 nor 127.0.0.0/8) or a
89
+ # name (never `localhost` nor under it); a port from 1 to 65535; a path that ends neither with
90
+ # `/` nor with `/api`. So no user name nor password, no query, no fragment, no IPv6 address, no
91
+ # whitespace.
92
+ #
93
+ # `rest` is `<url>/api`, the `<explorer>` of SPEC.md §31, "Explorers"; `web_socket` is `<url>`
94
+ # with `ws` for its leading `http`, then `/api/v1/ws`. `local`: its host is of a local network
95
+ # (a local IPv4 range, or a name under `.local`); `internet`: it is a node of the Internet
96
+ # (`https`, and a name whose last label is not `local`).
97
+ NodeUrl = Data.define(:url, :scheme, :host, :port, :local) do
98
+ def rest = "#{url}/api"
99
+
100
+ def web_socket = "ws#{url.delete_prefix("http")}/api/v1/ws"
101
+
102
+ def local? = local
103
+
104
+ def internet? = scheme == "https" && !NodeUrl.ipv4?(host) && !local
105
+
106
+ # Whether it is asked over TLS (`https`), else in clear HTTP (a local host only).
107
+ def tls? = scheme == "https"
108
+ end
109
+
110
+ # The rule of a node URL (NodeUrl.parse) and the checks of its parts.
111
+ class NodeUrl
112
+ # `<scheme>://<host>[:<port>][<path>]`: the host up to `:` or `/` (nothing that may start a
113
+ # user name, a query or a fragment), a port of 1 to 5 digits without a leading zero, a path
114
+ # of visible ASCII. The parts are then checked one by one.
115
+ SHAPE = %r{\A(https?)://([^/:?#@\\\s]+)(?::([1-9][0-9]{0,4}))?(/[\x21-\x7e]*)?\z}
116
+ # An IPv4 address: 4 numbers from 0 to 255, none with a leading zero (`0` alone is one).
117
+ OCTET = "(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])"
118
+ IPV4 = /\A#{OCTET}\.#{OCTET}\.#{OCTET}\.#{OCTET}\z/
119
+ # A label of a name: 1 to 63 of `a–z 0–9 -`, neither starting nor ending with `-`.
120
+ LABEL = /\A[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\z/
121
+ # A name's length, at most.
122
+ MAX_NAME_LENGTH = 253
123
+
124
+ # `value` as a node URL, nil when it is not one.
125
+ def self.parse(value)
126
+ return nil unless Text.well_formed?(value) && value.length <= Protocol::MAX_NODE_URL_LENGTH
127
+
128
+ match = SHAPE.match(value)
129
+ return nil unless match
130
+
131
+ scheme, host, port, path = match.captures
132
+ return nil if port && Integer(port, 10) > 65_535
133
+ return nil unless path?(path || "")
134
+
135
+ local = locality(host)
136
+ return nil if local.nil?
137
+ return nil if scheme == "http" && !local
138
+
139
+ new(url: value, scheme: scheme, host: host, port: port ? Integer(port, 10) : default_port(scheme),
140
+ local: local)
141
+ end
142
+
143
+ # The node URL `url` begins with: its scheme and authority (`<scheme>://<host>[:<port>]`) a
144
+ # node URL's, the rest anything (a path, as the explorer asks it). Nil when it is not so. What
145
+ # the gem's HTTP and WebSocket clients check before they ask in clear (`http`, `ws`): a local
146
+ # host only.
147
+ def self.origin_of(url)
148
+ match = %r{\A(https?|wss?)://([^/?#]*)}.match(url.to_s)
149
+ return nil unless match
150
+
151
+ scheme = match[1].sub(/\Aws/, "http")
152
+ parse("#{scheme}://#{match[2]}")
153
+ end
154
+
155
+ def self.default_port(scheme) = scheme == "https" ? 443 : 80
156
+
157
+ def self.ipv4?(host) = IPV4.match?(host)
158
+
159
+ # Whether `host` is local (true), of the Internet (false), or no node's host (nil).
160
+ def self.locality(host)
161
+ octets = IPV4.match(host)&.captures&.map { |octet| Integer(octet, 10) }
162
+ if octets
163
+ # Never the machine itself, nor "this network".
164
+ return nil if octets[0].zero? || octets[0] == 127
165
+
166
+ return local_ipv4?(octets)
167
+ end
168
+ return nil unless name?(host)
169
+
170
+ host.end_with?(".local")
171
+ end
172
+
173
+ # Whether an IPv4 address is of a local range: 10/8, 172.16/12, 192.168/16, 100.64/10 (the
174
+ # shared address space of RFC 6598, which Tailscale uses).
175
+ def self.local_ipv4?(octets)
176
+ a, b = octets
177
+ a == 10 || (a == 172 && b.between?(16, 31)) || (a == 192 && b == 168) || (a == 100 && b.between?(64, 127))
178
+ end
179
+
180
+ # Whether `host` is a name: 2 labels or more, the last starting with a letter, no `localhost`.
181
+ def self.name?(host)
182
+ return false if host.length > MAX_NAME_LENGTH
183
+
184
+ labels = host.split(".", -1)
185
+ return false unless labels.size >= 2 && labels.all? { |label| LABEL.match?(label) }
186
+
187
+ labels.last.match?(/\A[a-z]/) && labels.last != "localhost"
188
+ end
189
+
190
+ # Whether `path` (after the authority, empty when absent) is a node URL's: visible ASCII
191
+ # already; never `?`, `#`, `@` nor `\`; not `/` alone, no trailing `/`, no `/api` at the end
192
+ # (the node's URL, not its API's).
193
+ def self.path?(path)
194
+ return true if path.empty?
195
+ return false if path.match?(/[?#@\\]/)
196
+
197
+ !path.end_with?("/") && !path.match?(%r{/api\z}i)
198
+ end
199
+
200
+ private_class_method :default_port, :locality, :local_ipv4?, :name?, :path?
201
+ end
202
+
203
+ # When the nodes a call read failed a read, by node URL (the client's clock, Unix seconds): of
204
+ # one call alone (create_invoice, get_status, one wait_for_payment), shared by its reads and
205
+ # its WebSocket, never kept between calls. Thread-safe.
206
+ class NodeFailures
207
+ def initialize
208
+ @mutex = Mutex.new
209
+ @at = {}
210
+ end
211
+
212
+ def [](url) = @mutex.synchronize { @at[url] }
213
+
214
+ def []=(url, time)
215
+ @mutex.synchronize { @at[url] = time }
216
+ end
217
+ end
218
+
219
+ # The explorer of a call (SPEC.md §31, "Explorers"): mempool.space, or the channel's node
220
+ # (BitcoinNodes::Node, valid) with its fallback. Each read follows the fallback on its own; a
221
+ # node that fails is remembered in the call's NodeFailures, so that for 60 s it is asked after
222
+ # mempool.space. `now`: the client's clock (Unix seconds).
223
+ class CallExplorer
224
+ # An explorer a read may ask: :node or :mempool, its REST URL (`<explorer>`) and its
225
+ # WebSocket's.
226
+ Source = Data.define(:name, :rest, :web_socket) do
227
+ def node? = name == :node
228
+ end
229
+
230
+ MEMPOOL = Source.new(name: :mempool, rest: Protocol::MEMPOOL_URL, web_socket: Protocol::MEMPOOL_WEBSOCKET_URL)
231
+
232
+ # The channel's node (nil: mempool.space).
233
+ attr_reader :node
234
+
235
+ def initialize(node, failures, now)
236
+ at = node && NodeUrl.parse(node.url)
237
+ @node = at && node
238
+ @source = at && Source.new(name: :node, rest: at.rest, web_socket: at.web_socket)
239
+ @failures = failures
240
+ @now = now
241
+ end
242
+
243
+ # The explorers the next read asks, in order (BitcoinNodes.explorers_to_ask).
244
+ def sources
245
+ return [MEMPOOL] unless @node
246
+
247
+ failed_at = @failures[@node.url]
248
+ recently = !failed_at.nil? && @now.call - failed_at < Protocol::NODE_FAILED_RECENTLY_SECONDS
249
+ BitcoinNodes.explorers_to_ask(@node.fallback, recently).map { |name| name == :node ? @source : MEMPOOL }
250
+ end
251
+
252
+ # The node failed a read (or its WebSocket a connection): remembered for the call.
253
+ def node_failed
254
+ @failures[@node.url] = @now.call if @node
255
+ end
256
+
257
+ # One read of the explorer: the block with the `<explorer>` URL of each explorer of sources(),
258
+ # in order, and an HTTP context of that explorer's own (`http` with a stop of its own, which
259
+ # allows `http` to a local node alone: Http), until one answers. Each is stopped once it
260
+ # failed: what the block asked of it at the same time (the chain's height with the address's
261
+ # transactions) ends then, and the whole read is asked again of the next one, never part of
262
+ # it. NetworkError when every one failed; a cancellation (Cancelled) is raised as it is.
263
+ def read(http)
264
+ failures = []
265
+ sources.each do |source|
266
+ attempt = http.stop.child
267
+ begin
268
+ return yield(source.rest, http.with(stop: attempt, node: source.node?))
269
+ rescue NetworkError => e
270
+ http.stop.check!
271
+ node_failed if source.node?
272
+ failures << e
273
+ ensure
274
+ attempt.stop
275
+ end
276
+ end
277
+ raise failures.first if failures.size == 1
278
+
279
+ raise NetworkError.new("Neither the merchant's Bitcoin node nor mempool.space answered " \
280
+ "(#{failures.map(&:message).join("; ")})"), cause: failures.last
281
+ end
282
+ end
283
+ end
284
+ end
285
+ end