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 deadlock due to incorrect mutex #91

Merged
merged 8 commits into from
Oct 24, 2022
Merged
Changes from all commits
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
28 changes: 23 additions & 5 deletions types/btccache.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,25 @@ func (b *BTCCache) Init(ibs []*IndexedBlock) error {
return ErrTooManyEntries
}
for _, ib := range ibs {
if err := b.Add(ib); err != nil {
if err := b.add(ib); err != nil {
return err
}
}

return b.reverse()
}

// Add adds a new block to the cache. Thread-safe.
func (b *BTCCache) Add(ib *IndexedBlock) error {
b.Lock()
defer b.Unlock()

if b.Size() >= b.maxEntries {
return b.add(ib)
}

// Thread-unsafe version of Add
func (b *BTCCache) add(ib *IndexedBlock) error {
if b.size() >= b.maxEntries {
b.blocks = b.blocks[1:]
}

Expand All @@ -56,7 +62,7 @@ func (b *BTCCache) Tip() (*IndexedBlock, error) {
b.RLock()
defer b.RUnlock()

if b.Size() == 0 {
if b.size() == 0 {
return nil, ErrEmptyCache
}

Expand All @@ -68,25 +74,37 @@ func (b *BTCCache) RemoveLast() error {
b.Lock()
defer b.Unlock()

if b.Size() == 0 {
if b.size() == 0 {
return ErrEmptyCache
}

b.blocks = b.blocks[:len(b.blocks)-1]
return nil
}

// Size returns the size of the cache. Thread-safe.
func (b *BTCCache) Size() uint64 {
b.RLock()
defer b.RUnlock()

return b.size()
}

// thread-unsafe version of Size
func (b *BTCCache) size() uint64 {
return uint64(len(b.blocks))
}

func (b *BTCCache) reverse() error {
// Reverse reverses the order of blocks in cache in place. Thread-safe.
func (b *BTCCache) Reverse() error {
b.Lock()
defer b.Unlock()

Copy link
Member

Choose a reason for hiding this comment

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

Ditto, you can just do

	return b.reverse()

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

fixed

return b.reverse()
}

// thread-unsafe version of Reverse
func (b *BTCCache) reverse() error {
for i, j := 0, len(b.blocks)-1; i < j; i, j = i+1, j-1 {
b.blocks[i], b.blocks[j] = b.blocks[j], b.blocks[i]
}
Expand Down