forked from ferranbt/fastssz
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhash.go
More file actions
executable file
·276 lines (249 loc) · 7.32 KB
/
Copy pathhash.go
File metadata and controls
executable file
·276 lines (249 loc) · 7.32 KB
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
package generator
import (
"fmt"
"strings"
)
// hashTreeRoot creates a function that SSZ hashes the structs,
func (e *env) hashTreeRoot(name string, v *Value) string {
tmpl := `// HashTreeRoot ssz hashes the {{.name}} object
func (:: *{{.name}}) HashTreeRoot() ([32]byte, error) {
return ssz.HashWithDefaultHasher(::)
}
// HashTreeRootWith ssz hashes the {{.name}} object with a hasher
func (:: *{{.name}}) HashTreeRootWith(hh ssz.HashWalker) (err error) {
{{.hashTreeRoot}}
return
}`
data := map[string]interface{}{
"name": name,
"hashTreeRoot": v.hashTreeRootContainer(true),
}
str := execTmpl(tmpl, data)
return appendObjSignature(str, v)
}
func (v *Value) hashRoots(isList bool, elem Type) string {
subName := "i"
if v.e.c {
subName += "[:]"
}
inner := ""
if !v.e.c && elem == TypeBytes {
inner = `if len(i) != %d {
err = ssz.ErrBytesLength
return
}
`
inner = fmt.Sprintf(inner, v.e.s)
}
var appendFn string
var elemSize uint64
if elem == TypeBytes {
// [][]byte
if v.e.s != 32 {
// we need to use PutBytes in order to hash the result since
// is higher than 32 bytes
appendFn = "PutBytes"
elemSize = v.e.s
} else {
appendFn = "Append"
elemSize = 32
}
} else {
// []uint64
appendFn = "Append" + uintVToName(v.e)
elemSize = uint64(v.e.fixedSize())
}
var merkleize string
if isList {
// the limit for merkleize with mixin depends on the internal type
// if the type is basic, the size depends on CalculateLimit
// if the type is complex (TypeVector), the limit is the size.
// TODO: Generalize a list of complex objects
isComplex := false
if v.e.t == TypeBytes {
// TypeVector alias
isComplex = true
}
tmpl := `numItems := uint64(len(::.{{.name}}))
hh.MerkleizeWithMixin(subIndx, numItems, {{if .isComplex}} {{.listSize}} {{ else }} ssz.CalculateLimit({{.listSize}}, numItems, {{.elemSize}}) {{ end }})`
merkleize = execTmpl(tmpl, map[string]interface{}{
"name": v.name,
"listSize": v.s,
"elemSize": elemSize,
"isComplex": isComplex,
})
// when doing []uint64 we need to round up the Hasher bytes to 32
if elem == TypeUint {
merkleize = "hh.FillUpTo32()\n" + merkleize
}
} else {
merkleize = "hh.Merkleize(subIndx)"
}
tmpl := `{
{{.outer}}subIndx := hh.Index()
for _, i := range ::.{{.name}} {
{{.inner}}hh.{{.appendFn}}({{.subName}})
}
{{.merkleize}}
}`
return execTmpl(tmpl, map[string]interface{}{
"outer": v.validate(),
"inner": inner,
"name": v.name,
"subName": subName,
"appendFn": appendFn,
"merkleize": merkleize,
})
}
// takes a "name" param so that the variable name can be replaced with a local name
// ie within a for loop for a list, the we want to refer to "elem" w/o a receiver variable
// when not specified, name will be set to "::." + v.name. In the final templating pass,
// the output formatter replaces all instances of "::" with the receiver variable for the container.
// appendBytes is a control variable which changes the fastssz.Hasher method used to handle byte slices
// when it is false, the default behavior is to call PutBytes, which merkleizes the buffer after appending
// the bytes. when true, the generated code calls AppendBytes32, which appends the bytes to the buffer
// with padding and leaves the merkleization for a following step. This is because in the case of ByteLists,
// the length of the list needs to be mixed in as part of the merkleization process, which happens in a separate
// call to MerkleizeWithMixin.
func (v *Value) hashTreeRoot(name string, appendBytes bool) string {
if name == "" {
name = "::." + v.name
}
switch v.t {
case TypeContainer, TypeReference:
return v.hashTreeRootContainer(false)
case TypeBytes:
if v.c {
name += "[:]"
}
if v.isFixed() {
tmpl := `{{.validate}}hh.PutBytes({{.name}})`
return execTmpl(tmpl, map[string]interface{}{
"validate": v.validate(),
"name": name,
"size": v.s,
})
} else {
// dynamic bytes require special handling, need length mixed in
hMethod := "Append"
if appendBytes {
hMethod = "AppendBytes32"
}
tmpl := `{
elemIndx := hh.Index()
byteLen := uint64(len({{.name}}))
if byteLen > {{.maxLen}} {
err = ssz.ErrIncorrectListSize
return
}
hh.{{.hashMethod}}({{.name}})
hh.MerkleizeWithMixin(elemIndx, byteLen, ({{.maxLen}}+31)/32)
}`
return execTmpl(tmpl, map[string]interface{}{
"hashMethod": hMethod,
"name": name,
"maxLen": v.m,
})
}
case TypeUint:
if v.ref != "" || v.obj != "" {
// alias to Uint64
name = fmt.Sprintf("uint64(%s)", name)
}
bitLen := v.fixedSize() * 8
return fmt.Sprintf("hh.PutUint%d(%s)", bitLen, name)
case TypeBitList:
tmpl := `if len({{.name}}) == 0 {
err = ssz.ErrEmptyBitlist
return
}
hh.PutBitlist({{.name}}, {{.size}})
`
return execTmpl(tmpl, map[string]interface{}{
"name": name,
"size": v.m,
})
case TypeBool:
return fmt.Sprintf("hh.PutBool(%s)", name)
case TypeVector:
return v.hashRoots(false, v.e.t)
case TypeList:
if v.e.isFixed() {
if v.e.t == TypeUint || v.e.t == TypeBytes {
return v.hashRoots(true, v.e.t)
}
}
tmpl := `{
subIndx := hh.Index()
num := uint64(len({{.name}}))
if num > {{.num}} {
err = ssz.ErrIncorrectListSize
return
}
for _, elem := range {{.name}} {
{{.htrCall}}
}
hh.MerkleizeWithMixin(subIndx, num, {{.num}})
}`
var htrCall string
if v.e.t == TypeBytes {
eName := "elem"
// ByteLists should be represented as Value with TypeBytes and .m set instead of .s (isFixed == true)
htrCall = v.e.hashTreeRoot(eName, true)
} else {
htrCall = execTmpl(`if err = elem.HashTreeRootWith(hh); err != nil {
return
}`,
map[string]interface{}{"name": name})
}
return execTmpl(tmpl, map[string]interface{}{
"name": name,
"num": v.m,
"htrCall": htrCall,
})
case TypeTime:
return fmt.Sprintf("hh.PutUint64(uint64(%s.Unix()))", name)
default:
panic(fmt.Errorf("hash not implemented for type %s", v.t.String()))
}
}
func (v *Value) hashTreeRootContainer(start bool) string {
if !start {
tmpl := `{{ if .check }}if ::.{{.name}} == nil {
::.{{.name}} = new({{.obj}})
}
{{ end }}if err = ::.{{.name}}.HashTreeRootWith(hh); err != nil {
return
}`
// validate only for fixed structs
check := v.isFixed()
if v.isListElem() {
check = false
}
if v.noPtr {
check = false
}
return execTmpl(tmpl, map[string]interface{}{
"name": v.name,
"obj": v.objRef(),
"check": check,
})
}
out := []string{}
for indx, i := range v.o {
// the call to hashTreeRoot below is ugly because it's currently hacked to support ByteLists
// the first argument allows the element name to be overriden when calling .HashTreeRoot on it
// used to specify the name "elem" when called as part of a for loop iteration. when the string
// is empty, it defaults to the .name parameter of the value
// the second field tells the code generator to specifically generate a call to AppendBytes32
// this is used by List[List[byte, N]] so that lists of lists of bytes are not double-merkleized.
str := fmt.Sprintf("// Field (%d) '%s'\n%s\n", indx, i.name, i.hashTreeRoot("", false))
out = append(out, str)
}
tmpl := `indx := hh.Index()
{{.fields}}
hh.Merkleize(indx)`
return execTmpl(tmpl, map[string]interface{}{
"fields": strings.Join(out, "\n"),
})
}