openreceive-rails 0.4.35 → 0.6.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4d379815d45b9bcea47477d77267b201f05506b2bbe822d5cf7ca128d4b00ff7
4
- data.tar.gz: f9be4e02ea2ca4d022022e306e6912510d033de5cac53d4d881afc8e2924efdb
3
+ metadata.gz: aeaa1e90b42c1afd41d34802bf77e9b59b078fcd0beabda94f64a1b014dc5988
4
+ data.tar.gz: ccd3840fb0e33f607f14bd2ab4ba78e8d046f3197da480ea5715f94a9acd0c4a
5
5
  SHA512:
6
- metadata.gz: 1a890a9900f16000a933c4daa16c7e42ba59f7c8a6a48ecd86332ab53efd84d27759ff2842d14d59da5cef2b2f5cbfc9ff4584a31359e4bb7a1ffafb0d17323c
7
- data.tar.gz: 425abbe2117ebb6c491fdceacf1dda92f5ba5afbe00d4e6139accde6b2ceccd179b2729497c151394a17695d7af289a1e6b0411e981aa1de3f65752d8087b76a
6
+ metadata.gz: 58ad34d3ddcf9febd4462425014753430c430ec9de7b61148727dd4e3abe5c8aa42e81ef792c51048a5ffbc4163effaf7913143c2980c7c9dc7ca28b4e73ceb7
7
+ data.tar.gz: 4e819e1860469389d410b09594caa59327970b3b68cdd1496188b7403379f964ea4f5c83b3f82aff7e8df288574752834c2117a536e76b821e1ee78e1a71f2ed
data/CHANGELOG.md CHANGED
@@ -1,5 +1,42 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.0 - 2026-11-24
4
+
5
+ No breaking API change in this gem.
6
+
7
+ - Fixed: a paid order is never handed a new invoice or a swap deposit
8
+ address. Before a create mints another attempt for an order that has unpaid
9
+ ones, the engine checks those with the wallet (skipping any the request's
10
+ scan just checked) and answers 409 "already paid" if one was paid.
11
+ - Added: `payments/check` answers `paid` with the attempt that paid the order
12
+ on every attempt of a paid order, and `checkouts/prepare` names the order's
13
+ newest unpaid attempt as `pending_payment_hash`, so a reloaded page shows
14
+ the receipt without another pick.
15
+ - The swap changes of 0.6.0 come from `openreceive-server`; see its changelog.
16
+
17
+ ## 0.5.0 - 2026-11-16
18
+
19
+ No breaking API change in this gem. A Rails app with a custom ("headless")
20
+ checkout built on `@openreceive/browser/headless` must read the breaking
21
+ changes in the root changelog: a coin tile no longer starts a swap, and the
22
+ payment breakdown has no "Total" row. A page that renders the packaged checkout
23
+ (`@openreceive/elements`, `@openreceive/react` or the standalone checkout of
24
+ the same version) needs no change.
25
+
26
+ - Fixed: the default client address, used by `config.rate_limiting` and stored
27
+ on each payment, now follows `config.action_dispatch.trusted_proxies`. It was
28
+ Rack's `request.ip`, which ignores that setting, so an app behind a load
29
+ balancer or CDN with a public address counted the proxy as every payer even
30
+ after listing it. When the peer that connected is a trusted proxy, the
31
+ address is the one it forwarded; otherwise it is the peer itself, whatever
32
+ the forwarding headers say. A `config.client_ip` of your own still wins. An
33
+ app behind a proxy will see different `client_ip` values on new payments.
34
+ - Changed: the installer's initializer explains which address the per-IP
35
+ limit counts and when to list a proxy in
36
+ `config.action_dispatch.trusted_proxies`.
37
+ - The swap request guard and the rate limiting changes of 0.5.0 come from
38
+ `openreceive-server`; see its changelog.
39
+
3
40
  ## 0.4.35 - 2026-11-12
4
41
 
5
42
  Release with the complete 0.4.35 package family. No Ruby runtime changes
@@ -81,6 +81,21 @@ module OpenReceive
81
81
  OpenReceive.config.request_handler
