Start moving protocol-specific code to protocol.[ch]pp
[novacoin.git] / src / protocol.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
5
6 #include "protocol.h"
7
8 CMessageHeader::CMessageHeader()
9 {
10     memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
11     memset(pchCommand, 0, sizeof(pchCommand));
12     pchCommand[1] = 1;
13     nMessageSize = -1;
14     nChecksum = 0;
15 }
16
17 CMessageHeader::CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)
18 {
19     memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
20     strncpy(pchCommand, pszCommand, COMMAND_SIZE);
21     nMessageSize = nMessageSizeIn;
22     nChecksum = 0;
23 }
24
25 std::string CMessageHeader::GetCommand() const
26 {
27     if (pchCommand[COMMAND_SIZE-1] == 0)
28         return std::string(pchCommand, pchCommand + strlen(pchCommand));
29     else
30         return std::string(pchCommand, pchCommand + COMMAND_SIZE);
31 }
32
33 bool CMessageHeader::IsValid() const
34 {
35     // Check start string
36     if (memcmp(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)) != 0)
37         return false;
38
39     // Check the command string for errors
40     for (const char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)
41     {
42         if (*p1 == 0)
43         {
44             // Must be all zeros after the first zero
45             for (; p1 < pchCommand + COMMAND_SIZE; p1++)
46                 if (*p1 != 0)
47                     return false;
48         }
49         else if (*p1 < ' ' || *p1 > 0x7E)
50             return false;
51     }
52
53     // Message size
54     if (nMessageSize > MAX_SIZE)
55     {
56         printf("CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand().c_str(), nMessageSize);
57         return false;
58     }
59
60     return true;
61 }