Module: TonSdkRuby
- Extended by:
- TonSdkRuby
- Included in:
- TonSdkRuby, ActionSendMsg, ActionSendMsg, ActionSetCode, ActionSetCode, Address, Address, Builder, Builder, Cell, Cell, Coins, Coins, CommonMsgInfo, CommonMsgInfo, ExtInMsgInfo, ExtInMsgInfo, Hashmap, Hashmap, IntMsgInfo, IntMsgInfo, Mask, Mask, Message, Message, MessageOptions, MessageOptions, OutAction, OutAction, OutList, OutList, OutListOptions, OutListOptions, Provider, Provider, SimpleLib, SimpleLib, SimpleLibOptions, SimpleLibOptions, Slice, Slice, StateInit, StateInit, StateInitOptions, StateInitOptions, TickTock, TickTock, TickTockOptions, TickTockOptions, TonCenter, TonCenter, TonMnemonic, TonMnemonic
- Defined in:
- lib/ton-sdk-ruby.rb,
lib/ton-sdk-ruby/version.rb,
lib/ton-sdk-ruby/boc/cell.rb,
lib/ton-sdk-ruby/boc/mask.rb,
lib/ton-sdk-ruby/boc/slice.rb,
lib/ton-sdk-ruby/utils/bits.rb,
lib/ton-sdk-ruby/utils/hash.rb,
lib/ton-sdk-ruby/boc/builder.rb,
lib/ton-sdk-ruby/boc/hashmap.rb,
lib/ton-sdk-ruby/types/block.rb,
lib/ton-sdk-ruby/types/coins.rb,
lib/ton-sdk-ruby/types/address.rb,
lib/ton-sdk-ruby/utils/helpers.rb,
lib/ton-sdk-ruby/utils/numbers.rb,
lib/ton-sdk-ruby/boc/serializer.rb,
lib/ton-sdk-ruby/utils/checksum.rb,
lib/ton-sdk-ruby/providers/provider.rb,
lib/ton-sdk-ruby/providers/toncenter.rb,
lib/ton-sdk-ruby/johnny_mnemonic/utils.rb,
lib/ton-sdk-ruby/johnny_mnemonic/ton_mnemonic.rb
Defined Under Namespace
Modules: CellType
Classes: ActionSendMsg, ActionSetCode, Address, Builder, Cell, Coins, CommonMsgInfo, ExtInMsgInfo, Hashmap, HashmapE, IntMsgInfo, Mask, Message, MessageOptions, OutAction, OutList, OutListOptions, Provider, SimpleLib, SimpleLibOptions, Slice, StateInit, StateInitOptions, TickTock, TickTockOptions, TonCenter, TonMnemonic
Constant Summary
collapse
- VERSION =
"0.0.17"
- HASH_BITS =
256
- DEPTH_BITS =
16
- FLAG_BOUNCEABLE =
0x11
- FLAG_NON_BOUNCEABLE =
0x51
- FLAG_TEST_ONLY =
0x80
- INT32_MAX =
2147483647
- INT32_MIN =
-2147483648
- REACH_BOC_MAGIC_PREFIX =
hex_to_bytes('B5EE9C72')
- LEAN_BOC_MAGIC_PREFIX =
hex_to_bytes('68FF65F3')
- LEAN_BOC_MAGIC_PREFIX_CRC =
hex_to_bytes('ACC3A728')
Instance Method Summary
collapse
-
#augment(bits, divider = 8) ⇒ Object
-
#base64_to_bytes(base64) ⇒ Object
-
#bits_to_big_int(bits) ⇒ Object
-
#bits_to_big_uint(bits) ⇒ Object
-
#bits_to_bytes(bits) ⇒ Object
-
#bits_to_hex(bits) ⇒ Object
-
#bits_to_int_uint(bits, options = { type: 'int' }) ⇒ Object
-
#breadth_first_sort(root) ⇒ Object
-
#bytes_compare(a, b) ⇒ Object
-
#bytes_needed_for_words_bip39(word_count) ⇒ Object
-
#bytes_to_base64(data) ⇒ Object
-
#bytes_to_bits(data) ⇒ Object
-
#bytes_to_data_string(bytes) ⇒ Object
-
#bytes_to_hex(bytes) ⇒ Object
-
#bytes_to_string(bytes) ⇒ Object
-
#bytes_to_uint(bytes) ⇒ Object
-
#crc16(data) ⇒ Object
-
#crc16_bytes_be(data) ⇒ Object
-
#crc32c(data) ⇒ Object
-
#crc32c_bytes_le(data) ⇒ Object
-
#depth_first_sort(root) ⇒ Object
-
#deserialize(data, check_merkle_proofs = false) ⇒ Object
-
#deserialize_cell(remainder, ref_index_size) ⇒ Object
-
#deserialize_fift(data) ⇒ Object
-
#deserialize_header(bytes) ⇒ Object
-
#generate_words_bip39(length) ⇒ Object
-
#get_mapper(type) ⇒ Object
-
#hex_to_bits(hex) ⇒ Object
-
#hex_to_bytes(hex) ⇒ Object
-
#hex_to_data_string(hex) ⇒ Object
-
#read_json_from_link(link) ⇒ Object
-
#read_post_json_from_link(url, body, headers) ⇒ Object
-
#require_type(name, value, type) ⇒ Object
-
#rollback(bits) ⇒ Object
-
#serialize(root, options = {}) ⇒ Object
-
#serialize_cell(cell, hashmap, ref_index_size) ⇒ Object
-
#sha256(bytes) ⇒ Object
-
#sha512(bytes) ⇒ Object
-
#sign_cell(cell, private_key) ⇒ Object
-
#slice_into_chunks(arr, chunk_size) ⇒ Object
-
#string_to_bytes(value) ⇒ Object
-
#uint_to_hex(uint) ⇒ Object
-
#validate_library_reference(bits, refs) ⇒ Object
-
#validate_merkle_proof(bits, refs) ⇒ Object
-
#validate_merkle_update(bits, refs) ⇒ Object
-
#validate_ordinary(bits, refs) ⇒ Object
-
#validate_pruned_branch(bits, refs) ⇒ Object
Instance Method Details
#augment(bits, divider = 8) ⇒ Object
3
4
5
6
7
8
9
10
11
12
13
14
|
# File 'lib/ton-sdk-ruby/utils/bits.rb', line 3
def augment(bits, divider = 8)
bits = Array.new(bits)
amount = divider - (bits.size % divider)
overage = Array.new(amount, 0)
overage[0] = 1
if overage.size != 0 && overage.size != divider
return bits.concat(overage)
end
bits
end
|
#base64_to_bytes(base64) ⇒ Object
110
111
112
113
|
# File 'lib/ton-sdk-ruby/utils/helpers.rb', line 110
def base64_to_bytes(base64)
binary = Base64.strict_decode64(base64)
binary.bytes
end
|
#bits_to_big_int(bits) ⇒ Object
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
# File 'lib/ton-sdk-ruby/utils/numbers.rb', line 16
def bits_to_big_int(bits)
return { value: 0, is_safe: true } if bits.empty?
uint_result = bits_to_big_uint(bits)
uint = uint_result[:value]
size = bits.size
int = 1 << (size - 1)
value = uint >= int ? (uint - (int * 2)) : uint
is_safe = value >= Float::MIN.to_i && value <= Float::MAX.to_i
{
value: value,
is_safe: is_safe
}
end
|
#bits_to_big_uint(bits) ⇒ Object
3
4
5
6
7
8
9
10
11
12
13
14
|
# File 'lib/ton-sdk-ruby/utils/numbers.rb', line 3
def bits_to_big_uint(bits)
return { value: 0, is_safe: true } if bits.empty?
value = bits.reverse.each_with_index.inject(0) { |acc, (bit, i)| bit.to_i * (2 ** i) + acc }
is_safe = value <= Float::MAX.to_i
{
value: value,
is_safe: is_safe
}
end
|
#bits_to_bytes(bits) ⇒ Object
73
74
75
76
|
# File 'lib/ton-sdk-ruby/utils/helpers.rb', line 73
def bits_to_bytes(bits)
return [].pack("C*") if bits.empty?
hex_to_bytes(bits_to_hex(bits))
end
|
#bits_to_hex(bits) ⇒ Object
67
68
69
70
71
|
# File 'lib/ton-sdk-ruby/utils/helpers.rb', line 67
def bits_to_hex(bits)
bitstring = bits.join('')
hex = bitstring.scan(/.{1,4}/).map { |el| el.rjust(4, '0').to_i(2).to_s(16) }
hex.join('')
end
|
#bits_to_int_uint(bits, options = { type: 'int' }) ⇒ Object
32
33
34
35
36
37
38
39
40
41
|
# File 'lib/ton-sdk-ruby/utils/numbers.rb', line 32
def bits_to_int_uint(bits, options = { type: 'int' })
type = options[:type].to_s || 'uint'
result = if type == 'uint'
bits_to_big_uint(bits)
else
bits_to_big_int(bits)
end
result[:value]
end
|
#breadth_first_sort(root) ⇒ Object
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
|
# File 'lib/ton-sdk-ruby/boc/serializer.rb', line 279
def breadth_first_sort(root)
stack = root.dup
cells = root.map { |el| { cell: el, hash: el.hash } }
hash_indexes = cells.map.with_index { |el, i| [el[:hash], i] }.to_h
while stack.size > 0 do
length = stack.size
stack.each do |node|
node.refs.each do |ref|
hash = ref.hash
index = hash_indexes[hash]
if index != nil
val = cells[index]
cells[index] = nil
cells << val
else
cells << {cell: ref, hash: hash}
end
len = cells.size
stack.push(ref)
hash_indexes[hash] = len - 1
end
end
stack.shift(length)
end
idx = 0
result = cells.each_with_index.reduce({ cells: [], hashmap: {} }) do |acc, (el, i)|
unless el.nil?
acc[:cells].push(el[:cell])
acc[:hashmap][el[:hash]] = idx
idx += 1
end
acc
end
result
end
|
#bytes_compare(a, b) ⇒ Object
43
44
45
46
47
|
# File 'lib/ton-sdk-ruby/utils/helpers.rb', line 43
def bytes_compare(a, b)
return false if a.length != b.length
a.each_with_index.all? { |uint, i| uint == b[i] }
end
|
#bytes_needed_for_words_bip39(word_count) ⇒ Object
34
35
36
37
38
39
|
# File 'lib/ton-sdk-ruby/johnny_mnemonic/utils.rb', line 34
def bytes_needed_for_words_bip39(word_count)
full_entropy = word_count * 11
checksum = full_entropy % 32
initial_entropy = full_entropy - checksum
initial_entropy / 8
end
|
#bytes_to_base64(data) ⇒ Object
103
104
105
106
107
108
|
# File 'lib/ton-sdk-ruby/utils/helpers.rb', line 103
def bytes_to_base64(data)
bytes = data.is_a?(String) ? data.unpack("C*") : data
str = bytes.map(&:chr).join
Base64.strict_encode64(str)
end
|
#bytes_to_bits(data) ⇒ Object
53
54
55
56
57
58
59
60
61
62
63
64
65
|
# File 'lib/ton-sdk-ruby/utils/helpers.rb', line 53
def bytes_to_bits(data)
bytes = data.is_a?(Array) ? data : data.unpack("C*")
result = bytes.reduce([]) do |acc, uint|
chunk = uint.to_s(2)
.rjust(8, '0')
.split('')
.map(&:to_i)
acc.concat(chunk)
end
result
end
|
#bytes_to_data_string(bytes) ⇒ Object
90
91
92
93
|
# File 'lib/ton-sdk-ruby/utils/helpers.rb', line 90
def bytes_to_data_string(bytes)
raise 'Only byte array' unless bytes.is_a?(Array)
bytes.pack('C*')
end
|
#bytes_to_hex(bytes) ⇒ Object
78
79
80
81
82
83
84
|
# File 'lib/ton-sdk-ruby/utils/helpers.rb', line 78
def bytes_to_hex(bytes)
if bytes.is_a?(Array)
bytes.pack('C*').unpack('H*').first
else
bytes.unpack('H*').first
end
end
|
#bytes_to_string(bytes) ⇒ Object
86
87
88
|
# File 'lib/ton-sdk-ruby/utils/helpers.rb', line 86
def bytes_to_string(bytes)
bytes.pack("C*").force_encoding('utf-8')
end
|
#bytes_to_uint(bytes) ⇒ Object
32
33
34
35
36
37
38
39
40
41
|
# File 'lib/ton-sdk-ruby/utils/helpers.rb', line 32
def bytes_to_uint(bytes)
bytes = bytes.is_a?(Array) ? bytes : bytes.unpack("C*")
uint = bytes.each_with_index.inject(0) do |acc, (byte, i)|
acc *= 256
acc += byte
acc
end
uint
end
|
#crc16(data) ⇒ Object
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
# File 'lib/ton-sdk-ruby/utils/checksum.rb', line 3
def crc16(data)
poly = 0x1021
bytes = data.is_a?(String) ? data.unpack('C*') : Array.new(data)
int16 = bytes.reduce(0) do |acc, el|
crc = acc ^ (el << 8)
8.times do
crc = (crc & 0x8000) == 0x8000 ? (crc << 1) ^ poly : crc << 1
end
crc
end & 0xffff
[int16].pack("S").unpack1("S")
end
|
#crc16_bytes_be(data) ⇒ Object
19
20
21
22
|
# File 'lib/ton-sdk-ruby/utils/checksum.rb', line 19
def crc16_bytes_be(data)
crc = crc16(data)
[crc].pack("S>").bytes
end
|
#crc32c(data) ⇒ Object
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
# File 'lib/ton-sdk-ruby/utils/checksum.rb', line 24
def crc32c(data)
poly = 0x82f63b78
bytes = data.is_a?(String) ? data.unpack('C*') : Array.new(data)
int32 = bytes.reduce(0 ^ 0xffffffff) do |acc, el|
crc = acc ^ el
8.times do
crc = crc & 1 == 1 ? (crc >> 1) ^ poly : crc >> 1
end
crc
end ^ 0xffffffff
[int32].pack("L>").unpack1("L>")
end
|
#crc32c_bytes_le(data) ⇒ Object
41
42
43
44
|
# File 'lib/ton-sdk-ruby/utils/checksum.rb', line 41
def crc32c_bytes_le(data)
crc = crc32c(data)
[crc].pack("L<").bytes
end
|
#depth_first_sort(root) ⇒ Object
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
|
# File 'lib/ton-sdk-ruby/boc/serializer.rb', line 232
def depth_first_sort(root)
stack = [{
cell: Cell.new(refs: root),
children: root.length,
scanned: 0
}]
cells = []
hash_indexes = {}
process = lambda do |node|
ref = node[:cell].refs[node[:scanned]]
hash = ref.hash
index = hash_indexes[hash]
length = index.nil? ? cells.push(cell: ref, hash: hash) : cells.push(cells.delete_at(index))
stack.push(cell: ref, children: ref.refs.length, scanned: 0)
hash_indexes[hash] = length - 1
end
while !stack.empty?
current = stack.last
if current[:children] != current[:scanned]
process.call(current)
else
while !stack.empty? && current && current[:children] == current[:scanned]
stack.pop
current = stack.last
end
process.call(current) if current
end
end
result = cells.each_with_index.reduce({ cells: [], hashmap: {} }) do |acc, (el, i)|
unless el.nil?
acc[:cells].push(el[:cell])
acc[:hashmap][el[:hash]] = i
end
acc
end
result
end
|
#deserialize(data, check_merkle_proofs = false) ⇒ Object
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
|
# File 'lib/ton-sdk-ruby/boc/serializer.rb', line 191
def deserialize(data, check_merkle_proofs = false)
has_merkle_proofs = false
bytes = Array.new(data)
pointers = []
= (bytes)
[:cells_num].times do
deserialized = deserialize_cell([:cells_data], [:size_bytes])
[:cells_data] = deserialized[:remainder]
pointers.push(deserialized[:pointer])
end
pointers.each_with_index do |_, index|
pointer_index = pointers.length - index - 1
cell_builder = pointers[pointer_index][:builder]
cell_type = pointers[pointer_index][:type]
pointers[pointer_index][:refs].each do |ref_index|
ref_builder = pointers[ref_index][:builder]
ref_type = pointers[ref_index][:type]
raise "Topological order is broken" if ref_index < pointer_index
if ref_type == CellType::MerkleProof || ref_type == CellType::MerkleUpdate
has_merkle_proofs = true
end
cell_builder.store_ref(ref_builder.cell(ref_type))
end
if cell_type == CellType::MerkleProof || cell_type == CellType::MerkleUpdate
has_merkle_proofs = true
end
pointers[pointer_index][:cell] = cell_builder.cell(cell_type)
end
raise "BOC does not contain Merkle Proofs" if check_merkle_proofs && !has_merkle_proofs
[:root_list].map { |ref_index| pointers[ref_index][:cell] }
end
|
#deserialize_cell(remainder, ref_index_size) ⇒ Object
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
|
# File 'lib/ton-sdk-ruby/boc/serializer.rb', line 136
def deserialize_cell(remainder, ref_index_size)
raise "BoC not enough bytes to encode cell descriptors" if remainder.length < 2
refs_descriptor = remainder.shift
level = refs_descriptor >> 5
total_refs = refs_descriptor & 7
has_hashes = (refs_descriptor & 16) != 0
is_exotic = (refs_descriptor & 8) != 0
is_absent = total_refs == 7 && has_hashes
if is_absent
raise "BoC can't deserialize absent cell"
end
raise "BoC cell can't has more than 4 refs #{total_refs}" if total_refs > 4
bits_descriptor = remainder.shift
is_augmented = (bits_descriptor & 1) != 0
data_size = (bits_descriptor >> 1) + (is_augmented ? 1 : 0)
hashes_size = has_hashes ? (level + 1) * 32 : 0
depth_size = has_hashes ? (level + 1) * 2 : 0
required_bytes = hashes_size + depth_size + data_size + ref_index_size * total_refs
raise "BoC not enough bytes to encode cell data" if remainder.length < required_bytes
remainder.shift(hashes_size + depth_size) if has_hashes
bits = if is_augmented
rollback(bytes_to_bits(remainder.shift(data_size)))
else
bytes_to_bits(remainder.shift(data_size))
end
raise "BoC not enough bytes for an exotic cell type" if is_exotic && bits.length < 8
type = if is_exotic
bits_to_int_uint(bits[0, 8], { type: "int" })
else
CellType::Ordinary
end
raise "BoC an exotic cell can't be of ordinary type" if is_exotic && type == CellType::Ordinary
pointer = {
type: type,
builder: Builder.new(bits.length).store_bits(bits),
refs: Array.new(total_refs) { bytes_to_uint(remainder.shift(ref_index_size)) }
}
{ pointer: pointer, remainder: remainder }
end
|
#deserialize_fift(data) ⇒ Object
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
# File 'lib/ton-sdk-ruby/boc/serializer.rb', line 10
def deserialize_fift(data)
raise 'Can\'t deserialize. Empty fift hex.' if data.nil? || data.empty?
re = /((\s*)x{([0-9a-zA-Z_]+)}\n?)/mi
matches = data.scan(re) || []
raise 'Can\'t deserialize. Bad fift hex.' if matches.empty?
parse_fift_hex = lambda do |fift|
return [] if fift == '_'
bits = fift.split('')
.map { |el| el == '_' ? el : hex_to_bits(el).join('') }
.join('')
.sub(/1[0]*_$/, '')
.split('')
.map(&:to_i)
bits
end
if matches.length == 1
return [Cell.new(bits: parse_fift_hex.call(matches[0][2]))]
end
is_last_nested = lambda do |stack, indent|
last_stack_indent = stack[-1][:indent]
last_stack_indent != 0 && last_stack_indent >= indent
end
stack = matches.each_with_object([]).with_index do |(el, acc), i|
_, spaces, fift = el
is_last = i == matches.length - 1
indent = spaces.length
bits = parse_fift_hex.call(fift)
builder = Builder.new.store_bits(bits)
while !acc.empty? && is_last_nested.call(acc, indent)
b = acc.pop[:builder]
acc[-1][:builder].store_ref(b.cell)
end
if is_last
acc[-1][:builder].store_ref(builder.cell)
else
acc.push(indent: indent, builder: builder)
end
end
stack.map { |el| el[:builder].cell }
end
|
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
|
# File 'lib/ton-sdk-ruby/boc/serializer.rb', line 63
def (bytes)
raise 'Not enough bytes for magic prefix' if bytes.length < 4 + 1
crcbytes = bytes[0, bytes.length - 4]
prefix = bytes.shift(4)
flags_byte = bytes.shift
= {
has_index: true,
hash_crc32: nil,
has_cache_bits: false,
flags: 0,
size_bytes: flags_byte,
offset_bytes: nil,
cells_num: nil,
roots_num: nil,
absent_num: nil,
tot_cells_size: nil,
root_list: nil,
cells_data: nil
}
if bytes_compare(prefix, REACH_BOC_MAGIC_PREFIX)
[:has_index] = (flags_byte & 128) != 0
[:has_cache_bits] = (flags_byte & 32) != 0
[:flags] = (flags_byte & 16) * 2 + (flags_byte & 8)
[:size_bytes] = flags_byte % 8
[:hash_crc32] = flags_byte & 64
elsif bytes_compare(prefix, LEAN_BOC_MAGIC_PREFIX)
[:hash_crc32] = 0
elsif bytes_compare(prefix, LEAN_BOC_MAGIC_PREFIX_CRC)
[:hash_crc32] = 1
else
raise 'Bad magic prefix'
end
raise 'Not enough bytes for encoding cells counters' if bytes.length < 1 + 5 * [:size_bytes]
offset_bytes = bytes.shift
[:offset_bytes] = offset_bytes
[:cells_num] = bytes_to_uint(bytes.shift([:size_bytes]))
[:roots_num] = bytes_to_uint(bytes.shift([:size_bytes]))
[:absent_num] = bytes_to_uint(bytes.shift([:size_bytes]))
[:tot_cells_size] = bytes_to_uint(bytes.shift(offset_bytes))
raise 'Not enough bytes for encoding root cells hashes' if bytes.length < [:roots_num] * [:size_bytes]
[:root_list] = Array.new([:roots_num]) do
ref_index = bytes_to_uint(bytes.shift([:size_bytes]))
ref_index
end
if [:has_index]
raise 'Not enough bytes for index encoding' if bytes.length < [:offset_bytes] * [:cells_num]
Array.new([:cells_num]) { bytes.shift([:offset_bytes]) }
end
raise 'Not enough bytes for cells data' if bytes.length < [:tot_cells_size]
[:cells_data] = bytes.shift([:tot_cells_size])
if [:hash_crc32]
raise 'Not enough bytes for crc32c hashsum' if bytes.length < 4
result = crc32c_bytes_le(crcbytes)
raise 'Crc32c hashsum mismatch' unless bytes_compare(result, bytes.shift(4))
end
raise 'Too much bytes in BoC serialization' unless bytes.empty?
end
|
#generate_words_bip39(length) ⇒ Object
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
# File 'lib/ton-sdk-ruby/johnny_mnemonic/utils.rb', line 18
def generate_words_bip39(length)
current_file_path = File.expand_path(File.dirname(__FILE__))
bip0039en = JSON.parse(File.read("#{current_file_path}/words/english.json"))
entropy = SecureRandom.random_bytes(bytes_needed_for_words(length)).unpack('C*')
checksum_bits = derive_checksum_bits(entropy)
entropy_bits = bytes_to_bits(entropy)
full_bits = entropy_bits + checksum_bits
chunks = full_bits.join('').scan(/.{1,11}/)
words = chunks.map do |chunk|
index = chunk.to_i(2)
bip0039en[index]
end
words
end
|
#get_mapper(type) ⇒ Object
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
|
# File 'lib/ton-sdk-ruby/boc/cell.rb', line 144
def get_mapper(type)
map = {
CellType::Ordinary => {
validate: method(:validate_ordinary),
mask: -> (_b, r) { Mask.new(r.reduce(0) { |acc, el| acc | el.mask.value }) }
},
CellType::PrunedBranch => {
validate: method(:validate_pruned_branch),
mask: lambda { |b| Mask.new(bits_to_int_uint(b[8..15], { type: 'uint' })) }
},
CellType::LibraryReference => {
validate: method(:validate_library_reference),
mask: -> { Mask.new(0) }
},
CellType::MerkleProof => {
validate: method(:validate_merkle_proof),
mask: lambda { |_b, r| Mask.new(r[0].mask.value >> 1) }
},
CellType::MerkleUpdate => {
validate: method(:validate_merkle_update),
mask: lambda { |_b, r| Mask.new((r[0].mask.value | r[1].mask.value) >> 1) }
}
}
result = map[type]
if result.nil?
raise 'Unknown cell type'
end
result
end
|
#hex_to_bits(hex) ⇒ Object
18
19
20
21
22
23
24
25
26
27
28
29
30
|
# File 'lib/ton-sdk-ruby/utils/helpers.rb', line 18
def hex_to_bits(hex)
result = hex.split('').flat_map do |val|
chunk = val.to_i(16)
.to_s(2)
.rjust(4, '0')
.split('')
.map(&:to_i)
chunk
end
result
end
|
#hex_to_bytes(hex) ⇒ Object
49
50
51
|
# File 'lib/ton-sdk-ruby/utils/helpers.rb', line 49
def hex_to_bytes(hex)
hex.scan(/.{1,2}/).map { |byte| byte.to_i(16) }
end
|
#hex_to_data_string(hex) ⇒ Object
95
96
97
|
# File 'lib/ton-sdk-ruby/utils/helpers.rb', line 95
def hex_to_data_string(hex)
bytes_to_data_string(hex_to_bytes(hex))
end
|
#read_json_from_link(link) ⇒ Object
132
133
134
135
136
137
138
139
140
141
142
|
# File 'lib/ton-sdk-ruby/utils/helpers.rb', line 132
def read_json_from_link(link)
uri = URI.parse("#{link}")
request = Net::HTTP::Get.new(uri)
request.content_type = "application/json"
req_options = { use_ssl: uri.scheme == "https" }
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
JSON.parse(response.body)
end
|
#read_post_json_from_link(url, body, headers) ⇒ Object
144
145
146
147
148
149
150
151
152
153
154
155
156
157
|
# File 'lib/ton-sdk-ruby/utils/helpers.rb', line 144
def read_post_json_from_link(url, body, )
uri = URI.parse(url)
request = Net::HTTP::Post.new(uri)
request.content_type = "application/json"
.each do |name, value|
request[name.to_s] = value
end
request.body = JSON.generate(body)
req_options = { use_ssl: uri.scheme == "https" }
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
JSON.parse(response.body)
end
|
#require_type(name, value, type) ⇒ Object
159
160
161
|
# File 'lib/ton-sdk-ruby/utils/helpers.rb', line 159
def require_type(name, value, type)
raise "#{name} must be #{type}" unless value.is_a?(type)
end
|
#rollback(bits) ⇒ Object
16
17
18
19
20
21
22
23
24
|
# File 'lib/ton-sdk-ruby/utils/bits.rb', line 16
def rollback(bits)
index = bits.last(7).reverse.index(1)
if index.nil?
raise StandardError.new('Incorrectly augmented bits.')
end
bits[0, bits.length - (index + 1)]
end
|
#serialize(root, options = {}) ⇒ Object
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
|
# File 'lib/ton-sdk-ruby/boc/serializer.rb', line 338
def serialize(root, options = {})
root = [*root]
has_index = options.fetch(:has_index, false)
has_cache_bits = options.fetch(:has_cache_bits, false)
hash_crc32 = options.fetch(:hash_crc32, true)
topological_order = options.fetch(:topological_order, 'breadth-first')
flags = options.fetch(:flags, 0)
if topological_order == 'breadth-first'
breadth = breadth_first_sort(root)
cells_list = breadth[:cells]
hashmap = breadth[:hashmap]
else
breadth = depth_first_sort(root)
cells_list = breadth[:cells]
hashmap = breadth[:hashmap]
end
cells_num = cells_list.size
size = cells_num.to_s(2).size
size_bytes = [(size.to_f / 8).ceil, 1].max
cells_bits = []
size_index = []
cells_list.each do |cell|
bits = serialize_cell(cell, hashmap, size_bytes * 8)
cells_bits.concat(bits)
size_index.push(bits.length / 8)
end
full_size = cells_bits.length / 8
offset_bits = full_size.to_s(2).length
offset_bytes = [(offset_bits / 8.0).ceil, 1].max
builder_size = (32 + 3 + 2 + 3 + 8) +
(cells_bits.length) +
((size_bytes * 8) * 4) +
(offset_bytes * 8) +
(has_index ? (cells_list.length * (offset_bytes * 8)) : 0)
result = Builder.new(builder_size)
result.store_bytes(REACH_BOC_MAGIC_PREFIX)
.store_bit(has_index ? 1 : 0)
.store_bit(hash_crc32 ? 1 : 0)
.store_bit(has_cache_bits ? 1 : 0)
.store_uint(flags, 2)
.store_uint(size_bytes, 3)
.store_uint(offset_bytes, 8)
.store_uint(cells_num, size_bytes * 8)
.store_uint(root.length, size_bytes * 8)
.store_uint(0, size_bytes * 8)
.store_uint(full_size, offset_bytes * 8)
.store_uint(0, size_bytes * 8)
if has_index
cells_list.each_with_index do |_, index|
result.store_uint(size_index[index], offset_bytes * 8)
end
end
augmented_bits = augment(result.store_bits(cells_bits).bits)
bytes = bits_to_bytes(augmented_bits)
if hash_crc32
hashsum = crc32c_bytes_le(bytes)
bytes + hashsum
else
bytes
end
end
|
#serialize_cell(cell, hashmap, ref_index_size) ⇒ Object
322
323
324
325
326
327
328
329
330
331
332
333
334
335
|
# File 'lib/ton-sdk-ruby/boc/serializer.rb', line 322
def serialize_cell(cell, hashmap, ref_index_size)
representation = cell.get_refs_descriptor +
cell.get_bits_descriptor +
cell.get_augmented_bits
serialized = cell.refs.reduce(representation) do |acc, ref|
ref_index = hashmap[ref.hash]
bits = Array.new(ref_index_size) { |i| (ref_index >> i) & 1 }
acc + bits.reverse
end
serialized
end
|
#sha256(bytes) ⇒ Object
6
7
8
9
|
# File 'lib/ton-sdk-ruby/utils/hash.rb', line 6
def sha256(bytes)
digest = Digest::SHA256.digest(bytes.pack('C*'))
bytes_to_hex(digest)
end
|
#sha512(bytes) ⇒ Object
11
12
13
14
|
# File 'lib/ton-sdk-ruby/utils/hash.rb', line 11
def sha512(bytes)
digest = Digest::SHA512.digest(bytes.pack('C*'))
bytes_to_hex(digest)
end
|
#sign_cell(cell, private_key) ⇒ Object
126
127
128
129
130
|
# File 'lib/ton-sdk-ruby/utils/helpers.rb', line 126
def sign_cell(cell, private_key)
hash = hex_to_data_string(cell.hash)
data_key = hex_to_data_string(private_key)
Ed25519::SigningKey.new(data_key).sign(hash)
end
|
#slice_into_chunks(arr, chunk_size) ⇒ Object
115
116
117
118
119
120
121
122
123
124
|
# File 'lib/ton-sdk-ruby/utils/helpers.rb', line 115
def slice_into_chunks(arr, chunk_size)
res = []
(0...arr.length).step(chunk_size) do |i|
chunk = arr[i, chunk_size]
res.push(chunk)
end
res
end
|
#string_to_bytes(value) ⇒ Object
99
100
101
|
# File 'lib/ton-sdk-ruby/utils/helpers.rb', line 99
def string_to_bytes(value)
value.bytes
end
|
#uint_to_hex(uint) ⇒ Object
13
14
15
16
|
# File 'lib/ton-sdk-ruby/utils/helpers.rb', line 13
def uint_to_hex(uint)
hex = sprintf("%#x", uint)
hex[-(hex.length / 2 * 2)..-1]
end
|
#validate_library_reference(bits, refs) ⇒ Object
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
# File 'lib/ton-sdk-ruby/boc/cell.rb', line 55
def validate_library_reference(bits, refs)
size = 8 + HASH_BITS
if bits.length != size
raise "Library Reference cell must have exactly (8 + 256) bits, got \"#{bits.length}\""
end
if refs.length != 0
raise "Library Reference cell can't have refs, got \"#{refs.length}\""
end
type = bits_to_int_uint(bits[0..7], { type: 'int' })
if type != CellType::LibraryReference
raise "Library Reference cell type must be exactly #{CellType::LibraryReference}, got \"#{type}\""
end
end
|
#validate_merkle_proof(bits, refs) ⇒ Object
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
|
# File 'lib/ton-sdk-ruby/boc/cell.rb', line 74
def validate_merkle_proof(bits, refs)
size = 8 + HASH_BITS + DEPTH_BITS
if bits.length != size
raise "Merkle Proof cell must have exactly (8 + 256 + 16) bits, got \"#{bits.length}\""
end
if refs.length != 1
raise "Merkle Proof cell must have exactly 1 ref, got \"#{refs.length}\""
end
type = bits_to_int_uint(bits[0..7], { type: 'int' })
if type != CellType::MerkleProof
raise "Merkle Proof cell type must be exactly #{CellType::MerkleProof}, got \"#{type}\""
end
data = bits[8..-1]
proof_hash = bits_to_hex(data[0..(HASH_BITS - 1)])
proof_depth = bits_to_int_uint(data[HASH_BITS..(HASH_BITS + DEPTH_BITS - 1)], { type: 'uint' })
ref_hash = refs[0].hash(0)
ref_depth = refs[0].depth(0)
if proof_hash != ref_hash
raise "Merkle Proof cell ref hash must be exactly \"#{proof_hash}\", got \"#{ref_hash}\""
end
if proof_depth != ref_depth
raise "Merkle Proof cell ref depth must be exactly \"#{proof_depth}\", got \"#{ref_depth}\""
end
end
|
#validate_merkle_update(bits, refs) ⇒ Object
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
|
# File 'lib/ton-sdk-ruby/boc/cell.rb', line 107
def validate_merkle_update(bits, refs)
size = 8 + (2 * (256 + 16))
if bits.length != size
raise "Merkle Update cell must have exactly (8 + (2 * (256 + 16))) bits, got #{bits.length}"
end
if refs.length != 2
raise "Merkle Update cell must have exactly 2 refs, got #{refs.length}"
end
type = bits_to_int_uint(bits[0..7], { type: 'int' })
if type != CellType::MerkleUpdate
raise "Merkle Update cell type must be exactly #{CellType::MerkleUpdate}, got #{type}"
end
data = bits[8..-1]
hashes = [data[0..255], data[256..511]].map { |el| bits_to_hex(el) }
depths = [data[512..527], data[528..543]].map { |el| bits_to_int_uint(el, { type: 'uint' }) }
refs.each_with_index do |ref, i|
proof_hash = hashes[i]
proof_depth = depths[i]
ref_hash = ref.hash(0)
ref_depth = ref.depth(0)
if proof_hash != ref_hash
raise "Merkle Update cell ref ##{i} hash must be exactly '#{proof_hash}', got '#{ref_hash}'"
end
if proof_depth != ref_depth
raise "Merkle Update cell ref ##{i} depth must be exactly '#{proof_depth}', got '#{ref_depth}'"
end
end
end
|
#validate_ordinary(bits, refs) ⇒ Object
14
15
16
17
18
19
20
21
22
|
# File 'lib/ton-sdk-ruby/boc/cell.rb', line 14
def validate_ordinary(bits, refs)
if bits.length > 1023
raise "Ordinary cell can't have more than 1023 bits, got #{bits.length}"
end
if refs.length > 4
raise "Ordinary cell can't have more than 4 refs, got #{refs.length}"
end
end
|
#validate_pruned_branch(bits, refs) ⇒ Object
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
# File 'lib/ton-sdk-ruby/boc/cell.rb', line 24
def validate_pruned_branch(bits, refs)
min_size = 8 + 8 + (1 * (HASH_BITS + DEPTH_BITS))
if bits.length < min_size
raise "Pruned Branch cell can't have less than (8 + 8 + 256 + 16) bits, got #{bits.length}"
end
if refs.length != 0
raise "Pruned Branch cell can't have refs, got #{refs.length}"
end
type = bits_to_int_uint(bits[0...8], { type: 'int' })
if type != CellType::PrunedBranch
raise "Pruned Branch cell type must be exactly #{CellType::PrunedBranch}, got #{type}"
end
mask = Mask.new(bits_to_int_uint(bits[8...16], { type: 'uint' }))
if mask.level < 1 || mask.level > 3
raise "Pruned Branch cell level must be >= 1 and <= 3, got #{mask.level}"
end
hash_count = mask.apply(mask.level - 1)[:hashCount]
size = 8 + 8 + (hash_count * (HASH_BITS + DEPTH_BITS))
if bits.length != size
raise "Pruned Branch cell with level #{mask.level} must have exactly #{size} bits, got #{bits.length}"
end
end
|