mixin_bot 3.0.3 → 3.1.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 (48) hide show
  1. checksums.yaml +4 -4
  2. data/AGENTS.md +12 -2
  3. data/CHANGELOG.md +135 -0
  4. data/README.md +3 -2
  5. data/docs/agent/cli.md +4 -2
  6. data/lib/mixin_bot/address.rb +73 -62
  7. data/lib/mixin_bot/api/attachment.rb +18 -8
  8. data/lib/mixin_bot/api/blaze.rb +7 -2
  9. data/lib/mixin_bot/api/blaze_async.rb +169 -4
  10. data/lib/mixin_bot/api/computer_api.rb +7 -7
  11. data/lib/mixin_bot/api/encrypted_message.rb +75 -52
  12. data/lib/mixin_bot/api/multisig.rb +9 -7
  13. data/lib/mixin_bot/api/pin.rb +9 -8
  14. data/lib/mixin_bot/api/tip.rb +1 -1
  15. data/lib/mixin_bot/api/transaction.rb +70 -41
  16. data/lib/mixin_bot/api/transfer.rb +3 -2
  17. data/lib/mixin_bot/api/user.rb +6 -6
  18. data/lib/mixin_bot/api.rb +1 -0
  19. data/lib/mixin_bot/bot_auth.rb +1 -1
  20. data/lib/mixin_bot/cli/schema.rb +2 -0
  21. data/lib/mixin_bot/cli.rb +9 -3
  22. data/lib/mixin_bot/client.rb +43 -19
  23. data/lib/mixin_bot/computer.rb +39 -23
  24. data/lib/mixin_bot/configuration.rb +48 -8
  25. data/lib/mixin_bot/invoice.rb +126 -77
  26. data/lib/mixin_bot/nfo.rb +54 -43
  27. data/lib/mixin_bot/proxy.rb +184 -0
  28. data/lib/mixin_bot/transaction/decoder.rb +201 -138
  29. data/lib/mixin_bot/transaction/encoder.rb +156 -118
  30. data/lib/mixin_bot/transaction.rb +15 -1
  31. data/lib/mixin_bot/utils/address.rb +1 -1
  32. data/lib/mixin_bot/utils/amount.rb +25 -0
  33. data/lib/mixin_bot/utils/base58.rb +97 -0
  34. data/lib/mixin_bot/utils/crypto.rb +188 -56
  35. data/lib/mixin_bot/utils/cursor.rb +147 -0
  36. data/lib/mixin_bot/utils/decoder.rb +111 -6
  37. data/lib/mixin_bot/utils/encoder.rb +90 -21
  38. data/lib/mixin_bot/utils/options.rb +26 -0
  39. data/lib/mixin_bot/utils/sodium.rb +169 -0
  40. data/lib/mixin_bot/utils.rb +17 -2
  41. data/lib/mixin_bot/uuid.rb +6 -13
  42. data/lib/mixin_bot/version.rb +1 -1
  43. data/lib/mixin_bot.rb +1 -3
  44. data/lib/mvm/client.rb +44 -9
  45. data/lib/mvm/registry.rb +45 -17
  46. data/llms.txt +1 -1
  47. metadata +6 -44
  48. data/lib/mixin_bot/transaction/buffer.rb +0 -34
@@ -28,6 +28,8 @@ module MixinBot
28
28
  # This provides quantum-resistant security with compact signatures.
29
29
  #
30
30
  module Crypto
31
+ PIN_ITERATOR_LOCK = Mutex.new
32
+ private_constant :PIN_ITERATOR_LOCK
31
33
  ##
32
34
  # Generates a JWT access token for API authentication.
33
35
  #
@@ -85,15 +87,41 @@ module MixinBot
85
87
  if private_key.blank?
86
88
  raise ConfigurationNotValidError, 'private_key is required'
87
89
  elsif private_key.size == 64
88
- jwk = JOSE::JWK.from_okp [:Ed25519, private_key]
89
- jws = JOSE::JWS.from({ 'alg' => 'EdDSA' })
90
+ ed25519_jwt(payload, private_key) || begin
91
+ jwk = JOSE::JWK.from_okp [:Ed25519, private_key]
92
+ jws = JOSE::JWS.from({ 'alg' => 'EdDSA' })
93
+ JOSE::JWT.sign(jwk, jws, JOSE::JWT.from(payload)).compact
94
+ end
90
95
  else
