Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fix potential memory leak in BTCCache #160

Merged
merged 3 commits into from
Mar 8, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion types/btccache.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ func (b *BTCCache) Add(ib *IndexedBlock) {
// Thread-unsafe version of Add
func (b *BTCCache) add(ib *IndexedBlock) {
if b.size() >= b.maxEntries {
// dereference the 0-th block to ensure it will be garbage-collected
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given that the above checks b.size() >= b.maxEntries, there's a case in which we need to remove more than only one element to have b.maxEntries elements. I know this case can't appear in the current code, but since we have such condition, we should handle it properly. Otherwise, if we're sure that the case b.size() > b.maxEntries can't happen, we should panic in this case and handle the below using a condition b.size() == b.maxEntries

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agree, I'm inclined to panic when b.size() > b.maxEntries since BTC cache does not support adding multiple elements at the same time

// see https://stackoverflow.com/questions/55045402/memory-leak-in-golang-slice
b.blocks[0] = nil
b.blocks = b.blocks[1:]
}

Expand All @@ -85,6 +88,8 @@ func (b *BTCCache) RemoveLast() error {
return ErrEmptyCache
}

// dereference the last block to ensure it will be garbage-collected
b.blocks[len(b.blocks)-1] = nil
b.blocks = b.blocks[:len(b.blocks)-1]
return nil
}
Expand All @@ -94,7 +99,7 @@ func (b *BTCCache) RemoveAll() {
b.Lock()
defer b.Unlock()

b.blocks = b.blocks[:0]
b.blocks = []*IndexedBlock{}
}

// Size returns the size of the cache. Thread-safe.
Expand Down Expand Up @@ -210,5 +215,10 @@ func (b *BTCCache) Trim() {
return
}

// dereference b.blocks[:len(b.blocks)-int(b.maxEntries)] to ensure they will be garbage-collected
for i := range b.blocks[:len(b.blocks)-int(b.maxEntries)] {
b.blocks[i] = nil
}

b.blocks = b.blocks[len(b.blocks)-int(b.maxEntries):]
}