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
@@ -5,222 +5,254 @@ module MixinBot
5
5
  ##
6
6
  # Builds the binary encoding for a {Transaction} instance.
7
7
  #
8
+ # The encoding is accumulated in one binary String buffer: hex fields are
9
+ # +pack('H*')+ed straight into it and integers appended with the
10
+ # +MixinBot.utils.pack_*+ helpers, so no intermediate Array of bytes is built.
11
+ #
8
12
  class Encoder
9
13
  def initialize(transaction)
10
14
  @tx = transaction
11
15
  end
12
16
 
13
- def encode
17
+ def encode(compute_hash: true)
18
+ unless @tx.version.is_a?(Integer) && @tx.version.between?(Transaction::TX_VERSION, Transaction::SAFE_TX_VERSION)
19
+ raise InvalidTransactionFormatError, 'unsupported transaction version'
20
+ end
21
+
14
22
  raise InvalidTransactionFormatError, 'asset is required' if @tx.asset.blank?
15
23
  raise InvalidTransactionFormatError, 'inputs is required' if @tx.inputs.blank?
16
24
  raise InvalidTransactionFormatError, 'outputs is required' if @tx.outputs.blank?
17
25
 
18
- bytes = []
26
+ bytes = +''.b
27
+ bytes << Transaction::MAGIC_BINARY
28
+ bytes << [0, @tx.version].pack('CC')
29
+ bytes << fixed_hex(@tx.asset, 32)
19
30
 
20
- bytes.concat Transaction::MAGIC
21
- bytes.push(0, @tx.version)
22
- bytes.concat [@tx.asset].pack('H*').bytes
31
+ encode_inputs bytes
32
+ encode_outputs bytes
33
+ encode_references bytes if @tx.version >= Transaction::REFERENCES_TX_VERSION
23
34
 
24
- bytes.concat encode_inputs
25
- bytes.concat encode_outputs
26
- bytes.concat encode_references if @tx.version >= Transaction::REFERENCES_TX_VERSION
35
+ extra_bytes = @tx.extra.b
36
+ raise InvalidTransactionFormatError, 'extra is too long' if extra_bytes.bytesize > @tx.max_extra_size
27
37
 
28
- extra_bytes = @tx.extra.bytes
29
- raise InvalidTransactionFormatError, 'extra is too long' if extra_bytes.size > Transaction::MAX_EXTRA_SIZE
30
-
31
- bytes.concat MixinBot.utils.encode_uint32 extra_bytes.size
32
- bytes.concat extra_bytes
38
+ bytes << MixinBot.utils.pack_uint32(extra_bytes.bytesize)
39
+ bytes << extra_bytes
40
+ signature_offset = bytes.bytesize
41
+ if @tx.aggregated.nil?
42
+ encode_signatures bytes
43
+ else
44
+ encode_aggregated_signature bytes
45
+ end
33
46
 
34
- bytes.concat(@tx.aggregated.nil? ? encode_signatures : encode_aggregated_signature)
47
+ if @tx.safe_wire?
48
+ raise InvalidTransactionFormatError, 'transaction is too large' if bytes.bytesize > @tx.max_extra_size
35
49
 
36
- packed = bytes.pack('C*')
37
- @tx.hash = SHA3::Digest::SHA3_256.hexdigest packed
38
- @tx.hex = packed.unpack1('H*')
50
+ if compute_hash
51
+ payload = bytes.bytesize == signature_offset + 2 ? bytes : bytes.byteslice(0, signature_offset) << Transaction::NULL_BINARY
52
+ @tx.hash = Digest::Blake3.hexdigest(payload)
53
+ end
54
+ elsif compute_hash
55
+ @tx.hash = SHA3::Digest::SHA3_256.hexdigest(bytes)
56
+ end
57
+ @tx.hex = bytes.unpack1('H*')
39
58
 
40
59
  @tx
41
60
  end
42
61
 
62
+ def signature_bytes
63
+ bytes = +''.b
64
+ encode_signatures bytes
65
+ bytes
66
+ end
67
+
43
68
  private
