-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathssz.ts
1525 lines (1491 loc) · 52.1 KB
/
ssz.ts
1
2
3
4
5
6
7
8
9
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
61
62
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
135
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
190
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
231
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
278
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as P from 'micro-packed';
import { sha256 } from '@noble/hashes/sha2';
import { isBytes, isObject } from './utils.js';
/*
Simple serialize (SSZ) is the serialization method used on the Beacon Chain.
SSZ is designed to be deterministic and also to Merkleize efficiently.
SSZ can be thought of as having two components:
a serialization scheme and a Merkleization scheme
that is designed to work efficiently with the serialized data structure.
- https://github.com/ethereum/consensus-specs/blob/f5277700e3b89c4d62bd4e88a559c2b938c6b0a5/ssz/simple-serialize.md
- https://github.com/ethereum/consensus-specs/blob/f5277700e3b89c4d62bd4e88a559c2b938c6b0a5/ssz/merkle-proofs.md
- https://www.ssz.dev/show
API difference:
- containers (vec/list) have arguments like (len, child).
this is different from other SSZ library, but compatible with packed.
there is good reason to do that: it allows create anonymous structures inside:
`const t = SSZ.vector(10, SSZ.container({
...long multiline definition here...
}))`
if length is second argument it would look more complex and harder to read.
- bytes provided as bytes instead of hex strings (same as other libs)
*/
const BYTES_PER_CHUNK = 32; // Should be equal to digest size of hash
const EMPTY_CHUNK = new Uint8Array(BYTES_PER_CHUNK);
export type SSZCoder<T> = P.CoderType<T> & {
default: T;
info: { type: string };
// merkleRoot calculated differently for composite types (even if they are fixed size)
composite: boolean;
chunkCount: number;
// It is possible to create prover based on this, but we don't have one yet
chunks: (value: T) => Uint8Array[];
merkleRoot: (value: T) => Uint8Array;
_isStableCompat: (other: SSZCoder<any>) => boolean;
};
// Utils for hashing
function chunks(data: Uint8Array): Uint8Array[] {
const res = [];
for (let i = 0; i < Math.ceil(data.length / BYTES_PER_CHUNK); i++) {
const chunk = data.subarray(i * BYTES_PER_CHUNK, (i + 1) * BYTES_PER_CHUNK);
if (chunk.length === BYTES_PER_CHUNK) res.push(chunk);
else {
const tmp = EMPTY_CHUNK.slice();
tmp.set(chunk);
res.push(tmp);
}
}
return res;
}
const hash = (a: Uint8Array, b: Uint8Array): Uint8Array =>
sha256.create().update(a).update(b).digest();
const mixInLength = (root: Uint8Array, length: number) =>
hash(root, P.U256LE.encode(BigInt(length)));
// Will OOM without this, because tree padded to next power of two.
const zeroHashes = /* @__PURE__ */ (() => {
const res = [EMPTY_CHUNK];
for (let i = 0; i < 64; i++) res.push(hash(res[i], res[i]));
return res;
})();
const merkleize = (chunks: Uint8Array[], limit?: number): Uint8Array => {
let chunksLen = chunks.length;
if (limit !== undefined) {
if (limit < chunks.length) {
throw new Error(
`SSZ/merkleize: limit (${limit}) is less than the number of chunks (${chunks.length})`
);
}
chunksLen = limit;
}
// log2(next power of two), we cannot use binary ops since it can be bigger than 2**32.
const depth = Math.ceil(Math.log2(chunksLen));
if (chunks.length == 0) return zeroHashes[depth];
for (let l = 0; l < depth; l++) {
const level = [];
for (let i = 0; i < chunks.length; i += 2)
level.push(hash(chunks[i], i + 1 < chunks.length ? chunks[i + 1] : zeroHashes[l]));
chunks = level;
}
return chunks[0];
};
const checkSSZ = (o: any) => {
if (
typeof o !== 'object' ||
o === null ||
typeof o.encode !== 'function' ||
typeof o.decode !== 'function' ||
typeof o.merkleRoot !== 'function' ||
typeof o.composite !== 'boolean' ||
typeof o.chunkCount !== 'number'
) {
throw new Error(`SSZ: wrong element: ${o} (${typeof o})`);
}
};
// TODO: improve
const isStableCompat = <T>(a: SSZCoder<T>, b: SSZCoder<any>): boolean => {
if (a === b) return true; // fast path
const _a = a as any;
const _b = b as any;
if (_a.info && _b.info) {
const aI = _a.info;
const bI = _b.info;
// Bitlist[N] / Bitvector[N] field types are compatible if they share the same capacity N.
const bitTypes = ['bitList', 'bitVector'];
if (bitTypes.includes(aI.type) && bitTypes.includes(bI.type) && aI.N === bI.N) return true;
// List[T, N] / Vector[T, N] field types are compatible if T is compatible and if they also share the same capacity N.
const listTypes = ['list', 'vector'];
if (
listTypes.includes(aI.type) &&
listTypes.includes(bI.type) &&
aI.N === bI.N &&
aI.inner._isStableCompat(bI.inner)
) {
return true;
}
// Container / StableContainer[N] field types are compatible if all inner field types are compatible,
// if they also share the same field names in the same order, and for StableContainer[N] if they also
// share the same capacity N.
const contType = ['container', 'stableContainer'];
if (contType.includes(aI.type) && contType.includes(bI.type)) {
// both stable containers, but different capacity
if (aI.N !== undefined && bI.N !== undefined && aI.N !== bI.N) return false;
const kA = Object.keys(aI.fields);
const kB = Object.keys(bI.fields);
if (kA.length !== kB.length) return false;
for (let i = 0; i < kA.length; i++) {
const fA = kA[i];
const fB = kB[i];
if (fA !== fB) return false;
if (!aI.fields[fA]._isStableCompat(bI.fields[fA])) return false;
}
return true;
}
// Profile[X] field types are compatible with StableContainer types compatible with X, and
// are compatible with Profile[Y] where Y is compatible with X if also all inner field types
// are compatible. Differences solely in optionality do not affect merkleization compatibility.
if (aI.type === 'profile' || bI.type === 'profile') {
//console.log('PROF PROF?', aI.type, bI.type, aI.container._isStableCompat(bI));
if (aI.type === 'profile' && bI.type === 'stableContainer')
return aI.container._isStableCompat(b);
if (aI.type === 'stableContainer' && bI.type === 'profile')
return a._isStableCompat(bI.container);
if (aI.type === 'profile' && bI.type === 'profile')
return aI.container._isStableCompat(bI.container);
}
}
return false;
};
const basic = <T>(type: string, inner: P.CoderType<T>, def: T): SSZCoder<T> => ({
...inner,
default: def,
chunkCount: 1,
composite: false,
info: { type },
_isStableCompat(other) {
return isStableCompat(this, other);
},
chunks(value: T) {
return [this.merkleRoot(value)];
},
merkleRoot: (value: T) => {
const res = new Uint8Array(32);
res.set(inner.encode(value));
return res;
},
});
const int = (len: number, small = true) =>
P.apply(P.bigint(len, true), {
encode: (from) => {
if (!small) return from;
if (BigInt(Number(from)) !== BigInt(from))
throw new Error('ssz int: small integer is too big');
return Number(from);
},
decode: (to: bigint | number) => {
if (typeof to === 'bigint') return to;
if (typeof to !== 'number' || !Number.isSafeInteger(to))
throw new Error(`wrong type=${typeof to} expected number`);
return BigInt(to);
},
});
const _0n = BigInt(0);
export const uint8 = basic('uint8', int(1), 0);
export const uint16 = basic('uint16', int(2), 0);
export const uint32 = basic('uint32', int(4), 0);
export const uint64 = basic('uint64', int(8, false), _0n);
export const uint128 = basic('uint128', int(16, false), _0n);
export const uint256 = basic('uint256', int(32, false), _0n);
export const boolean = basic('boolean', P.bool, false);
const array = <T>(len: P.Length, inner: SSZCoder<T>): P.CoderType<T[]> => {
checkSSZ(inner);
let arr = P.array(len, inner);
// variable size arrays
if (inner.size === undefined) {
arr = P.wrap({
encodeStream: P.array(len, P.pointer(P.U32LE, inner)).encodeStream,
decodeStream: (r) => {
const res: T[] = [];
if (!r.leftBytes) return res;
const first = P.U32LE.decodeStream(r);
const len = (first - r.pos) / P.U32LE.size!;
if (!Number.isSafeInteger(len)) throw r.err('SSZ/array: wrong fixed size length');
const rest = P.array(len, P.U32LE).decodeStream(r);
const offsets = [first, ...rest];
// SSZ decoding requires very specific encoding and should throw on data constructed differently.
// There is also ZST problem here (as in ETH ABI), but it is impossible to exploit since
// definitions are hardcoded. Also, pointers very strict here.
for (let i = 0; i < offsets.length; i++) {
const pos = offsets[i];
const next = i + 1 < offsets.length ? offsets[i + 1] : r.totalBytes;
if (next < pos) throw r.err('SSZ/array: decreasing offset');
const len = next - pos;
if (r.pos !== pos) throw r.err('SSZ/array: wrong offset');
res.push(inner.decode(r.bytes(len)));
}
return res;
},
});
}
return arr;
};
type VectorType<T> = SSZCoder<T[]> & { info: { type: 'vector'; N: number; inner: SSZCoder<T> } };
/**
* Vector: fixed size ('len') array of elements 'inner'
*/
export const vector = <T>(len: number, inner: SSZCoder<T>): VectorType<T> => {
if (!Number.isSafeInteger(len) || len <= 0)
throw new Error(`SSZ/vector: wrong length=${len} (should be positive integer)`);
return {
...array(len, inner),
info: { type: 'vector', N: len, inner },
_isStableCompat(other) {
return isStableCompat(this, other);
},
default: new Array(len).fill(inner.default),
composite: true,
chunkCount: inner.composite ? Math.ceil((len * inner.size!) / 32) : len,
chunks(value) {
if (!inner.composite) return chunks(this.encode(value));
return value.map((i) => inner.merkleRoot(i));
},
merkleRoot(value) {
return merkleize(this.chunks(value));
},
};
};
type ListType<T> = SSZCoder<T[]> & { info: { type: 'list'; N: number; inner: SSZCoder<T> } };
/**
* List: dynamic array of 'inner' elements with length limit maxLen
*/
export const list = <T>(maxLen: number, inner: SSZCoder<T>): ListType<T> => {
checkSSZ(inner);
const coder = P.validate(array(null, inner), (value) => {
if (!Array.isArray(value) || value.length > maxLen)
throw new Error(`SSZ/list: wrong value=${value} (len=${value.length} maxLen=${maxLen})`);
return value;
});
return {
...coder,
info: { type: 'list', N: maxLen, inner },
_isStableCompat(other) {
return isStableCompat(this, other);
},
composite: true,
chunkCount: !inner.composite ? Math.ceil((maxLen * inner.size!) / BYTES_PER_CHUNK) : maxLen,
default: [],
chunks(value) {
if (inner.composite) return value.map((i) => inner.merkleRoot(i));
return chunks(this.encode(value));
},
merkleRoot(value) {
return mixInLength(merkleize(this.chunks(value), this.chunkCount), value.length);
},
};
};
const wrapPointer = <T>(p: P.CoderType<T>) => (p.size === undefined ? P.pointer(P.U32LE, p) : p);
const wrapRawPointer = <T>(p: P.CoderType<T>) => (p.size === undefined ? P.U32LE : p);
// TODO: improve, unclear how
const fixOffsets = (
r: P.Reader,
fields: Record<string, P.CoderType<any>>,
offsetFields: string[],
obj: Record<string, any>,
offset: number
) => {
const offsets = [];
for (const f of offsetFields) offsets.push(obj[f] + offset);
for (let i = 0; i < offsets.length; i++) {
// TODO: how to merge this with array?
const name = offsetFields[i];
const pos = offsets[i];
const next = i + 1 < offsets.length ? offsets[i + 1] : r.totalBytes;
if (next < pos) throw r.err('SSZ/container: decreasing offset');
const len = next - pos;
if (r.pos !== pos) throw r.err('SSZ/container: wrong offset');
obj[name] = fields[name].decode(r.bytes(len));
}
return obj;
};
type ContainerCoder<T extends Record<string, SSZCoder<any>>> = SSZCoder<{
[K in keyof T]: P.UnwrapCoder<T[K]>;
}> & { info: { type: 'container'; fields: T } };
/**
* Container: Encodes object with multiple fields. P.struct for SSZ.
*/
export const container = <T extends Record<string, SSZCoder<any>>>(
fields: T
): ContainerCoder<T> => {
if (!Object.keys(fields).length) throw new Error('SSZ/container: no fields');
const ptrCoder = P.struct(
Object.fromEntries(Object.entries(fields).map(([k, v]) => [k, wrapPointer(v)]))
) as ContainerCoder<T>;
const fixedCoder = P.struct(
Object.fromEntries(Object.entries(fields).map(([k, v]) => [k, wrapRawPointer(v)]))
);
const offsetFields = Object.keys(fields).filter((i) => fields[i].size === undefined);
const coder = P.wrap({
encodeStream: ptrCoder.encodeStream,
decodeStream: (r) => fixOffsets(r, fields, offsetFields, fixedCoder.decodeStream(r), 0) as any,
}) as ContainerCoder<T>;
return {
...coder,
info: { type: 'container', fields },
_isStableCompat(other) {
return isStableCompat(this, other);
},
size: offsetFields.length ? undefined : fixedCoder.size, // structure is fixed size if all fields is fixed size
default: Object.fromEntries(Object.entries(fields).map(([k, v]) => [k, v.default])) as {
[K in keyof T]: P.UnwrapCoder<T[K]>;
},
composite: true,
chunkCount: Object.keys(fields).length,
chunks(value: T) {
return Object.entries(fields).map(([k, v]) => v.merkleRoot(value[k]));
},
merkleRoot(value: T) {
return merkleize(this.chunks(value as any));
},
};
};
// Like 'P.bits', but different direction
const bitsCoder = (len: number): P.Coder<Uint8Array, boolean[]> => ({
encode: (data: Uint8Array): boolean[] => {
const res: boolean[] = [];
for (const byte of data) for (let i = 0; i < 8; i++) res.push(!!(byte & (1 << i)));
for (let i = len; i < res.length; i++) {
if (res[i]) throw new Error('SSZ/bitsCoder/encode: non-zero padding');
}
return res.slice(0, len);
},
decode: (data: boolean[]): Uint8Array => {
const res = new Uint8Array(Math.ceil(len / 8));
for (let i = 0; i < data.length; i++) if (data[i]) res[Math.floor(i / 8)] |= 1 << i % 8;
return res;
},
});
type BitVectorType = SSZCoder<boolean[]> & { info: { type: 'bitVector'; N: number } };
/**
* BitVector: array of booleans with fixed size
*/
export const bitvector = (len: number): BitVectorType => {
if (!Number.isSafeInteger(len) || len <= 0)
throw new Error(`SSZ/bitVector: wrong length=${len} (should be positive integer)`);
const bytesLen = Math.ceil(len / 8);
const coder = P.apply(P.bytes(bytesLen), bitsCoder(len));
return {
...coder,
info: { type: 'bitVector', N: len },
_isStableCompat(other) {
return isStableCompat(this, other);
},
default: new Array(len).fill(false),
composite: true,
chunkCount: Math.ceil(len / 256),
chunks(value) {
return chunks(this.encode(value));
},
merkleRoot(value: boolean[]) {
return merkleize(this.chunks(value), this.chunkCount);
},
};
};
type BitListType = SSZCoder<boolean[]> & { info: { type: 'bitList'; N: number } };
/**
* BitList: array of booleans with dynamic size (but maxLen limit)
*/
export const bitlist = (maxLen: number): BitListType => {
if (!Number.isSafeInteger(maxLen) || maxLen <= 0)
throw new Error(`SSZ/bitList: wrong max length=${maxLen} (should be positive integer)`);
let coder: P.CoderType<boolean[]> = P.wrap({
encodeStream: (w, value) => {
w.bytes(bitsCoder(value.length + 1).decode([...value, true])); // last true bit is terminator
},
decodeStream: (r) => {
const bytes = r.bytes(r.leftBytes); // use everything
if (!bytes.length || bytes[bytes.length - 1] === 0)
throw new Error('SSZ/bitlist: empty trailing byte');
const bits = bitsCoder(bytes.length * 8).encode(bytes);
const terminator = bits.lastIndexOf(true);
if (terminator === -1) throw new Error('SSZ/bitList: no terminator');
return bits.slice(0, terminator);
},
});
coder = P.validate(coder, (value) => {
if (!Array.isArray(value) || value.length > maxLen)
throw new Error(`SSZ/bitList/encode: wrong value=${value} (${typeof value})`);
return value;
});
return {
...coder,
info: { type: 'bitList', N: maxLen },
_isStableCompat(other) {
return isStableCompat(this, other);
},
size: undefined,
default: [],
chunkCount: Math.ceil(maxLen / 256),
composite: true,
chunks(value) {
const data = value.length ? bitvector(value.length).encode(value) : EMPTY_CHUNK;
return chunks(data);
},
merkleRoot(value: boolean[]) {
return mixInLength(merkleize(this.chunks(value), this.chunkCount), value.length);
},
};
};
/**
* Union type (None is null)
* */
export const union = (
...types: (SSZCoder<any> | null)[]
): SSZCoder<{ selector: number; value: any }> => {
if (types.length < 1 || types.length >= 128)
throw Error('SSZ/union: should have [1...128) types');
if (types[0] === null && types.length < 2)
throw new Error('SSZ/union: should have at least 2 types if first is null');
for (let i = 0; i < types.length; i++) {
if (i > 0 && types[i] === null) throw new Error('SSZ/union: only first type can be null');
if (types[i] !== null) checkSSZ(types[i]);
}
const coder = P.apply(
P.tag(
P.U8,
Object.fromEntries(
types.map((t, i) => [i, t === null ? P.magicBytes(P.EMPTY) : P.prefix(null, t)]) as any
)
),
{
encode: ({ TAG, data }) => ({ selector: TAG, value: data }),
decode: ({ selector, value }) => ({ TAG: selector, data: value }),
}
);
return {
...(coder as any),
size: undefined, // union is always variable size
chunkCount: NaN,
default: { selector: 0, value: types[0] === null ? null : types[0].default },
_isStableCompat(other) {
return isStableCompat(this, other);
},
composite: true,
chunks({ selector, value }) {
const type = types[selector];
if (type === null) return EMPTY_CHUNK;
return [types[selector]!.merkleRoot(value)];
},
merkleRoot: ({ selector, value }) => {
const type = types[selector];
if (type === null) return mixInLength(EMPTY_CHUNK, 0);
return mixInLength(types[selector]!.merkleRoot(value), selector);
},
};
};
type ByteListType = SSZCoder<Uint8Array> & {
info: { type: 'list'; N: number; inner: typeof byte };
};
/**
* ByteList: same as List(len, SSZ.byte), but returns Uint8Array
*/
export const bytelist = (maxLen: number): ByteListType => {
const coder = P.validate(P.bytes(null), (value) => {
if (!isBytes(value) || value.length > maxLen)
throw new Error(`SSZ/bytelist: wrong value=${value}`);
return value;
});
return {
...coder,
info: { type: 'list', N: maxLen, inner: byte },
_isStableCompat(other) {
return isStableCompat(this, other);
},
default: new Uint8Array([]),
composite: true,
chunkCount: Math.ceil(maxLen / 32),
chunks(value) {
return chunks(this.encode(value));
},
merkleRoot(value) {
return mixInLength(merkleize(this.chunks(value), this.chunkCount), value.length);
},
};
};
type ByteVectorType = SSZCoder<Uint8Array> & {
info: { type: 'vector'; N: number; inner: typeof byte };
};
/**
* ByteVector: same as Vector(len, SSZ.byte), but returns Uint8Array
*/
export const bytevector = (len: number): ByteVectorType => {
if (!Number.isSafeInteger(len) || len <= 0)
throw new Error(`SSZ/vector: wrong length=${len} (should be positive integer)`);
return {
...P.bytes(len),
info: { type: 'vector', N: len, inner: byte },
_isStableCompat(other) {
return isStableCompat(this, other);
},
default: new Uint8Array(len),
composite: true,
chunkCount: Math.ceil(len / 32),
chunks(value) {
return chunks(this.encode(value));
},
merkleRoot(value) {
return merkleize(this.chunks(value));
},
};
};
type StableContainerCoder<T extends Record<string, SSZCoder<any>>> = SSZCoder<{
[K in keyof T]?: P.UnwrapCoder<T[K]>;
}> & { info: { type: 'stableContainer'; N: number; fields: T } };
/**
* Same as container, but all values are optional using bitvector as prefix which indicates active fields
*/
export const stableContainer = <T extends Record<string, SSZCoder<any>>>(
N: number,
fields: T
): StableContainerCoder<T> => {
const fieldsNames = Object.keys(fields) as (keyof T)[];
const fieldsLen = fieldsNames.length;
if (!fieldsLen) throw new Error('SSZ/stableContainer: no fields');
if (fieldsLen > N) throw new Error('SSZ/stableContainer: more fields than N');
const bv = bitvector(N);
const coder = P.wrap({
encodeStream: (w, value) => {
const bsVal = new Array(N).fill(false);
for (let i = 0; i < fieldsLen; i++) if (value[fieldsNames[i]] !== undefined) bsVal[i] = true;
bv.encodeStream(w, bsVal);
const activeFields = fieldsNames.filter((_, i) => bsVal[i]);
const ptrCoder = P.struct(
Object.fromEntries(activeFields.map((k) => [k, wrapPointer(fields[k])]))
) as StableContainerCoder<T>;
w.bytes(ptrCoder.encode(value));
},
decodeStream: (r) => {
const bsVal = bv.decodeStream(r);
for (let i = fieldsLen; i < bsVal.length; i++) {
if (bsVal[i] !== false) throw new Error('stableContainer: non-zero padding');
}
const activeFields = fieldsNames.filter((_, i) => bsVal[i]);
const fixedCoder = P.struct(
Object.fromEntries(activeFields.map((k) => [k, wrapRawPointer(fields[k])]))
);
const offsetFields = activeFields.filter((i) => fields[i].size === undefined);
return fixOffsets(r, fields, offsetFields as any, fixedCoder.decodeStream(r), bv.size!);
},
}) as StableContainerCoder<T>;
return {
...coder,
info: { type: 'stableContainer', N, fields },
size: undefined,
default: Object.fromEntries(Object.entries(fields).map(([k, _v]) => [k, undefined])) as {
[K in keyof T]: P.UnwrapCoder<T[K]>;
},
_isStableCompat(other) {
return isStableCompat(this, other);
},
composite: true,
chunkCount: N,
chunks(value: P.UnwrapCoder<StableContainerCoder<T>>) {
const res = Object.entries(fields).map(([k, v]) =>
value[k] === undefined ? new Uint8Array(32) : v.merkleRoot(value[k])
);
while (res.length < N) res.push(new Uint8Array(32));
return res;
},
merkleRoot(value: P.UnwrapCoder<StableContainerCoder<T>>) {
const bsVal = new Array(N).fill(false);
for (let i = 0; i < fieldsLen; i++) if (value[fieldsNames[i]] !== undefined) bsVal[i] = true;
return hash(merkleize(this.chunks(value as any)), bv.merkleRoot(bsVal));
},
};
};
type ProfileCoder<
T extends Record<string, SSZCoder<any>>,
OptK extends keyof T & string,
ReqK extends keyof T & string,
> = SSZCoder<{ [K in ReqK]: P.UnwrapCoder<T[K]> } & { [K in OptK]?: P.UnwrapCoder<T[K]> }> & {
info: { type: 'profile'; container: StableContainerCoder<T> };
};
/**
* Profile - fixed subset of stableContainer.
* - fields and order of fields is exactly same as in underlying container
* - some fields may be excluded or required in profile (all fields in stable container are always optional)
* - adding new fields to underlying container won't change profile's constructed on top of it,
* because it is required to provide all list of optional fields.
* - type of field can be changed inside profile (but we should be very explicit about this) to same shape type.
*
* @example
* // class Shape(StableContainer[4]):
* // side: Optional[uint16]
* // color: Optional[uint8]
* // radius: Optional[uint16]
*
* // class Square(Profile[Shape]):
* // side: uint16
* // color: uint8
*
* // class Circle(Profile[Shape]):
* // color: uint8
* // radius: Optional[uint16]
* // ->
* const Shape = SSZ.stableContainer(4, {
* side: SSZ.uint16,
* color: SSZ.uint8,
* radius: SSZ.uint16,
* });
* const Square = profile(Shape, [], ['side', 'color']);
* const Circle = profile(Shape, ['radius'], ['color']);
* const Circle2 = profile(Shape, ['radius'], ['color'], { color: SSZ.byte });
*/
export const profile = <
T extends Record<string, SSZCoder<any>>,
OptK extends keyof T & string,
ReqK extends keyof T & string,
>(
c: StableContainerCoder<T>,
optFields: OptK[],
requiredFields: ReqK[] = [],
replaceType: Record<string, any> = {}
): ProfileCoder<T, OptK, ReqK> => {
checkSSZ(c);
if (c.info.type !== 'stableContainer') throw new Error('profile: expected stableContainer');
const containerFields: Set<string> = new Set(Object.keys(c.info.fields));
if (!Array.isArray(optFields)) throw new Error('profile: optional fields should be array');
const optFS: Set<string> = new Set(optFields);
for (const f of optFS) {
if (!containerFields.has(f)) throw new Error(`profile: unexpected optional field ${f}`);
}
if (!Array.isArray(requiredFields)) throw new Error('profile: required fields should be array');
const reqFS: Set<string> = new Set(requiredFields);
for (const f of reqFS) {
if (!containerFields.has(f)) throw new Error(`profile: unexpected required field ${f}`);
if (optFS.has(f as any as OptK))
throw new Error(`profile: field ${f} is declared both as optional and required`);
}
if (!isObject(replaceType)) throw new Error('profile: replaceType should be object');
for (const k in replaceType) {
if (!containerFields.has(k)) throw new Error(`profile/replaceType: unexpected field ${k}`);
if (!replaceType[k]._isStableCompat(c.info.fields[k]))
throw new Error(`profile/replaceType: incompatible field ${k}`);
}
// Order should be same
const allFields = Object.keys(c.info.fields).filter((i) => optFS.has(i) || reqFS.has(i));
// bv is omitted if all fields are required!
const fieldCoders = { ...c.info.fields, ...replaceType };
let coder: ProfileCoder<T, OptK, ReqK>;
if (optFS.size === 0) {
// All fields are required, it is just container, possible with size
coder = container(
Object.fromEntries(allFields.map((k) => [k, fieldCoders[k]]))
) as any as ProfileCoder<T, OptK, ReqK>;
} else {
// NOTE: we cannot merge this with stable container,
// because some fields are active and some is not (based on required/non-required)
const bv = bitvector(optFS.size);
const forFields = (fn: (f: string, optPos: number | undefined) => void) => {
let optPos = 0;
for (const f of allFields) {
const isOpt = optFS.has(f);
fn(f, isOpt ? optPos : undefined);
if (isOpt) optPos++;
}
};
coder = {
...P.wrap({
encodeStream: (w, value) => {
const bsVal = new Array(optFS.size).fill(false);
const ptrCoder: any = {};
forFields((f, optPos) => {
const val = (value as any)[f];
if (optPos !== undefined && val !== undefined) bsVal[optPos] = true;
if (optPos === undefined && val === undefined)
throw new Error(`profile.encode: empty required field ${f}`);
if (val !== undefined) ptrCoder[f] = wrapPointer(fieldCoders[f]);
});
bv.encodeStream(w, bsVal);
w.bytes(P.struct(ptrCoder).encode(value));
},
decodeStream: (r) => {
let bsVal = bv.decodeStream(r);
const fixedCoder: any = {};
const offsetFields: string[] = [];
forFields((f, optPos) => {
if (optPos !== undefined && bsVal[optPos] === false) return;
if (fieldCoders[f].size === undefined) offsetFields.push(f);
fixedCoder[f] = wrapRawPointer(fieldCoders[f]);
});
return fixOffsets(
r,
fieldCoders,
offsetFields,
P.struct(fixedCoder).decodeStream(r),
bv.size!
) as any;
},
}),
size: undefined,
} as ProfileCoder<T, OptK, ReqK>;
}
return {
...coder,
info: { type: 'profile', container: c },
default: Object.fromEntries(Array.from(reqFS).map((f) => [f, fieldCoders[f].default])) as {
[K in ReqK]: P.UnwrapCoder<T[K]>;
} & { [K in OptK]?: P.UnwrapCoder<T[K]> },
_isStableCompat(other) {
return isStableCompat(this, other);
},
composite: true,
chunkCount: c.info.N,
chunks(value: P.UnwrapCoder<ProfileCoder<T, OptK, ReqK>>) {
return c.chunks(value);
},
merkleRoot(value: P.UnwrapCoder<ProfileCoder<T, OptK, ReqK>>) {
return c.merkleRoot(value);
},
};
};
// Aliases
export const byte = uint8;
export const bit = boolean;
export const bool = boolean;
export const bytes = bytevector;
// TODO: this required for tests, but can be useful for other ETH related stuff.
// Also, blobs here. Since lib is pretty small (thanks to packed), why not?
// Deneb (last eth2 fork) types:
const MAX_VALIDATORS_PER_COMMITTEE = 2048;
const MAX_PROPOSER_SLASHINGS = 16;
const MAX_ATTESTER_SLASHINGS = 2;
const MAX_ATTESTATIONS = 128;
const MAX_DEPOSITS = 16;
const MAX_VOLUNTARY_EXITS = 16;
const MAX_TRANSACTIONS_PER_PAYLOAD = 1048576;
const BYTES_PER_LOGS_BLOOM = 256;
const MAX_EXTRA_DATA_BYTES = 32;
const DEPOSIT_CONTRACT_TREE_DEPTH = 2 ** 5;
const SYNC_COMMITTEE_SIZE = 512;
const MAX_BYTES_PER_TRANSACTION = 1073741824;
const MAX_BLS_TO_EXECUTION_CHANGES = 16;
const MAX_WITHDRAWALS_PER_PAYLOAD = 16;
const MAX_BLOB_COMMITMENTS_PER_BLOCK = 4096;
const SLOTS_PER_HISTORICAL_ROOT = 8192;
const HISTORICAL_ROOTS_LIMIT = 16777216;
const SLOTS_PER_EPOCH = 32;
const EPOCHS_PER_ETH1_VOTING_PERIOD = 64;
const VALIDATOR_REGISTRY_LIMIT = 1099511627776;
const EPOCHS_PER_HISTORICAL_VECTOR = 65536;
const EPOCHS_PER_SLASHINGS_VECTOR = 8192;
const JUSTIFICATION_BITS_LENGTH = 4;
const BYTES_PER_FIELD_ELEMENT = 32;
const FIELD_ELEMENTS_PER_BLOB = 4096;
const KZG_COMMITMENT_INCLUSION_PROOF_DEPTH = 17;
const SYNC_COMMITTEE_SUBNET_COUNT = 4;
const NEXT_SYNC_COMMITTEE_DEPTH = 5;
const BLOCK_BODY_EXECUTION_PAYLOAD_DEPTH = 4;
const FINALIZED_ROOT_DEPTH = 6;
// Electra
const MAX_COMMITTEES_PER_SLOT = 64;
const PENDING_PARTIAL_WITHDRAWALS_LIMIT = 134217728;
const PENDING_BALANCE_DEPOSITS_LIMIT = 134217728;
const PENDING_CONSOLIDATIONS_LIMIT = 262144;
const MAX_ATTESTER_SLASHINGS_ELECTRA = 1;
const MAX_ATTESTATIONS_ELECTRA = 8;
const MAX_DEPOSIT_REQUESTS_PER_PAYLOAD = 8192;
const MAX_WITHDRAWAL_REQUESTS_PER_PAYLOAD = 16;
const MAX_CONSOLIDATION_REQUESTS_PER_PAYLOAD = 1;
// We can reduce size if we inline these. But updates for new forks would be hard.
const Slot = uint64;
const Epoch = uint64;
const CommitteeIndex = uint64;
const ValidatorIndex = uint64;
const WithdrawalIndex = uint64;
const BlobIndex = uint64;
const Gwei = uint64;
const Root = bytevector(32);
const Hash32 = bytevector(32);
const Bytes32 = bytevector(32);
const Version = bytevector(4);
const DomainType = bytevector(4);
const ForkDigest = bytevector(4);
const Domain = bytevector(32);
const BLSPubkey = bytevector(48);
const KZGCommitment = bytevector(48);
const KZGProof = bytevector(48);
const BLSSignature = bytevector(96);
const Ether = uint64;
const ParticipationFlags = uint8;
const ExecutionAddress = bytevector(20);
const PayloadId = bytevector(8);
const Transaction = bytelist(MAX_BYTES_PER_TRANSACTION);
const Blob = bytevector(BYTES_PER_FIELD_ELEMENT * FIELD_ELEMENTS_PER_BLOB);
const Checkpoint = container({ epoch: Epoch, root: Root });
const AttestationData = container({
slot: Slot,
index: CommitteeIndex,
beacon_block_root: Root,
source: Checkpoint,
target: Checkpoint,
});
const Attestation = container({
aggregation_bits: bitlist(MAX_VALIDATORS_PER_COMMITTEE),
data: AttestationData,
signature: BLSSignature,
});
const AggregateAndProof = container({
aggregator_index: ValidatorIndex,
aggregate: Attestation,
selection_proof: BLSSignature,
});
const IndexedAttestation = container({
attesting_indices: list(MAX_VALIDATORS_PER_COMMITTEE, ValidatorIndex),
data: AttestationData,
signature: BLSSignature,
});
const AttesterSlashing = container({
attestation_1: IndexedAttestation,
attestation_2: IndexedAttestation,
});
const BLSToExecutionChange = container({
validator_index: ValidatorIndex,
from_bls_pubkey: BLSPubkey,
to_execution_address: ExecutionAddress,
});
const Withdrawal = container({
index: WithdrawalIndex,
validator_index: ValidatorIndex,
address: ExecutionAddress,
amount: Gwei,
});
const ExecutionPayload = container({
parent_hash: Hash32,
fee_recipient: ExecutionAddress,
state_root: Bytes32,
receipts_root: Bytes32,
logs_bloom: bytevector(BYTES_PER_LOGS_BLOOM),
prev_randao: Bytes32,
block_number: uint64,
gas_limit: uint64,
gas_used: uint64,
timestamp: uint64,
extra_data: bytelist(MAX_EXTRA_DATA_BYTES),
base_fee_per_gas: uint256,
block_hash: Hash32,
transactions: list(MAX_TRANSACTIONS_PER_PAYLOAD, Transaction),
withdrawals: list(MAX_WITHDRAWALS_PER_PAYLOAD, Withdrawal),
blob_gas_used: uint64,
excess_blob_gas: uint64,
});
MAX_WITHDRAWALS_PER_PAYLOAD;
const SigningData = container({ object_root: Root, domain: Domain });
const BeaconBlockHeader = container({
slot: Slot,
proposer_index: ValidatorIndex,
parent_root: Root,
state_root: Root,
body_root: Root,
});
const SignedBeaconBlockHeader = container({ message: BeaconBlockHeader, signature: BLSSignature });
const ProposerSlashing = container({
signed_header_1: SignedBeaconBlockHeader,
signed_header_2: SignedBeaconBlockHeader,
});
const DepositData = container({
pubkey: BLSPubkey,
withdrawal_credentials: Bytes32,
amount: Gwei,
signature: BLSSignature,
});
const Deposit = container({
proof: vector(DEPOSIT_CONTRACT_TREE_DEPTH + 1, Bytes32),
data: DepositData,
});
const VoluntaryExit = container({ epoch: Epoch, validator_index: ValidatorIndex });
const SyncAggregate = container({
sync_committee_bits: bitvector(SYNC_COMMITTEE_SIZE),
sync_committee_signature: BLSSignature,
});
const Eth1Data = container({
deposit_root: Root,
deposit_count: uint64,
block_hash: Hash32,
});
const SignedVoluntaryExit = container({ message: VoluntaryExit, signature: BLSSignature });
const SignedBLSToExecutionChange = container({
message: BLSToExecutionChange,
signature: BLSSignature,
});
const BeaconBlockBody = container({
randao_reveal: BLSSignature,
eth1_data: Eth1Data,
graffiti: Bytes32,
proposer_slashings: list(MAX_PROPOSER_SLASHINGS, ProposerSlashing),
attester_slashings: list(MAX_ATTESTER_SLASHINGS, AttesterSlashing),
attestations: list(MAX_ATTESTATIONS, Attestation),
deposits: list(MAX_DEPOSITS, Deposit),
voluntary_exits: list(MAX_VOLUNTARY_EXITS, SignedVoluntaryExit),
sync_aggregate: SyncAggregate,
execution_payload: ExecutionPayload,
bls_to_execution_changes: list(MAX_BLS_TO_EXECUTION_CHANGES, SignedBLSToExecutionChange),
blob_kzg_commitments: list(MAX_BLOB_COMMITMENTS_PER_BLOCK, KZGCommitment),
});
const BeaconBlock = container({
slot: Slot,
proposer_index: ValidatorIndex,
parent_root: Root,
state_root: Root,
body: BeaconBlockBody,
});
const SyncCommittee = container({
pubkeys: vector(SYNC_COMMITTEE_SIZE, BLSPubkey),
aggregate_pubkey: BLSPubkey,
});
const Fork = container({
previous_version: Version,
current_version: Version,
epoch: Epoch,
});
const Validator = container({
pubkey: BLSPubkey,
withdrawal_credentials: Bytes32,
effective_balance: Gwei,
slashed: boolean,
activation_eligibility_epoch: Epoch,
activation_epoch: Epoch,
exit_epoch: Epoch,
withdrawable_epoch: Epoch,
});
const ExecutionPayloadHeader = container({
parent_hash: Hash32,
fee_recipient: ExecutionAddress,
state_root: Bytes32,
receipts_root: Bytes32,
logs_bloom: bytevector(BYTES_PER_LOGS_BLOOM),
prev_randao: Bytes32,
block_number: uint64,
gas_limit: uint64,
gas_used: uint64,
timestamp: uint64,
extra_data: bytelist(MAX_EXTRA_DATA_BYTES),
base_fee_per_gas: uint256,
block_hash: Hash32,
transactions_root: Root,
withdrawals_root: Root,
blob_gas_used: uint64,
excess_blob_gas: uint64,
});
const HistoricalSummary = container({
block_summary_root: Root,
state_summary_root: Root,
});
const BeaconState = container({