91
96
  jwk = JOSE::JWK.from_pem private_key
92
97
  jws = JOSE::JWS.from({ 'alg' => 'RS512' })
98
+ jwt = JOSE::JWT.from payload
99
+ JOSE::JWT.sign(jwk, jws, jwt).compact
93
100
  end
101
+ end
94
102
 
95
- jwt = JOSE::JWT.from payload
96
- JOSE::JWT.sign(jwk, jws, jwt).compact
103
+ ##
104
+ # The compact JWS that JOSE::JWT.sign produced for an Ed25519 key, signed
105
+ # through libsodium instead: JOSE's protected header (it adds +typ+),
106
+ # the claims sorted by name, and the Ed25519 signature over
107
+ # <tt>header.claims</tt>. Byte for byte what the JOSE call returned, for
108
+ # the same payload and key.
109
+ #
110
+ # @param payload [Hash] the JWT claims
111
+ # @param signing_key [String] 64-byte Ed25519 signing key
112
+ # @return [String, nil] the token, or nil for a key libsodium does not sign with
113
+ #
114
+ ED25519_JWT_HEADER = Base64.urlsafe_encode64('{"alg":"EdDSA","typ":"JWT"}', padding: false).freeze
115
+
116
+ def ed25519_jwt(payload, signing_key)
117
+ claims = Base64.urlsafe_encode64(JSON.generate(payload.sort.to_h), padding: false)
118
+ signing_input = "#{ED25519_JWT_HEADER}.#{claims}"
119
+ # libsodium only, so that a key it does not sign with leaves the token
120
+ # to the JOSE path instead of raising here
121
+ signature = Sodium.ed25519_sign(signing_input, signing_key)
122
+ return unless signature
123
+
124
+ "#{signing_input}.#{Base64.urlsafe_encode64(signature, padding: false)}"
97
125
  end
98
126
 
99
127
  ##
@@ -124,10 +152,11 @@ module MixinBot
124
152
  # puts "Public: #{keys[:public_key]}"
125
153
  #
126
154
  def generate_ed25519_key
127
- ed25519_key = JOSE::JWA::Ed25519.keypair
155
+ public_key, signing_key = ed25519_keypair
156
+
128
157
  {
129
- private_key: Base64.urlsafe_encode64(ed25519_key[1], padding: false),
130
- public_key: Base64.urlsafe_encode64(ed25519_key[0], padding: false)
158
+ private_key: Base64.urlsafe_encode64(signing_key, padding: false),
159
+ public_key: Base64.urlsafe_encode64(public_key, padding: false)
131
160
  }
132
161
  end
133
162
 
@@ -151,6 +180,64 @@ module MixinBot
151
180
  }
152
181
  end
153
182
 
183
+ ##
184
+ # Derives the Ed25519 public key of a 32-byte seed.
185
+ #
186
+ # Used internally for configuration and ghost key generation.
187
+ #
188
+ # @param seed [String] 32-byte seed; omitted for a random one
189
+ # @return [Array(String, String)] public key and 64-byte signing key (seed + public key)
190
+ # @raise [ArgumentError] if +seed+ is given and not 32 bytes
191
+ #
192
+ def ed25519_keypair(seed = nil)
193
+ seed ||= SecureRandom.random_bytes(32)
194
+ Sodium.ed25519_keypair(seed) || JOSE::JWA::Ed25519.keypair(seed)
195
+ end
196
+
197
+ ##
198
+ # Signs a message with a 64-byte Ed25519 signing key.
199
+ #
200
+ # @param message [String] the message
201
+ # @param signing_key [String] 64-byte signing key
202
+ # @return [String] 64-byte signature
203
+ # @raise [ArgumentError] if +signing_key+ is not 64 bytes
204
+ #
205
+ def ed25519_sign(message, signing_key)
206
+ Sodium.ed25519_sign(message, signing_key) || JOSE::JWA::Ed25519.sign(message, signing_key)
207
+ end
208
+
209
+ ##
210
+ # The Curve25519 public key of an Ed25519 public key.
211
+ #
212
+ # @param public_key [String] 32-byte Ed25519 public key
213
+ # @return [String] 32-byte Curve25519 public key
214
+ # @raise [ArgumentError] if +public_key+ is not a valid point
215
+ #
216
+ def ed25519_pk_to_curve25519(public_key)
217
+ Sodium.ed25519_pk_to_curve25519(public_key) || JOSE::JWA::Ed25519.pk_to_curve25519(public_key)
218
+ end
219
+
220
+ ##
221
+ # Curve25519 shared secret (X25519).
222
+ #
223
+ # @param scalar [String] 32-byte Curve25519 private key
224
+ # @param point [String] 32-byte Curve25519 public key
225
+ # @return [String] 32-byte shared secret
226
+ # @raise [ArgumentError] if either argument is not 32 bytes
227
+ #
228
+ def x25519(scalar, point)
229
+ Sodium.x25519(scalar, point) || JOSE::JWA::X25519.shared_secret(point, scalar)
230
+ end
231
+
232
+ def message_shared_key(scalar, point)
233
+ raise ArgumentError, 'invalid Curve25519 public key' unless point.bytesize == 32
234
+
235
+ # RFC 7748 masks the high bit of u, as the Go X25519 implementation does.
236
+ high = point.getbyte(31)
237
+ point = point.dup.tap { |bytes| bytes.setbyte(31, high & 127) } if high >= 128
238
+ x25519(scalar, point)
239
+ end
240
+
154
241
  ##