44
69
 
45
- def encode_inputs
46
- bytes = []
70
+ # Appends +string+ preceded by its uint16 byte length.
71
+ def append_uint16_sized(bytes, string)
72
+ exceeds_limit = @tx.safe_wire? && string.bytesize > Transaction::MAX_ENCODE_INT
73
+ raise InvalidTransactionFormatError, 'field exceeds uint16 capacity' if exceeds_limit
47
74
 
48
- bytes.concat MixinBot.utils.encode_uint16(@tx.inputs.size)
75
+ bytes << MixinBot.utils.pack_uint16(string.bytesize)
76
+ bytes << string
77
+ end
78
+
79
+ def fixed_hex(value, size)
80
+ if @tx.safe_wire? && (!value.is_a?(String) || value.bytesize != size * 2 || !value.match?(/\A\h+\z/))
81
+ raise InvalidTransactionFormatError, "expected #{size} bytes of hex"
82
+ end
83
+
84
+ [value].pack('H*')
85
+ end
86
+
87
+ def wire_amount(amount)
88
+ return MixinBot.utils.pack_int((amount.to_d * 100_000_000).round) unless @tx.safe_wire?
89
+
90
+ integer = MixinBot.utils.safe_amount_units(amount)
91
+ integer.zero? ? ''.b : MixinBot.utils.pack_int(integer)
92
+ end
93
+
94
+ def append_count(bytes, size)
95
+ raise InvalidTransactionFormatError, 'too many items' if @tx.safe_wire? && size > Transaction::SAFE_SLICE_LIMIT
96
+
97
+ bytes << MixinBot.utils.pack_uint16(size)
98
+ end
99
+
100
+ def encode_inputs(bytes)
101
+ append_count bytes, @tx.inputs.size
49
102
 
50
103
  @tx.inputs.each do |input|
51
- bytes.concat [input['hash']].pack('H*').bytes
52
- bytes.concat MixinBot.utils.encode_uint16(input['index'])
104
+ if @tx.safe_wire? && !input['index'].between?(0, Transaction::SAFE_INPUT_INDEX_LIMIT)
105
+ raise InvalidTransactionFormatError, 'invalid input index'
106
+ end
107
+
108
+ bytes << fixed_hex(input['hash'], 32)
109
+ bytes << MixinBot.utils.pack_uint16(input['index'])
53
110
 
54
111
  genesis = input['genesis'] || ''
55
112
  if genesis.empty?
56
- bytes.concat Transaction::NULL_BYTES
113
+ bytes << Transaction::NULL_BINARY
57
114
  else
58
- genesis_bytes = [genesis].pack('H*').bytes
59
- bytes.concat MixinBot.utils.encode_uint16 genesis_bytes.size
60
- bytes.concat genesis_bytes
115
+ append_uint16_sized bytes, [genesis].pack('H*')
61
116
  end
62
117
 
63
118
  deposit = input['deposit']
64
119
  if deposit.nil?
65
- bytes.concat Transaction::NULL_BYTES
120
+ bytes << Transaction::NULL_BINARY
66
121
  else
67
- bytes.concat Transaction::MAGIC
68
- bytes.concat [deposit['chain']].pack('H*').bytes
122
+ bytes << Transaction::MAGIC_BINARY
123
+
124
+ bytes << fixed_hex(deposit['chain'], 32)
69
125
 
70
- asset_bytes = [deposit['asset']].pack('H*')
71
- bytes.concat MixinBot.utils.encode_uint16 asset_bytes.size
72
- bytes.concat asset_bytes.bytes
126
+ append_uint16_sized bytes, @tx.safe_wire? ? deposit['asset'].b : [deposit['asset']].pack('H*')
73
127
 
74
- transaction_bytes = [deposit['transaction']].pack('H*')
75
- bytes.concat MixinBot.utils.encode_uint16 transaction_bytes.size
76
- bytes.concat transaction_bytes.bytes
128
+ append_uint16_sized bytes, @tx.safe_wire? ? deposit['transaction'].b : [deposit['transaction']].pack('H*')
77
129
 
