@@ -1325,6 +1325,8 @@ class Peer {
13251325 }
13261326
13271327 _requestRange ( r ) {
1328+ if ( this . syncsProcessing > 0 ) return false
1329+
13281330 const { length, fork } = this . core . state
13291331
13301332 if ( r . blocks ) {
@@ -1343,31 +1345,39 @@ class Peer {
13431345 return false
13441346 }
13451347
1346- const end = Math . min ( this . core . state . length , Math . min ( r . end === - 1 ? this . remoteLength : r . end , this . remoteLength ) )
1348+ // if we can upgrade the remote, or the remote is ahead, then all the remotes blocks are valid
1349+ // otherwise truncate to the last length the remote has acked for us
1350+ const maxLocalLength = this . canUpgrade || this . remoteLength >= this . core . state . length
1351+ ? this . core . state . length
1352+ : fork === this . lastUpgradableFork ? Math . min ( this . lastUpgradableLength , this . core . state . length ) : 0
1353+
1354+ const end = Math . min ( maxLocalLength , Math . min ( r . end === - 1 ? this . remoteLength : r . end , this . remoteLength ) )
13471355 if ( end <= r . start || fork !== this . remoteFork ) return false
13481356
13491357 const len = end - r . start
13501358 const off = r . start + ( r . linear ? 0 : Math . floor ( Math . random ( ) * len ) )
13511359
13521360 let i = off
1361+ // should be way less than this, but this is worst case upper bound for the skiplist
1362+ let tries = this . inflight
13531363
1354- while ( true ) {
1364+ do {
13551365 i = this . _findNext ( i )
13561366 if ( i === - 1 || i >= end ) break
13571367
13581368 if ( this . _requestRangeBlock ( i , length ) ) return true
13591369 i ++
1360- }
1370+ } while ( tries -- > 0 )
13611371
13621372 i = r . start
13631373
1364- while ( true ) {
1374+ do {
13651375 i = this . _findNext ( i )
13661376 if ( i === - 1 || i >= off ) break
13671377
13681378 if ( this . _requestRangeBlock ( i , length ) ) return true
13691379 i ++
1370- }
1380+ } while ( tries -- > 0 )
13711381
13721382 this . _maybeWant ( r . start , len )
13731383 return false
0 commit comments