WhisperSystems/RedPhone — pull request #93 by Strilanc (2013-03-12 21:23:40+00:00)
Title: Fixed wraparound bugs in SequenceCounter

SequenceCounter appeared to be breaking when the short id wrapped around. It appeared to use the xor operator where a 'raised to' was intended, and could become stuck in a bad state because 'lastPhysicalSequenceNumber' never ever decreased.

I tested with the following:

java.util.Random r = new java.util.Random();
SequenceCounter s = new SequenceCounter();
long t = 0;
for (long i = 0; i < (1L << 32); i++) {
// perturb by an amount less than half of the wraparound range
t += r.nextInt(1 << 16) - (1 << 15);
// check if converter tracks the perturbation correctly
if (s.convertNext((short)t) != t)
throw new RuntimeException("desync");
}

which ran without throwing any desync exceptions.