diff --git a/blocksync/blocksync.go b/blocksync/blocksync.go index 9ba3988cff..f02f7e5ded 100644 --- a/blocksync/blocksync.go +++ b/blocksync/blocksync.go @@ -199,13 +199,14 @@ func (bs *blockSyncer) ProcessBlock(ctx context.Context, peer string, blk *block } tip := bs.tipHeightHandler() - if !bs.buf.AddBlock(tip, newPeerBlock(peer, blk)) { - return nil - } + added, targetHeight := bs.buf.AddBlock(tip, newPeerBlock(peer, blk)) bs.mu.Lock() defer bs.mu.Unlock() - if blk.Height() > bs.targetHeight { - bs.targetHeight = blk.Height() + if targetHeight > bs.targetHeight { + bs.targetHeight = targetHeight + } + if !added { + return nil } syncedHeight := tip for { diff --git a/blocksync/buffer.go b/blocksync/buffer.go index 03c800eaff..76cba05127 100644 --- a/blocksync/buffer.go +++ b/blocksync/buffer.go @@ -66,18 +66,21 @@ func (b *blockBuffer) Cleanup(height uint64) { } // AddBlock tries to put given block into buffer and flush buffer into blockchain. -func (b *blockBuffer) AddBlock(tipHeight uint64, blk *peerBlock) bool { +func (b *blockBuffer) AddBlock(tipHeight uint64, blk *peerBlock) (bool, uint64) { b.mu.Lock() defer b.mu.Unlock() blkHeight := blk.block.Height() - if blkHeight > tipHeight && blkHeight <= tipHeight+b.bufferSize { - if _, ok := b.blockQueues[blkHeight]; !ok { - b.blockQueues[blkHeight] = newUniQueue() - } - b.blockQueues[blkHeight].enque(blk) - return true + if blkHeight <= tipHeight { + return false, 0 + } + if blkHeight > tipHeight+b.bufferSize { + return false, tipHeight + b.bufferSize + } + if _, ok := b.blockQueues[blkHeight]; !ok { + b.blockQueues[blkHeight] = newUniQueue() } - return false + b.blockQueues[blkHeight].enque(blk) + return true, blkHeight } // GetBlocksIntervalsToSync returns groups of syncBlocksInterval are missing upto targetHeight.