Skip to content

Commit 7886318

Browse files
authored
fix(trie): Panic when deleting nonexistent keys from trie (GSR-10) (#2609)
* add check for common key length * add test case for nonexistent key
1 parent 1fa1c65 commit 7886318

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

lib/trie/trie.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -969,6 +969,10 @@ func (t *Trie) deleteBranch(branch *Node, key []byte) (
969969
}
970970

971971
commonPrefixLength := lenCommonPrefix(branch.Key, key)
972+
keyDoesNotExist := commonPrefixLength == len(key)
973+
if keyDoesNotExist {
974+
return branch, false, 0
975+
}
972976
childIndex := key[commonPrefixLength]
973977
childKey := key[commonPrefixLength+1:]
974978
child := branch.Children[childIndex]

lib/trie/trie_test.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3573,6 +3573,40 @@ func Test_Trie_delete(t *testing.T) {
35733573
},
35743574
updated: true,
35753575
},
3576+
"handle nonexistent key (no op)": {
3577+
trie: Trie{
3578+
generation: 1,
3579+
},
3580+
parent: &Node{
3581+
Key: []byte{1, 0, 2, 3},
3582+
Descendants: 1,
3583+
Children: padRightChildren([]*Node{
3584+
{ // full key 1, 0, 2
3585+
Key: []byte{2},
3586+
Value: []byte{1},
3587+
},
3588+
{ // full key 1, 1, 2
3589+
Key: []byte{2},
3590+
Value: []byte{2},
3591+
},
3592+
}),
3593+
},
3594+
key: []byte{1, 0, 2},
3595+
newParent: &Node{
3596+
Key: []byte{1, 0, 2, 3},
3597+
Descendants: 1,
3598+
Children: padRightChildren([]*Node{
3599+
{ // full key 1, 0, 2
3600+
Key: []byte{2},
3601+
Value: []byte{1},
3602+
},
3603+
{ // full key 1, 1, 2
3604+
Key: []byte{2},
3605+
Value: []byte{2},
3606+
},
3607+
}),
3608+
},
3609+
},
35763610
}
35773611

35783612
for name, testCase := range testCases {

0 commit comments

Comments
 (0)