155
242
  # Derives a public key from a private key.
156
243
  #
@@ -160,7 +247,7 @@ module MixinBot
160
247
  # @return [String] the derived public key
161
248
  #
162
249
  def shared_public_key(key)
163
- (JOSE::JWA::Edwards25519Point.stdbase * scalar_from_bytes(key[...64]).x.to_i).encode
250
+ ed25519_base_mult scalar_from_bytes(key[...64]).x.to_i
164
251
  end
165
252
 
166
253
  ##
@@ -180,10 +267,10 @@ module MixinBot
180
267
  end
181
268
 
182
269
  def sign(msg, key:)
183
- msg = Digest::Blake3.digest msg
184
-
185
- pub = shared_public_key key
270
+ sign_transaction_hash(Digest::Blake3.digest(msg), key:, public_key: shared_public_key(key))
271
+ end
186
272
 
273
+ def sign_transaction_hash(msg, key:, public_key:)
187
274
  y_scalar = scalar_from_bytes key
188
275
 
189
276
  key_digest = Digest::SHA512.digest key
@@ -191,15 +278,15 @@ module MixinBot
191
278
 
192
279
  z_scalar = scalar_from_bytes msg_digest[...64]
193
280
 
194
- r_point = JOSE::JWA::Edwards25519Point.stdbase * z_scalar.x.to_i
281
+ r_point = ed25519_base_mult z_scalar.x.to_i
195
282
 
196
- hram_digest = Digest::SHA512.digest(r_point.encode + pub + msg)
283
+ hram_digest = Digest::SHA512.digest(r_point + public_key + msg)
197
284
 
198
285
  x_scalar = scalar_from_bytes hram_digest[...64]
199
286
 
200
287
  s_scalar = (x_scalar * y_scalar) + z_scalar
201
288
 
202
- r_point.encode + s_scalar.to_bytes(32).ljust(32, "\x00")
289
+ r_point + s_scalar.to_bytes(32).ljust(32, "\x00")
203
290
  end
204
291
 
205
292
  def generate_unique_uuid(uuid1, uuid2)
@@ -327,73 +414,91 @@ module MixinBot
327
414
 
328
415
  # decrypt the encrpted pin, just for test
329
416
  def decrypt_pin(msg, shared_key:)
330
- msg = Base64.urlsafe_decode64 msg
331
- iv = msg[0..15]
332
- cipher = msg[16..47]
333
- alg = 'AES-256-CBC'
334
- decode_cipher = OpenSSL::Cipher.new(alg)
335
- decode_cipher.decrypt
336
- decode_cipher.iv = iv
417
+ msg = Base64.urlsafe_decode64(msg)
418
+ decode_cipher = OpenSSL::Cipher.new('AES-256-CBC').decrypt
419
+ decode_cipher.iv = msg.byteslice(0, 16)
337
420
  decode_cipher.key = shared_key
338
- decode_cipher.update(cipher)
421
+ decode_cipher.update(msg.byteslice(16..)) + decode_cipher.final
339
422
  end
