Skip to content

Commit 22541f1

Browse files
weiihanngballet
andauthored
refactor(tree): use const and type declaration (#421)
* refactor(tree): replace []byte with ExtStem []byte for stems use StemSize instead of 31 use ExtStem instead of []byte * refactor(tree): replace key/val size with const * Update tree.go * fix grammar in error message --------- Co-authored-by: Guillaume Ballet <[email protected]>
1 parent 5a8a683 commit 22541f1

14 files changed

+148
-129
lines changed

config.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,15 @@ import (
3030
)
3131

3232
const (
33+
KeySize = 32
3334
LeafValueSize = 32
3435
NodeWidth = 256
3536
NodeBitWidth byte = 8
3637
StemSize = 31
3738
)
3839

3940
func equalPaths(key1, key2 []byte) bool {
40-
return bytes.Equal(key1[:StemSize], key2[:StemSize])
41+
return bytes.Equal(KeyToStem(key1), KeyToStem(key2))
4142
}
4243

4344
// offset2key extracts the n bits of a key that correspond to the

conversion.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import (
1313

1414
// BatchNewLeafNodeData is a struct that contains the data needed to create a new leaf node.
1515
type BatchNewLeafNodeData struct {
16-
Stem []byte
16+
Stem Stem
1717
Values map[byte][]byte
1818
}
1919

debug.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ type (
3636
}
3737

3838
ExportableLeafNode struct {
39-
Stem []byte `json:"stem"`
39+
Stem Stem `json:"stem"`
4040
Values [][]byte `json:"values"`
4141

4242
C [32]byte `json:"commitment"`

empty.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ func (Empty) Commitment() *Point {
5353
return &id
5454
}
5555

56-
func (Empty) GetProofItems(keylist, NodeResolverFn) (*ProofElements, []byte, [][]byte, error) {
56+
func (Empty) GetProofItems(keylist, NodeResolverFn) (*ProofElements, []byte, []Stem, error) {
5757
return nil, nil, nil, errors.New("trying to produce a commitment for an empty subtree")
5858
}
5959

encoding.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ func parseLeafNode(serialized []byte, depth byte) (VerkleNode, error) {
9494
for i := 0; i < NodeWidth; i++ {
9595
if bit(bitlist, i) {
9696
if offset+LeafValueSize > len(serialized) {
97-
return nil, fmt.Errorf("verkle payload is too short, need at least %d and only have %d, payload = %x (%w)", offset+32, len(serialized), serialized, errSerializedPayloadTooShort)
97+
return nil, fmt.Errorf("verkle payload is too short, need at least %d and only have %d, payload = %x (%w)", offset+LeafValueSize, len(serialized), serialized, errSerializedPayloadTooShort)
9898
}
9999
values[i] = serialized[offset : offset+LeafValueSize]
100100
offset += LeafValueSize

hashednode.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ func (HashedNode) Commitment() *Point {
5858
panic("can not get commitment of a hash node")
5959
}
6060

61-
func (HashedNode) GetProofItems(keylist, NodeResolverFn) (*ProofElements, []byte, [][]byte, error) {
61+
func (HashedNode) GetProofItems(keylist, NodeResolverFn) (*ProofElements, []byte, []Stem, error) {
6262
return nil, nil, nil, errors.New("can not get the full path, and there is no proof of absence")
6363
}
6464

ipa.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -39,10 +39,10 @@ type (
3939
)
4040

4141
func FromLEBytes(fr *Fr, data []byte) error {
42-
if len(data) > 32 {
42+
if len(data) > LeafValueSize {
4343
return errors.New("data is too long")
4444
}
45-
var aligned [32]byte
45+
var aligned [LeafValueSize]byte
4646
copy(aligned[:], data)
4747
fr.SetBytesLE(aligned[:])
4848
return nil

proof_ipa.go

+32-29
Original file line numberDiff line numberDiff line change
@@ -45,16 +45,16 @@ type IPAProof struct {
4545
}
4646

4747
type VerkleProof struct {
48-
OtherStems [][31]byte `json:"otherStems"`
49-
DepthExtensionPresent []byte `json:"depthExtensionPresent"`
50-
CommitmentsByPath [][32]byte `json:"commitmentsByPath"`
51-
D [32]byte `json:"d"`
52-
IPAProof *IPAProof `json:"ipa_proof"`
48+
OtherStems [][StemSize]byte `json:"otherStems"`
49+
DepthExtensionPresent []byte `json:"depthExtensionPresent"`
50+
CommitmentsByPath [][32]byte `json:"commitmentsByPath"`
51+
D [32]byte `json:"d"`
52+
IPAProof *IPAProof `json:"ipa_proof"`
5353
}
5454

5555
func (vp *VerkleProof) Copy() *VerkleProof {
5656
ret := &VerkleProof{
57-
OtherStems: make([][31]byte, len(vp.OtherStems)),
57+
OtherStems: make([][StemSize]byte, len(vp.OtherStems)),
5858
DepthExtensionPresent: make([]byte, len(vp.DepthExtensionPresent)),
5959
CommitmentsByPath: make([][32]byte, len(vp.CommitmentsByPath)),
6060
IPAProof: &IPAProof{},
@@ -77,7 +77,7 @@ type Proof struct {
7777
Multipoint *ipa.MultiProof // multipoint argument
7878
ExtStatus []byte // the extension status of each stem
7979
Cs []*Point // commitments, sorted by their path in the tree
80-
PoaStems [][]byte // stems proving another stem is absent
80+
PoaStems []Stem // stems proving another stem is absent
8181
Keys [][]byte
8282
PreValues [][]byte
8383
PostValues [][]byte
@@ -92,7 +92,7 @@ type SuffixStateDiff struct {
9292
type SuffixStateDiffs []SuffixStateDiff
9393

9494
type StemStateDiff struct {
95-
Stem [31]byte `json:"stem"`
95+
Stem [StemSize]byte `json:"stem"`
9696
SuffixDiffs SuffixStateDiffs `json:"suffixDiffs"`
9797
}
9898

@@ -118,15 +118,15 @@ func (sd StateDiff) Copy() StateDiff {
118118
return ret
119119
}
120120

121-
func GetCommitmentsForMultiproof(root VerkleNode, keys [][]byte, resolver NodeResolverFn) (*ProofElements, []byte, [][]byte, error) {
121+
func GetCommitmentsForMultiproof(root VerkleNode, keys [][]byte, resolver NodeResolverFn) (*ProofElements, []byte, []Stem, error) {
122122
sort.Sort(keylist(keys))
123123
return root.GetProofItems(keylist(keys), resolver)
124124
}
125125

126126
// getProofElementsFromTree factors the logic that is used both in the proving and verification methods. It takes a pre-state
127127
// tree and an optional post-state tree, extracts the proof data from them and returns all the items required to build/verify
128128
// a proof.
129-
func getProofElementsFromTree(preroot, postroot VerkleNode, keys [][]byte, resolver NodeResolverFn) (*ProofElements, []byte, [][]byte, [][]byte, error) {
129+
func getProofElementsFromTree(preroot, postroot VerkleNode, keys [][]byte, resolver NodeResolverFn) (*ProofElements, []byte, []Stem, [][]byte, error) {
130130
// go-ipa won't accept no key as an input, catch this corner case
131131
// and return an empty result.
132132
if len(keys) == 0 {
@@ -228,7 +228,7 @@ func VerifyVerkleProof(proof *Proof, Cs []*Point, indices []uint8, ys []*Fr, tc
228228
// * Multipoint proof
229229
// it also returns the serialized keys and values
230230
func SerializeProof(proof *Proof) (*VerkleProof, StateDiff, error) {
231-
otherstems := make([][31]byte, len(proof.PoaStems))
231+
otherstems := make([][StemSize]byte, len(proof.PoaStems))
232232
for i, stem := range proof.PoaStems {
233233
copy(otherstems[i][:], stem)
234234
}
@@ -251,12 +251,13 @@ func SerializeProof(proof *Proof) (*VerkleProof, StateDiff, error) {
251251
var stemdiff *StemStateDiff
252252
var statediff StateDiff
253253
for i, key := range proof.Keys {
254-
if stemdiff == nil || !bytes.Equal(stemdiff.Stem[:], key[:31]) {
254+
stem := KeyToStem(key)
255+
if stemdiff == nil || !bytes.Equal(stemdiff.Stem[:], stem) {
255256
statediff = append(statediff, StemStateDiff{})
256257
stemdiff = &statediff[len(statediff)-1]
257-
copy(stemdiff.Stem[:], key[:31])
258+
copy(stemdiff.Stem[:], stem)
258259
}
259-
stemdiff.SuffixDiffs = append(stemdiff.SuffixDiffs, SuffixStateDiff{Suffix: key[31]})
260+
stemdiff.SuffixDiffs = append(stemdiff.SuffixDiffs, SuffixStateDiff{Suffix: key[StemSize]})
260261
newsd := &stemdiff.SuffixDiffs[len(stemdiff.SuffixDiffs)-1]
261262

262263
var valueLen = len(proof.PreValues[i])
@@ -302,14 +303,15 @@ func SerializeProof(proof *Proof) (*VerkleProof, StateDiff, error) {
302303
// can be used to rebuild a stateless version of the tree.
303304
func DeserializeProof(vp *VerkleProof, statediff StateDiff) (*Proof, error) {
304305
var (
305-
poaStems, keys [][]byte
306+
poaStems []Stem
307+
keys [][]byte
306308
prevalues, postvalues [][]byte
307309
extStatus []byte
308310
commitments []*Point
309311
multipoint ipa.MultiProof
310312
)
311313

312-
poaStems = make([][]byte, len(vp.OtherStems))
314+
poaStems = make([]Stem, len(vp.OtherStems))
313315
for i, poaStem := range vp.OtherStems {
314316
poaStems[i] = make([]byte, len(poaStem))
315317
copy(poaStems[i], poaStem[:])
@@ -347,8 +349,8 @@ func DeserializeProof(vp *VerkleProof, statediff StateDiff) (*Proof, error) {
347349
for _, stemdiff := range statediff {
348350
for _, suffixdiff := range stemdiff.SuffixDiffs {
349351
var k [32]byte
350-
copy(k[:31], stemdiff.Stem[:])
351-
k[31] = suffixdiff.Suffix
352+
copy(k[:StemSize], stemdiff.Stem[:])
353+
k[StemSize] = suffixdiff.Suffix
352354
keys = append(keys, k[:])
353355
if suffixdiff.CurrentValue != nil {
354356
prevalues = append(prevalues, suffixdiff.CurrentValue[:])
@@ -394,8 +396,9 @@ func PreStateTreeFromProof(proof *Proof, rootC *Point) (VerkleNode, error) { //
394396
}
395397
stems := make([][]byte, 0, len(proof.Keys))
396398
for _, k := range proof.Keys {
397-
if len(stems) == 0 || !bytes.Equal(stems[len(stems)-1], k[:31]) {
398-
stems = append(stems, k[:31])
399+
stem := KeyToStem(k)
400+
if len(stems) == 0 || !bytes.Equal(stems[len(stems)-1], stem) {
401+
stems = append(stems, stem)
399402
}
400403
}
401404
if len(stems) != len(proof.ExtStatus) {
@@ -469,10 +472,10 @@ func PreStateTreeFromProof(proof *Proof, rootC *Point) (VerkleNode, error) { //
469472
si.values = map[byte][]byte{}
470473
si.stem = stems[i]
471474
for j, k := range proof.Keys { // TODO: DoS risk, use map or binary search.
472-
if bytes.Equal(k[:31], si.stem) {
473-
si.values[k[31]] = proof.PreValues[j]
474-
si.has_c1 = si.has_c1 || (k[31] < 128)
475-
si.has_c2 = si.has_c2 || (k[31] >= 128)
475+
if bytes.Equal(KeyToStem(k), si.stem) {
476+
si.values[k[StemSize]] = proof.PreValues[j]
477+
si.has_c1 = si.has_c1 || (k[StemSize] < 128)
478+
si.has_c2 = si.has_c2 || (k[StemSize] >= 128)
476479
}
477480
}
478481
default:
@@ -501,8 +504,8 @@ func PreStateTreeFromProof(proof *Proof, rootC *Point) (VerkleNode, error) { //
501504
continue
502505
}
503506

504-
if bytes.Equal(k[:31], info[string(p)].stem) {
505-
values[k[31]] = proof.PreValues[i]
507+
if bytes.Equal(KeyToStem(k), info[string(p)].stem) {
508+
values[k[StemSize]] = proof.PreValues[i]
506509
}
507510
}
508511
comms, err = root.CreatePath(p, info[string(p)], comms, values)
@@ -535,8 +538,8 @@ func PostStateTreeFromStateDiff(preroot VerkleNode, statediff StateDiff) (Verkle
535538
}
536539

537540
if overwrites {
538-
var stem [31]byte
539-
copy(stem[:31], stemstatediff.Stem[:])
541+
var stem [StemSize]byte
542+
copy(stem[:StemSize], stemstatediff.Stem[:])
540543
if err := postroot.(*InternalNode).InsertValuesAtStem(stem[:], values, nil); err != nil {
541544
return nil, fmt.Errorf("error overwriting value in post state: %w", err)
542545
}
@@ -547,7 +550,7 @@ func PostStateTreeFromStateDiff(preroot VerkleNode, statediff StateDiff) (Verkle
547550
return postroot, nil
548551
}
549552

550-
type bytesSlice [][]byte
553+
type bytesSlice []Stem
551554

552555
func (x bytesSlice) Len() int { return len(x) }
553556
func (x bytesSlice) Less(i, j int) bool { return bytes.Compare(x[i], x[j]) < 0 }

proof_json.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ func (vp *VerkleProof) UnmarshalJSON(data []byte) error {
170170
}
171171
copy(vp.D[:], currentValueBytes)
172172

173-
vp.OtherStems = make([][31]byte, len(aux.OtherStems))
173+
vp.OtherStems = make([][StemSize]byte, len(aux.OtherStems))
174174
for i, c := range aux.OtherStems {
175175
val, err := PrefixedHexStringToBytes(c)
176176
if err != nil {

proof_test.go

+6-6
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ func TestMultiProofVerifyMultipleLeavesWithAbsentStem(t *testing.T) {
136136
const leafCount = 10
137137

138138
var keys [][]byte
139-
var absentstem [31]byte
139+
var absentstem [StemSize]byte
140140
root := New()
141141
for i := 0; i < leafCount; i++ {
142142
key := make([]byte, 32)
@@ -148,7 +148,7 @@ func TestMultiProofVerifyMultipleLeavesWithAbsentStem(t *testing.T) {
148148
keys = append(keys, key)
149149
}
150150
if i == 3 {
151-
copy(absentstem[:], key[:31])
151+
copy(absentstem[:], key[:StemSize])
152152
}
153153
}
154154
root.Commit()
@@ -610,7 +610,7 @@ func TestStemStateDiffJSONMarshalUn(t *testing.T) {
610610
t.Parallel()
611611

612612
ssd := StemStateDiff{
613-
Stem: [31]byte{10},
613+
Stem: [StemSize]byte{10},
614614
SuffixDiffs: []SuffixStateDiff{{
615615
Suffix: 0x41,
616616
CurrentValue: &[32]byte{
@@ -702,7 +702,7 @@ func TestVerkleProofMarshalUnmarshalJSON(t *testing.T) {
702702
t.Parallel()
703703

704704
vp1 := &VerkleProof{
705-
OtherStems: [][31]byte{{1}, {2}, {3}},
705+
OtherStems: [][StemSize]byte{{1}, {2}, {3}},
706706
DepthExtensionPresent: []byte{4, 5, 6},
707707
CommitmentsByPath: [][32]byte{{7}, {8}, {9}},
708708
D: [32]byte{10},
@@ -1125,7 +1125,7 @@ func TestGenerateProofWithOnlyAbsentKeys(t *testing.T) {
11251125
for i := 0; i < common.VectorLength; i++ {
11261126
var key [32]byte
11271127
copy(key[:], presentKey)
1128-
key[31] = byte(i)
1128+
key[StemSize] = byte(i)
11291129
if _, err := droot.Get(key[:], nil); err != errIsPOAStub {
11301130
t.Fatalf("expected ErrPOALeafValue, got %v", err)
11311131
}
@@ -1136,7 +1136,7 @@ func TestGenerateProofWithOnlyAbsentKeys(t *testing.T) {
11361136
for i := 0; i < common.VectorLength; i++ {
11371137
var key [32]byte
11381138
copy(key[:], presentKey)
1139-
key[31] = byte(i)
1139+
key[StemSize] = byte(i)
11401140
if err := droot.Insert(key[:], zeroKeyTest, nil); err != errIsPOAStub {
11411141
t.Fatalf("expected ErrPOALeafValue, got %v", err)
11421142
}

0 commit comments

Comments
 (0)