82
82
  end
83
83
 
84
+ # Engine mode checks a reference's earlier unpaid attempts against the
85
+ # wallet before a create mints another, skipping those the around_action's
86
+ # gated pass already checked (OpenReceive.check_earlier_attempts!).
87
+ # Advanced mode (custom repository) has no engine-owned rows to check.
88
+ def openreceive_create_arguments
89
+ return {} if OpenReceive.config.advanced_hooks?
90
+
91
+ reconcile_pass = @openreceive_reconcile_pass
92
+ {
93
+ check_earlier_attempts: lambda do |reference|
94
+ OpenReceive.check_earlier_attempts!(reference, reconcile_pass: reconcile_pass)
95
+ end
96
+ }
97
+ end
98
+
84
99
  # Always server-generated (matches RackApp and JS): client-supplied
85
100
  # X-Request-Id values are unvalidated content and are never reflected.
86
101
  def openreceive_request_id
@@ -14,7 +14,8 @@ module OpenReceive
14
14
  openreceive_respond(openreceive_handler.create_checkout(
15
15
  raw_body: openreceive_raw_body,
16
16
  request: request,
17
- request_id: openreceive_request_id
17
+ request_id: openreceive_request_id,
18
+ **openreceive_create_arguments
18
19
  ))
19
20
  end
20
21
  end
@@ -7,7 +7,7 @@ module OpenReceive
7
7
  end
8
8
 
9
9
  def create
10
- respond_with(:create_swap)
10
+ respond_with(:create_swap, **openreceive_create_arguments)
11
11
  end
12
12
 
13
13
  def status
@@ -20,12 +20,13 @@ module OpenReceive
20
20
 
21
21
  private
22
22
 
23
- def respond_with(method)
23
+ def respond_with(method, **arguments)
24
24
  openreceive_respond(openreceive_handler.public_send(
25
25
  method,
26
26
  raw_body: openreceive_raw_body,
27
27
  request: request,
28
- request_id: openreceive_request_id
28
+ request_id: openreceive_request_id,
29
+ **arguments
29
30
  ))
30
31
  end
31
32
  end
@@ -279,6 +279,21 @@ class OpenReceivePayment < ActiveRecord::Base
279
279
  end
280
280
  end
281
281
 
282
+ # One reference's pending attempts, superseded ones included (a superseded
283
+ # invoice can still be paid), as the same reconciliation DTO. A create
284
+ # checks these against the wallet before minting another attempt.
285
+ def self.pending_attempts_for(reference)
286
+ OpenReceiveMeta.assert_supported_schema!
287
+ pending.where(reference: reference.to_s).order(created_at: :asc, payment_hash: :asc)
288
+ .pluck(:payment_hash, :created_at, :checkout_data).map do |hash, created_at, checkout|
289
+ {
290
+ "payment_hash" => hash, "created_at" => created_at.to_i,
291
+ "expires_at" => settlement_expires_at(checkout, hash),
292
+ "created_at_source" => checkout["created_at_source"] || checkout[:created_at_source] || "host"
293
+ }
294
+ end
295
+ end
296
+
282
297
  # Same reconciliation DTO for authenticated by-hash notification lookup.
283
298
  def self.find_pending_attempt(payment_hash)
284
299
  OpenReceiveMeta.assert_supported_schema!
@@ -84,8 +84,13 @@ OpenReceive.configure do |config|
84
84
 
85
85
  # Recommended for public web shops: cap invoice creation per client IP,
86
86
  # counted from the engine-owned openreceive_payments rows. Leave it off for
87
- # point-of-sale deployments where many payers share one IP. Behind a proxy,
88
- # configure Rails' trusted proxies so request.ip is the payer.
87
+ # point-of-sale deployments where many payers share one IP.
88
+ #
89
+ # The address counted is the one that connected to your app. When that is
90
+ # one of your trusted proxies, it is the client the proxy forwarded
91
+ # (request.remote_ip) instead. Rails trusts private addresses already; list
92
+ # a proxy with a public address (a cloud load balancer, a CDN) in
93
+ # config.action_dispatch.trusted_proxies, or all its payers share one limit.
89
94
  # config.rate_limiting = true
