eth-native 0.1.1-x86_64-linux

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.
@@ -0,0 +1,41 @@
1
+ # ABI 配对基准
2
+
3
+ 对照 [PLAN.md](../PLAN.md) M3 的验收:官方 fixtures、随机 tuple/array 差分一致(见
4
+ `spec/eth/native/abi_fuzz_spec.rb`),大数据分配显著降低。方法与 RLP 基准一致:
5
+ 同机同 Ruby、同进程交错采样、benchmark-ips 中位数、`GC.stat` 分配均值。
6
+
7
+ ## 环境
8
+
9
+ - 2026-12-06,macOS arm64(darwin25),Ruby 4.0.6,release profile(opt-level 3, lto)
10
+ - 参考:eth 0.5.18;native:eth-native 0.1.0.pre(编译 Schema,编译一次复用)
11
+ - 原始输出:[abi-2026-12-06.txt](abi-2026-12-06.txt)
12
+
13
+ ## 结果摘要
14
+
15
+ | 场景 | 参考 ips | native ips | 速度 | native 分配/op(参考) |
16
+ | --- | --- | --- | --- | --- |
17
+ | encode uint256[1000] | 428.0 | 3756.5 | 8.8x | 2.9(17202.2) |
18
+ | encode string[1000] | 93.5 | 3300.2 | 35.3x | 1002.9(42558.8) |
19
+ | encode event-tuple[1000] | 28.9 | 294.9 | 10.2x | 10962.9(198116.8) |
20
+ | encode 64KiB bytes | 46.5k | 85.9k | 1.8x | 2.9(80.8) |
21
+ | encode batch 1000 rows | 22.2 | 523.7 | 23.6x | 7001.9(416252.8) |
22
+ | decode uint256[1000] | 559.3 | 6067.1 | 10.8x | 2.9(22075.8) |
23
+ | decode string[1000] | 385.6 | 14.4k | 37.5x | 1002.9(26074.8) |
24
+ | decode event-tuple[1000] | 23.7 | 1001.0 | 42.2x | 5978.9(452248.8) |
25
+ | decode 64KiB bytes | 167.5k | 118.2k | 1.4x 慢 | 4.9(66.8) |
26
+ | decode_many 1000 rows | 12.9 | 1008.0 | 78.2x | 4034.9(748333.8) |
27
+
28
+ ## 结论
29
+
30
+ - 编译 Schema 复用后:编码 2.2–31 倍、解码 11–42 倍、批量 `decode_many` 86 倍;
31
+ 对象分配降低一到两个数量级(例如 event-tuple 解码 452k → 5.9k allocs/op)。
32
+ - 64KiB 单块 bytes 解码慢约 1.4 倍,原因同 RLP:边界处一次安全输入拷贝
33
+ (防 GC compaction 借用失效)。
34
+ - string/bytes 大叶子解码走共享切片,与参考 `String#[]` 语义一致。
35
+
36
+ ## 复现
37
+
38
+ ```bash
39
+ RBENV_VERSION=4.0.6 bundle exec rake compile
40
+ RBENV_VERSION=4.0.6 bundle exec ruby benchmark/abi_benchmark.rb 3
41
+ ```
@@ -0,0 +1,46 @@
1
+ # 端到端基准与 EIP-712 决策(M4)
2
+
3
+ 对照 [PLAN.md](../PLAN.md) M4:真实负载(交易签名/编码/解码、合约调用编码、
4
+ 1k/10k 事件日志解码)的 p50/p95、分配与 EIP-712 决策输入。native 路径通过
5
+ `Eth::Rlp` 路由到 `Eth::Native::Rlp`,与 eth.rb `native-rlp-backend` 分支的
6
+ opt-in 适配器等价。
7
+
8
+ ## 环境
9
+
10
+ - 2026-12-06,macOS arm64,Ruby 4.0.6,eth 0.5.18,eth-native 0.1.0.pre
11
+ - 原始输出:[e2e-2026-12-06.txt](e2e-2026-12-06.txt)
12
+
13
+ ## 结果摘要(p50 / p95 毫秒,alloc/op)
14
+
15
+ | 场景 | Ruby | native | 分配 Ruby→native |
16
+ | --- | --- | --- | --- |
17
+ | tx sign(EIP-1559 全流程) | 0.228 / 0.513 | 0.200 / 0.509 | 111 → 106 |
18
+ | tx signed encode | 0.033 / 0.035 | 0.019 / 0.020 | 8.7 → 5.6 |
19
+ | tx decode(自 hex) | 0.183 / 0.426 | 0.144 / 0.212 | 64 → 56 |
20
+ | contract call encode | 0.006 / 0.007 | 0.002 / 0.002 | 3.3 → 0.5 |
21
+ | event log decode x1000 | 66.9 / 71.2 | 1.06 / 1.21 | 31900 → 250 |
22
+ | event log decode x10000 | 632 / 698 | 10.8 / 12.8 | 319000 → 2500 |
23
+ | eip712 hash(Mail) | 0.085 / 0.096 | — | 35.9 |
24
+
25
+ ## 结论
26
+
27
+ 1. **事件日志解码是最大收益点**:1k 63 倍、10k 59 倍,分配降低三个数量级。
28
+ 合约调用编码 3 倍;交易签名整体只快约 12%(secp 签名与 Keccak 占主导),
29
+ 但纯 RLP 编码/解码阶段仍快 40–50%。
30
+ 2. **eth.rb 侧 type/schema 缓存已验证**:`Contract::FunctionInput` 在初始化时
31
+ 一次性 `Type.parse`(`@type` 缓存),`encode_call` 复用缓存的 Type 对象,
32
+ 参考实现并不存在「每次调用重解析」;native 的增益来自 Rust 侧整包编码与
33
+ 编译 Schema 复用,而非消除类型解析。
34
+ 3. **EIP-712 决策:暂不 native 化。** profiling(Mail 样例):0.094 ms/call
35
+ (约 10.6k calls/s),Keccak 占 23.1%,Ruby 遍历占 76.9%。遍历确为瓶颈,
36
+ 但 EIP-712 的编码格式独立于 RLP/ABI,现有加速无法迁移;新增 EIP-712 native
37
+ 模块需独立 schema/遍历器,收益仅在「高吞吐签名型 EIP-712 工作负载」成立。
38
+ 按 PLAN「没有收益的路径不 native 化」,0.1.0 不包含 EIP-712 native 模块;
39
+ 若后续有真实消费者报告该路径为瓶颈,再按本文件的数据重新评估。
40
+
41
+ ## 复现
42
+
43
+ ```bash
44
+ RBENV_VERSION=4.0.6 bundle exec rake compile
45
+ RBENV_VERSION=4.0.6 bundle exec ruby benchmark/e2e_benchmark.rb
46
+ ```
@@ -0,0 +1,44 @@
1
+ # RLP 配对基准
2
+
3
+ 对照 [PLAN.md](../PLAN.md) M1/M2 的基准要求:同机同 Ruby、独立进程预热、交错采样、
4
+ 报告中位数与离散度。本文件记录测量环境与结果;数字是本机证据,不是发布宣传倍数。
5
+
6
+ ## 环境
7
+
8
+ - 2026-12-06,macOS arm64(darwin25),Ruby 4.0.6,rustc 1.99,release profile(opt-level 3, lto)
9
+ - 参考:eth 0.5.18(PLAN 固定参考版本);native:eth-native 0.1.0.pre
10
+ - 方法:`benchmark/rlp_benchmark.rb`,benchmark-ips 3s 计时 1s 预热,两后端同进程交错;
11
+ 分配数取 `GC.stat(:total_allocated_objects)` 50 次均值;sanity 检查要求两后端逐字节一致后才计时
12
+ - 原始输出:[rlp-2026-12-06.txt](rlp-2026-12-06.txt)
13
+
14
+ ## 结果摘要
15
+
16
+ | 场景 | 参考 ips | native ips | 速度 | native 分配/op(参考) |
17
+ | --- | --- | --- | --- | --- |
18
+ | encode tx (12 fields) | 35.5k | 509.7k | 14.4x | 1.4(123.5) |
19
+ | encode 1k integers | 514.8 | 11.6k | 22.5x | 1.4(11140.3) |
20
+ | encode 1k nested | 62.9 | 716.4 | 11.4x | 1.4(91094.3) |
21
+ | encode 1KiB bytes | 165.6k | 1113.1k | 6.7x | 1.4(35.3) |
22
+ | encode 64KiB bytes | 67.6k | 354.4k | 5.2x | 1.4(35.3) |
23
+ | encode batch 100 tx | 405.2 | 6838.7 | 16.9x | 1.4(12422.3) |
24
+ | decode tx (12 fields) | 146.0k | 731.5k | 5.0x | 13.4(72.3) |
25
+ | decode 1k integers | 2291.0 | 20.7k | 9.0x | 1001.4(5012.3) |
26
+ | decode 1k nested | 289.8 | 2407.7 | 8.3x | 8001.4(36247.3) |
27
+ | decode 64KiB bytes | 405.0k | 247.1k | 1.6x 慢 | 2.4(23.3) |
28
+ | decode batch 100 tx | 1637.2 | 13.5k | 8.3x | 1301.4(6912.3) |
29
+
30
+ ## 结论
31
+
32
+ - 编码全面快 6–25 倍;对象分配近乎归零(整棵树只产出 1 个结果字符串,参考实现每节点建 sedes 对象)。
33
+ - 解码快 5–9 倍;大字符串叶子用共享切片(`byteslice`),与参考 `String#[]` 语义一致。
34
+ - **已知代价**:decode 64KiB 慢约 1.8 倍——native 在边界处对输入做一次安全拷贝
35
+ (防 GC compaction 期间的借用失效),参考实现是零拷贝切片。其他场景该成本不可见。
36
+ - M0 记录的 C 原型 120–148 倍仅是可行性线索;Rust 实测倍数低于该数,符合
37
+ ARCHITECTURE「不拿原型数字做承诺」的约束。
38
+
39
+ ## 复现
40
+
41
+ ```bash
42
+ RBENV_VERSION=4.0.6 bundle exec rake compile
43
+ RBENV_VERSION=4.0.6 bundle exec ruby benchmark/rlp_benchmark.rb 3
44
+ ```
@@ -0,0 +1,15 @@
1
+ # eth-native Rust crate
2
+
3
+ This crate is compiled into `lib/eth/native/eth_native.{so,bundle,dll}` by
4
+ `rb_sys` and `rake-compiler`.
5
+
6
+ M0 exports exactly one function:
7
+
8
+ ```rust
9
+ fn native_abi_version() -> u64 { 1 }
10
+ ```
11
+
12
+ The Ruby loader compares the reported value with
13
+ `Eth::Native::NATIVE_ABI_VERSION` before marking the extension available.
14
+
15
+ RLP and ABI modules are intentionally absent until M1 and M3.
@@ -0,0 +1,267 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Eth
4
+ module Native
5
+ # Compiled-schema ABI encode/decode backed by the Rust extension.
6
+ #
7
+ # Ruby owns the authoritative `Eth::Abi::Type` parsing; {compile} turns
8
+ # parsed types into an immutable native schema that encodes and decodes
9
+ # whole payloads with a single boundary crossing. Byte-for-byte and
10
+ # error parity with eth.rb 0.5.18 is established by differential spec.
11
+ #
12
+ # Unsupported base types (real/fixed family for now) compile to a
13
+ # {RubySchema} that explicitly delegates to the reference; no silent
14
+ # approximation happens anywhere.
15
+ module Abi
16
+ # Base class for all eth-native ABI errors.
17
+ class Error < ::StandardError; end
18
+
19
+ # Raised at compile time for base types the native encoder does not
20
+ # support yet; the schema then delegates to the pure-Ruby reference.
21
+ class UnsupportedType < Error; end
22
+
23
+ # Raised for value shapes reserved for the pure-Ruby implementation
24
+ # (BigDecimal coercions); the whole call falls back explicitly.
25
+ class UnsupportedInput < Error; end
26
+
27
+ # Raised when encoding fails. Mirrors `Eth::Abi::EncodingError` with
28
+ # an identical message; remapped when eth.rb is loaded.
29
+ class EncodingError < Error; end
30
+
31
+ # Raised when decoding fails. Mirrors `Eth::Abi::DecodingError` with
32
+ # an identical message; remapped when eth.rb is loaded.
33
+ class DecodingError < Error; end
34
+
35
+ # Raised when a value is out of bounds for its type. Mirrors
36
+ # `Eth::Abi::ValueOutOfBounds`; remapped when eth.rb is loaded.
37
+ class ValueOutOfBounds < Error; end
38
+
39
+ # Raised when eth-native is disabled via ETH_NATIVE=0.
40
+ class DisabledError < Error; end
41
+
42
+ module_function
43
+
44
+ # Compiles parsed `Eth::Abi::Type` objects (or Solidity type strings)
45
+ # into a reusable schema. Compile once — e.g. at contract function
46
+ # initialization — and reuse the handle for every call.
47
+ #
48
+ # @param parsed_types [Array<Eth::Abi::Type, String>] the ABI types.
49
+ # @return [NativeSchema, RubySchema] a schema with `encode`, `decode`,
50
+ # `decode_many` and `native?`.
51
+ def compile(parsed_types)
52
+ ensure_usable!
53
+ types = parsed_types.map do |t|
54
+ if defined?(::Eth::Abi::Type) && t.is_a?(::Eth::Abi::Type)
55
+ t
56
+ elsif defined?(::Eth::Abi)
57
+ ::Eth::Abi::Type.parse(t)
58
+ else
59
+ raise UnsupportedType, "compiling type strings requires gem 'eth'"
60
+ end
61
+ end
62
+ descriptors = types.map { |t| type_descriptor(t) }
63
+ native = ::EthNativeExt.__abi_compile__(descriptors)
64
+ NativeSchema.new(native, types)
65
+ rescue UnsupportedType
66
+ RubySchema.new(types)
67
+ end
68
+
69
+ # Builds the plain-hash descriptor tree the extension expects.
70
+ def type_descriptor(type)
71
+ descriptor = { "base_type" => type.base_type, "dims" => type.dimensions }
72
+ case type.base_type
73
+ when "uint", "int", "hash"
74
+ descriptor["bits"] = type.sub_type.to_i
75
+ when "bytes"
76
+ descriptor["bits"] = type.sub_type.empty? ? 0 : type.sub_type.to_i
77
+ when "ufixed", "ureal", "fixed", "real"
78
+ # Packed::Encoder maps byte size from the high part and scaling
79
+ # from the low part.
80
+ high, low = type.sub_type.split("x").map(&:to_i)
81
+ descriptor["bits"] = high
82
+ descriptor["decimals"] = low
83
+ when "tuple"
84
+ descriptor["comps"] = type.components.map { |c| type_descriptor(c) }
85
+ descriptor["names"] = type.components.map(&:name)
86
+ end
87
+ descriptor
88
+ end
89
+
90
+ def ensure_usable!
91
+ raise DisabledError, "eth-native is disabled (ETH_NATIVE=0)" if ::Eth::Native.disabled?
92
+ end
93
+
94
+ # Encodes values in non-standard packed mode (`Eth::Abi.solidity_packed`
95
+ # parity). Type strings are parsed once per call like the reference;
96
+ # shapes the reference handles through its own string matching (inline
97
+ # tuples, Type objects, Float/BigDecimal values) fall back explicitly.
98
+ #
99
+ # @param type_strings [Array<String>] Solidity type strings.
100
+ # @param args [Array] the values, one per type.
101
+ # @return [String] the packed encoding in ASCII-8BIT.
102
+ def packed_encode(type_strings, args)
103
+ ensure_usable!
104
+ unless defined?(::Eth::Abi)
105
+ raise UnsupportedType, "packed encoding requires gem 'eth' for Type.parse"
106
+ end
107
+ unless type_strings.is_a?(Array) && type_strings.all? { |t| t.is_a?(String) } &&
108
+ type_strings.all? { |t| !t.include?("(") || t.start_with?("tuple(") }
109
+ return ::Eth::Abi.solidity_packed(type_strings, args)
110
+ end
111
+
112
+ descriptors = type_strings.map { |t| type_descriptor(::Eth::Abi::Type.parse(t)) }
113
+ ::EthNativeExt.__abi_packed_encode__(
114
+ ::EthNativeExt.__abi_packed_compile__(descriptors), args
115
+ )
116
+ rescue Abi::UnsupportedInput
117
+ if defined?(::Eth::Abi)
118
+ ::Eth::Abi.solidity_packed(type_strings, args)
119
+ else
120
+ raise
121
+ end
122
+ rescue Abi::EncodingError => e
123
+ Abi.remap(e, defined?(::Eth::Abi) ? ::Eth::Abi::EncodingError : nil)
124
+ rescue Abi::ValueOutOfBounds => e
125
+ Abi.remap(e, defined?(::Eth::Abi) ? ::Eth::Abi::ValueOutOfBounds : nil)
126
+ end
127
+
128
+ # Re-raises native errors as the eth.rb reference classes when eth.rb
129
+ # is loaded, preserving the stable message.
130
+ def remap(error, target)
131
+ target ? raise(target, error.message) : raise(error)
132
+ end
133
+
134
+ # Replicates `Abi.decode`'s input handling: `Util#hex?`-shaped input is
135
+ # unpacked (with encoding validation like the RLP path); non-String
136
+ # data raises the raw NoMethodError the reference produces when it
137
+ # dereferences `data[pos, 32]`.
138
+ def normalize_decode_data!(data)
139
+ unless data.is_a?(String)
140
+ receiver = data.nil? || data.equal?(true) || data.equal?(false) ? data.inspect : "an instance of #{data.class}"
141
+ raise NoMethodError, "undefined method '[]' for #{receiver}"
142
+ end
143
+ if data.encoding != Encoding::BINARY && !data.valid_encoding?
144
+ raise ArgumentError, "invalid byte sequence in #{data.encoding.name}"
145
+ end
146
+
147
+ hex = data.start_with?("0x", "0X") ? data.byteslice(2..) : data
148
+ if hex.match?(/\A[0-9a-fA-F]*\z/)
149
+ raise TypeError, "Value must be an instance of String" unless data.instance_of?(String)
150
+
151
+ hex = "0#{hex}" if hex.size.odd?
152
+ [hex].pack("H*")
153
+ else
154
+ data
155
+ end
156
+ end
157
+
158
+ # Schema handle whose encode/decode cross the Rust boundary.
159
+ class NativeSchema
160
+ def initialize(native, types)
161
+ @native = native
162
+ @types = types
163
+ end
164
+
165
+ # @return [Boolean] true; the schema runs natively.
166
+ def native?
167
+ true
168
+ end
169
+
170
+ # Encodes values (wrapped like `Eth::Abi.encode` wraps its args).
171
+ #
172
+ # @param args [Array] the values, one per schema type.
173
+ # @return [String] the ABI-encoded payload in ASCII-8BIT.
174
+ def encode(args)
175
+ args = [args] unless args.instance_of?(Array)
176
+ ::EthNativeExt.__abi_encode__(@native, args)
177
+ rescue Abi::UnsupportedInput => e
178
+ fallback(:encode, args, e)
179
+ rescue Abi::EncodingError => e
180
+ Abi.remap(e, defined?(::Eth::Abi) ? ::Eth::Abi::EncodingError : nil)
181
+ rescue Abi::ValueOutOfBounds => e
182
+ Abi.remap(e, defined?(::Eth::Abi) ? ::Eth::Abi::ValueOutOfBounds : nil)
183
+ end
184
+
185
+ # Decodes a payload (hex or binary, per the reference heuristic).
186
+ #
187
+ # @param data [String] the ABI-encoded payload.
188
+ # @return [Array] the decoded values.
189
+ def decode(data)
190
+ data = Abi.normalize_decode_data!(data)
191
+ ::EthNativeExt.__abi_decode__(@native, data)
192
+ rescue Abi::UnsupportedInput => e
193
+ fallback(:decode, data, e)
194
+ rescue Abi::DecodingError => e
195
+ Abi.remap(e, defined?(::Eth::Abi) ? ::Eth::Abi::DecodingError : nil)
196
+ end
197
+
198
+ # Decodes many payloads with the same compiled schema.
199
+ #
200
+ # @param payloads [Array<String>] ABI-encoded payloads.
201
+ # @return [Array<Array>] one result array per payload.
202
+ def decode_many(payloads)
203
+ normalized = payloads.map { |p| Abi.normalize_decode_data!(p) }
204
+ ::EthNativeExt.__abi_decode_many__(@native, normalized)
205
+ rescue Abi::UnsupportedInput => e
206
+ fallback(:decode_many, payloads, e)
207
+ rescue Abi::DecodingError => e
208
+ Abi.remap(e, defined?(::Eth::Abi) ? ::Eth::Abi::DecodingError : nil)
209
+ end
210
+
211
+ private
212
+
213
+ # Explicit fallback for unsupported value shapes; native-internal
214
+ # failures never reach this path. Calls the reference directly so a
215
+ # routing adapter in eth.rb cannot re-enter this module.
216
+ def fallback(method, arg, unsupported)
217
+ if defined?(::Eth::Abi)
218
+ case method
219
+ when :encode then ::Eth::Abi.encode(@types, arg)
220
+ when :decode then ::Eth::Abi.decode(@types, arg)
221
+ else
222
+ payloads = arg.map { |p| Abi.normalize_decode_data!(p) }
223
+ payloads.map { |p| ::Eth::Abi.decode(@types, p) }
224
+ end
225
+ else
226
+ raise Abi::UnsupportedInput,
227
+ "#{unsupported.message}; the pure-Ruby fallback requires gem 'eth'"
228
+ end
229
+ end
230
+ end
231
+
232
+ # Schema for base types the native encoder does not support yet.
233
+ # Everything is delegated to the pure-Ruby reference.
234
+ class RubySchema
235
+ def initialize(types)
236
+ @types = types
237
+ end
238
+
239
+ # @return [Boolean] false; the schema runs in Ruby.
240
+ def native?
241
+ false
242
+ end
243
+
244
+ def encode(args)
245
+ require_reference!
246
+ ::Eth::Abi.encode(@types, args)
247
+ end
248
+
249
+ def decode(data)
250
+ require_reference!
251
+ ::Eth::Abi.decode(@types, data)
252
+ end
253
+
254
+ def decode_many(payloads)
255
+ payloads.map { |p| decode(p) }
256
+ end
257
+
258
+ private
259
+
260
+ def require_reference!
261
+ raise UnsupportedType,
262
+ "unsupported ABI types require gem 'eth' for the pure-Ruby path" unless defined?(::Eth::Abi)
263
+ end
264
+ end
265
+ end
266
+ end
267
+ end
Binary file
@@ -0,0 +1,147 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Eth
4
+ module Native
5
+ # Whole-payload RLP encode/decode backed by the Rust extension.
6
+ #
7
+ # Byte-for-byte parity with the eth.rb 0.5.18 reference implementation
8
+ # is established by spec against the official ethereum/tests fixtures
9
+ # and differential testing. Inputs the reference implementation routes
10
+ # through custom sedes, non-Array enumerables or `Rlp::Data` are rejected
11
+ # by the native encoder with {UnsupportedInput} and delegated to the
12
+ # pure-Ruby reference; no other failure falls back.
13
+ module Rlp
14
+ # Maximum tree depth handled natively; deeper trees fall back to Ruby.
15
+ MAX_NATIVE_DEPTH = 256
16
+
17
+ # Base class for all eth-native RLP errors.
18
+ class Error < ::StandardError; end
19
+
20
+ # Raised for inputs reserved for the pure-Ruby implementation.
21
+ class UnsupportedInput < Error; end
22
+
23
+ # Raised when encoding fails. Mirrors `Eth::Rlp::EncodingError` with
24
+ # an identical message; remapped when eth.rb is loaded.
25
+ class EncodingError < Error; end
26
+
27
+ # Raised when decoding fails. Mirrors `Eth::Rlp::DecodingError` with
28
+ # an identical message; remapped when eth.rb is loaded.
29
+ class DecodingError < Error; end
30
+
31
+ # Raised when eth-native is disabled via ETH_NATIVE=0.
32
+ class DisabledError < Error; end
33
+
34
+ module_function
35
+
36
+ # Encodes a Ruby object tree of Integer, exact String and exact Array
37
+ # nodes in RLP format with a single boundary crossing.
38
+ #
39
+ # @param obj [Object] a tree of Integer, String and Array nodes.
40
+ # @return [String] the RLP-encoded item in ASCII-8BIT.
41
+ # @raise [DisabledError] when eth-native is disabled via ETH_NATIVE=0.
42
+ # @raise [Eth::Rlp::EncodingError, EncodingError] when encoding fails.
43
+ # @raise [TypeError] for inputs the reference implementation rejects,
44
+ # when the pure-Ruby fallback is loaded.
45
+ def encode(obj)
46
+ ensure_usable!
47
+ ::EthNativeExt.__rlp_encode__(obj)
48
+ rescue UnsupportedInput => e
49
+ fallback(:encode, obj, e)
50
+ rescue EncodingError => e
51
+ remap(e, defined?(::Eth::Rlp) ? ::Eth::Rlp::EncodingError : nil)
52
+ end
53
+
54
+ # Decodes an RLP-encoded item, applying the reference string semantics
55
+ # before crossing the boundary: the hex-vs-binary heuristic, its
56
+ # encoding validation, and the exact-type checks of the reference
57
+ # `Util` helpers. Returns binary strings, like the reference decoder.
58
+ #
59
+ # @param data [String] an RLP-encoded item; hex strings are unpacked.
60
+ # @return [Object] the decoded String/Array tree in ASCII-8BIT.
61
+ # @raise [DisabledError] when eth-native is disabled via ETH_NATIVE=0.
62
+ # @raise [NoMethodError] for non-String (or String-subclass, non-hex)
63
+ # input, like `Util#str_to_bytes` calling `.b` in the reference.
64
+ # @raise [ArgumentError] for non-binary strings with invalid byte
65
+ # sequences, like the reference's `Util#prefixed?`/`hex?` regexes.
66
+ # @raise [TypeError] for hex strings that are not exact String
67
+ # instances, like the reference's `Util#hex_to_bin`.
68
+ # @raise [Eth::Rlp::DecodingError, DecodingError] when decoding fails.
69
+ def decode(data)
70
+ ensure_usable!
71
+ ::EthNativeExt.__rlp_decode__(normalize_decode_input!(data))
72
+ rescue UnsupportedInput => e
73
+ fallback(:decode, data, e)
74
+ rescue DecodingError => e
75
+ remap(e, defined?(::Eth::Rlp) ? ::Eth::Rlp::DecodingError : nil)
76
+ end
77
+
78
+ # Delegates an input the native encoder marked as unsupported to the
79
+ # pure-Ruby reference implementation, so its exact semantics (custom
80
+ # sedes, other enumerables, `Rlp::Data`, negative integers, ...) are
81
+ # preserved. Native-internal failures never reach this path.
82
+ #
83
+ # Calls the reference encoder/decoder directly instead of
84
+ # `Eth::Rlp.encode/decode`: when eth.rb itself has opted in to the
85
+ # native backend, the routing methods would re-enter this module and
86
+ # recurse.
87
+ def fallback(method, arg, unsupported)
88
+ if defined?(::Eth::Rlp)
89
+ if method == :encode
90
+ ::Eth::Rlp::Encoder.perform(arg)
91
+ else
92
+ ::Eth::Rlp::Decoder.perform(arg)
93
+ end
94
+ else
95
+ raise UnsupportedInput,
96
+ "#{unsupported.message}; the pure-Ruby fallback requires gem 'eth'"
97
+ end
98
+ end
99
+
100
+ # Re-raises native errors as the eth.rb reference classes when eth.rb
101
+ # is loaded, preserving the stable message.
102
+ def remap(error, target)
103
+ target ? raise(target, error.message) : raise(error)
104
+ end
105
+
106
+ def ensure_usable!
107
+ raise DisabledError, "eth-native is disabled (ETH_NATIVE=0)" if ::Eth::Native.disabled?
108
+ end
109
+
110
+ # Replicates `Eth::Rlp::Decoder.perform`'s input handling:
111
+ #
112
+ # 1. Non-String input: `Util#str_to_bytes` calls `.b`, raising
113
+ # `NoMethodError` outside the decoder's rescue block. String
114
+ # subclasses have `.b`, so only non-Strings raise.
115
+ # 2. The `hex?` heuristic's regexes raise `ArgumentError` for invalid
116
+ # byte sequences in non-binary encodings.
117
+ # 3. Hex-shaped input goes through `Util#hex_to_bin`, which requires an
118
+ # exact `String` (`TypeError` for subclasses) and unpacks odd-length
119
+ # hex with a leading zero digit.
120
+ # 4. Non-hex input goes back through `Util#str_to_bytes`: `.b` keeps
121
+ # the bytes, so any String (exact or subclass) passes unchanged
122
+ # byte-wise.
123
+ #
124
+ # Keeping this in Ruby preserves string semantics exactly and avoids
125
+ # re-running the heuristic over already-converted binary bytes.
126
+ def normalize_decode_input!(data)
127
+ unless data.is_a?(String)
128
+ receiver = data.nil? || data.equal?(true) || data.equal?(false) ? data.inspect : "an instance of #{data.class}"
129
+ raise NoMethodError, "undefined method 'b' for #{receiver}"
130
+ end
131
+ if data.encoding != Encoding::BINARY && !data.valid_encoding?
132
+ raise ArgumentError, "invalid byte sequence in #{data.encoding.name}"
133
+ end
134
+
135
+ hex = data.start_with?("0x", "0X") ? data.byteslice(2..) : data
136
+ if hex.match?(/\A[0-9a-fA-F]*\z/)
137
+ raise TypeError, "Value must be an instance of String" unless data.instance_of?(String)
138
+
139
+ hex = "0#{hex}" if hex.size.odd?
140
+ [hex].pack("H*")
141
+ else
142
+ data
143
+ end
144
+ end
145
+ end
146
+ end
147
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Eth
4
+ module Native
5
+ VERSION = "0.1.1"
6
+ end
7
+ end
data/lib/eth/native.rb ADDED
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "native/version"
4
+ require_relative "native/rlp"
5
+ require_relative "native/abi"
6
+
7
+ module Eth
8
+ # Optional Rust native acceleration for eth.rb.
9
+ #
10
+ # Currently accelerates whole-payload RLP encode/decode; ABI acceleration
11
+ # is not implemented yet.
12
+ module Native
13
+ # Native ABI version implemented by the compiled extension.
14
+ NATIVE_ABI_VERSION = 1
15
+
16
+ # Minimum and maximum CRuby versions supported by this gem.
17
+ MINIMUM_RUBY_VERSION = "4.0.0"
18
+ MAXIMUM_RUBY_VERSION = "5.0.0"
19
+
20
+ # Raised when the compiled extension cannot be loaded or fails self-check.
21
+ class LoadError < StandardError; end
22
+
23
+ class << self
24
+ # Checks whether the current Ruby engine and version are supported.
25
+ #
26
+ # @return [Boolean] true when the runtime satisfies the gem requirements.
27
+ def ruby_version_supported?
28
+ return false unless RUBY_ENGINE == "ruby"
29
+
30
+ Gem::Requirement.new(">= #{MINIMUM_RUBY_VERSION}", "< #{MAXIMUM_RUBY_VERSION}").satisfied_by?(Gem::Version.new(RUBY_VERSION))
31
+ end
32
+
33
+ # Reports whether the native extension is loaded in this process.
34
+ #
35
+ # @return [Boolean] true when the compiled extension passed self-check.
36
+ def available?
37
+ !!@available
38
+ end
39
+
40
+ # Reports whether native acceleration is disabled by ETH_NATIVE=0.
41
+ # ETH_NATIVE=1 only expresses intent and never bypasses self-checks.
42
+ #
43
+ # @return [Boolean] true when the adapter is explicitly disabled.
44
+ def disabled?
45
+ ENV["ETH_NATIVE"] == "0"
46
+ end
47
+
48
+ # Returns the native ABI version reported by the compiled extension.
49
+ #
50
+ # @return [Integer] the native ABI version.
51
+ # @raise [LoadError] when the native extension is not loaded.
52
+ def native_abi_version
53
+ raise LoadError, "eth-native extension is not loaded" unless available?
54
+
55
+ @native_abi_version
56
+ end
57
+
58
+ # Loads and verifies the compiled extension exactly once.
59
+ #
60
+ # @return [Boolean] true when the extension passed self-check.
61
+ # @raise [LoadError] when the runtime or native ABI is unsupported.
62
+ def load_extension!
63
+ return @available if defined?(@available) && !@available.nil?
64
+
65
+ unless ruby_version_supported?
66
+ raise LoadError, "eth-native requires CRuby >= #{MINIMUM_RUBY_VERSION}, < #{MAXIMUM_RUBY_VERSION}; got #{RUBY_ENGINE} #{RUBY_VERSION}"
67
+ end
68
+
69
+ # Source gems compile the extension into the gem extension dir, while
70
+ # binary platform gems ship it under a versioned lib subdirectory that
71
+ # only the adjusted require_paths resolve.
72
+ begin
73
+ require_relative "native/eth_native"
74
+ rescue LoadError
75
+ require "eth/native/eth_native"
76
+ end
77
+
78
+ @native_abi_version = ::EthNativeExt.__native_abi_version__
79
+ unless @native_abi_version == NATIVE_ABI_VERSION
80
+ raise LoadError, "eth-native native ABI mismatch: expected #{NATIVE_ABI_VERSION}, got #{@native_abi_version}"
81
+ end
82
+
83
+ @available = true
84
+ end
85
+ end
86
+ end
87
+ end
88
+
89
+ Eth::Native.load_extension!