340
423
 
341
- # use timestamp(timestamp) for iterator as default: must be bigger than the previous,
342
- # the first time must be greater than 0. After a new session created, it will be reset to 0.
343
424
  def encrypt_pin(pin, **kwargs)
344
- pin = MixinBot.utils.decode_key pin
425
+ pin = pin_bytes(pin)
345
426
 
346
427
  shared_key = kwargs[:shared_key]
347
428
  raise ArgumentError, 'shared_key is required' if shared_key.blank?
429
+ raise ArgumentError, 'pin is required' if pin.blank?
348
430
 
349
- iterator ||= kwargs[:iterator] || Time.now.utc.to_i
350
- tszero = iterator % 0x100
351
- tsone = (iterator % 0x10000) >> 8
352
- tstwo = (iterator % 0x1000000) >> 16
353
- tsthree = (iterator % 0x100000000) >> 24
354
- tsstring = "#{tszero.chr}#{tsone.chr}#{tstwo.chr}#{tsthree.chr}\u0000\u0000\u0000\u0000"
355
- encrypt_content = pin + tsstring + tsstring
356
- pad_count = 16 - (encrypt_content.length % 16)
357
- padded_content =
358
- if pad_count.positive?
359
- encrypt_content + (pad_count.chr * pad_count)
360
- else
361
- encrypt_content
362
- end
431
+ now = Time.now
432
+ iterator = kwargs[:iterator]
433
+ iterator ||= PIN_ITERATOR_LOCK.synchronize do
434
+ @pin_iterator = [((now.to_i * 1_000_000_000) + now.nsec), @pin_iterator.to_i + 1].max
435
+ end
436
+ raise ArgumentError, 'invalid PIN iterator' unless iterator.is_a?(Integer) && iterator.between?(1, (1 << 64) - 1)
363
437
 
364
- alg = 'AES-256-CBC'
365
- aes = OpenSSL::Cipher.new(alg)
366
- iv = OpenSSL::Cipher.new(alg).random_iv
367
- aes.encrypt
438
+ plaintext = pin.b + [now.to_i, iterator].pack('Q<2')
439
+ aes = OpenSSL::Cipher.new('AES-256-CBC').encrypt
368
440
  aes.key = shared_key
441
+ iv = aes.random_iv
369
442
  aes.iv = iv
370
- cipher = aes.update(padded_content)
371
- msg = iv + cipher
372
- Base64.urlsafe_encode64 msg, padding: false
443
+ Base64.urlsafe_encode64(iv + aes.update(plaintext) + aes.final, padding: false)
373
444
  end
374
445
 
375
446
  def tip_public_key(key, counter: 0)
376
447
  raise ArgumentError, 'invalid key' if key.size < 32
377
448
 
378
- (key[0...32].bytes + MixinBot::Utils.encode_uint64(counter + 1)).pack('c*').unpack1('H*')
449
+ (key.byteslice(0, 32).b + MixinBot::Utils.pack_uint64(counter + 1)).unpack1('H*')
379
450
  end
380
451
 
381
452
  def hash_scalar(pkey, output_index)
382
- tmp = [output_index].pack('Q<').reverse
453
+ raise ArgumentError, 'invalid ghost output index' unless output_index.is_a?(Integer) && output_index.between?(0, (1 << 64) - 1)
454
+
455
+ tmp = +''.b
456
+ while output_index >= 128
457
+ tmp << ((output_index & 127) | 128)
458
+ output_index >>= 7
459
+ end
460
+ tmp << output_index
383
461
 
384
462
  hash1 = Digest::Blake3.digest(pkey + tmp)
385
463
  hash2 = Digest::Blake3.digest hash1
386
464
 
387
- hash3 = Digest::Blake3.digest(hash1 + hash2)
465
+ scalar = scalar_from_bytes(hash1 + hash2).to_bytes(256)
466
+ hash3 = Digest::Blake3.digest(scalar)
388
467
  hash4 = Digest::Blake3.digest hash3
389
468
 
390
469
  hash3 + hash4
391
470
  end
392
471
 
