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
@@ -19,22 +19,40 @@ module MixinBot
19
19
  MixinBot::Transaction.new(**txn).encode.hex
20
20
  end
21
21
 
22
+ ##
23
+ # Big-endian unsigned 16-bit integer as an Array of bytes.
24
+ #
25
+ # @param int [Integer] values outside 0..65_535 keep only their low 16 bits, as +Array#pack+ does
26
+ # @return [Array<Integer>] 2 bytes, most significant first
27
+ # @raise [MixinBot::ArgumentError] if +int+ is not an Integer
28
+ # @see #pack_uint16
29
+ #
22
30
  def encode_uint16(int)
23
- raise ArgumentError, "only support int #{int}" unless int.is_a?(Integer)
24
-
25
- [int].pack('S*').bytes.reverse
31
+ pack_uint16(int).bytes
26
32
  end
27
33
 
34
+ ##
35
+ # Big-endian unsigned 32-bit integer as an Array of bytes.
36
+ #
37
+ # @param int [Integer] values outside 0..4_294_967_295 keep only their low 32 bits, as +Array#pack+ does
38
+ # @return [Array<Integer>] 4 bytes, most significant first
39
+ # @raise [MixinBot::ArgumentError] if +int+ is not an Integer
40
+ # @see #pack_uint32
41
+ #
28
42
  def encode_uint32(int)
29
- raise ArgumentError, "only support int #{int}" unless int.is_a?(Integer)
30
-
31
- [int].pack('L*').bytes.reverse
43
+ pack_uint32(int).bytes
32
44
  end
33
45
 
46
+ ##
47
+ # Big-endian unsigned 64-bit integer as an Array of bytes.
48
+ #
49
+ # @param int [Integer] values outside 0..2^64-1 keep only their low 64 bits, as +Array#pack+ does
50
+ # @return [Array<Integer>] 8 bytes, most significant first
51
+ # @raise [MixinBot::ArgumentError] if +int+ is not an Integer
52
+ # @see #pack_uint64
53
+ #
34
54
  def encode_uint64(int)
35
- raise ArgumentError, "only support int #{int}" unless int.is_a?(Integer)
36
-
37
- [int].pack('Q*').bytes.reverse
55
+ pack_uint64(int).bytes
38
56
  end
39
57
 
40
58
  ##
@@ -50,22 +68,73 @@ module MixinBot
50
68
  encode_int(int)
51
69
  end
52
70
 
71
+ ##
72
+ # Minimal big-endian integer as an Array of bytes: no leading zero bytes, zero as +[0]+.
73
+ #
74
+ # @param int [Integer]
75
+ # @return [Array<Integer>] most significant byte first
76
+ # @raise [MixinBot::ArgumentError] if +int+ is not a non-negative Integer
77
+ # @see #pack_int
78
+ #
53
79
  def encode_int(int)
54
- raise ArgumentError, 'not integer' unless int.is_a?(Integer)
80
+ pack_int(int).bytes
81
+ end
55
82
 
56
- bytes = []
57
- if int.zero?
58
- bytes.push(0)
59
- else
60
- loop do
61
- break if int.zero?
83
+ ##
84
+ # Packs an unsigned 16-bit integer in big-endian order: the binary String form of {#encode_uint16}.
85
+ #
86
+ # @param int [Integer] values outside 0..65_535 keep only their low 16 bits, as +Array#pack+ does
87
+ # @return [String] 2-byte binary String
88
+ # @raise [MixinBot::ArgumentError] if +int+ is not an Integer
89
+ #
90
+ def pack_uint16(int)
91
+ raise ArgumentError, "only support int #{int}" unless int.is_a?(Integer)
62
92
 