78
- bytes.concat MixinBot.utils.encode_uint64 deposit['index']
130
+ bytes << MixinBot.utils.pack_uint64(deposit['index'])
79
131
 
80
- amount_bytes = MixinBot.utils.bytes_of deposit['amount']
81
- bytes.concat MixinBot.utils.encode_uint16 amount_bytes.size
82
- bytes.concat amount_bytes
132
+ amount = @tx.safe_wire? ? wire_amount(deposit['amount']) : MixinBot.utils.bytes_of(deposit['amount']).pack('C*')
133
+ append_uint16_sized bytes, amount
83
134
  end
84
135
 
85
136
  mint = input['mint']
86
137
  if mint.nil?
87
- bytes.concat Transaction::NULL_BYTES
138
+ bytes << Transaction::NULL_BINARY
88
139
  else
89
- bytes.concat Transaction::MAGIC
140
+ bytes << Transaction::MAGIC_BINARY
90
141
 
91
142
  group = mint['group'] || ''
92
143
  if group.empty?
93
- bytes.concat Transaction::NULL_BYTES
144
+ bytes << Transaction::NULL_BINARY
94
145
  else
95
- group_bytes = [group].pack('H*')
96
- bytes.concat MixinBot.utils.encode_uint16 group_bytes.size
97
- bytes.concat group_bytes.bytes
146
+ append_uint16_sized bytes, @tx.safe_wire? ? group.b : [group].pack('H*')
98
147
  end
99
148
 
100
- bytes.concat MixinBot.utils.encode_uint64 mint['batch']
149
+ bytes << MixinBot.utils.pack_uint64(mint['batch'])
101
150
 
102
- amount_bytes = MixinBot.utils.encode_int mint['amount']
103
- bytes.concat MixinBot.utils.encode_uint16 amount_bytes.size
104
- bytes.concat amount_bytes
151
+ append_uint16_sized bytes, @tx.safe_wire? ? wire_amount(mint['amount']) : MixinBot.utils.pack_int(mint['amount'])
105
152
  end
106
153
  end
107
-
108
- bytes
109
154
  end
110
155
 
111
- def encode_outputs
112
- bytes = []
113
-
114
- bytes.concat MixinBot.utils.encode_uint16 @tx.outputs.size
156
+ def encode_outputs(bytes)
157
+ append_count bytes, @tx.outputs.size
115
158
 
116
159
  @tx.outputs.each do |output|
117
160
  type = output['type'] || 0
118
- bytes.push(0x00, type)
161
+ bytes << [0x00, type].pack('CC')
119
162
 
120
- amount_bytes = MixinBot.utils.encode_int((output['amount'].to_d * 1e8).round)
121
- bytes.concat MixinBot.utils.encode_uint16 amount_bytes.size
122
- bytes.concat amount_bytes
163
+ append_uint16_sized bytes, wire_amount(output['amount'])
123
164
 
124
- bytes.concat MixinBot.utils.encode_uint16 output['keys'].size
125
- output['keys'].each do |key|
126
- bytes.concat [key].pack('H*').bytes
165
+ keys = @tx.safe_wire? ? output.fetch('keys', []) : output['keys']
166
+ append_count bytes, keys.size
167
+ keys.each do |key|
168
+ bytes << fixed_hex(key, 32)
127
169
  end
128
170
 
129
- bytes.concat [output['mask']].pack('H*').bytes
171
+ mask = output['mask']
172
+ bytes << (@tx.safe_wire? && mask.blank? ? ("\0".b * 32) : fixed_hex(mask, 32))
130
173
 
131
- script_bytes = [output['script']].pack('H*').bytes
132
- bytes.concat MixinBot.utils.encode_uint16 script_bytes.size
133
- bytes.concat script_bytes
174
+ append_uint16_sized bytes, [@tx.safe_wire? ? output['script'].to_s : output['script']].pack('H*')
134
175
 
135
176
  withdrawal = output['withdrawal']