90
95
 
91
96
  # Settlement discovery is opportunistic by default: every engine request
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "ipaddr"
3
4
  require "openreceive/server"
4
5
 
5
6
  module OpenReceive
@@ -63,9 +64,10 @@ module OpenReceive
63
64
  # engine-owned openreceive_payments rows; or a Hash with
64
65
  # limit_per_hour / limit_per_day. Mutually exclusive with rate_limit.
65
66
  @rate_limiting = false
66
- # Client IP attribution: a proc receiving the framework request.
67
- # Defaults to ActionDispatch::Request#ip (which honors the app's
68
- # trusted-proxy configuration).
67
+ # Client IP attribution: a proc receiving the framework request. nil
68
+ # (the default) takes the address that connected, or the client a
69
+ # trusted proxy forwarded (config.action_dispatch.trusted_proxies); see
70
+ # default_client_ip. A proc set here replaces that default.
69
71
  @client_ip = nil
70
72
  # nil (the default) mirrors the JS createOpenReceive defaults: the
71
73
  # price provider becomes the built-in cached live price feed (with
@@ -140,7 +142,7 @@ module OpenReceive
140
142
  end
141
143
 
142
144
  def reset_runtime!
143
- %i[@service @request_handler @settlement_hook @resolved_nwc_client].each do |name|
145
+ %i[@service @request_handler @settlement_hook @resolved_nwc_client @rails_trusted_proxies].each do |name|
144
146
  remove_instance_variable(name) if instance_variable_defined?(name)
145
147
  end
146
148
  self
@@ -205,15 +207,10 @@ module OpenReceive
205
207
  DEFAULT_RATE_LIMIT_PER_HOUR = 60
206
208
  HOUR_SECONDS = 3_600
207
209
  DAY_SECONDS = 86_400
210
+ REFUSAL_WARNING_SECONDS = 60
208
211
 
209
212
  def resolved_client_ip
210
- extractor = @client_ip || lambda do |request|
211
- if request.respond_to?(:ip)
212
- request.ip
213
- elsif request.is_a?(Hash)
214
- request["REMOTE_ADDR"]
215
- end
216
- end
213
+ extractor = @client_ip || method(:default_client_ip)
217
214
  # Mirrors the JS handler: the extracted IP (custom hook or framework
218
215
  # default) is normalized into the bucket the limiter counts with (IPv6
219
216
  # /64, v4-mapped collapsed) and that same bucket is what gets stamped on
@@ -221,6 +218,66 @@ module OpenReceive
221
218
  ->(request) { OpenReceive::Server::ClientIp.attributed(extractor.call(request)) }
222
219
  end
223
220
 