63
- bytes.push int & 255
64
- int = (int / (2**8)) | 0
65
- end
66
- end
93
+ [int].pack('n')
94
+ end
95
+
96
+ ##
97
+ # Packs an unsigned 32-bit integer in big-endian order: the binary String form of {#encode_uint32}.
98
+ #
99
+ # @param int [Integer] values outside 0..4_294_967_295 keep only their low 32 bits, as +Array#pack+ does
100
+ # @return [String] 4-byte binary String
101
+ # @raise [MixinBot::ArgumentError] if +int+ is not an Integer
102
+ #
103
+ def pack_uint32(int)
104
+ raise ArgumentError, "only support int #{int}" unless int.is_a?(Integer)
105
+
106
+ [int].pack('N')
107
+ end
108
+
109
+ ##
110
+ # Packs an unsigned 64-bit integer in big-endian order: the binary String form of {#encode_uint64}.
111
+ #
112
+ # @param int [Integer] values outside 0..2^64-1 keep only their low 64 bits, as +Array#pack+ does
113
+ # @return [String] 8-byte binary String
114
+ # @raise [MixinBot::ArgumentError] if +int+ is not an Integer
115
+ #
116
+ def pack_uint64(int)
117
+ raise ArgumentError, "only support int #{int}" unless int.is_a?(Integer)
118
+
119
+ [int].pack('Q>')
120
+ end
121
+
122
+ ##
123
+ # Packs an integer in minimal big-endian form (see {#encode_int}): no leading zero bytes, zero as a single 0x00.
124
+ #
125
+ # @param int [Integer]
126
+ # @return [String] 1+ byte binary String
127
+ # @raise [MixinBot::ArgumentError] if +int+ is not a non-negative Integer
128
+ #
129
+ def pack_int(int)
130
+ raise ArgumentError, 'not integer' unless int.is_a?(Integer)
131
+ raise ArgumentError, "not non-negative integer #{int}" if int.negative?
132
+
133
+ return "\x00".b if int.zero?
67
134
 
68
- bytes.reverse
135
+ hex = int.to_s(16)
136
+ hex = "0#{hex}" if hex.length.odd?
137
+ [hex].pack('H*')
69
138
  end
70
139
 
