Merge pull request #2134 from kcalvinalvin/2024-03-07-make-duplicate-entries-on-mapslice-impossible

blockchain: fix a bug where a duplicate entry is possible in the mapslice
This commit is contained in:
Olaoluwa Osuntokun 2024-03-08 17:54:08 -08:00 committed by GitHub
commit 8ed234b9f5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 26 additions and 1 deletions

View File

@ -99,7 +99,8 @@ func (ms *mapSlice) put(op wire.OutPoint, entry *UtxoEntry, totalEntryMemory uin
ms.mtx.Lock() ms.mtx.Lock()
defer ms.mtx.Unlock() defer ms.mtx.Unlock()
for i, maxNum := range ms.maxEntries { // Look for the key in the maps.
for i := range ms.maxEntries {
m := ms.maps[i] m := ms.maps[i]
_, found := m[op] _, found := m[op]
if found { if found {
@ -107,6 +108,10 @@ func (ms *mapSlice) put(op wire.OutPoint, entry *UtxoEntry, totalEntryMemory uin
m[op] = entry m[op] = entry
return // Return as we were successful in adding the entry. return // Return as we were successful in adding the entry.
} }
}
for i, maxNum := range ms.maxEntries {
m := ms.maps[i]
if len(m) >= maxNum { if len(m) >= maxNum {
// Don't try to insert if the map already at max since // Don't try to insert if the map already at max since
// that'll force the map to allocate double the memory it's // that'll force the map to allocate double the memory it's

View File

@ -69,6 +69,26 @@ func TestMapSlice(t *testing.T) {
t.Fatalf("expected len of %d, got %d", len(m), ms.length()) t.Fatalf("expected len of %d, got %d", len(m), ms.length())
} }
// Delete the first element in the first map.
ms.delete(test.keys[0])
delete(m, test.keys[0])
// Try to insert the last element in the mapslice again.
ms.put(test.keys[len(test.keys)-1], &UtxoEntry{}, 0)
m[test.keys[len(test.keys)-1]] = &UtxoEntry{}
// Check that the duplicate didn't make it in.
if len(m) != ms.length() {
t.Fatalf("expected len of %d, got %d", len(m), ms.length())
}
ms.put(test.keys[0], &UtxoEntry{}, 0)
m[test.keys[0]] = &UtxoEntry{}
if len(m) != ms.length() {
t.Fatalf("expected len of %d, got %d", len(m), ms.length())
}
for _, key := range test.keys { for _, key := range test.keys {
expected, found := m[key] expected, found := m[key]
if !found { if !found {