472
+ def generate_xin_ghost_keys(members, index)
473
+ scalar = scalar_from_bytes(SecureRandom.random_bytes(64)).to_bytes(256)
474
+ keys = members.map do |member|
475
+ payload = parse_main_address(member)
476
+ derive_ghost_public_key(scalar, payload.byteslice(32, 32), payload.byteslice(0, 32), index).unpack1('H*')
477
+ end
478
+ { 'mask' => shared_public_key(scalar).unpack1('H*'), 'keys' => keys }
479
+ end
480
+
481
+ def valid_xin_point?(encoded)
482
+ point = JOSE::JWA::Edwards25519Point.stdbase.decode(encoded) unless Sodium::CORE
483
+ return Sodium.ed25519_point?(encoded) if Sodium::CORE
484
+
485
+ point.encode == encoded && encoded != Sodium::IDENTITY &&
486
+ (point * JOSE::JWA::Edwards25519Point::L).encode == Sodium::IDENTITY
487
+ rescue ::ArgumentError, OpenSSL::BNError
488
+ false
489
+ end
490
+
393
491
  def multiply_keys(public_key:, private_key:)
394
- public_point = JOSE::JWA::Edwards25519Point.stdbase.decode public_key
395
- private_scalar = scalar_from_bytes private_key
396
- (public_point * private_scalar.x.to_i).encode
492
+ scalar = scalar_from_bytes(private_key).x.to_i
493
+
494
+ # libsodium multiplies a canonical, on-curve point that is not of low
495
+ # order, and checks the point itself.
496
+ product = Sodium.ed25519_point_mult(public_key, scalar)
497
+ return product if product
498
+
499
+ # Not a point libsodium multiplies: JOSE raises for an invalid one and
500
+ # multiplies a low-order point itself.
501
+ (JOSE::JWA::Edwards25519Point.stdbase.decode(public_key) * scalar).encode
397
502
  end
398
503
 
399
504
  def derive_ghost_public_key(private_key, view_key, spend_key, index)
@@ -401,10 +506,15 @@ module MixinBot
401
506
 
402
507
  x = hash_scalar mult_value, index
403
508
 
404
- p1 = JOSE::JWA::Edwards25519Point.stdbase.decode spend_key
405
- p2 = JOSE::JWA::Edwards25519Point.stdbase * scalar_from_bytes(x).x.to_i
509
+ p2 = ed25519_base_mult scalar_from_bytes(x).x.to_i
406
510
 
407
- (p1 + p2).encode
511
+ # +p2+ is a point this gem produced, so only +spend_key+ is checked.
512
+ # Not a point libsodium adds to: JOSE decodes and adds it as before.
513
+ Sodium.ed25519_add(spend_key, p2, other_is_valid: true) || begin
514
+ base = JOSE::JWA::Edwards25519Point.stdbase
515
+ point = base.decode(spend_key) + (base * scalar_from_bytes(x).x.to_i)
516
+ point.encode
517
+ end
408
518
  end
409
519
 
410
520
  def derive_ghost_private_key(public_key, view_key, spend_key, index)
@@ -415,7 +525,29 @@ module MixinBot
415
525
  x_scalar = scalar_from_bytes x
416
526
  y_scalar = scalar_from_bytes spend_key
417
527
 
418
- (x_scalar + y_scalar).to_bytes(32)
528
+ (x_scalar + y_scalar).to_bytes(256)
529
+ end
530
+
531
+ private
532
+
533
+ def pin_bytes(pin)
534
+ return MixinBot.utils.decode_key(pin) unless pin.is_a?(String)
535
+
536
+ if pin.length == 6
537
+ raise ArgumentError, 'legacy PIN must contain six digits' unless pin.match?(/\A[0-9]{6}\z/)
538
+
539
+ return pin
540
+ end
541
+
542
+ return pin if pin.encoding == Encoding::BINARY && [32, 40, 64].include?(pin.bytesize)
543
+ return [pin].pack('H*') if pin.bytesize.even? && pin.match?(/\A\h+\z/)
544
+
545
+ MixinBot.utils.decode_key(pin)
546
+ end
547
+
548
+ # scalar * B as a compressed point
549
+ def ed25519_base_mult(scalar)
550
+ Sodium.ed25519_base_mult(scalar) || (JOSE::JWA::Edwards25519Point.stdbase * scalar).encode
419
551
  end
420
552
  end
421
553
  end
