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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +66 -0
- data/LICENSE +21 -0
- data/README.md +754 -0
- data/SECURITY.md +25 -0
- data/lib/sattleme/checkout/cancellation.rb +195 -0
- data/lib/sattleme/checkout/client.rb +1438 -0
- data/lib/sattleme/checkout/errors.rb +165 -0
- data/lib/sattleme/checkout/http_client.rb +294 -0
- data/lib/sattleme/checkout/internal/bolt11.rb +187 -0
- data/lib/sattleme/checkout/internal/channel.rb +147 -0
- data/lib/sattleme/checkout/internal/checkout_link.rb +294 -0
- data/lib/sattleme/checkout/internal/concurrency.rb +450 -0
- data/lib/sattleme/checkout/internal/crypto.rb +63 -0
- data/lib/sattleme/checkout/internal/currencies.rb +47 -0
- data/lib/sattleme/checkout/internal/declaration.rb +135 -0
- data/lib/sattleme/checkout/internal/derive.rb +153 -0
- data/lib/sattleme/checkout/internal/event.rb +110 -0
- data/lib/sattleme/checkout/internal/http.rb +129 -0
- data/lib/sattleme/checkout/internal/json.rb +457 -0
- data/lib/sattleme/checkout/internal/key.rb +116 -0
- data/lib/sattleme/checkout/internal/lnurl.rb +238 -0
- data/lib/sattleme/checkout/internal/nip44.rb +113 -0
- data/lib/sattleme/checkout/internal/onchain/address.rb +58 -0
- data/lib/sattleme/checkout/internal/onchain/basics.rb +352 -0
- data/lib/sattleme/checkout/internal/onchain/lease.rb +326 -0
- data/lib/sattleme/checkout/internal/onchain/merchant_acceptance.rb +168 -0
- data/lib/sattleme/checkout/internal/onchain/node.rb +285 -0
- data/lib/sattleme/checkout/internal/onchain/payment.rb +345 -0
- data/lib/sattleme/checkout/internal/onchain/rest.rb +323 -0
- data/lib/sattleme/checkout/internal/onchain/watch.rb +119 -0
- data/lib/sattleme/checkout/internal/onchain/witness.rb +260 -0
- data/lib/sattleme/checkout/internal/order.rb +228 -0
- data/lib/sattleme/checkout/internal/protocol.rb +260 -0
- data/lib/sattleme/checkout/internal/rates.rb +373 -0
- data/lib/sattleme/checkout/internal/record.rb +179 -0
- data/lib/sattleme/checkout/internal/relay_pool.rb +823 -0
- data/lib/sattleme/checkout/internal/sales.rb +238 -0
- data/lib/sattleme/checkout/internal/secp256k1.rb +234 -0
- data/lib/sattleme/checkout/internal/text.rb +144 -0
- data/lib/sattleme/checkout/internal/urls.rb +172 -0
- data/lib/sattleme/checkout/models.rb +247 -0
- data/lib/sattleme/checkout/version.rb +9 -0
- data/lib/sattleme/checkout/websocket_client.rb +487 -0
- data/lib/sattleme/checkout.rb +72 -0
- metadata +112 -0
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "uri"
|
|
4
|
+
|
|
5
|
+
module Sattleme
|
|
6
|
+
module Checkout
|
|
7
|
+
module Internal
|
|
8
|
+
# The merchant's Lightning address (LUD-16, LUD-06, LUD-12, LUD-21; SPEC.md §16, §18, §22):
|
|
9
|
+
# plain HTTPS requests to the merchant's LNURL server (breez.tips), which makes invoices for
|
|
10
|
+
# the merchant's wallet even while it is offline.
|
|
11
|
+
module Lnurl
|
|
12
|
+
LIGHTNING_ADDRESS = /\A([a-z0-9\-_.+]+)@([a-z0-9-]+(?:\.[a-z0-9-]+)+)\z/
|
|
13
|
+
|
|
14
|
+
# The LNURL-pay parameters of the merchant's Lightning address: its callback (an https URL),
|
|
15
|
+
# its bounds in millisatoshis, its metadata (the invoices' description hash is its SHA-256)
|
|
16
|
+
# and the longest comment it takes (LUD-12, 0 when none).
|
|
17
|
+
PayRequest = Data.define(:callback, :min_sendable_msat, :max_sendable_msat, :metadata, :comment_allowed) do
|
|
18
|
+
# Whole sats the Lightning address accepts: its bounds rounded inwards (the minimum up,
|
|
19
|
+
# the maximum down), so that a whole-sat amount within them is within the service's.
|
|
20
|
+
def sendable_sats
|
|
21
|
+
[(min_sendable_msat + 999) / 1000, max_sendable_msat / 1000]
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
# The description hash of its invoices (hex): SHA-256 of the UTF-8 of its metadata.
|
|
25
|
+
def description_hash
|
|
26
|
+
Text.hex(Crypto.sha256(Text.utf8(metadata)))
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
# What the Lightning address answered: an invoice and its LUD-21 verify URL, not checked.
|
|
31
|
+
InvoiceAnswer = Data.define(:pr, :verify)
|
|
32
|
+
|
|
33
|
+
# What the Lightning part of a payment check needs of an invoice.
|
|
34
|
+
LightningInvoice = Data.define(:bolt11, :payment_hash, :verify_url, :expires_at)
|
|
35
|
+
|
|
36
|
+
# The Lightning part of an invoice's payment: "open", "expired", or "paid" with its preimage.
|
|
37
|
+
Part = Data.define(:state, :preimage) do
|
|
38
|
+
def self.open = new(state: "open", preimage: nil)
|
|
39
|
+
def self.expired = new(state: "expired", preimage: nil)
|
|
40
|
+
def self.paid(preimage) = new(state: "paid", preimage: preimage)
|
|
41
|
+
def paid? = state == "paid"
|
|
42
|
+
def open? = state == "open"
|
|
43
|
+
def expired? = state == "expired"
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
module_function
|
|
47
|
+
|
|
48
|
+
# LUD-16: the LNURL-pay endpoint of a Lightning address (ASCII whitespace around it removed,
|
|
49
|
+
# ASCII letters lowered, as the app reads it), or nil when it is not one. The endpoint is an
|
|
50
|
+
# https URL (SPEC.md §16): its domain is never an IP address, nor `localhost`.
|
|
51
|
+
def address_url(address)
|
|
52
|
+
return nil unless Text.well_formed?(address)
|
|
53
|
+
|
|
54
|
+
match = LIGHTNING_ADDRESS.match(Text.ascii_lower(Text.trim_ascii(address)))
|
|
55
|
+
return nil unless match
|
|
56
|
+
|
|
57
|
+
url = "https://#{match[2]}/.well-known/lnurlp/#{match[1]}"
|
|
58
|
+
Urls.https_url(url) ? url : nil
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
# An LNURL error answer (LUD-06): `{"status": "ERROR", "reason": …}`, `ERROR` in any case.
|
|
62
|
+
def service_error?(body)
|
|
63
|
+
body.is_a?(Hash) && Text.well_formed?(body["status"]) && Text.ascii_lower(body["status"]) == "error"
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# An LNURL answer (SPEC.md §16): [:json, object], or [:refusal, reason] for the service's
|
|
67
|
+
# refusal sent with a 2xx or a client error status but 408 and 429. Anything else, or no
|
|
68
|
+
# JSON object, is no answer: NetworkError.
|
|
69
|
+
def get(url, http)
|
|
70
|
+
answer = Http.get_json(url, http)
|
|
71
|
+
status = answer.status
|
|
72
|
+
refusal_status = status.between?(400, 499) && status != 408 && status != 429
|
|
73
|
+
if (answer.ok? || refusal_status) && service_error?(answer.body)
|
|
74
|
+
reason = answer.body["reason"]
|
|
75
|
+
return [:refusal, reason.is_a?(String) ? reason : ""]
|
|
76
|
+
end
|
|
77
|
+
unless answer.ok? && answer.body.is_a?(Hash)
|
|
78
|
+
raise NetworkError, "#{Urls.host_of(url)} answered HTTP #{status} without an LNURL answer"
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
[:json, answer.body]
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# Millisatoshis of a JSON number: a non-negative safe integer, else nil.
|
|
85
|
+
def msat(value)
|
|
86
|
+
Json.safe_integer?(value) && value >= 0 ? value.to_i : nil
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
# The pay request of the Lightning address (LUD-16): a refusal is no answer (NetworkError);
|
|
90
|
+
# an answer that is not a pay request is InvalidInvoiceError.
|
|
91
|
+
def pay_request(address, http)
|
|
92
|
+
url = address_url(address)
|
|
93
|
+
raise InvalidInvoiceError, "The merchant's Lightning address is invalid" unless url
|
|
94
|
+
|
|
95
|
+
kind, json = get(url, http)
|
|
96
|
+
raise NetworkError, "#{Urls.host_of(url)} refused the Lightning address: #{json}" if kind == :refusal
|
|
97
|
+
|
|
98
|
+
callback = json["callback"]
|
|
99
|
+
min = msat(json["minSendable"])
|
|
100
|
+
max = msat(json["maxSendable"])
|
|
101
|
+
unless json["tag"] == "payRequest" && Urls.https_url(callback) && min && max && min <= max &&
|
|
102
|
+
Text.well_formed?(json["metadata"])
|
|
103
|
+
raise InvalidInvoiceError, "#{Urls.host_of(url)} gave no valid LNURL-pay request"
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
comment_allowed = json["commentAllowed"]
|
|
107
|
+
comment_allowed = Json.safe_integer?(comment_allowed) ? [comment_allowed.to_i, 0].max : 0
|
|
108
|
+
PayRequest.new(callback: callback, min_sendable_msat: min, max_sendable_msat: max,
|
|
109
|
+
metadata: json["metadata"], comment_allowed: comment_allowed)
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
# The callback's URL for an invoice (SPEC.md §17, step 5): its fragment (from its first `#`)
|
|
113
|
+
# dropped, since the parameters added after it would never reach the server, and
|
|
114
|
+
# `parameters` set as URLSearchParams#set sets them: the callback's first pair of a name
|
|
115
|
+
# takes its value, its other pairs of that name are removed, a name it lacks is added at the
|
|
116
|
+
# end; its other pairs are kept as written. Values are form-urlencoded.
|
|
117
|
+
def callback_url(callback, parameters)
|
|
118
|
+
path, query = callback.sub(/#.*\z/m, "").split("?", 2)
|
|
119
|
+
placed = {}
|
|
120
|
+
pairs = (query || "").split("&", -1).filter_map do |pair|
|
|
121
|
+
name = form_name(pair)
|
|
122
|
+
if parameters.key?(name)
|
|
123
|
+
next if placed[name]
|
|
124
|
+
|
|
125
|
+
placed[name] = true
|
|
126
|
+
form_pair(name, parameters[name])
|
|
127
|
+
elsif !pair.empty?
|
|
128
|
+
pair
|
|
129
|
+
end
|
|
130
|
+
end
|
|
131
|
+
parameters.each { |name, value| pairs << form_pair(name, value) unless placed[name] }
|
|
132
|
+
"#{path}?#{pairs.join("&")}"
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
# The name of a query's pair, form-decoded (`+` a space, `%XX` its byte); nil when it does
|
|
136
|
+
# not decode to UTF-8, as no parameter set is named so.
|
|
137
|
+
def form_name(pair)
|
|
138
|
+
name = URI.decode_www_form_component(pair.split("=", 2)[0])
|
|
139
|
+
name.valid_encoding? ? name : nil
|
|
140
|
+
rescue ArgumentError
|
|
141
|
+
nil
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
def form_pair(name, value)
|
|
145
|
+
"#{URI.encode_www_form_component(name)}=#{URI.encode_www_form_component(value)}"
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
# Asks the Lightning address for an invoice of `sats` (LUD-06): `amount` in millisatoshis,
|
|
149
|
+
# `expiry` in seconds, and `comment` only when its UTF-8 fits `comment_allowed` (LUD-12
|
|
150
|
+
# does not say how a comment's length counts: bytes are never fewer than characters). The
|
|
151
|
+
# answer is not checked: check_invoice does.
|
|
152
|
+
def request_invoice(pay, sats:, expiry_seconds:, comment:, http:)
|
|
153
|
+
parameters = { "amount" => (sats * 1000).to_s, "expiry" => expiry_seconds.to_s }
|
|
154
|
+
if comment && !comment.empty? && Text.utf8_length(comment) <= pay.comment_allowed
|
|
155
|
+
parameters["comment"] = comment
|
|
156
|
+
end
|
|
157
|
+
kind, json = get(callback_url(pay.callback, parameters), http)
|
|
158
|
+
raise NetworkError, "The Lightning address refused the invoice: #{json}" if kind == :refusal
|
|
159
|
+
|
|
160
|
+
pr = json["pr"]
|
|
161
|
+
verify = json["verify"]
|
|
162
|
+
unless pr.is_a?(String) && verify.is_a?(String)
|
|
163
|
+
raise InvalidInvoiceError, "The Lightning address gave no invoice or no verify URL (LUD-21)"
|
|
164
|
+
end
|
|
165
|
+
|
|
166
|
+
InvoiceAnswer.new(pr: pr, verify: verify)
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
# Checks an invoice before it is declared or shown (SPEC.md §18): Bitcoin mainnet, exactly
|
|
170
|
+
# `sats`, the merchant's description hash (breez.tips serves the invoices of all its users),
|
|
171
|
+
# a verify URL in https on the callback's host, an expiry no longer than asked, a date
|
|
172
|
+
# within 5 minutes of the clock, time left before its end. InvalidInvoiceError naming the
|
|
173
|
+
# first check failed. The decoded invoice.
|
|
174
|
+
def check_invoice(answer, pay:, sats:, duration_seconds:, now:)
|
|
175
|
+
decoded = Text.well_formed?(answer.pr) ? Bolt11.decode(answer.pr) : nil
|
|
176
|
+
raise InvalidInvoiceError, "Not a BOLT11 invoice" unless decoded
|
|
177
|
+
raise InvalidInvoiceError, "Not a Bitcoin mainnet invoice" unless decoded.network == "bc"
|
|
178
|
+
unless decoded.amount_msat == sats * 1000
|
|
179
|
+
raise InvalidInvoiceError,
|
|
180
|
+
"The invoice's amount differs from the order's"
|
|
181
|
+
end
|
|
182
|
+
unless decoded.description_hash == pay.description_hash
|
|
183
|
+
raise InvalidInvoiceError, "The invoice does not pay the merchant's Lightning address"
|
|
184
|
+
end
|
|
185
|
+
|
|
186
|
+
verify = Urls.https_url(answer.verify)
|
|
187
|
+
unless verify && Urls.same_host?(verify, Urls.https_url(pay.callback))
|
|
188
|
+
raise InvalidInvoiceError, "No verify URL (LUD-21) on the Lightning address's host"
|
|
189
|
+
end
|
|
190
|
+
raise InvalidInvoiceError, "The invoice lasts longer than asked" if decoded.expiry_seconds > duration_seconds
|
|
191
|
+
raise InvalidInvoiceError, "The invoice has no time left" if decoded.expiry_seconds <= 0
|
|
192
|
+
if (decoded.timestamp - now).abs > Protocol::CLOCK_TOLERANCE_SECONDS
|
|
193
|
+
raise InvalidInvoiceError, "The invoice's date is too far from this server's clock"
|
|
194
|
+
end
|
|
195
|
+
# Dated up to 5 minutes back, a short invoice may already be over: never declared nor shown.
|
|
196
|
+
raise InvalidInvoiceError, "The invoice has no time left" if decoded.expires_at <= now
|
|
197
|
+
|
|
198
|
+
decoded
|
|
199
|
+
end
|
|
200
|
+
|
|
201
|
+
# The Lightning part of an invoice's payment (LUD-21, SPEC.md §22), checked: the verify
|
|
202
|
+
# answer names this very invoice (`pr`, whatever the case of its ASCII letters), `settled`
|
|
203
|
+
# is true and the preimage's SHA-256 is the payment hash. After the invoice's end and its
|
|
204
|
+
# grace period, "not settled" and "Not found" are final (`expired`); before, any refusal of
|
|
205
|
+
# the service keeps it `open`. NetworkError when the service gives no answer (or another
|
|
206
|
+
# refusal past the grace), InvalidInvoiceError when its answer is about another invoice or
|
|
207
|
+
# its preimage is wrong.
|
|
208
|
+
def verify_payment(invoice, http, now)
|
|
209
|
+
final = now >= invoice.expires_at + Protocol::GRACE_SECONDS
|
|
210
|
+
kind, json = get(invoice.verify_url, http)
|
|
211
|
+
if kind == :refusal
|
|
212
|
+
return Part.open unless final
|
|
213
|
+
return Part.expired if json == Protocol::NOT_FOUND_REASON
|
|
214
|
+
|
|
215
|
+
raise NetworkError, "The payment check was refused: #{json}"
|
|
216
|
+
end
|
|
217
|
+
pr = json["pr"]
|
|
218
|
+
raise InvalidInvoiceError, "The payment check names no invoice (LUD-21 pr)" unless pr.is_a?(String)
|
|
219
|
+
# BOLT11 is case-insensitive (bech32): the same invoice may be written in upper case.
|
|
220
|
+
unless Text.well_formed?(pr) && Text.ascii_lower(pr) == Text.ascii_lower(invoice.bolt11)
|
|
221
|
+
raise InvalidInvoiceError, "The payment check is about another invoice"
|
|
222
|
+
end
|
|
223
|
+
return final ? Part.expired : Part.open unless json["settled"] == true
|
|
224
|
+
|
|
225
|
+
preimage = json["preimage"]
|
|
226
|
+
raise InvalidInvoiceError, "Paid without a valid preimage" unless Text.match?(preimage, /\A[0-9a-fA-F]{64}\z/)
|
|
227
|
+
|
|
228
|
+
proof = Text.ascii_lower(preimage)
|
|
229
|
+
unless Text.hex(Crypto.sha256(Text.hex_bytes(proof))) == invoice.payment_hash
|
|
230
|
+
raise InvalidInvoiceError, "The preimage does not match the payment hash"
|
|
231
|
+
end
|
|
232
|
+
|
|
233
|
+
Part.paid(proof)
|
|
234
|
+
end
|
|
235
|
+
end
|
|
236
|
+
end
|
|
237
|
+
end
|
|
238
|
+
end
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Sattleme
|
|
4
|
+
module Checkout
|
|
5
|
+
module Internal
|
|
6
|
+
# NIP-44 version 2 (https://github.com/nostr-protocol/nips/blob/master/44.md, SPEC.md §12):
|
|
7
|
+
# ChaCha20, HMAC-SHA256 over the nonce and the ciphertext, per-message keys from a random
|
|
8
|
+
# 32-byte nonce, plaintexts padded. Checked against the official vectors. The conversation key
|
|
9
|
+
# is a 32-byte HKDF output used as it is, but inside a registry declaration and a lease:
|
|
10
|
+
# the ECDH conversation key.
|
|
11
|
+
module Nip44
|
|
12
|
+
VERSION = 2
|
|
13
|
+
MIN_PLAINTEXT = 1
|
|
14
|
+
MAX_PLAINTEXT = 0xFFFF
|
|
15
|
+
|
|
16
|
+
# A payload of another version (empty, `#`…, or another version byte): a newer client's.
|
|
17
|
+
class UnknownVersion < StandardError; end
|
|
18
|
+
|
|
19
|
+
# A payload that is not a NIP-44 v2 encryption under this key.
|
|
20
|
+
class Invalid < StandardError; end
|
|
21
|
+
|
|
22
|
+
# A plaintext longer than NIP-44 v2 holds (65 535 bytes): an invoice too long to be declared.
|
|
23
|
+
class TooLong < ArgumentError; end
|
|
24
|
+
|
|
25
|
+
module_function
|
|
26
|
+
|
|
27
|
+
# The conversation key of a secret key and an x-only public key (hex): the x coordinate of
|
|
28
|
+
# their ECDH, through HKDF-extract with the salt "nip44-v2". ArgumentError for a key out of
|
|
29
|
+
# range or off the curve.
|
|
30
|
+
def conversation_key(secret, public_key)
|
|
31
|
+
raise ArgumentError, "Invalid public key" unless Text.hex32?(public_key)
|
|
32
|
+
|
|
33
|
+
shared = Secp256k1.shared_x(secret, Text.hex_bytes(public_key))
|
|
34
|
+
Crypto.hkdf_extract("nip44-v2", shared)
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# The padded length of a plaintext of `length` bytes (`calc_padded_len`).
|
|
38
|
+
def padded_length(length)
|
|
39
|
+
return 32 if length <= 32
|
|
40
|
+
|
|
41
|
+
next_power = 1 << (length - 1).bit_length
|
|
42
|
+
chunk = next_power <= 256 ? 32 : next_power / 8
|
|
43
|
+
chunk * (((length - 1) / chunk) + 1)
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# The ChaCha20 key and nonce and the HMAC key of one message (`get_message_keys`).
|
|
47
|
+
def message_keys(conversation_key, nonce)
|
|
48
|
+
raise ArgumentError, "Invalid conversation key" unless conversation_key.bytesize == 32
|
|
49
|
+
raise ArgumentError, "Invalid nonce" unless nonce.bytesize == 32
|
|
50
|
+
|
|
51
|
+
keys = Crypto.hkdf_expand(conversation_key, nonce, 76)
|
|
52
|
+
[keys.byteslice(0, 32), keys.byteslice(32, 12), keys.byteslice(44, 32)]
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# The payload of the well-formed text `text` under `conversation_key`, with a fresh nonce
|
|
56
|
+
# of `random` (32 bytes).
|
|
57
|
+
def encrypt(text, conversation_key, random)
|
|
58
|
+
encrypt_with_nonce(text, conversation_key, random.call(32))
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
# Encryption with a given nonce: for the official vectors only.
|
|
62
|
+
def encrypt_with_nonce(text, conversation_key, nonce)
|
|
63
|
+
chacha_key, chacha_nonce, hmac_key = message_keys(conversation_key, nonce)
|
|
64
|
+
ciphertext = Crypto.chacha20(chacha_key, chacha_nonce, pad(text))
|
|
65
|
+
mac = Crypto.hmac(hmac_key, nonce + ciphertext)
|
|
66
|
+
Base64.encode(VERSION.chr + nonce + ciphertext + mac)
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
# The text of a payload: UnknownVersion for another version, Invalid when it is malformed
|
|
70
|
+
# or not sealed with `conversation_key`.
|
|
71
|
+
def decrypt(payload, conversation_key)
|
|
72
|
+
raise Invalid, "not a payload" unless payload.is_a?(String)
|
|
73
|
+
raise UnknownVersion if payload.empty? || payload.start_with?("#")
|
|
74
|
+
raise Invalid, "Invalid payload size" unless payload.length.between?(132, 87_472)
|
|
75
|
+
|
|
76
|
+
data = Base64.decode(payload)
|
|
77
|
+
raise Invalid, "Invalid payload" if data.nil? || !data.bytesize.between?(99, 65_603)
|
|
78
|
+
raise UnknownVersion unless data.getbyte(0) == VERSION
|
|
79
|
+
|
|
80
|
+
nonce = data.byteslice(1, 32)
|
|
81
|
+
ciphertext = data.byteslice(33, data.bytesize - 65)
|
|
82
|
+
chacha_key, chacha_nonce, hmac_key = message_keys(conversation_key, nonce)
|
|
83
|
+
# Constant time: the comparison does not stop at the first byte that differs.
|
|
84
|
+
unless Crypto.same?(Crypto.hmac(hmac_key, nonce + ciphertext), data.byteslice(-32, 32))
|
|
85
|
+
raise Invalid, "Invalid MAC"
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
unpad(Crypto.chacha20(chacha_key, chacha_nonce, ciphertext))
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
def pad(text)
|
|
92
|
+
bytes = text.b
|
|
93
|
+
raise TooLong, "Plaintext longer than #{MAX_PLAINTEXT} bytes" if bytes.bytesize > MAX_PLAINTEXT
|
|
94
|
+
raise ArgumentError, "Empty plaintext" if bytes.bytesize < MIN_PLAINTEXT
|
|
95
|
+
|
|
96
|
+
padded = [bytes.bytesize].pack("n") + bytes
|
|
97
|
+
padded + ("\x00".b * (2 + padded_length(bytes.bytesize) - padded.bytesize))
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
def unpad(padded)
|
|
101
|
+
length = padded.byteslice(0, 2).unpack1("n")
|
|
102
|
+
raise Invalid, "Invalid padding" if length < MIN_PLAINTEXT || padded.bytesize != 2 + padded_length(length)
|
|
103
|
+
|
|
104
|
+
# Strict UTF-8: a byte order mark is kept, as U+FEFF (SPEC.md §2).
|
|
105
|
+
text = Text.decode_utf8(padded.byteslice(2, length))
|
|
106
|
+
raise Invalid, "Invalid UTF-8" if text.nil?
|
|
107
|
+
|
|
108
|
+
text
|
|
109
|
+
end
|
|
110
|
+
end
|
|
111
|
+
end
|
|
112
|
+
end
|
|
113
|
+
end
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Sattleme
|
|
4
|
+
module Checkout
|
|
5
|
+
module Internal
|
|
6
|
+
# Deposit addresses (SPEC.md §31, "Deposit addresses", "Payment URIs"): the taproot
|
|
7
|
+
# addresses the merchant's wallet hands out, in their one spelling, and what the shop's page
|
|
8
|
+
# shows of an invoice as one QR code.
|
|
9
|
+
module Addresses
|
|
10
|
+
# `bc1p` and 58 more characters.
|
|
11
|
+
LENGTH = 62
|
|
12
|
+
# The witness version (1) and the 32-byte program, as 5-bit words.
|
|
13
|
+
PROGRAM_WORDS = 53
|
|
14
|
+
|
|
15
|
+
module_function
|
|
16
|
+
|
|
17
|
+
# Whether `value` is a deposit address: the bech32m encoding (BIP-350) of the human-readable
|
|
18
|
+
# part `bc`, witness version 1 and a 32-byte program (BIP-341), in lowercase. Another
|
|
19
|
+
# network, witness version or length, bech32 instead of bech32m, upper case or a padding
|
|
20
|
+
# with bits that are not zero is not one.
|
|
21
|
+
def deposit?(value)
|
|
22
|
+
return false unless Text.match?(value, /\Abc1[02-9ac-hj-np-z]+\z/) && value.length == LENGTH
|
|
23
|
+
|
|
24
|
+
decoded = Bech32.decode(value, Bech32::BECH32M)
|
|
25
|
+
return false unless decoded && decoded.hrp == "bc"
|
|
26
|
+
|
|
27
|
+
words = decoded.words
|
|
28
|
+
# 52 words after the version: 256 bits of program and 4 bits of padding, which are zeros.
|
|
29
|
+
words.size == PROGRAM_WORDS && words[0] == 1 && words[-1].nobits?(0b1111)
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# Where the leases of `address` are in the registry: HMAC(registry key, "onchain/v1/" +
|
|
33
|
+
# address).
|
|
34
|
+
def lease_address(registry_key, address)
|
|
35
|
+
Text.hex(Crypto.hmac(registry_key, (Protocol::LEASE_ADDRESS_PREFIX + address).b))
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# `sats` in bitcoins, exact, as BIP-21's `amount`: no trailing zero in the fraction, no
|
|
39
|
+
# fraction when whole (49 000 sats is "0.00049", 100 000 000 sats is "1").
|
|
40
|
+
def btc_amount(sats)
|
|
41
|
+
whole, fraction = sats.divmod(Protocol::SATS_PER_BTC)
|
|
42
|
+
fraction = fraction.to_s.rjust(8, "0").sub(/0+\z/, "")
|
|
43
|
+
fraction.empty? ? whole.to_s : "#{whole}.#{fraction}"
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# What the shop's page shows as one QR code: `bitcoin:<address>?amount=<BTC>`, with
|
|
47
|
+
# `&lightning=<invoice>` when there is one (BIP-21, the "unified QR" wallets read), or
|
|
48
|
+
# `lightning:<invoice>` without an address. Both are written as they are (lowercase).
|
|
49
|
+
def payment_uri(address, sats, bolt11)
|
|
50
|
+
return "lightning:#{bolt11}" if address.nil?
|
|
51
|
+
|
|
52
|
+
uri = "bitcoin:#{address}?amount=#{btc_amount(sats)}"
|
|
53
|
+
bolt11.nil? ? uri : "#{uri}&lightning=#{bolt11}"
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
end
|
|
58
|
+
end
|