-
Notifications
You must be signed in to change notification settings - Fork 5
/
state_roots.go
83 lines (71 loc) · 2.12 KB
/
state_roots.go
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
package customtypes
import (
"fmt"
fssz "github.com/prysmaticlabs/fastssz"
fieldparams "github.com/theQRL/qrysm/v4/config/fieldparams"
)
var _ fssz.HashRoot = (StateRoots)([][32]byte{})
var _ fssz.Marshaler = (*StateRoots)(nil)
var _ fssz.Unmarshaler = (*StateRoots)(nil)
// StateRoots represents block roots of the beacon state.
type StateRoots [][32]byte
// HashTreeRoot returns calculated hash root.
func (r StateRoots) HashTreeRoot() ([32]byte, error) {
return fssz.HashWithDefaultHasher(r)
}
// HashTreeRootWith hashes a StateRoots object with a Hasher from the default HasherPool.
func (r StateRoots) HashTreeRootWith(hh *fssz.Hasher) error {
index := hh.Index()
for _, sRoot := range r {
hh.Append(sRoot[:])
}
hh.Merkleize(index)
return nil
}
// UnmarshalSSZ deserializes the provided bytes buffer into the StateRoots object.
func (r *StateRoots) UnmarshalSSZ(buf []byte) error {
if len(buf) != r.SizeSSZ() {
return fmt.Errorf("expected buffer of length %d received %d", r.SizeSSZ(), len(buf))
}
roots := StateRoots(make([][32]byte, fieldparams.StateRootsLength))
for i := range roots {
copy(roots[i][:], buf[i*32:(i+1)*32])
}
*r = roots
return nil
}
// MarshalSSZTo marshals StateRoots with the provided byte slice.
func (r StateRoots) MarshalSSZTo(dst []byte) ([]byte, error) {
marshalled, err := r.MarshalSSZ()
if err != nil {
return nil, err
}
return append(dst, marshalled...), nil
}
// MarshalSSZ marshals StateRoots into a serialized object.
func (r StateRoots) MarshalSSZ() ([]byte, error) {
marshalled := make([]byte, fieldparams.StateRootsLength*32)
for i, r32 := range r {
for j, rr := range r32 {
marshalled[i*32+j] = rr
}
}
return marshalled, nil
}
// SizeSSZ returns the size of the serialized object.
func (_ StateRoots) SizeSSZ() int {
return fieldparams.StateRootsLength * 32
}
// Slice converts a customtypes.StateRoots object into a 2D byte slice.
// Each item in the slice is a copy of the original item.
func (r StateRoots) Slice() [][]byte {
if r == nil {
return nil
}
sRoots := make([][]byte, len(r))
for i, root := range r {
tmp := root
sRoots[i] = tmp[:]
}
return sRoots
}