136
177
  if withdrawal.nil?
137
- bytes.concat Transaction::NULL_BYTES
178
+ bytes << Transaction::NULL_BINARY
179
+ elsif @tx.safe_wire?
180
+ bytes << Transaction::MAGIC_BINARY
181
+ append_uint16_sized bytes, withdrawal['address'].to_s.b
182
+ append_uint16_sized bytes, withdrawal['tag'].to_s.b
138
183
  else
139
- bytes.concat Transaction::MAGIC
184
+ bytes << Transaction::MAGIC_BINARY
140
185
 
141
- bytes.concat [withdrawal['chain']].pack('H*').bytes
186
+ bytes << [withdrawal['chain']].pack('H*')
142
187
 
143
- asset_bytes = [withdrawal['asset']].pack('H*')
144
- bytes.concat MixinBot.utils.encode_uint16 asset_bytes.bytesize
145
- bytes.concat asset_bytes.bytes
188
+ append_uint16_sized bytes, [withdrawal['asset']].pack('H*')
146
189
 
147
190
  address = withdrawal['address'] || ''
148
191
  if address.empty?
149
- bytes.concat Transaction::NULL_BYTES
192
+ bytes << Transaction::NULL_BINARY
150
193
  else
151
- address_bytes = [address].pack('H*').bytes
152
- bytes.concat MixinBot.utils.encode_uint16 address_bytes.size
153
- bytes.concat address_bytes
194
+ append_uint16_sized bytes, [address].pack('H*')
154
195
  end
155
196
 
156
197
  tag = withdrawal['tag'] || ''
157
198
  if tag.empty?
158
- bytes.concat Transaction::NULL_BYTES
199
+ bytes << Transaction::NULL_BINARY
159
200
  else
160
- tag_bytes = [tag].pack('H*').bytes
161
- bytes.concat MixinBot.utils.encode_uint16 tag_bytes.size
162
- bytes.concat tag_bytes
201
+ append_uint16_sized bytes, [tag].pack('H*')
163
202
  end
164
203
  end
165
204
  end
166
-
167
- bytes
168
205
  end
169
206
 
170
- def encode_references
171
- bytes = []
172
-
207
+ def encode_references(bytes)
173
208
  references = Array(@tx.references)
174
- bytes.concat MixinBot.utils.encode_uint16 references.size
209
+
210
+ append_count bytes, references.size
175
211
 
176
212
  references.each do |reference|
177
- bytes.concat [reference].pack('H*').bytes
213
+ bytes << fixed_hex(reference, 32)
178
214
  end
179
-
180
- bytes
181
215
  end
182
216
 
183
- def encode_aggregated_signature
184
- bytes = []
217
+ def encode_aggregated_signature(bytes)
218
+ bytes << MixinBot.utils.pack_uint16(Transaction::MAX_ENCODE_INT)
219
+ bytes << MixinBot.utils.pack_uint16(Transaction::AGGREGATED_SIGNATURE_PREFIX)
185
220
 
186
- bytes.concat MixinBot.utils.encode_uint16 Transaction::MAX_ENCODE_INT
187
- bytes.concat MixinBot.utils.encode_uint16 Transaction::AGGREGATED_SIGNATURE_PREFIX
188
- bytes.concat [@tx.aggregated['signature']].pack('H*').bytes
221
+ signature = fixed_hex(@tx.aggregated['signature'], 64)
222
+ bytes << signature
189
223
 
190
224
  signers = @tx.aggregated['signers'] || []
225
+ raise ArgumentError, 'too many aggregated signers' if signers.size > Transaction::MAX_ENCODE_INT
226
+
191
227
  if signers.empty?
192
- bytes.concat Transaction::AGGREGATED_SIGNATURE_ORDINAY_MASK
193
- bytes.concat Transaction::NULL_BYTES
194
- return bytes
228
+ bytes << Transaction::AGGREGATED_SIGNATURE_ORDINAY_MASK.first
229
+ bytes << Transaction::NULL_BINARY
230
+ return
195
231
  end
