SparseMerkleTrie depth fix & regression tests (#11778)

This commit is contained in:
David Theodore 2022-12-15 00:50:12 -06:00 committed by GitHub
parent 1fbb3f3e51
commit 159228b34f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 37 additions and 4 deletions

View File

@ -57,8 +57,9 @@ func (m *SparseMerkleTrie) validate() error {
if m.depth >= uint(len(m.branches)) {
return errors.New("depth is greater than or equal to number of branches")
}
if m.depth >= 64 {
return errors.New("depth exceeds 64") // PowerOf2 would overflow.
if m.depth >= 63 {
return errors.New("supported merkle trie depth exceeded (max uint64 depth is 63, " +
"theoretical max sparse merkle trie depth is 64)") // PowerOf2 would overflow.
}
return nil
@ -69,6 +70,11 @@ func GenerateTrieFromItems(items [][]byte, depth uint64) (*SparseMerkleTrie, err
if len(items) == 0 {
return nil, errors.New("no items provided to generate Merkle trie")
}
if depth >= 63 {
return nil, errors.New("supported merkle trie depth exceeded (max uint64 depth is 63, " +
"theoretical max sparse merkle trie depth is 64)") // PowerOf2 would overflow
}
leaves := items
layers := make([][][]byte, depth+1)
transformedLeaves := make([][]byte, len(leaves))

View File

@ -65,9 +65,10 @@ func TestCreateTrieFromProto_Validation(t *testing.T) {
{
trie: &ethpb.SparseMerkleTrie{
Layers: genValidLayers(66),
Depth: 65,
Depth: 63,
},
errString: "depth exceeds 64",
errString: "supported merkle trie depth exceeded (max uint64 depth is 63, " +
"theoretical max sparse merkle trie depth is 64)",
},
}
for _, tt := range tests {
@ -153,6 +154,32 @@ func TestGenerateTrieFromItems_NoItemsProvided(t *testing.T) {
}
}
func TestGenerateTrieFromItems_DepthSupport(t *testing.T) {
items := [][]byte{
[]byte("A"),
[]byte("BB"),
[]byte("CCC"),
[]byte("DDDD"),
[]byte("EEEEE"),
[]byte("FFFFFF"),
[]byte("GGGGGGG"),
}
// max supported depth is 62 (uint64 will overflow above this)
// max theoretical depth is 64
var max_supported_trie_depth uint64 = 62
// Supported depth
m1, err := trie.GenerateTrieFromItems(items, max_supported_trie_depth)
require.NoError(t, err)
proof, err := m1.MerkleProof(2)
require.NoError(t, err)
require.Equal(t, len(proof), int(max_supported_trie_depth)+1)
// Unsupported depth
_, err = trie.GenerateTrieFromItems(items, max_supported_trie_depth+1)
errString := "supported merkle trie depth exceeded (max uint64 depth is 63, " +
"theoretical max sparse merkle trie depth is 64)"
require.ErrorContains(t, errString, err)
}
func TestMerkleTrie_VerifyMerkleProofWithDepth(t *testing.T) {
items := [][]byte{
[]byte("A"),