71
140
  def nft_memo(collection, token, extra)
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MixinBot
4
+ module Utils
5
+ ##
6
+ # Initialization options keyed by Symbol or String, as
7
+ # +with_indifferent_access+ accepts them, without its cost for the
8
+ # Symbol-keyed calls that are the common case.
9
+ #
10
+ # @api private
11
+ module Options
12
+ module_function
13
+
14
+ ##
15
+ # Returns +args+ with every key a Symbol, or +args+ itself when they
16
+ # already are. A key that is neither is named by what +to_s+ gives.
17
+ #
18
+ # @param args [Hash] options
19
+ # @return [Hash]
20
+ #
21
+ def symbolize(args)
22
+ args.keys.all?(Symbol) ? args : args.transform_keys(&:to_sym)
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,169 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MixinBot
4
+ module Utils
5
+ ##
6
+ # The libsodium calls behind the SDK's curve arithmetic, bound through
7
+ # RbNaCl's FFI setup (rbnacl is a runtime dependency and loads libsodium
8
+ # when the gem is required).
9
+ #
10
+ # Before this module the work went to JOSE's pure-Ruby curve
11
+ # implementations: about 6 ms and 44 000 objects per scalar
12
+ # multiplication, paid once per encrypted message, once more per session
13
+ # of that message, per Safe signature and per ghost key.
14
+ #
15
+ # Every function returns what the JOSE call returns for the inputs
16
+ # libsodium accepts, and nil for anything else, so that the caller can
17
+ # fall back to the JOSE code, which then computes or raises exactly as it
18
+ # always did. What libsodium refuses: low-order and non-canonical points,
19
+ # a shared secret of all zeros, and a product that is the identity point.
20
+ #
21
+ # Only public libsodium functions are bound. The scalar multiplications use
22
+ # the *noclamp* variants (libsodium >= 1.0.18), which take the scalar as it
23
+ # is — every scalar the gem passes is reduced modulo L, so there is nothing
24
+ # to clamp — and which validate their point argument themselves, so a
25
+ # caller does not have to pay for a separate check. What they refuse, they
26
+ # refuse for the same reason `crypto_core_ed25519_is_valid_point` does:
27
+ # a point that is not canonical, not on the curve, of low order, or off the
28
+ # main subgroup.
29
+ #
30
+ # The Edwards point functions need libsodium >= 1.0.18; where they are
31
+ # missing {CORE} is false and the callers' JOSE fallbacks stay in use.
32
+ #
33
+ # @api private
34
+ module Sodium
35
+ extend RbNaCl::Sodium
36
+
37
+ POINT_BYTES = 32
38
+ ZERO_POINT = ("\0" * POINT_BYTES).b.freeze
39
+ BASE_POINT = ['5866666666666666666666666666666666666666666666666666666666666666'].pack('H*').freeze
40
+ WORD_MASK = (1 << 64) - 1
41
+ # the group order; a scalar that is a multiple of it multiplies to the identity
42
+ L = JOSE::JWA::Edwards25519Point::L
43
+ # the noclamp multiplications mask bit 255; the gem's scalars are below 2**253 anyway
44
+ TWO_254 = 1 << 254
45
+ # the identity point (0, 1), as JOSE encodes a zero product
46
+ IDENTITY = ("\x01".b + ("\0".b * (POINT_BYTES - 1))).freeze
47
+
48
+ sodium_function :scalarmult_curve25519, :crypto_scalarmult_curve25519, %i[pointer pointer pointer]
49
+ sodium_function :pk_to_curve25519, :crypto_sign_ed25519_pk_to_curve25519, %i[pointer pointer]
50
+ sodium_function :seed_keypair, :crypto_sign_ed25519_seed_keypair, %i[pointer pointer pointer]
51
+ sodium_function :sign_detached, :crypto_sign_detached, %i[pointer pointer pointer ulong_long pointer]
52
+
53
+ CORE =
54
+ begin
55
+ sodium_function :noclamp_base, :crypto_scalarmult_ed25519_base_noclamp, %i[pointer pointer]
56
+ sodium_function :noclamp_point, :crypto_scalarmult_ed25519_noclamp, %i[pointer pointer pointer]
57
+ sodium_function :sodium_add, :crypto_core_ed25519_add, %i[pointer pointer pointer]
58
+ sodium_function_with_return_code :is_valid_point, :crypto_core_ed25519_is_valid_point, %i[pointer]
59
+ true
60
+ rescue FFI::NotFoundError
61
+ false
62
+ end
63
+
64
+ module_function
65
+
66
+ # [public_key, signing_key] for a 32-byte seed, the signing key being seed + public_key.
67
+ # nil for a seed of any other size.
68
+ def ed25519_keypair(seed)
69
+ return unless bytes32?(seed)
70
+
71
+ public_key = RbNaCl::Util.zeros(POINT_BYTES)
72
+ signing_key = RbNaCl::Util.zeros(POINT_BYTES * 2)
73
+ seed_keypair(public_key, signing_key, seed) && [public_key, signing_key]
74
+ end
75
+
76
+ # 64-byte Ed25519 signature. nil unless the message is a String and the signing key 64 bytes.
77
+ def ed25519_sign(message, signing_key)
78
+ return unless message.is_a?(String) && signing_key.is_a?(String) && signing_key.bytesize == POINT_BYTES * 2
79
+
80
+ signature = RbNaCl::Util.zeros(POINT_BYTES * 2)
81
+ sign_detached(signature, nil, message, message.bytesize, signing_key) && signature
82
+ end
83
+
84
+ # Curve25519 public key for an Ed25519 public key. nil unless it is a point libsodium accepts.
85
+ def ed25519_pk_to_curve25519(public_key)
86
+ return unless bytes32?(public_key)
87
+
88
+ curve_public_key = RbNaCl::Util.zeros(POINT_BYTES)
89
+ pk_to_curve25519(curve_public_key, public_key) && curve_public_key
90
+ end
91
+
92
+ # X25519 shared secret for a 32-byte scalar and a canonical 32-byte u.
93
+ # nil otherwise: JOSE reduces a u of 2**255 or more modulo p where
94
+ # libsodium masks its high bit, and raises instead of returning zeros.
95
+ def x25519(scalar, point)
96
+ return unless bytes32?(scalar) && bytes32?(point) && point.getbyte(POINT_BYTES - 1) < 0x80
97
+
98
+ shared = RbNaCl::Util.zeros(POINT_BYTES)
99
+ return unless scalarmult_curve25519(shared, scalar, point) && shared != ZERO_POINT
100
+
101
+ shared
102
+ end
103
+
104
+ # scalar * B for an Integer 0 <= scalar < 2**254, as a compressed point. nil for anything else, and without {CORE}.
105
+ def ed25519_base_mult(scalar)
106
+ return unless scalar?(scalar)
107
+
108
+ product = RbNaCl::Util.zeros(POINT_BYTES)
109
+ return product if noclamp_base(product, little_endian(scalar))
110
+
111
+ # libsodium refuses a product that is the identity, which is what a
112
+ # scalar that is a multiple of L multiplies to; JOSE encodes it as (0, 1).
113
+ (scalar % L).zero? ? IDENTITY : nil
114
+ end
115
+
116
+ # Whether libsodium multiplies +point+: a canonical, on-curve encoding that is not of low order.
117
+ def ed25519_point?(point)
118
+ CORE && bytes32?(point) && is_valid_point(point) == 1
119
+ end
120
+
121
+ # scalar * P for a point {#ed25519_point?} accepts and an Integer 0 <= scalar < 2**254. nil otherwise.
122
+ def ed25519_point_mult(point, scalar)
123
+ return unless scalar?(scalar) && bytes32?(point)
124
+
125
+ product = RbNaCl::Util.zeros(POINT_BYTES)
126
+ return product if noclamp_point(product, little_endian(scalar), point)
127
+
128
+ # Refused: either a point libsodium does not multiply, or the identity
129
+ # product of a scalar that is a multiple of L. Only the latter is ours
130
+ # to answer, and only for a point it would have multiplied.
131
+ (scalar % L).zero? && ed25519_point?(point) ? IDENTITY : nil
132
+ end
133
+
134
+ # P + Q for two points {#ed25519_point?} accepts. nil otherwise.
135
+ #
136
+ # +other_is_valid+ skips the check of +other+, for a point this module
137
+ # produced itself: {#ed25519_base_mult} returns a point of the
138
+ # prime-order subgroup, or the identity, and libsodium adds both.
139
+ def ed25519_add(point, other, other_is_valid: false)
140
+ return unless ed25519_point?(point) && (other_is_valid || ed25519_point?(other))
141
+
142
+ sum = RbNaCl::Util.zeros(POINT_BYTES)
143
+ sodium_add(sum, point, other) && sum
144
+ end
145
+
146
+ # An Integer below 2**255 as 32 little-endian bytes.
147
+ def little_endian(int)
148
+ [int & WORD_MASK, (int >> 64) & WORD_MASK, (int >> 128) & WORD_MASK, (int >> 192) & WORD_MASK].pack('Q<4')
149
+ end
150
+
151
+ def bytes32?(bytes)
152
+ bytes.is_a?(String) && bytes.bytesize == POINT_BYTES
153
+ end
154
+
155
+ # The Edwards point functions are there, and +scalar+ is an Integer they can take
156
+ def scalar?(scalar)
157
+ CORE && scalar.is_a?(Integer) && scalar >= 0 && scalar < TWO_254
158
+ end
159
+
160
+ if CORE
161
+ # the binding multiplies the base point by one as it should
162
+ base = RbNaCl::Util.zeros(POINT_BYTES)
163
+ raise 'libsodium produced an unexpected Ed25519 base point' unless noclamp_base(base, little_endian(1)) && base == BASE_POINT
164
+ end
165
+ end
166
+
167
+ private_constant :Sodium
168
+ end
169
+ end
@@ -2,9 +2,13 @@
2
2
 
