eth-compress 0.0.0-security → 0.2.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.
@@ -0,0 +1,398 @@
1
+ import { LibZip } from 'solady';
2
+
3
+ const MAX_160_BIT = (1n << 160n) - 1n;
4
+
5
+ const _normHex = (hex: string): string => hex.replace(/^0x/, '').toLowerCase();
6
+
7
+ const _hexToUint8Array = (hex: string): Uint8Array => {
8
+ const normalized = _normHex(hex);
9
+ const len = normalized.length;
10
+ const bytes = new Uint8Array(len / 2);
11
+ for (let i = 0; i < len; i += 2) {
12
+ bytes[i / 2] = Number.parseInt(normalized.slice(i, i + 2), 16);
13
+ }
14
+ return bytes;
15
+ };
16
+
17
+ const _uint8ArrayToHex = (bytes: Uint8Array): string => {
18
+ let hex = '';
19
+ for (let i = 0; i < bytes.length; i++) {
20
+ hex += bytes[i].toString(16).padStart(2, '0');
21
+ }
22
+ return hex;
23
+ };
24
+
25
+ /**
26
+ * Generates FastLZ (LZ77) decompressor bytecode. The generated code decompresses incoming calldata and forwards it to the target address.
27
+ * @param address - Target contract address
28
+ * @see {@link https://github.com/Vectorized/solady/blob/main/src/utils/LibZip.sol}
29
+ * @pure
30
+ */
31
+ //! @__PURE__
32
+ export const flzFwdBytecode = (address: string): string =>
33
+ `0x365f73${_normHex(address)}815b838110602f575f80848134865af1503d5f803e3d5ff35b803590815f1a8060051c908115609857600190600783149285831a6007018118840218600201948383011a90601f1660081b0101808603906020811860208211021890815f5b80830151818a015201858110609257505050600201019201916018565b82906075565b6001929350829150019101925f5b82811060b3575001916018565b85851060c1575b60010160a6565b936001818192355f1a878501530194905060ba56`;
34
+
35
+ /**
36
+ * Generates RLE (run-length encoded) decompressor bytecode. The generated code decompresses incoming calldata and forwards it to the target address.
37
+ * @param address - Target contract address
38
+ * @see {@link https://github.com/Vectorized/solady/blob/main/src/utils/LibZip.sol}
39
+ * @pure
40
+ */
41
+ //! @__PURE__
42
+ export const rleFwdBytecode = (address: string): string =>
43
+ `0x5f5f5b368110602d575f8083813473${_normHex(address)}5af1503d5f803e3d5ff35b600180820192909160031981019035185f1a8015604c57815301906002565b505f19815282820192607f9060031981019035185f1a818111156072575b160101906002565b838101368437606a56`;
44
+
45
+ /**
46
+ * JIT Compiles decompressor bytecode
47
+ * @param calldata - Calldata to compress
48
+ * @pure
49
+ */
50
+ //! @__PURE__
51
+ export const jitBytecode = function (calldata: string): string {
52
+ return _jitDecompressor('0x' + _normHex(calldata));
53
+ };
54
+
55
+ const _jitDecompressor = function (calldata: string): string {
56
+ const hex = _normHex(calldata);
57
+ const originalBuf = _hexToUint8Array(hex);
58
+
59
+ // Right‑align the 4‑byte selector in the first 32‑byte slot (offset 28),
60
+ // so that everything after the selector is reconstructed on mostly
61
+ // word‑aligned boundaries. This keeps the ABI words (and therefore most
62
+ // calldata reconstruction) 32‑byte aligned in memory.
63
+ // That way we avoid encoding offsets for writes (most of the time),
64
+ const padding = 28;
65
+ const buf = new Uint8Array(padding + originalBuf.length);
66
+ buf.set(originalBuf, padding);
67
+
68
+ const n = buf.length;
69
+
70
+ let ops: number[] = [];
71
+ let data: (number[] | null)[] = [];
72
+ let stack: bigint[] = [];
73
+ let stackFreq2 = new Map<bigint, number>();
74
+ let trackedMemSize = 0;
75
+ let mem = new Map<number, bigint>();
76
+ const getStackIdx = (val: bigint): number => {
77
+ const idx = stack.lastIndexOf(val);
78
+ return idx === -1 ? -1 : stack.length - 1 - idx;
79
+ };
80
+
81
+ const opFreq = new Map<number, number>();
82
+ const dataFreq = new Map<number[] | null, number>();
83
+ const stackFreq = new Map<bigint, number>();
84
+ const wordCache = new Map<string, number>();
85
+ const wordCacheCost = new Map<string, number>();
86
+ const roundUp32 = (x: number) => (x + 31) & ~31;
87
+
88
+ let pushCounter = 0;
89
+ const stackCnt = new Map<bigint, number>();
90
+
91
+ const pop2 = (): [bigint, bigint] => [stack.pop()!, stack.pop()!];
92
+ const MASK32 = (1n << 256n) - 1n;
93
+
94
+ const bump = <K>(m: Map<K, number>, k: K) => m.set(k, (m.get(k) || 0) + 1);
95
+ const pushOp = (op: number) => {
96
+ ops.push(op);
97
+ bump(opFreq, op);
98
+ };
99
+ const pushD = (d: number[] | null) => {
100
+ data.push(d || null);
101
+ bump(dataFreq, d || null);
102
+ };
103
+ const pushS = (v: bigint) => {
104
+ stack.push(v);
105
+ bump(stackFreq, v);
106
+ bump(stackFreq2, v);
107
+ ++pushCounter;
108
+ stackCnt.set(v, pushCounter);
109
+ };
110
+
111
+ const trackMem = (offset: number, size: number) => {
112
+ trackedMemSize = roundUp32(offset + size);
113
+ };
114
+
115
+ const addOp = (op: number, imm?: number[]) => {
116
+ if (op === 0x59) {
117
+ pushS(BigInt(trackedMemSize));
118
+ } else if (op === 0x1b) {
119
+ // SHL
120
+ const [shift, val] = pop2();
121
+ pushS((val << shift) & MASK32);
122
+ } else if (op === 0x17) {
123
+ // OR
124
+ const [a, b] = pop2();
125
+ pushS((a | b) & MASK32);
126
+ } else if ((op >= 0x60 && op <= 0x7f) || op === 0x5f) {
127
+ // PUSH
128
+ let v = 0n;
129
+ for (const b of imm || []) v = (v << 8n) | BigInt(b);
130
+ const idx = getStackIdx(v);
131
+ pushS(v);
132
+ if (idx !== -1 && op != 0x5f) {
133
+ if (stackFreq2.get(v)! * 2 < stackFreq.get(v)!) {
134
+ pushOp(128 + idx);
135
+ pushD(null);
136
+ }
137
+ return;
138
+ }
139
+ if (v == 224n) {
140
+ // Special‑case the literal 0xe0 (224):
141
+ // the decompressor is always deployed at 0x...00e0, so the final
142
+ // byte of ADDRESS is exactly 0xe0. Since we must send our own
143
+ // address with the eth_call anyway, we can synthesize this value
144
+ // with a single opcode instead of encoding a literal, effectively
145
+ // giving us one more hot constant slot on the stack.
146
+ pushOp(0x30); // ADDRESS
147
+ pushD(null);
148
+ return;
149
+ }
150
+ } else if (op === 0x51) {
151
+ // MLOAD
152
+ const k = Number(stack.pop()!);
153
+ pushS(mem.has(k) ? mem.get(k)! : 0n);
154
+ } else if (op === 0x52) {
155
+ // MSTORE
156
+ const [offset, value] = pop2();
157
+ const k = Number(offset);
158
+ mem.set(k, value & MASK32);
159
+ trackMem(k, 32);
160
+ } else if (op === 0x53) {
161
+ // MSTORE8
162
+ const [offset, _] = pop2();
163
+ trackMem(Number(offset), 1);
164
+ } else if (op === 0xf3) {
165
+ // RETURN
166
+ pop2();
167
+ }
168
+ pushOp(op);
169
+ pushD(imm || null);
170
+ };
171
+
172
+ const op = (opcode: number) => addOp(opcode);
173
+ const pushN = (value: number | bigint) => {
174
+ if (value > 0 && value === trackedMemSize) return addOp(0x59);
175
+ if (!value) return addOp(0x5f, undefined); // PUSH0
176
+ let v = BigInt(value);
177
+ let bytes: number[] = [];
178
+ while (v) {
179
+ bytes.unshift(Number(v & 0xffn));
180
+ v >>= 8n;
181
+ }
182
+ return addOp(0x5f + bytes.length, bytes);
183
+ };
184
+ const pushB = (buf: Uint8Array) => addOp(0x5f + buf.length, Array.from(buf));
185
+ const cntWords = (hex: string, wordHex: string) =>
186
+ (hex.match(new RegExp(wordHex, 'g')) || []).length;
187
+
188
+ // Rough cost model
189
+ const estShlCost = (seg: Array<{ s: number; e: number }>) => {
190
+ let cost = 0;
191
+ let first = true;
192
+ for (const { s, e } of seg) {
193
+ cost += 1 + e - s + 1; // PUSH segLen bytes
194
+ if (31 - e > 0) cost += 1 /* PUSH1 */ + 1 /* shift byte */ + 1 /* SHL */;
195
+ if (!first) cost += 1; // OR
196
+ first = false;
197
+ }
198
+ return cost;
199
+ };
200
+
201
+ type PlanStep =
202
+ | { t: 'num'; v: number | bigint }
203
+ | { t: 'bytes'; b: Uint8Array }
204
+ | { t: 'op'; o: number };
205
+
206
+ const plan: PlanStep[] = [];
207
+ const emitPushN = (v: number | bigint) => (plan.push({ t: 'num', v }), pushN(v));
208
+ const emitPushB = (b: Uint8Array) => (plan.push({ t: 'bytes', b }), pushB(b));
209
+ const emitOp = (o: number) => (plan.push({ t: 'op', o }), op(o));
210
+
211
+ // First pass: decide how to build each 32-byte word without emitting bytecode
212
+ for (let base = 0; base < n; base += 32) {
213
+ const word = new Uint8Array(32);
214
+ word.set(buf.slice(base, Math.min(base + 32, n)), 0);
215
+
216
+ const seg: Array<{ s: number; e: number }> = [];
217
+ for (let i = 0; i < 32; ) {
218
+ while (i < 32 && word[i] === 0) ++i;
219
+ if (i >= 32) break;
220
+ const s = i;
221
+ while (i < 32 && word[i] !== 0) ++i;
222
+ seg.push({ s, e: i - 1 });
223
+ }
224
+
225
+ if (!seg.length) continue;
226
+
227
+ const byte8s = seg.every(({ s, e }) => s === e);
228
+ if (byte8s) {
229
+ for (const { s } of seg) {
230
+ emitPushN(word[s]);
231
+ emitPushN(base + s);
232
+ emitOp(0x53); // MSTORE8
233
+ }
234
+ continue;
235
+ }
236
+
237
+ // Decide whether to build this word via SHL/OR or as a single literal word
238
+ const literal = word.slice(seg[0].s);
239
+ const literalCost = 1 + literal.length;
240
+
241
+ const baseBytes = Math.ceil(Math.log2(base + 1) / 8);
242
+ const wordHex = _uint8ArrayToHex(word);
243
+ if (literalCost > 8) {
244
+ if (wordCache.has(wordHex)) {
245
+ if (literalCost > wordCacheCost.get(wordHex)! + baseBytes) {
246
+ emitPushN(wordCache.get(wordHex)!);
247
+ emitOp(0x51);
248
+ emitPushN(base);
249
+ emitOp(0x52); // MSTORE
250
+ continue;
251
+ }
252
+ } else if (wordCacheCost.get(wordHex) != -1) {
253
+ const reuseCost = baseBytes + 3;
254
+ const freq = cntWords(hex, wordHex);
255
+ wordCacheCost.set(wordHex, freq * 32 > freq * reuseCost ? reuseCost : -1);
256
+ wordCache.set(wordHex, base);
257
+ }
258
+ }
259
+
260
+ if (literalCost <= estShlCost(seg)) {
261
+ emitPushB(literal);
262
+ } else {
263
+ let first = true;
264
+ for (const { s, e } of seg) {
265
+ const suffix0s = 31 - e;
266
+ emitPushB(word.slice(s, e + 1));
267
+ if (suffix0s > 0) {
268
+ emitPushN(suffix0s * 8);
269
+ emitOp(0x1b); // SHL
270
+ }
271
+ if (!first) emitOp(0x17); // OR
272
+ first = false;
273
+ }
274
+ }
275
+ emitPushN(base);
276
+ emitOp(0x52); // MSTORE
277
+ }
278
+
279
+ ops = [];
280
+ data = [];
281
+ stack = [];
282
+ trackedMemSize = 0;
283
+ mem = new Map();
284
+
285
+ // Pre 2nd pass. Push most frequent literals into stack.
286
+ Array.from(stackFreq.entries())
287
+ .filter(([val, freq]) => freq > 1 && val !== 0n && val !== 224n)
288
+ .filter(([val, _]) => {
289
+ return typeof val === 'number' ? val : Number(val) <= MAX_160_BIT;
290
+ })
291
+ .sort((a, b) => stackCnt.get(b[0])! - stackCnt.get(a[0])!)
292
+ .slice(0, 14)
293
+ .forEach(([val, _]) => {
294
+ pushN(val);
295
+ });
296
+
297
+ stackFreq2 = new Map();
298
+ // Second pass: emit ops and track mem/stack
299
+ for (const step of plan) {
300
+ if (step.t === 'num') pushN(step.v);
301
+ else if (step.t === 'bytes') pushB(step.b);
302
+ else if (step.t === 'op') op(step.o);
303
+ }
304
+
305
+ // CALL stack layout (top to bottom): gas, address, value, argsOffset, argsSize, retOffset, retSize
306
+ //
307
+ // Opcodes breakdown:
308
+ // - 0x5f5f: PUSH0 PUSH0 (retSize=0, retOffset=0)
309
+ // - pushN(originalBuf.length): argsSize = actual data length
310
+ // - pushN(padding): argsOffset (skip leading alignment bytes)
311
+ // - 0x34: CALLVALUE (value)
312
+ // - 0x5f35: PUSH0 CALLDATALOAD (address from calldata[0])
313
+ // - 0x5a: GAS (remaining gas)
314
+ // - 0xf1: CALL
315
+ // - 0x50: POP (discard success value)
316
+ //
317
+ // RETURNDATACOPY(destOffset=0, offset=0, length=RETURNDATASIZE):
318
+ // - 0x3d5f5f3e: RETURNDATASIZE PUSH0 PUSH0 RETURNDATACOPY
319
+ //
320
+ // RETURN(offset=0, size=RETURNDATASIZE):
321
+ // - 0x3d5ff3: RETURNDATASIZE PUSH0 RETURN
322
+
323
+ op(0x5f); // PUSH0 (retSize)
324
+ op(0x5f); // PUSH0 (retOffset)
325
+ pushN(originalBuf.length); // argsSize = actual data length
326
+ pushN(padding); // argsOffset = padding
327
+
328
+ const out: number[] = [];
329
+ for (let i = 0; i < ops.length; ++i) {
330
+ out.push(ops[i]);
331
+ if (ops[i] >= 0x60 && ops[i] <= 0x7f && data[i]) out.push(...data[i]!);
332
+ }
333
+
334
+ // - CALLVALUE, load target address from calldata[0], GAS, CALL
335
+ // - RETURNDATACOPY(0, 0, RETURNDATASIZE)
336
+ // - RETURN(0, RETURNDATASIZE)
337
+ return '0x' + _uint8ArrayToHex(new Uint8Array(out)) + '345f355af1503d5f5f3e3d5ff3';
338
+ };
339
+
340
+ const MIN_SIZE_FOR_COMPRESSION = 800;
341
+ const DECOMPRESSOR_ADDRESS = '0x00000000000000000000000000000000000000e0';
342
+
343
+ const _jit = 'jit';
344
+ const _flz = 'flz';
345
+ const _cd = 'cd';
346
+
347
+ /**
348
+ * Compresses eth_call payload using JIT, FastLZ (FLZ), or calldata RLE (CD) compression.
349
+ * Auto-selects best algorithm if not specified. Only compresses if >800 bytes and beneficial.
350
+ * @param payload - eth_call RPC payload
351
+ * @param alg - 'jit' | 'flz' | 'cd' | undefined (auto)
352
+ * @returns (un)compressed eth_call payload
353
+ * @pure
354
+ */
355
+ //! @__PURE__
356
+ export const compress_call = function (payload: any, alg?: string): any {
357
+ const rpcMethod = payload.params?.[0]?.method || payload.method;
358
+ if (rpcMethod && rpcMethod !== 'eth_call') return payload;
359
+
360
+ const hex = _normHex(payload.data || '0x');
361
+ const originalSize = (payload.data || '0x').length;
362
+ if (originalSize < MIN_SIZE_FOR_COMPRESSION) return payload;
363
+
364
+ const targetAddress = payload.to || '';
365
+ const data = '0x' + hex;
366
+
367
+ const autoSelect = !alg && originalSize < 1150;
368
+ const flz = alg === _flz || autoSelect ? LibZip.flzCompress(data) : null;
369
+ const cd = alg === _cd || autoSelect ? LibZip.cdCompress(data) : null;
370
+
371
+ const selectedMethod =
372
+ alg || (originalSize >= 1150 ? _jit : flz!.length < cd!.length ? _flz : _cd);
373
+
374
+ let bytecode: string;
375
+ let calldata: string;
376
+
377
+ if (selectedMethod === _jit) {
378
+ bytecode = _jitDecompressor(data);
379
+ calldata = '0x' + _normHex(targetAddress).padStart(64, '0');
380
+ } else {
381
+ const isFlz = selectedMethod === _flz;
382
+ calldata = isFlz ? flz! : cd!;
383
+ bytecode = isFlz ? flzFwdBytecode(targetAddress) : rleFwdBytecode(targetAddress);
384
+ }
385
+
386
+ const compressedSize = bytecode.length + calldata.length;
387
+ if (compressedSize >= originalSize) return payload;
388
+
389
+ return {
390
+ ...payload,
391
+ to: DECOMPRESSOR_ADDRESS,
392
+ data: calldata,
393
+ stateDiff: {
394
+ ...(payload.stateDiff || {}),
395
+ [DECOMPRESSOR_ADDRESS]: { code: bytecode },
396
+ },
397
+ };
398
+ };
package/package.json CHANGED
@@ -1,13 +1,134 @@
1
1
  {
2
- "name": "eth-compress",
3
- "version": "0.0.0-security",
4
- "description": "SECURITY HOLDING",
5
- "repository": { "type": "git", "url": "git+https://github.com/tadpole-labs/eth-compress.git" },
6
- "homepage": "https://github.com/tadpole-labs/eth-compress",
7
- "bugs": "https://github.com/tadpole-labs/eth-compress/issues",
8
- "license": "Apache-2.0 OR MIT",
9
- "engines": { "node": ">=22" },
10
- "files": [],
11
- "main": "index.js"
12
- }
13
-
2
+ "name": "eth-compress",
3
+ "version": "0.2.0",
4
+ "private": false,
5
+ "type": "module",
6
+ "description": "Client-to-server compression (viem-compatible) module for compressed, gas-efficient, low-latency eth_call requests.",
7
+ "keywords": [
8
+ "eth_call compress",
9
+ "compression",
10
+ "json-rpc compress",
11
+ "calldata compress",
12
+ "latency",
13
+ "viem"
14
+ ],
15
+ "bugs": "https://github.com/tadpole-labs/eth-compress/issues",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/tadpole-labs/eth-compress.git"
19
+ },
20
+ "homepage": "https://github.com/tadpole-labs/eth-compress",
21
+ "license": "Apache-2.0 OR MIT",
22
+ "main": "./_esm/index.node.js",
23
+ "types": "./_types/index.d.ts",
24
+ "typings": "./_types/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./_types/index.d.ts",
28
+ "node": {
29
+ "types": "./_types/index.d.ts",
30
+ "import": "./_esm/index.node.js",
31
+ "require": "./_cjs/index.node.cjs",
32
+ "default": "./_esm/index.node.js"
33
+ },
34
+ "browser": {
35
+ "types": "./_types/index.d.ts",
36
+ "import": "./_esm/index.js",
37
+ "require": "./_cjs/index.cjs",
38
+ "default": "./_esm/index.js"
39
+ },
40
+ "development": "./index.node.ts",
41
+ "import": "./_esm/index.node.js",
42
+ "require": "./_cjs/index.node.cjs",
43
+ "default": "./_esm/index.node.js"
44
+ },
45
+ "./compressor": {
46
+ "types": "./_types/jit-compressor.d.ts",
47
+ "development": "./jit-compressor.ts",
48
+ "import": "./_esm/jit-compressor.js",
49
+ "require": "./_cjs/jit-compressor.cjs",
50
+ "default": "./_esm/jit-compressor.js"
51
+ },
52
+ "./types": {
53
+ "types": "./_types/index.d.ts",
54
+ "default": "./_types/index.d.ts"
55
+ },
56
+ "./package.json": "./package.json"
57
+ },
58
+ "typesVersions": {
59
+ "*": {
60
+ "*": [
61
+ "./_types/*"
62
+ ],
63
+ "compressor": [
64
+ "./_types/jit-compressor.d.ts"
65
+ ],
66
+ "types": [
67
+ "./_types/index.d.ts"
68
+ ]
69
+ }
70
+ },
71
+ "files": [
72
+ "*.ts",
73
+ "*.d.ts",
74
+ "_esm/**/*.js",
75
+ "_esm/**/*.js.map",
76
+ "_cjs/**/*.cjs",
77
+ "_cjs/**/*.cjs.map",
78
+ "_types/**/*.d.ts",
79
+ "_types/**/*.d.ts.map",
80
+ "README.md",
81
+ "LICENSE"
82
+ ],
83
+ "scripts": {
84
+ "build": "pnpm run clean && bun scripts/build.ts",
85
+ "clean": "rm -rf dist *.tgz",
86
+ "test:jit": "vitest run test/jit-compress.test.ts --config test/vitest.config.ts",
87
+ "test:demo": "vitest run test/demo.test.ts --config test/vitest.config.ts",
88
+ "test": "pnpm run build && vitest run --config test/vitest.config.ts",
89
+ "lint": "biome lint .",
90
+ "lint:fix": "biome lint --write .",
91
+ "format": "biome format --write .",
92
+ "format:check": "biome format .",
93
+ "check": "biome check .",
94
+ "check:fix": "biome check --write .",
95
+ "ci:install": "pnpm install --frozen-lockfile --ignore-scripts"
96
+ },
97
+ "engines": {
98
+ "node": ">=22",
99
+ "pnpm": ">=10"
100
+ },
101
+ "packageManager": "pnpm@10.20.0",
102
+ "pnpm": {
103
+ "peerDependencyRules": {
104
+ "ignoreMissing": [
105
+ "@types/react"
106
+ ]
107
+ }
108
+ },
109
+ "dependencies": {
110
+ "solady": "0.1.26"
111
+ },
112
+ "devDependencies": {
113
+ "@biomejs/biome": "2.3.5",
114
+ "@types/bun": "1.3.2",
115
+ "@types/node": "24.10.1",
116
+ "typescript": "5.9.3",
117
+ "@ethereumjs/common": "10.1.0",
118
+ "@ethereumjs/util": "10.1.0",
119
+ "viem": "2.39.0",
120
+ "@ethereumjs/vm": "10.1.0",
121
+ "esbuild": "0.27.00",
122
+ "vitest": "4.0.9"
123
+ },
124
+ "browserslist": [
125
+ ">0.3%",
126
+ "chrome >= 80",
127
+ "edge >= 80",
128
+ "firefox >= 113",
129
+ "safari >= 16.4",
130
+ "ios_saf >= 16.4",
131
+ "not dead"
132
+ ],
133
+ "sideEffects": false
134
+ }