@@ -0,0 +1,147 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MixinBot
4
+ module Utils
5
+ ##
6
+ # Forward-only reader over a binary String.
7
+ #
8
+ # This is the decode-side counterpart of building a payload with
9
+ # +String#<<+ on a binary buffer: the cursor walks the original string
10
+ # with +byteslice+/+getbyte+ instead of materialising it as an Array of
11
+ # Integers, so nothing is copied until it is read and truncated input
12
+ # fails at the field that is missing rather than decoding short values.
13
+ #
14
+ # The underlying string is never mutated. Every reader except {#peek}
15
+ # advances the cursor and raises {MixinBot::ArgumentError} when fewer
16
+ # bytes remain than the field needs.
17
+ #
18
+ # @example Read a big-endian, length-prefixed field
19
+ # cursor = MixinBot::Utils::Cursor.new("\x00\x04test".b)
20
+ # cursor.read_uint16 # => 4
21
+ # cursor.read(4) # => "test"
22
+ # cursor.empty? # => true
23
+ #
24
+ class Cursor
25
+ ##
26
+ # @return [Integer] byte offset of the next read
27
+ attr_reader :pos
28
+
29
+ ##
30
+ # @param bytes [String] the string to read from; it is never mutated. Any other
31
+ # encoding than ASCII-8BIT is copied once so that every slice read is binary.
32
+ # @param pos [Integer] byte offset to start at
33
+ def initialize(bytes, pos = 0)
34
+ @bytes = bytes.encoding == Encoding::ASCII_8BIT ? bytes : bytes.b
35
+ @pos = pos
36
+ end
37
+
38
+ ##
39
+ # Returns the next +count+ bytes and advances the cursor.
40
+ #
41
+ # @param count [Integer] number of bytes to read
42
+ # @return [String] an ASCII-8BIT String of +count+ bytes
43
+ # @raise [MixinBot::ArgumentError] if fewer than +count+ bytes remain
44
+ def read(count)
45
+ ensure_available!(count)
46
+ slice = @bytes.byteslice(@pos, count)
47
+ @pos += count
48
+ slice
49
+ end
50
+
51
+ ##
52
+ # Reads an unsigned 8-bit integer (one byte) in big-endian order.
53
+ #
54
+ # @return [Integer]
55
+ # @raise [MixinBot::ArgumentError] if the cursor is at the end
56
+ def read_uint8
57
+ ensure_available!(1)
58
+ value = @bytes.getbyte(@pos)
59
+ @pos += 1
60
+ value
61
+ end
62
+
63
+ ##
64
+ # Reads an unsigned 16-bit integer in big-endian order ({MixinBot::Utils::Encoder#pack_uint16} layout).
65
+ #
66
+ # @return [Integer]
67
+ # @raise [MixinBot::ArgumentError] if fewer than 2 bytes remain
68
+ def read_uint16
69
+ read_packed(2, 'n')
70
+ end
71
+
72
+ ##
73
+ # Reads an unsigned 32-bit integer in big-endian order ({MixinBot::Utils::Encoder#pack_uint32} layout).
74
+ #
75
+ # @return [Integer]
76
+ # @raise [MixinBot::ArgumentError] if fewer than 4 bytes remain
77
+ def read_uint32
78
+ read_packed(4, 'N')
79
+ end
80
+
81
+ ##
82
+ # Reads an unsigned 64-bit integer in big-endian order ({MixinBot::Utils::Encoder#pack_uint64} layout).
83
+ #
84
+ # @return [Integer]
85
+ # @raise [MixinBot::ArgumentError] if fewer than 8 bytes remain
86
+ def read_uint64
87
+ read_packed(8, 'Q>')
88
+ end
89
+
90
+ ##
91
+ # Reads a big-endian integer of +count+ bytes ({MixinBot::Utils::Encoder#pack_int} layout).
92
+ # Zero bytes read as +0+.
93
+ #
94
+ # @param count [Integer] number of bytes to read
95
+ # @return [Integer]
96
+ # @raise [MixinBot::ArgumentError] if fewer than +count+ bytes remain
97
+ def read_int(count)
98
+ ensure_available!(count)
99
+ value = 0
100
+ offset = @pos
101
+ last = offset + count
102
+ while offset < last
103
+ value = (value << 8) | @bytes.getbyte(offset)
104
+ offset += 1
105
+ end
106
+ @pos = last
107
+ value
108
+ end
109
+
110
+ ##
111
+ # Returns up to +count+ bytes without advancing the cursor.
112
+ #
113
+ # @param count [Integer] number of bytes to look at
114
+ # @return [String] an ASCII-8BIT String, shorter than +count+ bytes near the end of the input
115
+ def peek(count)
116
+ @bytes.byteslice(@pos, count)
117
+ end
118
+
119
+ ##
120
+ # @return [Integer] number of bytes left to read
121
+ def size
122
+ @bytes.bytesize - @pos
123
+ end
124
+
125
+ ##
126
+ # @return [Boolean] true when every byte has been read
127
+ def empty?
128
+ size.zero?
129
+ end
130
+
131
+ private
132
+
133
+ def read_packed(count, format)
134
+ ensure_available!(count)
135
+ value = @bytes.unpack1(format, offset: @pos)
136
+ @pos += count
137
+ value
138
+ end
139
+
140
+ def ensure_available!(count)
141
+ return if !count.negative? && @pos + count <= @bytes.bytesize
142
+
143
+ raise ArgumentError, "not enough bytes: need #{count} at #{pos}, have #{size}"
144
+ end
145
+ end
146
+ end
147
+ end
@@ -3,17 +3,34 @@
3
3
  module MixinBot