3
3
  require_relative 'utils/address'
4
4
  require_relative 'utils/amount'
5
+ require_relative 'utils/base58'
5
6
  require_relative 'utils/crypto'
7
+ require_relative 'utils/cursor'
6
8
  require_relative 'utils/decoder'
7
9
  require_relative 'utils/encoder'
10
+ require_relative 'utils/options'
11
+ require_relative 'utils/sodium'
8
12
 
9
13
  module MixinBot
10
14
  ##
@@ -19,23 +23,30 @@ module MixinBot
19
23
  # - Ghost key derivation
20
24
  # - Address validation
21
25
  #
26
+ # [MixinBot::Utils::Base58] Base58 of the bitcoin alphabet, as Mixin addresses use
27
+ # - Leading zero bytes become leading +1+s, and back
28
+ #
22
29
  # [MixinBot::Utils::Crypto] Cryptographic operations
23
30
  # - JWT token generation
31
+ # - Ed25519 / Curve25519 primitives (through libsodium)
24
32
  # - Key generation and management
25
33
  # - Transaction signing
26
34
  # - PIN encryption
27
35
  # - UUID generation
28
36
  #
29
37
  # [MixinBot::Utils::Decoder] Data decoding utilities
30
- # - Integer decoding
38
+ # - Integer decoding (Array of bytes, or binary String via +unpack_*+)
31
39
  # - Transaction decoding
