Skip to content
This repository was archived by the owner on Sep 6, 2022. It is now read-only.

Commit ccdc39e

Browse files
committed
fix: make timestamps strictly increasing
On Linux, this is almost always the case. Windows, however, doesn't have nanosecond accuracy. We make the timestamp sequence numbers strictly increasing by returning the last timestamp + 1 where necessary.
1 parent e5b6740 commit ccdc39e

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

peer/record.go

+14-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package peer
22

33
import (
44
"fmt"
5+
"sync/atomic"
56
"time"
67

78
pb "github.com/libp2p/go-libp2p-core/peer/pb"
@@ -125,9 +126,21 @@ func PeerRecordFromProtobuf(msg *pb.PeerRecord) (*PeerRecord, error) {
125126
return record, nil
126127
}
127128

129+
var lastTimestamp uint64
130+
128131
// TimestampSeq is a helper to generate a timestamp-based sequence number for a PeerRecord.
129132
func TimestampSeq() uint64 {
130-
return uint64(time.Now().UnixNano())
133+
now := uint64(time.Now().UnixNano())
134+
previous := atomic.LoadUint64(&lastTimestamp)
135+
// If the new time is not greater than the last tiemstamp, or if someone else beats us to
136+
// updateing the timestamp, just use last+1.
137+
//
138+
// Technically, last+1 could be before "now". But it's still strictly increasing and close
139+
// enough.
140+
if now <= previous || !atomic.CompareAndSwapUint64(&lastTimestamp, previous, now) {
141+
now = atomic.AddUint64(&lastTimestamp, 1)
142+
}
143+
return now
131144
}
132145

133146
// Domain is used when signing and validating PeerRecords contained in Envelopes.

0 commit comments

Comments
 (0)