196
232
 
197
233
  signers.each_with_index do |sig, i|
198
234
  raise ArgumentError, 'signers not sorted' if i.positive? && sig <= signers[i - 1]
199
- raise ArgumentError, 'signers not sorted' if sig > Transaction::MAX_ENCODE_INT
235
+ raise ArgumentError, 'invalid signer index' unless sig.between?(0, Transaction::MAX_ENCODE_INT)
200
236
  end
201
237
 
202
238
  max = signers.last
203
- sig_byte_len = [@tx.aggregated['signature']].pack('H*').bytes.size
204
- if ((max / 8) + 1) > sig_byte_len
205
- bytes.concat Transaction::AGGREGATED_SIGNATURE_SPARSE_MASK
206
- bytes.concat MixinBot.utils.encode_uint16 signers.size
207
- signers.each { |signer| bytes.concat MixinBot.utils.encode_uint16(signer) }
239
+ sparse_threshold = @tx.safe_wire? ? signers.size * 2 : signature.bytesize
240
+ if ((max / 8) + 1) > sparse_threshold
241
+ bytes << Transaction::AGGREGATED_SIGNATURE_SPARSE_MASK.first
242
+ bytes << MixinBot.utils.pack_uint16(signers.size)
243
+ signers.each { |signer| bytes << MixinBot.utils.pack_uint16(signer) }
208
244
  else
209
245
  masks_bytes = Array.new((max / 8) + 1, 0)
210
246
  signers.each do |signer|
211
247
  masks_bytes[signer / 8] ^= (1 << (signer % 8))
212
248
  end
213
- bytes.concat Transaction::AGGREGATED_SIGNATURE_ORDINAY_MASK
214
- bytes.concat MixinBot.utils.encode_uint16 masks_bytes.size
215
- bytes.concat masks_bytes
249
+ bytes << Transaction::AGGREGATED_SIGNATURE_ORDINAY_MASK.first
250
+ bytes << MixinBot.utils.pack_uint16(masks_bytes.size)
251
+ bytes << masks_bytes.pack('C*')
216
252
  end
217
-
218
- bytes
219
253
  end
220
254
 
221
- def encode_signatures
222
- bytes = []
223
-
255
+ def encode_signatures(bytes)
224
256
  sl =
225
257
  if @tx.signatures.is_a? Array
226
258
  @tx.signatures.size
@@ -228,20 +260,26 @@ module MixinBot
228
260
  0
229
261
  end
230
262
 
231
- raise ArgumentError, 'signatures overflow' if sl == Transaction::MAX_ENCODE_INT
263
+ if sl >= Transaction::MAX_ENCODE_INT || (@tx.safe_wire? && sl > Transaction::SAFE_SLICE_LIMIT)
264
+ raise ArgumentError, 'signatures overflow'
265
+ end
232
266
 
233
- bytes.concat MixinBot.utils.encode_uint16 sl
267
+ bytes << MixinBot.utils.pack_uint16(sl)
234
268
 
235
269
  if sl.positive?
236
270
  @tx.signatures.each do |signature|
237
- bytes.concat MixinBot.utils.encode_uint16 signature.keys.size
271
+ bytes << MixinBot.utils.pack_uint16(signature.keys.size)
238
272
 
239
273
  signature.keys.sort.each do |key|
240
- signature_bytes = [signature[key]].pack('H*').bytes
241
- raise ArgumentError, 'Signature should be 64 bytes' if signature_bytes.size != 64
274
+ if @tx.safe_wire? && (!key.is_a?(Integer) || !key.between?(0, Transaction::MAX_ENCODE_INT))
275
+ raise ArgumentError, 'invalid signature index'
276
+ end
277
+
278
+ signature_bytes = fixed_hex(signature[key], 64)
279
+ raise ArgumentError, 'Signature should be 64 bytes' if signature_bytes.bytesize != 64
242
280
 
243
- bytes.concat MixinBot.utils.encode_uint16 key
244
- bytes.concat signature_bytes
281
+ bytes << MixinBot.utils.pack_uint16(key)
282
+ bytes << signature_bytes
245
283
  end