32
40
  # - Key decoding
33
41
  #
34
42
  # [MixinBot::Utils::Encoder] Data encoding utilities
35
- # - Integer encoding
43
+ # - Integer encoding (Array of bytes, or binary String via +pack_*+)
36
44
  # - Transaction encoding
37
45
  # - Binary packing
38
46
  #
47
+ # [MixinBot::Utils::Cursor] Forward-only reader over a binary String
48
+ # - Bounds-checked reads for decode paths
49
+ #
39
50
  # == Usage
40
51
  #
41
52
  # Access utilities through the MixinBot.utils shortcut:
@@ -52,6 +63,10 @@ module MixinBot
52
63
  # # Decode a key
53
64
  # key = MixinBot.utils.decode_key(encoded_key)
54
65
  #
66
+ # # Build and read binary payloads (NFO memos, invoices, raw transactions)
67
+ # payload = MixinBot.utils.pack_uint16(4) + 'test'.b
68
+ # MixinBot::Utils::Cursor.new(payload).read_uint16 # => 4
69
+ #
55
70
  module Utils
56
71
  extend MixinBot::Utils::Address
57
72
  extend MixinBot::Utils::Amount
@@ -62,13 +62,13 @@ module MixinBot
62
62
  # uuid = MixinBot::UUID.new(raw: binary_string)
63
63
  #
64
64
  def initialize(**args)
65
- args = args.with_indifferent_access
65
+ args = MixinBot::Utils::Options.symbolize args
66
66
 
67
67
  @hex = args[:hex]
68
68
  @raw = args[:raw]
69
69
 
70
70
  raise MixinBot::InvalidUuidFormatError if raw.present? && raw.size != 16
71
- raise MixinBot::InvalidUuidFormatError if hex.present? && hex.gsub('-', '').size != 32
71
+ raise MixinBot::InvalidUuidFormatError if hex.present? && hex.delete('-').size != 32
72
72
  end
73
73
 
74
74
  ##
@@ -85,7 +85,7 @@ module MixinBot
85
85
  if raw.present?
86
86
  raw
87
87
  elsif hex.present?
88
- [hex.gsub('-', '')].pack('H*')
88
+ [hex.delete('-')].pack('H*')
89
89
  end
90
90
  end
91
91
 
@@ -102,19 +102,12 @@ module MixinBot
102
102
  def unpacked
103
103
  _hex =
104
104
  if hex.present?
105
- hex.gsub('-', '')
105
+ hex.delete('-')
106
106
  elsif raw.present?
107
- _hex = raw.unpack1('H*')
107
+ raw.unpack1('H*')
108
108
  end
109
109
 
110
- format(
111
- '%<first>s-%<second>s-%<third>s-%<forth>s-%<fifth>s',
112
- first: _hex[0..7],
113
- second: _hex[8..11],
114
- third: _hex[12..15],
115
- forth: _hex[16..19],
116
- fifth: _hex[20..]
117
- )
110
+ "#{_hex[0, 8]}-#{_hex[8, 4]}-#{_hex[12, 4]}-#{_hex[16, 4]}-#{_hex[20..]}"
118
111
  end
119
112
  end
120
113
  end
@@ -11,5 +11,5 @@ module MixinBot
11
11
  #
12
12
  # @see https://semver.org/
13
13
  #
14
- VERSION = '3.0.3'
14
+ VERSION = '3.1.0'
15
15
  end
data/lib/mixin_bot.rb CHANGED
@@ -3,7 +3,6 @@
3
3
  # third-party dependencies
4
4
  require 'English'
5
5
  require 'active_support/all'
6
- require 'base58'
7
6
  require 'base64'
8
7
  require 'bigdecimal'
9
8
  require 'bigdecimal/util'
@@ -14,7 +13,6 @@ require 'faraday'
14
13
  require 'faraday/multipart'
