Skip to content

Commit 9038b18

Browse files
committed
-fuzzmessagestest=N : randomly corrupt 1-of-N sent messages
I needed this to test the new "reject" p2p message, but it should be generally useful for fuzz-testing network message handling code.
1 parent d5d1425 commit 9038b18

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

src/net.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1894,3 +1894,38 @@ uint64 CNode::GetTotalBytesSent()
18941894
LOCK(cs_totalBytesSent);
18951895
return nTotalBytesSent;
18961896
}
1897+
1898+
void CNode::Fuzz(int nChance)
1899+
{
1900+
if (!fSuccessfullyConnected) return; // Don't fuzz initial handshake
1901+
if (GetRand(nChance) != 0) return; // Fuzz 1 of every nChance messages
1902+
1903+
switch (GetRand(3))
1904+
{
1905+
case 0:
1906+
// xor a random byte with a random value:
1907+
if (!ssSend.empty()) {
1908+
CDataStream::size_type pos = GetRand(ssSend.size());
1909+
ssSend[pos] ^= (unsigned char)(GetRand(256));
1910+
}
1911+
break;
1912+
case 1:
1913+
// delete a random byte:
1914+
if (!ssSend.empty()) {
1915+
CDataStream::size_type pos = GetRand(ssSend.size());
1916+
ssSend.erase(ssSend.begin()+pos);
1917+
}
1918+
break;
1919+
case 2:
1920+
// insert a random byte at a random position
1921+
{
1922+
CDataStream::size_type pos = GetRand(ssSend.size());
1923+
char ch = (char)GetRand(256);
1924+
ssSend.insert(ssSend.begin()+pos, ch);
1925+
}
1926+
break;
1927+
}
1928+
// Chance of more than one change half the time:
1929+
// (more changes exponentially less likely):
1930+
Fuzz(2);
1931+
}

src/net.h

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,9 @@ class CNode
218218
static CCriticalSection cs_setBanned;
219219
int nMisbehavior;
220220

221+
// Basic fuzz-testing
222+
void Fuzz(int nChance); // modifies ssSend
223+
221224
public:
222225
uint256 hashContinue;
223226
CBlockIndex* pindexLastGetBlocksBegin;
@@ -434,12 +437,17 @@ class CNode
434437
// TODO: Document the precondition of this function. Is cs_vSend locked?
435438
void EndMessage() UNLOCK_FUNCTION(cs_vSend)
436439
{
437-
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
440+
// The -*messagestest options are intentionally not documented in the help message,
441+
// since they are only used during development to debug the networking code and are
442+
// not intended for end-users.
443+
if (mapArgs.count("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 2)) == 0)
438444
{
439445
LogPrint("net", "dropmessages DROPPING SEND MESSAGE\n");
440446
AbortMessage();
441447
return;
442448
}
449+
if (mapArgs.count("-fuzzmessagestest"))
450+
Fuzz(GetArg("-fuzzmessagestest", 10));
443451

444452
if (ssSend.size() == 0)
445453
return;

0 commit comments

Comments
 (0)