Skip to content

Commit

Permalink
Merge pull request #2134 from kcalvinalvin/2024-03-07-make-duplicate-…
Browse files Browse the repository at this point in the history
…entries-on-mapslice-impossible

blockchain: fix a bug where a duplicate entry is possible in the mapslice
  • Loading branch information
Roasbeef committed Mar 9, 2024
2 parents e63bf03 + 059a668 commit 8ed234b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
7 changes: 6 additions & 1 deletion blockchain/utxocache.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,14 +99,19 @@ func (ms *mapSlice) put(op wire.OutPoint, entry *UtxoEntry, totalEntryMemory uin
ms.mtx.Lock()
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]
_, found := m[op]
if found {
// If the key is found, overwrite it.
m[op] = 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 {
// Don't try to insert if the map already at max since
// that'll force the map to allocate double the memory it's
Expand Down
20 changes: 20 additions & 0 deletions blockchain/utxocache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,26 @@ func TestMapSlice(t *testing.T) {
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 {
expected, found := m[key]
if !found {
Expand Down

0 comments on commit 8ed234b

Please sign in to comment.