15
14
  require 'faraday/retry'
16
15
  require 'jose'
17
- require 'msgpack'
18
16
  require 'open3'
19
17
  require 'openssl'
20
18
  require 'rbnacl'
@@ -25,6 +23,7 @@ require_relative 'mixin_bot/address'
25
23
  require_relative 'mixin_bot/models'
26
24
  require_relative 'mixin_bot/session_store'
27
25
  require_relative 'mixin_bot/cache_store_adapter'
26
+ require_relative 'mixin_bot/transaction'
28
27
  require_relative 'mixin_bot/api'
29
28
  require_relative 'mixin_bot/blaze/reactor'
30
29
  require_relative 'mixin_bot/bot_auth'
@@ -37,7 +36,6 @@ require_relative 'mixin_bot/url_scheme'
37
36
  require_relative 'mixin_bot/utils'
38
37
  require_relative 'mixin_bot/nfo'
39
38
  require_relative 'mixin_bot/uuid'
40
- require_relative 'mixin_bot/transaction'
41
39
  require_relative 'mixin_bot/version'
42
40
  require_relative 'mvm'
43
41
 
data/lib/mvm/client.rb CHANGED
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative '../mixin_bot/proxy'
4
+
3
5
  module MVM
4
6
  ##
5
7
  # HTTP client for MVM services.
@@ -42,18 +44,31 @@ module MVM
42
44
  # - Debug logging
43
45
  #
44
46
  # @param host [String] the service hostname
47
+ # @param proxy [String, URI, Hash, MixinBot::Proxy, nil] optional HTTP/HTTPS proxy override
45
48
  #
46
49
  # @example
47
50
  # client = MVM::Client.new('bridge.mvm.dev')
48
51
  #
49
- def initialize(host)
52
+ def initialize(host, proxy: nil)
50
53
  @host = host
51
- @conn = Faraday.new(url: "#{SERVER_SCHEME}://#{host}") do |f|
52
- f.request :json
53
- f.request :retry
54
- f.response :raise_error
55
- f.response :logger
56
- f.response :json
54
+ @proxy = proxy
55
+ @conn_mutex = Mutex.new
56
+ rebuild_connection!
57
+ end
58
+
59
+ ##
60
+ # Returns the Faraday connection, rebuilding it when effective proxy changes.
61
+ #
62
+ # @return [Faraday::Connection]
63
+ #
64
+ def conn
65
+ effective = effective_proxy_config
66
+ return @conn if @conn && @conn_proxy == effective
67
+
68
+ @conn_mutex.synchronize do
69
+ effective = effective_proxy_config
70
+ rebuild_connection!(effective) if @conn.nil? || @conn_proxy != effective
71
+ @conn
57
72
  end
58
73
  end
59
74
 
@@ -68,7 +83,7 @@ module MVM
68
83
  # response = client.get('/info')
69
84
  #
70
85
  def get(path, **)
71
- @conn.get(path, **).body
86
+ conn.get(path, **).body
72
87
  end
73
88
 
74
89
  ##
@@ -82,7 +97,27 @@ module MVM
82
97
  # response = client.post('/users', public_key: '0x...')
83
98
  #
84
99
  def post(path, **)
85
- @conn.post(path, **).body
100
+ conn.post(path, **).body
101
+ end
102
+
103
+ private
104
+
105
+ def effective_proxy_config
106
+ @proxy.nil? ? MixinBot.config.proxy_config : MixinBot::Proxy.parse(@proxy)
107
+ end
108
+
109
+ def rebuild_connection!(proxy_config = effective_proxy_config)
110
+ conn_opts = { url: "#{SERVER_SCHEME}://#{host}" }
111
+ conn_opts[:proxy] = proxy_config.faraday_options if proxy_config
112
+
113
+ @conn = Faraday.new(**conn_opts) do |f|
114
+ f.request :json
115
+ f.request :retry
116
+ f.response :raise_error
117
+ f.response :logger
118
+ f.response :json
119
+ end
120
+ @conn_proxy = proxy_config
86
121
  end
87
122
  end
88
123
  end
data/lib/mvm/registry.rb CHANGED
@@ -25,17 +25,7 @@ module MVM
25
25
  end