221
+ # The client address when the host set no config.client_ip. The engine's
222
+ # controllers pass a Rails request; bare handler calls pass a Rack env
223
+ # Hash or nothing.
224
+ #
225
+ # For a Rails request the address that connected (REMOTE_ADDR) decides.
226
+ # When it is one of the app's trusted proxies, the client is the one that
227
+ # proxy forwarded: request.remote_ip. Any other address is the client
228
+ # itself, whatever X-Forwarded-For, Client-Ip or Forwarded say: a client
229
+ # that connects directly cannot choose its address, and a public proxy
230
+ # the app has not listed is counted as one client.
231
+ def default_client_ip(request)
232
+ if defined?(::ActionDispatch::Request) && request.is_a?(::ActionDispatch::Request)
233
+ rails_client_ip(request)
234
+ elsif request.respond_to?(:ip)
235
+ request.ip
236
+ elsif request.is_a?(Hash)
237
+ request["REMOTE_ADDR"]
238
+ end
239
+ end
240
+
241
+ def rails_client_ip(request)
242
+ peer = connecting_address(request)
243
+ # No address connected (a Unix socket): attributed as before, by Rack.
244
+ return request.ip if peer.nil?
245
+ return peer unless rails_trusted_proxies.any? { |proxy| proxy === peer }
246
+
247
+ begin
248
+ request.remote_ip
249
+ rescue StandardError
250
+ # RemoteIp raises when Client-Ip and X-Forwarded-For disagree (its
251
+ # spoofing check). Such a request is attributed as before, by Rack.
252
+ request.ip
253
+ end
254
+ end
255
+
256
+ # REMOTE_ADDR when it is one IP address, nil otherwise. An IPv4-mapped
257
+ # IPv6 address is read as its IPv4, so Rails' IPv4 ranges match it.
258
+ def connecting_address(request)
259
+ raw = request.remote_addr.to_s.strip
260
+ address = IPAddr.new(raw)
261
+ range = address.to_range
262
+ return nil unless range.begin == range.end
263
+
264
+ address.ipv4_mapped? ? address.native.to_s : raw
265
+ rescue ArgumentError
266
+ nil
267
+ end
268
+
269
+ # The app's trusted proxies, resolved by Rails itself: its RemoteIp
270
+ # middleware turns config.action_dispatch.trusted_proxies into the list
271
+ # it filters with, which is Rails' own private ranges when the app sets
272
+ # none. Matched the way that middleware matches (proxy === address).
273
+ def rails_trusted_proxies
274
+ @rails_trusted_proxies ||= begin
275
+ application = defined?(::Rails) && ::Rails.respond_to?(:application) ? ::Rails.application : nil
276
+ configured = application&.config&.action_dispatch&.trusted_proxies
277
+ ::ActionDispatch::RemoteIp.new(nil, true, configured).proxies
278
+ end
279
+ end
280
+
224
281
  # The built-in limiter (config.rate_limiting): a COUNT over the
225
282
  # engine-owned rows' client_ip within the rolling window, throttling only
226
283
  # the invoice-minting actions — identical semantics to the JS handler.
@@ -240,6 +297,24 @@ module OpenReceive
240
297
  limit_per_day = positive_rate_limit(limit_per_day, "limit_per_day") unless limit_per_day.nil?
241
298
  extract_ip = resolved_client_ip
242
299
  warned_unattributable = false
300
+ warned_not_a_payer = false
301
+ last_refusal_warning = nil
302
+ # Say which address was refused, at most once a minute. When that
303
+ # address is the host's own proxy, every payer shares its budget and
304
+ # this line is the only place the operator can see why checkouts
305
+ # stopped. The wording follows the JS limiter's.
306
+ refuse = lambda do |ip, counted, limit, window, at|
307
+ if last_refusal_warning.nil? || at - last_refusal_warning >= REFUSAL_WARNING_SECONDS
308
+ last_refusal_warning = at
309
+ rails_logger&.warn(
310
+ "[openreceive] rate limiting refused a new payment from #{ip}: #{counted} made in the " \
311
+ "last #{window}, limit #{limit}. If #{ip} is your proxy, load balancer or CDN " \
312
+ "rather than one payer, every payer is sharing this limit: pass the payer's own " \
313
+ "address — see https://openreceive.org/guides/rate-limiting.md"
314
+ )
315
+ end
316
+ raise OpenReceive::Server::RateLimitedError, BUILT_IN_RATE_LIMIT_MESSAGE
317
+ end
243
318
  lambda do |context|
244
319
  next true unless %w[checkout.create swap.create].include?(context[:action].to_s)
245
320
  ip = extract_ip.call(context[:request]).to_s
@@ -256,13 +331,30 @@ module OpenReceive
256
331
  end
257
332
  next true
258
333
  end
334
+ unless OpenReceive::Server::ClientIp.payer_address?(ip)
335
+ # A loopback or private address is the host's own proxy or network,
336
+ # never a payer on the internet. Counting it would put every payer
337
+ # in one bucket and stop the whole site at the limit, so it is not
338
+ # counted. Said once per process.
339
+ unless warned_not_a_payer
340
+ warned_not_a_payer = true
341
+ rails_logger&.warn(
342
+ "[openreceive] rate limiting is on, but this request's client address is #{ip}, a " \
343
+ "private or loopback address: your own proxy or network, not the payer. Limiting " \
344
+ "it would make every payer share one limit, so the request was allowed and such " \
345
+ "requests are not limited. Pass the payer's own address — see " \
346
+ "https://openreceive.org/guides/rate-limiting.md"
347
+ )
348
+ end
349
+ next true
350
+ end
259
351
  now = Time.now