246
284
  end
247
285
  end
@@ -9,11 +9,18 @@ module MixinBot
9
9
  TX_VERSION = 2
10
10
  MAX_ENCODE_INT = 0xFFFF
11
11
  MAX_EXTRA_SIZE = 512
12
+ SAFE_MAX_EXTRA_SIZE = 4 * 1024 * 1024
13
+ SAFE_SLICE_LIMIT = 256
14
+ SAFE_INPUT_INDEX_LIMIT = 1024
12
15
  NULL_BYTES = [0x00, 0x00].freeze
13
16
  AGGREGATED_SIGNATURE_PREFIX = 0xFF01
14
17
  AGGREGATED_SIGNATURE_ORDINAY_MASK = [0x00].freeze
15
18
  AGGREGATED_SIGNATURE_SPARSE_MASK = [0x01].freeze
16
19
 
20
+ # Binary String forms of MAGIC and NULL_BYTES: what {Encoder} appends to its buffer and {Decoder} compares against.
21
+ MAGIC_BINARY = MAGIC.pack('C*').freeze
22
+ NULL_BINARY = NULL_BYTES.pack('C*').freeze
23
+
17
24
  attr_accessor :version, :asset, :inputs, :outputs, :extra, :signatures, :aggregated, :references, :hex, :hash
18
25
 
19
26
  def initialize(**kwargs)
@@ -36,6 +43,14 @@ module MixinBot
36
43
  Decoder.new(self).decode
37
44
  end
38
45
 
46
+ def safe_wire?
47
+ version == SAFE_TX_VERSION
48
+ end
49
+
50
+ def max_extra_size
51
+ safe_wire? ? SAFE_MAX_EXTRA_SIZE : MAX_EXTRA_SIZE
52
+ end
53
+
39
54
  def to_h
