Skip to content

Commit

Permalink
fix(trie): Panic when deleting nonexistent keys from trie (GSR-10) (#…
Browse files Browse the repository at this point in the history
…2609)

* add check for common key length

* add test case for nonexistent key
  • Loading branch information
edwardmack committed Jun 20, 2022
1 parent 1fa1c65 commit 7886318
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/trie/trie.go
Original file line number Diff line number Diff line change
Expand Up @@ -969,6 +969,10 @@ func (t *Trie) deleteBranch(branch *Node, key []byte) (
}

commonPrefixLength := lenCommonPrefix(branch.Key, key)
keyDoesNotExist := commonPrefixLength == len(key)
if keyDoesNotExist {
return branch, false, 0
}
childIndex := key[commonPrefixLength]
childKey := key[commonPrefixLength+1:]
child := branch.Children[childIndex]
Expand Down
34 changes: 34 additions & 0 deletions lib/trie/trie_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3573,6 +3573,40 @@ func Test_Trie_delete(t *testing.T) {
},
updated: true,
},
"handle nonexistent key (no op)": {
trie: Trie{
generation: 1,
},
parent: &Node{
Key: []byte{1, 0, 2, 3},
Descendants: 1,
Children: padRightChildren([]*Node{
{ // full key 1, 0, 2
Key: []byte{2},
Value: []byte{1},
},
{ // full key 1, 1, 2
Key: []byte{2},
Value: []byte{2},
},
}),
},
key: []byte{1, 0, 2},
newParent: &Node{
Key: []byte{1, 0, 2, 3},
Descendants: 1,
Children: padRightChildren([]*Node{
{ // full key 1, 0, 2
Key: []byte{2},
Value: []byte{1},
},
{ // full key 1, 1, 2
Key: []byte{2},
Value: []byte{2},
},
}),
},
},
}

for name, testCase := range testCases {
Expand Down

0 comments on commit 7886318

Please sign in to comment.