4
4
  module Utils
5
5
  module Decoder
6
+ RSA_HEADER = '-----BEGIN RSA PRIVATE KEY-----'
7
+
6
8
  def decode_key(key)
7
9
  return if key.blank?
8
10
 
9
- if key.match?(/\A\h{64,}\z/i)
10
- [key].pack('H*')
11
- elsif key.match?(/^-----BEGIN RSA PRIVATE KEY-----/)
12
- key.gsub('\\r\\n', "\n").gsub("\r\n", "\n")
13
- elsif key.match?(/\d{6}/) || (key.size % 32).zero?
11
+ # Sniff text formats against whitespace-free copies so keys copied out
12
+ # of hand-crafted keystores (stray spaces, wrapped lines, trailing
13
+ # newlines) still decode; the raw-binary pass-through must keep
14
+ # checking the original string, since removing whitespace could
15
+ # change its size.
16
+ stripped = key.strip
17
+ compact = key.gsub(/\s+/, '')
18
+
19
+ if compact.match?(/\A\h{64,}\z/i)
20
+ [compact].pack('H*')
21
+ elsif stripped.start_with?(RSA_HEADER)
22
+ stripped.gsub('\\r\\n', "\n").gsub("\r\n", "\n")
23
+ elsif stripped.include?(RSA_HEADER)
24
+ # ::ArgumentError, matching the out-of-alphabet raise from
25
+ # Base64.urlsafe_decode64 below, so callers can rescue one class
26
+ # for every malformed text key.
27
+ raise ::ArgumentError, "text before the #{RSA_HEADER} header"
28
+ elsif compact.match?(/\A\d{6}\z/)
29
+ compact
30
+ elsif (key.size % 32).zero?
14
31
  key
15
32
  else
16
- Base64.urlsafe_decode64 key
33
+ Base64.urlsafe_decode64 compact
17
34
  end
18
35
  end
19
36
 
@@ -21,30 +38,118 @@ module MixinBot
21
38
  MixinBot::Transaction.new(hex:).decode.to_h
22
39
  end
23
40
 
41
+ ##
42
+ # Big-endian unsigned 16-bit integer from an Array of bytes.
43
+ #
44
+ # @param bytes [Array<Integer>] most significant byte first
45
+ # @return [Integer, nil] nil when +bytes+ is shorter than 2 elements
46
+ # @raise [MixinBot::ArgumentError] if +bytes+ is not an Array
47
+ # @see #unpack_uint16
48
+ #
24
49
  def decode_uint16(bytes)
25
50
  raise ArgumentError, "only support bytes #{bytes}" unless bytes.is_a?(Array)
26
51
 
27
52
  bytes.reverse.pack('C*').unpack1('S*')
28
53
  end
29
54
 
55
+ ##
56
+ # Big-endian unsigned 32-bit integer from an Array of bytes.
57
+ #
58
+ # @param bytes [Array<Integer>] most significant byte first
59
+ # @return [Integer, nil] nil when +bytes+ is shorter than 4 elements
60
+ # @raise [MixinBot::ArgumentError] if +bytes+ is not an Array
61
+ # @see #unpack_uint32
62
+ #
30
63
  def decode_uint32(bytes)