260
- over_hour = OpenReceivePayment.count_attempts_from_ip(ip, now - HOUR_SECONDS) >= limit_per_hour
261
- raise OpenReceive::Server::RateLimitedError, BUILT_IN_RATE_LIMIT_MESSAGE if over_hour
352
+ last_hour = OpenReceivePayment.count_attempts_from_ip(ip, now - HOUR_SECONDS)
353
+ refuse.call(ip, last_hour, limit_per_hour, "hour", now) if last_hour >= limit_per_hour
262
354
 
263
- if limit_per_day &&
264
- OpenReceivePayment.count_attempts_from_ip(ip, now - DAY_SECONDS) >= limit_per_day
265
- raise OpenReceive::Server::RateLimitedError, BUILT_IN_RATE_LIMIT_MESSAGE
355
+ if limit_per_day
356
+ last_day = OpenReceivePayment.count_attempts_from_ip(ip, now - DAY_SECONDS)
357
+ refuse.call(ip, last_day, limit_per_day, "24 hours", now) if last_day >= limit_per_day
266
358
  end
267
359
  true
268
360
  end
@@ -290,14 +382,15 @@ module OpenReceive
290
382
  lambda do |action:, request:, reference:, input:, pay_in_asset: nil|
291
383
  # Before the host is asked for a price: a host may well answer nil for an
292
384
  # order it already knows is paid, and "unknown order" is the wrong thing
293
- # to tell the payer who paid it.
294
- if %w[checkout.prepare checkout.create swap.create].include?(action)
385
+ # to tell the payer who paid it. payments/check reads it too, to answer
386
+ # `paid` on every attempt of a paid order.
387
+ paid = nil
388
+ if %w[checkout.prepare checkout.create swap.create payment.check].include?(action)
295
389
  paid = OpenReceivePayment.where(reference: reference, status: "settled").order(:created_at).first
296
- if paid
390
+ if paid && action != "payment.check"
297
391
  raise OpenReceive::Server::ConflictError, "This reference is already paid." unless action == "checkout.prepare"
298
392
 
299
- next({ payment_hash: paid.payment_hash, checkout: paid.checkout_data, paid: true,
300
- paid_at: paid.paid_at&.to_i, swap: !paid.swap_data.nil? }.compact)
393
+ next(paid_attempt(paid).merge(paid: true))
301
394
  end
302
395
  end
303
396
  pricing = %w[checkout.prepare swap.quote checkout.create swap.create].include?(action)
@@ -308,8 +401,16 @@ module OpenReceive
308
401
  # the minting service stays exactly the price.
309
402
  amount = price_only(price)
310
403
  description = price_description(price)
311
- if %w[checkout.prepare swap.quote].include?(action)
312
- next({ amount: amount, description: description }.compact)
404
+ next({ amount: amount, description: description }.compact) if action == "swap.quote"
405
+
406
+ if action == "checkout.prepare"
407
+ # The attempt a picker opened on this reference watches: the newest
408
+ # one still pending, superseded or not, since a superseded invoice
409
+ # can still be paid. Any pending attempt would do (`paid` answers for
410
+ # the whole order); the newest is the one most likely still on the
411
+ # payer's wallet screen.
412
+ pending = OpenReceivePayment.where(reference: reference).pending.newest_first.pick(:payment_hash)
413
+ next({ amount: amount, description: description, pending_payment_hash: pending }.compact)
313
414
  end
314
415
 
315
416
  requested_hash = input["payment_hash"] || input[:payment_hash]
@@ -332,11 +433,19 @@ module OpenReceive
332
433
  description: description,
333
434
  payment_hash: payment&.payment_hash,
334
435
  checkout: payment&.checkout_data,
335
- swap_data: payment&.swap_data
436
+ swap_data: payment&.swap_data,
437
+ paid_attempt: paid && paid_attempt(paid)
336
438
  }.compact
