Skip to content

Commit 06ce050

Browse files
KrzysFRabdullin
authored andcommitted
Use a better source of randomness for the VersionStamp random tokens
- Use Guid.NewGuid() to generate random bits
1 parent aad1f2e commit 06ce050

File tree

2 files changed

+6
-5
lines changed

2 files changed

+6
-5
lines changed

FoundationDB.Client/FdbTransaction.cs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -306,17 +306,18 @@ private ulong GenerateNewVersionStampToken()
306306
// Since this is supposed to be a version number with a ~1M tickrate per seconds, we will play it safe, and force the 8 highest bits to 1,
307307
// meaning that we only reduce the database potential lifetime but 1/256th, before getting into trouble.
308308
//
309-
// By doing some empirical testing, it also seems that the last 16 bits are a transction batch order which is usually a low number.
309+
// By doing some empirical testing, it also seems that the last 16 bits are a transaction batch order which is usually a low number.
310310
// Again, we will force the 4 highest bit to 1 to reduce the change of collision with a complete version stamp.
311311
//
312312
// So the final token will look like: 'FF xx xx xx xx xx xx xx Fy yy', were 'x' is the random token, and 'y' will lowest 12 bits of the transaction retry count
313313

314-
var rnd = new Random(); //TODO: singleton? (need locking!!)
315314
ulong x;
316315
unsafe
317316
{
318-
double r = rnd.NextDouble();
319-
x = *(ulong*) &r;
317+
// use a 128-bit guid as the source of entropy for our new token
318+
Guid rnd = Guid.NewGuid();
319+
ulong* p = (ulong*) &rnd;
320+
x = p[0] ^ p[1];
320321
}
321322
x |= 0xFF00000000000000UL;
322323

FoundationDB.Tests/TransactionFacts.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2000,7 +2000,7 @@ public async Task Test_VersionStamps_Share_The_Same_Token_Per_Transaction_Attemp
20002000
{
20012001
// should return a 80-bit incomplete stamp, using a random token
20022002
var x = tr.CreateVersionStamp();
2003-
Log($"> x : {x} with token '{x.ToSlice():X}'");
2003+
Log($"> x : {x.ToSlice():X} => {x}");
20042004
Assert.That(x.IsIncomplete, Is.True, "Placeholder token should be incomplete");
20052005
Assert.That(x.HasUserVersion, Is.False);
20062006
Assert.That(x.UserVersion, Is.Zero);

0 commit comments

Comments
 (0)