40
55
  {
41
56
  version:,
@@ -52,6 +67,5 @@ module MixinBot
52
67
  end
53
68
  end
54
69
 
55
- require_relative 'transaction/buffer'
56
70
  require_relative 'transaction/encoder'
57
71
  require_relative 'transaction/decoder'
@@ -33,7 +33,7 @@ module MixinBot
33
33
  amount = kwargs[:amount]
34
34
 
35
35
  members = [members] if members.is_a? String
36
- amount = format('%.8f', amount.to_d.to_r).gsub(/\.?0+$/, '')
36
+ amount = safe_amount(amount)
37
37
 
38
38
  {
39
39
  members:,
@@ -56,6 +56,31 @@ module MixinBot
56
56
  (value.to_d * (10**decimals)).floor
57
57
  end
58
58
 
59
+ SAFE_AMOUNT_PRECISION = 8
60
+ SAFE_AMOUNT_SCALE = 10**SAFE_AMOUNT_PRECISION
61
+
62
+ def safe_amount_units(amount)
63
+ value = BigDecimal(amount.to_s, exception: false)
64
+ raise ArgumentError, 'invalid Safe amount' unless value&.finite? && !value.negative?
65
+
66
+ _, digits, _, exponent = value.split
67
+ integer_digits = exponent + SAFE_AMOUNT_PRECISION
68
+ return 0 unless integer_digits.positive? && !value.zero?
69
+
70
+ digits.byteslice(0, integer_digits).ljust(integer_digits, '0').to_i
71
+ end
72
+
73
+ def format_safe_amount(units)
74
+ whole, fraction = units.divmod(SAFE_AMOUNT_SCALE)
75
+ return whole.to_s if fraction.zero?
76
+
77
+ "#{whole}.#{fraction.to_s.rjust(SAFE_AMOUNT_PRECISION, '0').sub(/0+\z/, '')}"
78
+ end
79
+
80
+ def safe_amount(amount)
81
+ format_safe_amount(safe_amount_units(amount))
82
+ end
83
+
59
84
  private
60
85
 
61
86
  def validated_amount_string(amount)
@@ -0,0 +1,97 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MixinBot
4
+ module Utils
5
+ ##
6
+ # Base58 with the bitcoin alphabet, the one Mixin addresses use. It
7
+ # reads and writes what the base58 gem does, without that gem's big
8
+ # integer arithmetic per digit: digits are converted ten at a time
9
+ # (58**10 fits in a machine integer) around a few big integer operations
10
+ # per value, which is what addresses and invoices spend most of their
11
+ # time on.
12
+ #
13
+ # @api private
14
+ module Base58
15
+ ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
16
+ # the digit value of every alphabet byte; nil anywhere else
17
+ DIGITS = ALPHABET.each_byte.with_index.to_h.freeze
18
+ # the digit for the value 0, which also stands for a leading zero byte
19
+ ONE = '1'
20
+
21
+ CHUNK_DIGITS = 10
22
+ CHUNK_BASE = 58**CHUNK_DIGITS
23
+
24
+ module_function
25
+
26
+ ##
27
+ # Base58 of a binary String, a leading +1+ per leading zero byte.
28
+ #
29
+ # @param binary [String] the bytes, ASCII-8BIT
30
+ # @return [String] the digits, UTF-8 as the base58 gem returns them
31
+ # @raise [::ArgumentError] unless +binary+ is a binary String, as the gem insists
32
+ #
33
+ def encode(binary)
34
+ raise ::ArgumentError, 'Value passed is not a String.' unless binary.is_a?(String)
35
+ raise ::ArgumentError, 'Value passed is not binary.' unless binary.encoding == Encoding::ASCII_8BIT
36
+
37
+ integer = binary.unpack1('H*').to_i(16)
38
+ zero = integer.zero?
39
+ digits = +''
40
+ while integer >= CHUNK_BASE
41
+ integer, chunk = integer.divmod(CHUNK_BASE)
42
+ CHUNK_DIGITS.times do
43
+ digits << ALPHABET.getbyte(chunk % 58)
44
+ chunk /= 58
45
+ end
46
+ end
47
+ while integer.positive?
48
+ digits << ALPHABET.getbyte(integer % 58)
49
+ integer /= 58
50
+ end
51
+ digits.reverse!
52
+
53
+ leading = 0
54
+ leading += 1 while leading < binary.bytesize && binary.getbyte(leading).zero?
55
+ # the gem writes the value 0 as one digit, an empty input included
56
+ leading -= 1 if zero
57
+
58
+ (leading.positive? ? ONE * leading : '') + (digits.empty? ? ONE : digits)
59
+ end
60
+
61
+ ##
62
+ # The bytes of a base58 String, each leading +1+ being a zero byte.
63
+ #
64
+ # @param string [String] the digits
65
+ # @return [String] an ASCII-8BIT String
66
+ # @raise [::ArgumentError] if +string+ has a byte that is not a digit
67
+ #
68
+ def decode(string)
69
+ integer = 0
70
+ chunk = 0
71
+ scale = 1
72
+ string.each_byte do |byte|
73
+ digit = DIGITS[byte]
74
+ raise ::ArgumentError, 'Value passed not a valid Base58 String.' unless digit
75
+
76
+ chunk = (chunk * 58) + digit
77
+ scale *= 58
78
+ next unless scale == CHUNK_BASE
79
+
80
+ integer = (integer * CHUNK_BASE) + chunk
81
+ chunk = 0
82
+ scale = 1
83
+ end
84
+ integer = (integer * scale) + chunk
85
+
86
+ leading = 0
87
+ leading += 1 while leading < string.bytesize && string.getbyte(leading) == 49
88
+ # an all-+1+ string (or an empty one) is zeros only: the gem leaves the last one to the value
89
+ leading -= 1 if integer.zero?
90
+
91
+ hex = integer.to_s(16)
92
+ hex = "0#{hex}" if hex.size.odd?
93
+ leading.positive? ? ("\0".b * leading) + [hex].pack('H*') : [hex].pack('H*')
94
+ end
95
+ end
96
+ end
97
+ end