337
439
  end
338
440
  end
339
441
 
442
+ # The attempt that paid a reference, as the request handler builds its
443
+ # `paid` object (OpenAPI PaidAttempt) from it.
444
+ def paid_attempt(payment)
445
+ { payment_hash: payment.payment_hash, checkout: payment.checkout_data,
446
+ paid_at: payment.paid_at&.to_i, swap: !payment.swap_data.nil? }.compact
447
+ end
448
+
340
449
  # The price alone. A host that returns a display string beside it must not
341
450
  # have that string reach the amount resolver.
342
451
  def price_only(price)
@@ -5,6 +5,6 @@ module OpenReceive
5
5
  # top-level `::Rails` framework constant — engine code always references the framework as
6
6
  # `::Rails` to avoid shadowing.
7
7
  module Rails
8
- VERSION = "0.4.35"
8
+ VERSION = "0.6.0"
9
9
  end
10
10
  end
@@ -15,6 +15,11 @@ module OpenReceive
15
15
  # Wallet-history pages a request-path pass may walk, mirroring the JS
16
16
  # OPENRECEIVE_RECONCILE_SCAN_MAX_PAGES.
17
17
  RECONCILE_SCAN_MAX_PAGES = 50
18
+ # How far back an earlier attempt's invoice may have expired and still be
19
+ # checked before a new attempt is minted. A payment lands before its invoice
20
+ # expires; this only covers the scan that has not caught up with it yet.
21
+ # Mirrors the JS handler's EARLIER_ATTEMPT_LOOKBACK_SECONDS.
22
+ EARLIER_ATTEMPT_LOOKBACK_SECONDS = 10 * 60
18
23
  # Cap on the `openreceive:notifications` worker's resubscribe backoff, and
19
24
  # the subscription lifetime past which the ramp resets to 1s.
20
25
  NOTIFICATIONS_MAX_BACKOFF_SECONDS = 60
@@ -172,6 +177,33 @@ module OpenReceive
172
177
  { "reason" => "scan_failed" }
173
178
  end
174
179
 
180
+ # The engine's create routes call this right before a new attempt is
181
+ # minted (the request handler's check_earlier_attempts hook): the
182
+ # reference's pending attempts whose invoice expired no more than
183
+ # EARLIER_ATTEMPT_LOOKBACK_SECONDS ago, minus those this request's own
184
+ # gated pass (`reconcile_pass`) already checked, go through one ungated
185
+ # reconcile_attempts! pass. Returns its checks; the handler refuses the
186
+ # mint as "already paid" when one came back settled, and as retryable
187
+ # when this raises. The gated pass at the top of the request is skipped
188
+ # while the gate is closed (3 to 12 s between scans), so a payment made
189
+ # just before a reload would otherwise go unseen. Mirrors the JS handler's
190
+ # assertEarlierAttemptsUnpaid.
191
+ def check_earlier_attempts!(reference, reconcile_pass: nil, now: nil)
192
+ observed_at = Integer(now || Time.now.to_i)
193
+ checked = if reconcile_pass.is_a?(Hash) && reconcile_pass["reason"] == "ran"
194
+ Array(reconcile_pass["checks"]).map { |check| check.fetch("payment_hash").to_s.downcase }
195
+ else
196
+ []
197
+ end
198
+ earlier = OpenReceivePayment.pending_attempts_for(reference).select do |attempt|
199
+ attempt.fetch("expires_at") + EARLIER_ATTEMPT_LOOKBACK_SECONDS > observed_at &&
200
+ !checked.include?(attempt.fetch("payment_hash").downcase)
201
+ end
202
+ return [] if earlier.empty?
203
+
204
+ reconcile_attempts!(earlier, now: observed_at)
205
+ end
206
+
175
207
  # Opt-in NWC-02 notifications: subscribe to the configured NWC client's
176
208
  # `payment_received` notifications. Notifications are authenticated wallet
177
209
  # data — a payload that satisfies the shared settlement rule (`settled_at`
@@ -268,6 +300,54 @@ module OpenReceive
268
300
  false