26
26
 
27
27
  def users_from_contract(contract)
28
- bytes = @rpc.call(@registry, 'users', contract).bytes
29
- members = []
30
- length = bytes.shift(2).reverse.pack('C*').unpack1('S*')
31
- length.times do
32
- members << MixinBot::UUID.new(raw: bytes.shift(16).pack('C*')).unpacked
33
- end
34
- threshold = bytes.shift(2).reverse.pack('C*').unpack1('S*')
35
- {
36
- members:,
37
- threshold:
38
- }.with_indifferent_access
28
+ self.class.decode_users(@rpc.call(@registry, 'users', contract))
39
29
  end
40
30
 
41
31
  def user_from_contract(contract)
@@ -52,13 +42,51 @@ module MVM
52
42
  end
53
43
 
54
44
  def contract_from_multisig(user_ids, threshold)
55
- bytes = []
56
- bytes.concat(MixinBot.utils.encode_uint16(user_ids.length))
57
- bytes.concat([user_ids.sort.join.gsub('-', '')].pack('H*').bytes)
58
- bytes.concat(MixinBot.utils.encode_uint16(threshold))
45
+ @rpc.call @registry, 'contracts', self.class.multisig_id(user_ids, threshold)
46
+ end
47
+
48
+ class << self
49
+ ##
50
+ # Decodes what the Registry's +users+ view returns for a contract: the
51
+ # number of members and the threshold as big-endian uint16s, around the
52
+ # 16-byte member ids.
53
+ #
54
+ # @param payload [String] the ABI-decoded +bytes+ value
55
+ # @return [ActiveSupport::HashWithIndifferentAccess] +members+ as unpacked
56
+ # user ids, and +threshold+
57
+ # @raise [MixinBot::ArgumentError] if the payload ends before every
58
+ # member, or the threshold after them, is read
59
+ #
60
+ def decode_users(payload)
61
+ cursor = MixinBot::Utils::Cursor.new(payload)
62
+ members = Array.new(cursor.read_uint16) { MixinBot::UUID.new(raw: cursor.read(16)).unpacked }
63
+
64
+ { members:, threshold: cursor.read_uint16 }.with_indifferent_access
65
+ end
66
+
67
+ ##
68
+ # The Registry id of a multisig: keccak256 over the member count, the
69
+ # sorted 16-byte member ids and the threshold, the integers as
70
+ # big-endian uint16s.
71
+ #
72
+ # @param user_ids [Array<String>] member user ids
73
+ # @param threshold [Integer] the multisig threshold
74
+ # @return [Integer] the id as it is passed to the Registry's +contracts+ view
75
+ # @raise [MixinBot::InvalidUuidFormatError] for a user id that is not 32 hex digits
76
+ # @raise [ArgumentError] for a blank user id
77
+ #
78
+ def multisig_id(user_ids, threshold)
79
+ bytes = MixinBot.utils.pack_uint16(user_ids.length)
80
+ user_ids.sort.each do |user_id|
81
+ packed = MixinBot::UUID.new(hex: user_id).packed
82
+ raise ArgumentError, 'invalid user_id: blank' unless packed
59
83
 
60
- hash = Eth::Util.bin_to_prefixed_hex(Eth::Util.keccak256(bytes.pack('C*')))
61
- @rpc.call @registry, 'contracts', hash.to_i(16)
84
+ bytes << packed
85
+ end
86
+ bytes << MixinBot.utils.pack_uint16(threshold)
87
+
88
+ Eth::Util.keccak256(bytes).unpack1('H*').to_i(16)
89
+ end
62
90
  end
63
91
  end
64
92
  end
data/llms.txt CHANGED
@@ -1,6 +1,6 @@
1
1
  # MixinBot
2
2
 
3
- > Ruby SDK and CLI for Mixin Network: Safe UTXO transfers, REST API, Blaze messaging, transaction crypto, optional MVM helpers. Ruby >= 4.0. Gem version 3.0.3.
3
+ > Ruby SDK and CLI for Mixin Network: Safe UTXO transfers, REST API, Blaze messaging, transaction crypto, optional MVM helpers. Ruby >= 4.0. Gem version 3.1.0.
4
4
 
5
5
  Important notes:
6
6