31
64
  raise ArgumentError, "only support bytes #{bytes}" unless bytes.is_a?(Array)
32
65
 
33
66
  bytes.reverse.pack('C*').unpack1('L*')
34
67
  end
35
68
 
69
+ ##
70
+ # Big-endian unsigned 64-bit integer from an Array of bytes.
71
+ #
72
+ # @param bytes [Array<Integer>] most significant byte first
73
+ # @return [Integer, nil] nil when +bytes+ is shorter than 8 elements
74
+ # @raise [MixinBot::ArgumentError] if +bytes+ is not an Array
75
+ # @see #unpack_uint64
76
+ #
36
77
  def decode_uint64(bytes)
37
78
  raise ArgumentError, "only support bytes #{bytes}" unless bytes.is_a?(Array)
38
79
 
39
80
  bytes.reverse.pack('C*').unpack1('Q*')
40
81
  end
41
82
 
83
+ ##
84
+ # Big-endian integer value of an Array of bytes; an empty Array reads as +0+.
85
+ #
86
+ # @param bytes [Array<Integer>] most significant byte first
87
+ # @return [Integer]
88
+ # @raise [MixinBot::ArgumentError] if +bytes+ is not an Array
89
+ # @see #unpack_int
90
+ #
42
91
  def decode_int(bytes)
43
92
  raise ArgumentError, "only support bytes #{bytes}" unless bytes.is_a?(Array)
44
93
 
45
94
  bytes.reduce(0) { |sum, byte| (sum << 8) + byte }
46
95
  end
47
96
 
97
+ ##
98
+ # Reads a big-endian unsigned 16-bit integer from the first 2 bytes of a binary String.
99
+ #
100
+ # @param bytes [String]
101
+ # @return [Integer, nil] nil when +bytes+ is shorter than 2 bytes
102
+ # @raise [MixinBot::ArgumentError] if +bytes+ is not a String
103
+ # @see #decode_uint16
104
+ #
105
+ def unpack_uint16(bytes)
106
+ raise ArgumentError, "only support binary #{bytes}" unless bytes.is_a?(String)
107
+
108
+ bytes.unpack1('n')
109
+ end
110
+
111
+ ##
112
+ # Reads a big-endian unsigned 32-bit integer from the first 4 bytes of a binary String.
113
+ #
114
+ # @param bytes [String]
115
+ # @return [Integer, nil] nil when +bytes+ is shorter than 4 bytes
116
+ # @raise [MixinBot::ArgumentError] if +bytes+ is not a String
117
+ # @see #decode_uint32
118
+ #
119
+ def unpack_uint32(bytes)
120
+ raise ArgumentError, "only support binary #{bytes}" unless bytes.is_a?(String)
121
+
122
+ bytes.unpack1('N')
123
+ end
124
+
125
+ ##
126
+ # Reads a big-endian unsigned 64-bit integer from the first 8 bytes of a binary String.
127
+ #
128
+ # @param bytes [String]
129
+ # @return [Integer, nil] nil when +bytes+ is shorter than 8 bytes
130
+ # @raise [MixinBot::ArgumentError] if +bytes+ is not a String
131
+ # @see #decode_uint64
132
+ #
133
+ def unpack_uint64(bytes)
134
+ raise ArgumentError, "only support binary #{bytes}" unless bytes.is_a?(String)
135
+
136
+ bytes.unpack1('Q>')
137
+ end
138
+
139
+ ##
140
+ # Reads the big-endian integer value of every byte in a binary String; an empty String reads as +0+.
141
+ #
142
+ # @param bytes [String]
143
+ # @return [Integer]
144
+ # @raise [MixinBot::ArgumentError] if +bytes+ is not a String
145
+ # @see #decode_int
146
+ #
147
+ def unpack_int(bytes)
148
+ raise ArgumentError, "only support binary #{bytes}" unless bytes.is_a?(String)
149
+
150
+ MixinBot::Utils::Cursor.new(bytes).read_int(bytes.bytesize)
151
+ end
152
+
48
153
  def hex_to_uuid(hex)
49
154
  MixinBot::UUID.new(hex:).unpacked
50
155
  end