269
301
  end
270
302
 
303
+ # One ungated, bounded reconcile over exactly these attempts (the JS
304
+ # reconcileHostPayments({ attempts })): no gate claim and no scheduler
305
+ # checkpoint, one Service#reconcile_payments walk capped at
306
+ # RECONCILE_SCAN_MAX_PAGES and RECONCILE_SCAN_TIMEOUT_SECONDS. Settlements
307
+ # go through the settlement hook (write-once + on_paid) and terminal
308
+ # transitions are recorded, like any pass. Unlike the gated pass it raises
309
+ # instead of warning: a failed delivery, a wallet error, or a walk the
310
+ # deadline cut short means the check did not finish, and its caller must
311
+ # not act as if it had. A hash the page cap left undecided is simply
312
+ # omitted, as in the JS walk.
313
+ def reconcile_attempts!(attempts, now: nil)
314
+ return [] if attempts.empty?
315
+
316
+ observed_at = Integer(now || Time.now.to_i)
317
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + RECONCILE_SCAN_TIMEOUT_SECONDS
318
+ checks = config.service.reconcile_payments(
319
+ "attempts" => attempts, "max_pages" => RECONCILE_SCAN_MAX_PAGES, "deadline" => deadline
320
+ )
321
+ by_hash = attempts.to_h { |attempt| [attempt.fetch("payment_hash").downcase, attempt] }
322
+ # One failing delivery must not starve the rest; the first failure is
323
+ # raised once every check has had its turn.
324
+ failures = []
325
+ checks.each do |checked|
326
+ attempt = by_hash[checked.fetch("payment_hash").downcase]
327
+ next if attempt.nil?
328
+
329
+ if checked["status"] == "settled"
330
+ config.settlement_hook.call(
331
+ "payment_hash" => checked.fetch("payment_hash"),
332
+ "paid_at" => checked.fetch("paid_at"),
333
+ "details" => checked["details"]
334
+ )
335
+ else
336
+ record_attempt_transition(attempt, checked, observed_at)
337
+ end
338
+ rescue StandardError => e
339
+ failures << e
340
+ end
341
+ raise failures.first unless failures.empty?
342
+ if checks.length < attempts.length && Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline
343
+ raise OpenReceive::WalletUnavailableError,
344
+ "the wallet history walk reached its #{RECONCILE_SCAN_TIMEOUT_SECONDS}s deadline " \
345
+ "before every attempt was checked"
346
+ end
347
+
348
+ checks
349
+ end
350
+
271
351
  # Closure is decided by the shared reconciliation rules from a scan result
272
352
  # the wallet actually returned; a nil transition means keep waiting.
273
353
  def record_attempt_transition(attempt, checked, observed_at)
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: openreceive-rails
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.4.35
4
+ version: 0.6.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - OpenReceive
@@ -15,28 +15,28 @@ dependencies:
15
15
  requirements:
16
16
  - - '='
17
17
  - !ruby/object:Gem::Version
18
- version: 0.4.35
18
+ version: 0.6.0
19
19
  type: :runtime
20
20
  prerelease: false
21
21
  version_requirements: !ruby/object:Gem::Requirement
22
22
  requirements:
23
23
  - - '='
24
24
  - !ruby/object:Gem::Version
25
- version: 0.4.35
25
+ version: 0.6.0
26
26
  - !ruby/object:Gem::Dependency
27
27
  name: openreceive-server
28
28
  requirement: !ruby/object:Gem::Requirement
29
29
  requirements:
30
30
  - - '='
31
31
  - !ruby/object:Gem::Version
32
- version: 0.4.35
32
+ version: 0.6.0
33
33
  type: :runtime
34
34
  prerelease: false
35
35
  version_requirements: !ruby/object:Gem::Requirement
36
36
  requirements:
37
37
  - - '='
38
38
  - !ruby/object:Gem::Version
39
- version: 0.4.35
39
+ version: 0.6.0
40
40
  - !ruby/object:Gem::Dependency
41
41
  name: rails
42
42
  requirement: !ruby/object:Gem::Requirement