Test and fix anti-replay functions
diff --git a/library/ssl_tls.c b/library/ssl_tls.c
index 31be3ca..d48ccf5 100644
--- a/library/ssl_tls.c
+++ b/library/ssl_tls.c
@@ -2697,10 +2697,12 @@
 /*
  * DTLS anti-replay: RFC 6347 4.1.2.6
  *
- * - in_window_top is the highest record sequence number seen
- * - the lsb of in_window is set iff in_window_top - 1 has been seen
- *   ...
- *   the msb of in_window is set iff in_window_top - 64 has been seen
+ * in_window is a field of bits numbered from 0 (lsb) to 63 (msb).
+ * Bit n is set iff record number in_window_top - n has been seen.
+ *
+ * Usually, in_window_top is the last record number seen and the lsb of
+ * in_window is set. The only exception is the initial state (record number 0
+ * not seen yet).
  */
 #if defined(POLARSSL_SSL_DTLS_ANTI_REPLAY)
 static void ssl_dtls_replay_reset( ssl_context *ssl )
@@ -2730,10 +2732,7 @@
     if( rec_seqnum > ssl->in_window_top )
         return( 0 );
 
-    if( rec_seqnum == ssl->in_window_top )
-        return( -1 );
-
-    bit = ssl->in_window_top - rec_seqnum - 1;
+    bit = ssl->in_window_top - rec_seqnum;
 
     if( bit >= 64 )
         return( -1 );
@@ -2757,20 +2756,19 @@
         uint64_t shift = rec_seqnum - ssl->in_window_top;
 
         if( shift >= 64 )
-            ssl->in_window = 0;
+            ssl->in_window = 1;
         else
+        {
             ssl->in_window <<= shift;
+            ssl->in_window |= 1;
+        }
 
         ssl->in_window_top = rec_seqnum;
     }
-    else if( rec_seqnum == ssl->in_window_top )
-    {
-        ; /* Can't happen, but anyway, nothing to do if it happened */
-    }
     else
     {
         /* Mark that number as seen in the current window */
-        uint64_t bit = ssl->in_window_top - rec_seqnum - 1;
+        uint64_t bit = ssl->in_window_top - rec_seqnum;
 
         if( bit < 64 ) /* Always true, but be extra sure */
             ssl->in_window |= (uint64_t) 1 << bit;