[utils] implement Verhoeff checksum calculation and validation (#9966)

This commit adds `Utils::VerhoeffChecksum` class along with public OT
APIs and related CLI commands for Verhoeff checksum calculation and
validation. Unit test `test_checksum` is updated to test the new
module.
This commit is contained in:
Abtin Keshavarzian
2024-04-08 17:11:43 -07:00
committed by GitHub
parent 8212acd133
commit 5c6b8328bc
14 changed files with 575 additions and 1 deletions
+62
View File
@@ -30,11 +30,13 @@
#include "common/message.hpp"
#include "common/numeric_limits.hpp"
#include "common/random.hpp"
#include "common/string.hpp"
#include "instance/instance.hpp"
#include "net/checksum.hpp"
#include "net/icmp6.hpp"
#include "net/ip4_types.hpp"
#include "net/udp6.hpp"
#include "utils/verhoeff_checksum.hpp"
#include "test_platform.h"
#include "test_util.hpp"
@@ -467,6 +469,62 @@ public:
}
};
#if OPENTHREAD_CONFIG_VERHOEFF_CHECKSUM_ENABLE
void TestVerhoeffChecksum(void)
{
static constexpr uint16_t kMaxStringSize = 50;
const char *kExamples[] = {"307318421", "487300178", "123455672", "0", "15",
"999999994", "000000001", "100000000", "2363"};
const char *kInvalidFormats[] = {
"307 318421",
"307318421 ",
" 307318421",
"ABCDE",
};
char string[kMaxStringSize];
char checksum;
char expectedChecksum;
printf("\nVerhoeffChecksum\n");
for (const char *example : kExamples)
{
uint16_t length = StringLength(example, kMaxStringSize - 1);
memcpy(string, example, length + 1);
printf("- \"%s\"\n", string);
SuccessOrQuit(Utils::VerhoeffChecksum::Validate(string));
expectedChecksum = string[length - 1];
string[length - 1] = (expectedChecksum == '0') ? '9' : (expectedChecksum - 1);
VerifyOrQuit(Utils::VerhoeffChecksum::Validate(string) == kErrorFailed);
string[length - 1] = '\0';
SuccessOrQuit(Utils::VerhoeffChecksum::Calculate(string, checksum));
VerifyOrQuit(checksum == expectedChecksum);
string[length - 1] = expectedChecksum == '0' ? '9' : (expectedChecksum - 1);
}
printf("\nInvalid format:\n");
for (const char *example : kInvalidFormats)
{
printf("- \"%s\"\n", example);
VerifyOrQuit(Utils::VerhoeffChecksum::Validate(example) == kErrorInvalidArgs);
VerifyOrQuit(Utils::VerhoeffChecksum::Calculate(example, checksum) == kErrorInvalidArgs);
}
}
#endif // OPENTHREAD_CONFIG_VERHOEFF_CHECKSUM_ENABLE
} // namespace ot
int main(void)
@@ -477,6 +535,10 @@ int main(void)
ot::TestTcp4MessageChecksum();
ot::TestUdp4MessageChecksum();
ot::TestIcmp4MessageChecksum();
#if OPENTHREAD_CONFIG_VERHOEFF_CHECKSUM_ENABLE
ot::TestVerhoeffChecksum();
#endif
printf("All tests passed\n");
return 0;
}