Improve log messages and general code cleanup in CaModule

Change-Id: Ie455ec14594e7662800faa887da72574bff73407
diff --git a/src/ca-module.cpp b/src/ca-module.cpp
index 9ac7453..9606e24 100644
--- a/src/ca-module.cpp
+++ b/src/ca-module.cpp
@@ -19,27 +19,26 @@
  */
 
 #include "ca-module.hpp"
-#include "detail/crypto-helpers.hpp"
 #include "challenge/challenge-module.hpp"
 #include "name-assignment/assignment-func.hpp"
 #include "detail/challenge-encoder.hpp"
+#include "detail/crypto-helpers.hpp"
 #include "detail/error-encoder.hpp"
 #include "detail/info-encoder.hpp"
-#include "detail/request-encoder.hpp"
 #include "detail/probe-encoder.hpp"
+#include "detail/request-encoder.hpp"
 
 #include <ndn-cxx/metadata-object.hpp>
 #include <ndn-cxx/security/signing-helpers.hpp>
 #include <ndn-cxx/security/verification-helpers.hpp>
-#include <ndn-cxx/util/io.hpp>
 #include <ndn-cxx/util/logger.hpp>
 #include <ndn-cxx/util/random.hpp>
 #include <ndn-cxx/util/string-helper.hpp>
 
 namespace ndncert::ca {
 
-const time::seconds DEFAULT_DATA_FRESHNESS_PERIOD = 1_s;
-const time::seconds REQUEST_VALIDITY_PERIOD_NOT_BEFORE_GRACE_PERIOD = 120_s;
+constexpr time::milliseconds DEFAULT_DATA_FRESHNESS_PERIOD = 1_s;
+constexpr time::seconds REQUEST_VALIDITY_PERIOD_NOT_BEFORE_GRACE_PERIOD = 120_s;
 
 NDN_LOG_INIT(ndncert.ca);
 
@@ -61,16 +60,6 @@
   registerPrefix();
 }
 
-CaModule::~CaModule()
-{
-  for (auto& handle : m_interestFilterHandles) {
-    handle.cancel();
-  }
-  for (auto& handle : m_registeredPrefixHandles) {
-    handle.unregister();
-  }
-}
-
 void
 CaModule::registerPrefix()
 {
@@ -85,61 +74,57 @@
     identity = m_keyChain.getPib().getIdentity(m_config.caProfile.caPrefix);
   }
 
-  auto prefixHandle = m_face.registerPrefix(prefix,
+  m_registeredPrefixes.emplace_back(m_face.registerPrefix(prefix,
     [&] (const Name& name) {
       // register INFO RDR metadata prefix
       const auto& metaDataComp = ndn::MetadataObject::getKeywordComponent();
       auto filterId = m_face.setInterestFilter(Name(name).append("INFO").append(metaDataComp),
                                                [this] (auto&&, const auto& i) { onCaProfileDiscovery(i); });
-      m_interestFilterHandles.push_back(filterId);
+      m_interestFilters.emplace_back(std::move(filterId));
 
       // register PROBE prefix
       filterId = m_face.setInterestFilter(Name(name).append("PROBE"),
                                           [this] (auto&&, const auto& i) { onProbe(i); });
-      m_interestFilterHandles.push_back(filterId);
+      m_interestFilters.emplace_back(std::move(filterId));
 
       // register NEW prefix
       filterId = m_face.setInterestFilter(Name(name).append("NEW"),
                                           [this] (auto&&, const auto& i) { onNewRenewRevoke(i, RequestType::NEW); });
-      m_interestFilterHandles.push_back(filterId);
+      m_interestFilters.emplace_back(std::move(filterId));
 
-      // register SELECT prefix
+      // register CHALLENGE prefix
       filterId = m_face.setInterestFilter(Name(name).append("CHALLENGE"),
                                           [this] (auto&&, const auto& i) { onChallenge(i); });
-      m_interestFilterHandles.push_back(filterId);
+      m_interestFilters.emplace_back(std::move(filterId));
 
       // register REVOKE prefix
       filterId = m_face.setInterestFilter(Name(name).append("REVOKE"),
                                           [this] (auto&&, const auto& i) { onNewRenewRevoke(i, RequestType::REVOKE); });
-      m_interestFilterHandles.push_back(filterId);
+      m_interestFilters.emplace_back(std::move(filterId));
 
-      NDN_LOG_TRACE("Prefix " << name << " got registered");
+      NDN_LOG_TRACE("Prefix " << name << " registered successfully");
     },
-    [this] (auto&&, const auto& reason) { onRegisterFailed(reason); },
-    ndn::signingByIdentity(identity));
-  m_registeredPrefixHandles.push_back(prefixHandle);
+    [] (auto&&, const auto& reason) {
+      NDN_THROW(std::runtime_error("Failed to register prefix: " + reason));
+    },
+    ndn::signingByIdentity(identity)));
 }
 
-void
-CaModule::setStatusUpdateCallback(const StatusUpdateCallback& onUpdateCallback)
-{
-  m_statusUpdateCallback = onUpdateCallback;
-}
-
-Data
+const Data&
 CaModule::getCaProfileData()
 {
   if (m_profileData == nullptr) {
     auto key = m_keyChain.getPib().getIdentity(m_config.caProfile.caPrefix).getDefaultKey();
-    Block contentTLV = infotlv::encodeDataContent(m_config.caProfile, key.getDefaultCertificate());
+    Block content = infotlv::encodeDataContent(m_config.caProfile, key.getDefaultCertificate());
 
     Name infoPacketName(m_config.caProfile.caPrefix);
-    auto segmentComp = ndn::name::Component::fromSegment(0);
+    auto segmentComp = Name::Component::fromSegment(0);
     infoPacketName.append("CA").append("INFO").appendVersion().append(segmentComp);
     m_profileData = std::make_unique<Data>(infoPacketName);
-    m_profileData->setFinalBlock(segmentComp);
-    m_profileData->setContent(contentTLV);
     m_profileData->setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
+    m_profileData->setFinalBlock(segmentComp);
+    m_profileData->setContent(content);
+
     m_keyChain.sign(*m_profileData, signingByIdentity(m_config.caProfile.caPrefix));
   }
   return *m_profileData;
@@ -148,73 +133,78 @@
 void
 CaModule::onCaProfileDiscovery(const Interest&)
 {
-  NDN_LOG_TRACE("Received CA Profile MetaData discovery Interest");
-  if (m_profileData == nullptr) {
-    m_profileData = std::make_unique<Data>(getCaProfileData());
-  }
+  NDN_LOG_TRACE("Received CA profile metadata discovery Interest");
+
+  const auto& profileDataName = getCaProfileData().getName();
   ndn::MetadataObject metadata;
-  metadata.setVersionedName(m_profileData->getName().getPrefix(-1));
-  Name discoveryInterestName(m_profileData->getName().getPrefix(-2));
+  metadata.setVersionedName(profileDataName.getPrefix(-1));
+  Name discoveryInterestName(profileDataName.getPrefix(-2));
   discoveryInterestName.append(ndn::MetadataObject::getKeywordComponent());
   m_face.put(metadata.makeData(discoveryInterestName, m_keyChain, signingByIdentity(m_config.caProfile.caPrefix)));
+
+  NDN_LOG_TRACE("Sent CA profile metadata");
 }
 
 void
 CaModule::onProbe(const Interest& request)
 {
-  // PROBE Naming Convention: /<CA-Prefix>/CA/PROBE/[ParametersSha256DigestComponent]
+  // PROBE naming convention: /<CA-Prefix>/CA/PROBE/<ParametersSha256Digest>
   NDN_LOG_TRACE("Received PROBE request");
 
-  // process PROBE requests: collect probe parameters
-  std::vector<ndn::Name> redirectionNames;
-  std::vector<ndn::PartialName> availableComponents;
+  // process PROBE request: collect probe parameters
+  std::multimap<std::string, std::string> parameters;
   try {
-    auto parameters = probetlv::decodeApplicationParameters(request.getApplicationParameters());
-
-    // collect redirections
-    for (auto &item : m_config.redirection) {
-      if (item.second->isRedirecting(parameters)) {
-        redirectionNames.push_back(item.first->getFullName());
-      }
-    }
-
-    // collect name assignments
-    for (auto &item : m_config.nameAssignmentFuncs) {
-      auto names = item->assignName(parameters);
-      availableComponents.insert(availableComponents.end(), names.begin(), names.end());
-    }
+    parameters = probetlv::decodeApplicationParameters(request.getApplicationParameters());
   }
   catch (const std::exception& e) {
-    NDN_LOG_ERROR("[CaModule::onProbe]Error in decoding TLV: " << e.what());
+    NDN_LOG_ERROR("Cannot decode PROBE parameters: " << e.what());
     return;
   }
 
+  // collect redirections
+  std::vector<ndn::Name> redirectionNames;
+  for (const auto& item : m_config.redirection) {
+    if (item.second->isRedirecting(parameters)) {
+      redirectionNames.push_back(item.first->getFullName());
+    }
+  }
+
+  // collect name assignments
+  std::vector<ndn::PartialName> availableComponents;
+  for (const auto& item : m_config.nameAssignmentFuncs) {
+    auto names = item->assignName(parameters);
+    availableComponents.insert(availableComponents.end(), names.begin(), names.end());
+  }
+
   if (availableComponents.empty() && redirectionNames.empty()) {
-    m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
-                                       "Cannot generate available names from parameters provided."));
+    NDN_LOG_TRACE("Cannot generate available names");
+    m_face.put(makeErrorPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
+                               "Cannot generate available names from parameters provided."));
     return;
   }
 
   std::vector<Name> availableNames;
-  for (const auto &component : availableComponents) {
-    Name newIdentityName = m_config.caProfile.caPrefix;
-    newIdentityName.append(component);
-    availableNames.push_back(newIdentityName);
+  availableNames.reserve(availableComponents.size());
+  for (const auto& component : availableComponents) {
+    availableNames.push_back(Name(m_config.caProfile.caPrefix).append(component));
   }
 
-  Data result;
-  result.setName(request.getName());
+  Data result(request.getName());
+  result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
   result.setContent(probetlv::encodeDataContent(availableNames, m_config.caProfile.maxSuffixLength,
                                                 redirectionNames));
-  result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
   m_keyChain.sign(result, signingByIdentity(m_config.caProfile.caPrefix));
   m_face.put(result);
-  NDN_LOG_TRACE("Handle PROBE: send out the PROBE response");
+  NDN_LOG_TRACE("Sent PROBE response");
 }
 
 void
 CaModule::onNewRenewRevoke(const Interest& request, RequestType requestType)
 {
+  // NEW naming convention: /<CA-Prefix>/CA/NEW/<ParametersSha256Digest>
+  // REVOKE naming convention: /<CA-Prefix>/CA/REVOKE/<ParametersSha256Digest>
+  NDN_LOG_TRACE("Received " << requestType << " request");
+
   // verify ca cert validity
   auto caCert = m_keyChain.getPib()
                           .getIdentity(m_config.caProfile.caPrefix)
@@ -222,68 +212,53 @@
                           .getDefaultCertificate();
   if (!caCert.isValid()) {
     NDN_LOG_ERROR("Server certificate invalid/expired");
-    m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::BAD_VALIDITY_PERIOD,
-                                       "Server certificate invalid/expired"));
+    m_face.put(makeErrorPacket(request.getName(), ErrorCode::BAD_VALIDITY_PERIOD,
+                               "Server certificate invalid/expired"));
     return;
   }
 
-  // NEW Naming Convention: /<CA-prefix>/CA/NEW/[SignedInterestParameters_Digest]
-  // REVOKE Naming Convention: /<CA-prefix>/CA/REVOKE/[SignedInterestParameters_Digest]
   // get ECDH pub key and cert request
-  const auto& parameterTLV = request.getApplicationParameters();
-  std::vector <uint8_t> ecdhPub;
+  const auto& paramsBlock = request.getApplicationParameters();
+  std::vector<uint8_t> ecdhPub;
   std::shared_ptr<Certificate> clientCert;
   try {
-    requesttlv::decodeApplicationParameters(parameterTLV, requestType, ecdhPub, clientCert);
+    requesttlv::decodeApplicationParameters(paramsBlock, requestType, ecdhPub, clientCert);
   }
   catch (const std::exception& e) {
-    if (!parameterTLV.hasValue()) {
-      NDN_LOG_ERROR("Empty TLV obtained from the Interest parameter.");
-      m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
-                                         "Empty TLV obtained from the Interest parameter."));
-      return;
+    if (!paramsBlock.hasValue()) {
+      NDN_LOG_ERROR("Empty parameters in request");
+      m_face.put(makeErrorPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
+                                 "Malformed request parameters."));
     }
-
-    NDN_LOG_ERROR("Unrecognized self-signed certificate: " << e.what());
-    m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
-                                       "Unrecognized self-signed certificate."));
+    else {
+      NDN_LOG_ERROR("Cannot decode request parameters: " << e.what());
+      m_face.put(makeErrorPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
+                                 "Malformed request parameters."));
+    }
     return;
   }
 
   if (ecdhPub.empty()) {
-    NDN_LOG_ERROR("Empty ECDH PUB obtained from the Interest parameter.");
-    m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
-                                       "Empty ECDH PUB obtained from the Interest parameter."));
-    return;
-  }
-
-  // get server's ECDH pub key
-  ECDHState ecdh;
-  std::vector <uint8_t> sharedSecret;
-  try {
-    sharedSecret = ecdh.deriveSecret(ecdhPub);
-  }
-  catch (const std::exception& e) {
-    NDN_LOG_ERROR("Cannot derive a shared secret using the provided ECDH key: " << e.what());
-    m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
-                                       "Cannot derive a shared secret using the provided ECDH key."));
+    NDN_LOG_ERROR("Empty ECDH public key in request parameters");
+    m_face.put(makeErrorPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
+                               "Malformed request parameters."));
     return;
   }
 
   // verify identity name
-  if (!m_config.caProfile.caPrefix.isPrefixOf(clientCert->getIdentity())
-      || !Certificate::isValidName(clientCert->getName())
-      || clientCert->getIdentity().size() <= m_config.caProfile.caPrefix.size()) {
-    NDN_LOG_ERROR("An invalid certificate name is being requested " << clientCert->getName());
-    m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::NAME_NOT_ALLOWED,
-                                       "An invalid certificate name is being requested."));
+  if (!Certificate::isValidName(clientCert->getName()) ||
+      !m_config.caProfile.caPrefix.isPrefixOf(clientCert->getIdentity()) ||
+      clientCert->getIdentity().size() <= m_config.caProfile.caPrefix.size()) {
+    NDN_LOG_ERROR("Invalid certificate name requested: " << clientCert->getName());
+    m_face.put(makeErrorPacket(request.getName(), ErrorCode::NAME_NOT_ALLOWED,
+                               "Invalid certificate name requested."));
     return;
   }
   if (m_config.caProfile.maxSuffixLength) {
     if (clientCert->getIdentity().size() > m_config.caProfile.caPrefix.size() + *m_config.caProfile.maxSuffixLength) {
-      NDN_LOG_ERROR("An invalid certificate name is being requested " << clientCert->getName());
-      m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::NAME_NOT_ALLOWED,
-                                         "An invalid certificate name is being requested."));
+      NDN_LOG_ERROR("Invalid certificate name requested: " << clientCert->getName());
+      m_face.put(makeErrorPacket(request.getName(), ErrorCode::NAME_NOT_ALLOWED,
+                                 "Invalid certificate name requested."));
       return;
     }
   }
@@ -295,36 +270,49 @@
     if (notBefore < currentTime - REQUEST_VALIDITY_PERIOD_NOT_BEFORE_GRACE_PERIOD ||
         notAfter > currentTime + m_config.caProfile.maxValidityPeriod ||
         notAfter <= notBefore) {
-      NDN_LOG_ERROR("An invalid validity period is being requested.");
-      m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::BAD_VALIDITY_PERIOD,
-                                         "An invalid validity period is being requested."));
+      NDN_LOG_ERROR("Invalid validity period requested");
+      m_face.put(makeErrorPacket(request.getName(), ErrorCode::BAD_VALIDITY_PERIOD,
+                                 "Invalid validity period requested."));
       return;
     }
 
-    // verify signature
+    // verify signatures
     if (!ndn::security::verifySignature(*clientCert, *clientCert)) {
-      NDN_LOG_ERROR("Invalid signature in the self-signed certificate.");
-      m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::BAD_SIGNATURE,
-                                         "Invalid signature in the self-signed certificate."));
+      NDN_LOG_ERROR("Invalid signature in the self-signed certificate");
+      m_face.put(makeErrorPacket(request.getName(), ErrorCode::BAD_SIGNATURE,
+                                 "Invalid signature in the self-signed certificate."));
       return;
     }
     if (!ndn::security::verifySignature(request, *clientCert)) {
-      NDN_LOG_ERROR("Invalid signature in the Interest packet.");
-      m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::BAD_SIGNATURE,
-                                         "Invalid signature in the Interest packet."));
+      NDN_LOG_ERROR("Invalid signature in the Interest packet");
+      m_face.put(makeErrorPacket(request.getName(), ErrorCode::BAD_SIGNATURE,
+                                 "Invalid signature in the Interest packet."));
       return;
     }
   }
   else if (requestType == RequestType::REVOKE) {
-    //verify cert is from this CA
+    // verify cert is from this CA
     if (!ndn::security::verifySignature(*clientCert, caCert)) {
-      NDN_LOG_ERROR("Invalid signature in the certificate to revoke.");
-      m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::BAD_SIGNATURE,
-                                         "Invalid signature in the certificate to revoke."));
+      NDN_LOG_ERROR("Invalid signature in the certificate to revoke");
+      m_face.put(makeErrorPacket(request.getName(), ErrorCode::BAD_SIGNATURE,
+                                 "Invalid signature in the certificate to revoke."));
       return;
     }
   }
 
+  // derive server's ECDH pub key
+  ECDHState ecdh;
+  std::vector<uint8_t> sharedSecret;
+  try {
+    sharedSecret = ecdh.deriveSecret(ecdhPub);
+  }
+  catch (const std::exception& e) {
+    NDN_LOG_ERROR("Cannot derive a shared secret using the provided ECDH public key: " << e.what());
+    m_face.put(makeErrorPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
+                               "Cannot derive a shared secret using the provided ECDH public key."));
+    return;
+  }
+
   // create new request instance
   uint8_t requestIdData[32];
   Block certNameTlv = clientCert->getName().wireEncode();
@@ -333,8 +321,8 @@
   }
   catch (const std::runtime_error& e) {
     NDN_LOG_ERROR("Error computing the request ID: " << e.what());
-    m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
-                                       "Error computing the request ID."));
+    m_face.put(makeErrorPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
+                               "Error computing the request ID."));
     return;
   }
   RequestId id;
@@ -357,20 +345,20 @@
     m_storage->addRequest(requestState);
   }
   catch (const std::runtime_error&) {
-    NDN_LOG_ERROR("Duplicate Request ID: The same request has been seen before.");
-    m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
-                                       "Duplicate Request ID: The same request has been seen before."));
+    NDN_LOG_ERROR("Duplicate request ID " << ndn::toHex(id));
+    m_face.put(makeErrorPacket(request.getName(), ErrorCode::INVALID_PARAMETER, "Duplicate request ID."));
     return;
   }
 
-  Data result;
-  result.setName(request.getName());
+  Data result(request.getName());
   result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
   result.setContent(requesttlv::encodeDataContent(ecdh.getSelfPubKey(),
                                                   salt, requestState.requestId,
                                                   m_config.caProfile.supportedChallenges));
   m_keyChain.sign(result, signingByIdentity(m_config.caProfile.caPrefix));
   m_face.put(result);
+  NDN_LOG_TRACE("Sent " << requestType << " response");
+
   if (m_statusUpdateCallback) {
     m_statusUpdateCallback(requestState);
   }
@@ -379,105 +367,135 @@
 void
 CaModule::onChallenge(const Interest& request)
 {
+  NDN_LOG_TRACE("Received CHALLENGE request");
+
   // get certificate request state
   auto requestState = getCertificateRequest(request);
   if (requestState == nullptr) {
-    NDN_LOG_ERROR("No certificate request state can be found.");
-    m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
-                                       "No certificate request state can be found."));
+    NDN_LOG_ERROR("No pending certificate request found");
+    m_face.put(makeErrorPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
+                               "No pending certificate request found."));
     return;
   }
 
   // verify signature
   if (!ndn::security::verifySignature(request, requestState->cert)) {
-    NDN_LOG_ERROR("Invalid Signature in the Interest packet.");
-    m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::BAD_SIGNATURE,
-                                       "Invalid Signature in the Interest packet."));
+    NDN_LOG_ERROR("Invalid signature in the Interest packet");
+    m_face.put(makeErrorPacket(request.getName(), ErrorCode::BAD_SIGNATURE,
+                               "Invalid signature in the Interest packet."));
     return;
   }
 
   // decrypt the parameters
-  ndn::Buffer paramTLVPayload;
+  ndn::Buffer plaintext;
   try {
-    paramTLVPayload = decodeBlockWithAesGcm128(request.getApplicationParameters(), requestState->encryptionKey.data(),
-                                               requestState->requestId.data(), requestState->requestId.size(),
-                                               requestState->decryptionIv, requestState->encryptionIv);
+    plaintext = decodeBlockWithAesGcm128(request.getApplicationParameters(), requestState->encryptionKey.data(),
+                                         requestState->requestId.data(), requestState->requestId.size(),
+                                         requestState->decryptionIv, requestState->encryptionIv);
   }
   catch (const std::exception& e) {
-    NDN_LOG_ERROR("Interest paramaters decryption failed: " << e.what());
+    NDN_LOG_ERROR("Cannot decrypt challenge parameters: " << e.what());
     m_storage->deleteRequest(requestState->requestId);
-    m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
-                                       "Interest paramaters decryption failed."));
+    m_face.put(makeErrorPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
+                               "Malformed challenge parameters."));
     return;
   }
-  if (paramTLVPayload.empty()) {
-    NDN_LOG_ERROR("No parameters are found after decryption.");
+  if (plaintext.empty()) {
+    NDN_LOG_ERROR("Empty parameters after decryption");
     m_storage->deleteRequest(requestState->requestId);
-    m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
-                                       "No parameters are found after decryption."));
+    m_face.put(makeErrorPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
+                               "Malformed challenge parameters."));
     return;
   }
 
-  auto paramTLV = ndn::makeBinaryBlock(tlv::EncryptedPayload, paramTLVPayload);
+  auto paramTLV = ndn::makeBinaryBlock(tlv::EncryptedPayload, plaintext);
   paramTLV.parse();
 
   // load the corresponding challenge module
   std::string challengeType = readString(paramTLV.get(tlv::SelectedChallenge));
   auto challenge = ChallengeModule::createChallengeModule(challengeType);
   if (challenge == nullptr) {
-    NDN_LOG_TRACE("Unrecognized challenge type: " << challengeType);
+    NDN_LOG_TRACE("Unsupported challenge type: " << challengeType);
     m_storage->deleteRequest(requestState->requestId);
-    m_face.put(
-      generateErrorDataPacket(request.getName(), ErrorCode::INVALID_PARAMETER, "Unrecognized challenge type."));
+    m_face.put(makeErrorPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
+                               "Unsupported challenge type."));
     return;
   }
 
-  NDN_LOG_TRACE("CHALLENGE module to be load: " << challengeType);
-  auto errorInfo = challenge->handleChallengeRequest(paramTLV, *requestState);
-  if (std::get<0>(errorInfo) != ErrorCode::NO_ERROR) {
+  NDN_LOG_TRACE("Using challenge: " << challengeType);
+  auto [errCode, errMsg] = challenge->handleChallengeRequest(paramTLV, *requestState);
+  if (errCode != ErrorCode::NO_ERROR) {
     m_storage->deleteRequest(requestState->requestId);
-    m_face.put(generateErrorDataPacket(request.getName(), std::get<0>(errorInfo), std::get<1>(errorInfo)));
+    m_face.put(makeErrorPacket(request.getName(), errCode, errMsg));
     return;
   }
 
   Block payload;
   if (requestState->status == Status::PENDING) {
-    // if challenge succeeded
-    if (requestState->requestType == RequestType::NEW || requestState->requestType == RequestType::RENEW) {
+    NDN_LOG_TRACE("Challenge succeeded");
+    if (requestState->requestType == RequestType::NEW ||
+        requestState->requestType == RequestType::RENEW) {
       auto issuedCert = issueCertificate(*requestState);
       requestState->cert = issuedCert;
       requestState->status = Status::SUCCESS;
       m_storage->deleteRequest(requestState->requestId);
-
       payload = challengetlv::encodeDataContent(*requestState, issuedCert.getName(),
                                                 m_config.caProfile.forwardingHint);
-      NDN_LOG_TRACE("Challenge succeeded. Certificate has been issued: " << issuedCert.getName());
     }
     else if (requestState->requestType == RequestType::REVOKE) {
+      // TODO: where is the code to revoke?
       requestState->status = Status::SUCCESS;
       m_storage->deleteRequest(requestState->requestId);
-      // TODO: where is the code to revoke?
       payload = challengetlv::encodeDataContent(*requestState);
-      NDN_LOG_TRACE("Challenge succeeded. Certificate has been revoked");
     }
   }
   else {
     payload = challengetlv::encodeDataContent(*requestState);
     m_storage->updateRequest(*requestState);
-    NDN_LOG_TRACE("No failure no success. Challenge moves on");
+    NDN_LOG_TRACE("Challenge continues");
   }
 
-  Data result;
-  result.setName(request.getName());
+  Data result(request.getName());
   result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
   result.setContent(payload);
   m_keyChain.sign(result, signingByIdentity(m_config.caProfile.caPrefix));
   m_face.put(result);
+  NDN_LOG_TRACE("Sent CHALLENGE response");
+
   if (m_statusUpdateCallback) {
     m_statusUpdateCallback(*requestState);
   }
 }
 
+std::unique_ptr<RequestState>
+CaModule::getCertificateRequest(const Interest& request)
+{
+  Name::Component component;
+  try {
+    component = request.getName().at(m_config.caProfile.caPrefix.size() + 2);
+  }
+  catch (const std::exception& e) {
+    NDN_LOG_ERROR("Cannot extract request ID from Interest name: " << e.what());
+    return nullptr;
+  }
+
+  RequestId requestId;
+  if (component.value_size() != requestId.size()) {
+    NDN_LOG_ERROR("Invalid request ID of length " << component.value_size());
+    return nullptr;
+  }
+  std::memcpy(requestId.data(), component.value(), requestId.size());
+
+  try {
+    NDN_LOG_TRACE("Retrieving request with ID " << ndn::toHex(requestId));
+    return std::make_unique<RequestState>(m_storage->getRequest(requestId));
+  }
+  catch (const std::exception& e) {
+    NDN_LOG_ERROR("Cannot fetch certificate request record from storage: " << e.what());
+    return nullptr;
+  }
+}
+
 Certificate
 CaModule::issueCertificate(const RequestState& requestState)
 {
@@ -486,45 +504,16 @@
   opts.validity = requestState.cert.getValidityPeriod();
   auto newCert = m_keyChain.makeCertificate(requestState.cert,
                                             signingByIdentity(m_config.caProfile.caPrefix), opts);
-  NDN_LOG_TRACE("Signed new certificate: " << newCert);
+  NDN_LOG_TRACE("Certificate issued: " << newCert);
   return newCert;
 }
 
-std::unique_ptr <RequestState>
-CaModule::getCertificateRequest(const Interest& request)
-{
-  RequestId requestId;
-  try {
-    auto& component = request.getName().at(m_config.caProfile.caPrefix.size() + 2);
-    std::memcpy(requestId.data(), component.value(), component.value_size());
-  }
-  catch (const std::exception& e) {
-    NDN_LOG_ERROR("Cannot read the request ID out from the request: " << e.what());
-    return nullptr;
-  }
-  try {
-    NDN_LOG_TRACE("Request Id to query the database " << ndn::toHex(requestId));
-    return std::make_unique<RequestState>(m_storage->getRequest(requestId));
-  }
-  catch (const std::exception& e) {
-    NDN_LOG_ERROR("Cannot get certificate request record from the storage: " << e.what());
-    return nullptr;
-  }
-}
-
-void
-CaModule::onRegisterFailed(const std::string& reason)
-{
-  NDN_LOG_ERROR("Failed to register prefix in local hub's daemon, REASON: " << reason);
-}
-
 Data
-CaModule::generateErrorDataPacket(const Name& name, ErrorCode error, const std::string& errorInfo)
+CaModule::makeErrorPacket(const Name& name, ErrorCode errorCode, std::string_view errorInfo)
 {
-  Data result;
-  result.setName(name);
+  Data result(name);
   result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
-  result.setContent(errortlv::encodeDataContent(error, errorInfo));
+  result.setContent(errortlv::encodeDataContent(errorCode, errorInfo));
   m_keyChain.sign(result, signingByIdentity(m_config.caProfile.caPrefix));
   return result;
 }
diff --git a/src/ca-module.hpp b/src/ca-module.hpp
index 719c3f3..6e85aa9 100644
--- a/src/ca-module.hpp
+++ b/src/ca-module.hpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /*
- * Copyright (c) 2017-2022, Regents of the University of California.
+ * Copyright (c) 2017-2024, Regents of the University of California.
  *
  * This file is part of ndncert, a certificate management system based on NDN.
  *
@@ -22,7 +22,6 @@
 #define NDNCERT_CA_MODULE_HPP
 
 #include "detail/ca-configuration.hpp"
-#include "detail/crypto-helpers.hpp"
 #include "detail/ca-storage.hpp"
 
 #include <ndn-cxx/face.hpp>
@@ -46,8 +45,6 @@
   CaModule(ndn::Face& face, ndn::KeyChain& keyChain, const std::string& configPath,
            const std::string& storageType = "ca-storage-sqlite3");
 
-  ~CaModule();
-
   CaConfig&
   getCaConf()
   {
@@ -61,13 +58,19 @@
   }
 
   void
-  setStatusUpdateCallback(const StatusUpdateCallback& onUpdateCallback);
+  setStatusUpdateCallback(StatusUpdateCallback cb)
+  {
+    m_statusUpdateCallback = std::move(cb);
+  }
 
-  Data
+  const Data&
   getCaProfileData();
 
 NDNCERT_PUBLIC_WITH_TESTS_ELSE_PRIVATE:
   void
+  registerPrefix();
+
+  void
   onCaProfileDiscovery(const Interest& request);
 
   void
@@ -79,35 +82,27 @@
   void
   onChallenge(const Interest& request);
 
-  void
-  onRegisterFailed(const std::string& reason);
-
   std::unique_ptr<RequestState>
   getCertificateRequest(const Interest& request);
 
   Certificate
   issueCertificate(const RequestState& requestState);
 
-  void
-  registerPrefix();
-
   Data
-  generateErrorDataPacket(const Name& name, ErrorCode error, const std::string& errorInfo);
+  makeErrorPacket(const Name& name, ErrorCode errorCode, std::string_view errorInfo);
 
 NDNCERT_PUBLIC_WITH_TESTS_ELSE_PRIVATE:
   ndn::Face& m_face;
+  ndn::KeyChain& m_keyChain;
   CaConfig m_config;
   std::unique_ptr<CaStorage> m_storage;
-  ndn::KeyChain& m_keyChain;
+
   uint8_t m_requestIdGenKey[32];
   std::unique_ptr<Data> m_profileData;
-  /**
-   * StatusUpdate Callback function
-   */
   StatusUpdateCallback m_statusUpdateCallback;
 
-  std::list<ndn::RegisteredPrefixHandle> m_registeredPrefixHandles;
-  std::list<ndn::InterestFilterHandle> m_interestFilterHandles;
+  std::vector<ndn::ScopedRegisteredPrefixHandle> m_registeredPrefixes;
+  std::vector<ndn::ScopedInterestFilterHandle> m_interestFilters;
 };
 
 } // namespace ndncert::ca
diff --git a/src/challenge/challenge-email.cpp b/src/challenge/challenge-email.cpp
index c4de9ce..26d42f5 100644
--- a/src/challenge/challenge-email.cpp
+++ b/src/challenge/challenge-email.cpp
@@ -49,56 +49,59 @@
 {
   params.parse();
   auto currentTime = time::system_clock::now();
+
   if (request.status == Status::BEFORE_CHALLENGE) {
     // for the first time, init the challenge
     std::string emailAddress = readString(params.get(tlv::ParameterValue));
     auto lastComponentRequested = readString(request.cert.getIdentity().get(-1));
     if (lastComponentRequested != emailAddress) {
-      NDN_LOG_TRACE("Email and requested name do not match. Email " << emailAddress
-                    << " - requested last component " << lastComponentRequested);
+      NDN_LOG_TRACE("Email and requested name do not match: email=" << emailAddress
+                    << " requested=" << lastComponentRequested);
     }
     std::string emailCode = generateSecretCode();
     JsonSection secretJson;
     secretJson.add(PARAMETER_KEY_CODE, emailCode);
     // send out the email
     sendEmail(emailAddress, emailCode, request);
-    NDN_LOG_TRACE("Secret for request " << ndn::toHex(request.requestId) << " : " << emailCode);
+    NDN_LOG_TRACE("Secret for request " << ndn::toHex(request.requestId) << " is " << emailCode);
     return returnWithNewChallengeStatus(request, NEED_CODE, std::move(secretJson),
                                         m_maxAttemptTimes, m_secretLifetime);
   }
+
   if (request.challengeState) {
     if (request.challengeState->challengeStatus == NEED_CODE ||
         request.challengeState->challengeStatus == WRONG_CODE) {
-      NDN_LOG_TRACE("Challenge Interest arrives. Challenge Status: " << request.challengeState->challengeStatus);
+      NDN_LOG_TRACE("Challenge status: " << request.challengeState->challengeStatus);
       // the incoming interest should bring the pin code
       std::string givenCode = readString(params.get(tlv::ParameterValue));
       auto secret = request.challengeState->secrets;
       // check if run out of time
       if (currentTime - request.challengeState->timestamp >= m_secretLifetime) {
+        NDN_LOG_TRACE("Secret expired");
         return returnWithError(request, ErrorCode::OUT_OF_TIME, "Secret expired.");
       }
       // check if provided secret is correct
       if (givenCode == secret.get<std::string>(PARAMETER_KEY_CODE)) {
         // the code is correct
-        NDN_LOG_TRACE("Correct secret code. Challenge succeeded.");
+        NDN_LOG_TRACE("Secret is correct, challenge succeeded");
         return returnWithSuccess(request);
       }
       // otherwise, check remaining attempt times
       if (request.challengeState->remainingTries > 1) {
         auto remainTime = m_secretLifetime - (currentTime - request.challengeState->timestamp);
-        NDN_LOG_TRACE("Wrong secret code provided. Remaining Tries - 1.");
+        NDN_LOG_TRACE("Wrong secret, remaining tries = " << request.challengeState->remainingTries - 1);
         return returnWithNewChallengeStatus(request, WRONG_CODE, std::move(secret),
                                             request.challengeState->remainingTries - 1,
                                             time::duration_cast<time::seconds>(remainTime));
       }
       else {
-        // run out times
-        NDN_LOG_TRACE("Wrong secret code provided. Ran out of tries. Challenge failed.");
+        NDN_LOG_TRACE("Wrong secret, no tries remaining");
         return returnWithError(request, ErrorCode::OUT_OF_TRIES, "Ran out of tries.");
       }
     }
   }
-  return returnWithError(request, ErrorCode::INVALID_PARAMETER, "Unexpected status or challenge status");
+
+  return returnWithError(request, ErrorCode::INVALID_PARAMETER, "Unexpected challenge status.");
 }
 
 // For Client
@@ -116,7 +119,7 @@
     result.emplace(PARAMETER_KEY_CODE, "Incorrect code, please try again");
   }
   else {
-    NDN_THROW(std::runtime_error("Unexpected status or challenge status."));
+    NDN_THROW(std::runtime_error("Unexpected challenge status"));
   }
   return result;
 }
@@ -128,7 +131,7 @@
   Block request(tlv::EncryptedPayload);
   if (status == Status::BEFORE_CHALLENGE) {
     if (params.size() != 1 || params.find(PARAMETER_KEY_EMAIL) == params.end()) {
-      NDN_THROW(std::runtime_error("Wrong parameter provided."));
+      NDN_THROW(std::runtime_error("Wrong parameter provided"));
     }
     request.push_back(ndn::makeStringBlock(tlv::SelectedChallenge, CHALLENGE_TYPE));
     request.push_back(ndn::makeStringBlock(tlv::ParameterKey, PARAMETER_KEY_EMAIL));
@@ -136,14 +139,14 @@
   }
   else if (status == Status::CHALLENGE && (challengeStatus == NEED_CODE || challengeStatus == WRONG_CODE)) {
     if (params.size() != 1 || params.find(PARAMETER_KEY_CODE) == params.end()) {
-      NDN_THROW(std::runtime_error("Wrong parameter provided."));
+      NDN_THROW(std::runtime_error("Wrong parameter provided"));
     }
     request.push_back(ndn::makeStringBlock(tlv::SelectedChallenge, CHALLENGE_TYPE));
     request.push_back(ndn::makeStringBlock(tlv::ParameterKey, PARAMETER_KEY_CODE));
     request.push_back(ndn::makeStringBlock(tlv::ParameterValue, params.find(PARAMETER_KEY_CODE)->second));
   }
   else {
-    NDN_THROW(std::runtime_error("Unexpected status or challenge status."));
+    NDN_THROW(std::runtime_error("Unexpected challenge status"));
   }
   request.encode();
   return request;
@@ -168,11 +171,10 @@
   boost::process::child child(command);
   child.wait();
   if (child.exit_code() != 0) {
-    NDN_LOG_TRACE("EmailSending Script " + m_sendEmailScript + " fails.");
+    NDN_LOG_ERROR("Email sending script " + m_sendEmailScript + " failed");
   }
   else {
-    NDN_LOG_TRACE("EmailSending Script " + m_sendEmailScript +
-              " was executed successfully with return value 0.");
+    NDN_LOG_TRACE("Email sending script " + m_sendEmailScript + " succeeded");
   }
 }
 
diff --git a/src/challenge/challenge-pin.cpp b/src/challenge/challenge-pin.cpp
index 2662055..f38c778 100644
--- a/src/challenge/challenge-pin.cpp
+++ b/src/challenge/challenge-pin.cpp
@@ -43,47 +43,49 @@
 {
   params.parse();
   auto currentTime = time::system_clock::now();
+
   if (request.status == Status::BEFORE_CHALLENGE) {
-    NDN_LOG_TRACE("Challenge Interest arrives. Init the challenge");
+    NDN_LOG_TRACE("Begin challenge");
     // for the first time, init the challenge
     std::string secretCode = generateSecretCode();
     JsonSection secretJson;
     secretJson.add(PARAMETER_KEY_CODE, secretCode);
-    NDN_LOG_TRACE("Secret for request " << ndn::toHex(request.requestId)
-                  << " : " << secretCode);
+    NDN_LOG_TRACE("Secret for request " << ndn::toHex(request.requestId) << " is " << secretCode);
     return returnWithNewChallengeStatus(request, NEED_CODE, std::move(secretJson), m_maxAttemptTimes,
                                         m_secretLifetime);
   }
+
   if (request.challengeState) {
     if (request.challengeState->challengeStatus == NEED_CODE ||
         request.challengeState->challengeStatus == WRONG_CODE) {
-      NDN_LOG_TRACE("Challenge Interest arrives. Challenge Status: " << request.challengeState->challengeStatus);
+      NDN_LOG_TRACE("Challenge status: " << request.challengeState->challengeStatus);
       // the incoming interest should bring the pin code
       std::string givenCode = readString(params.get(tlv::ParameterValue));
       auto secret = request.challengeState->secrets;
       if (currentTime - request.challengeState->timestamp >= m_secretLifetime) {
+        NDN_LOG_TRACE("Secret expired");
         return returnWithError(request, ErrorCode::OUT_OF_TIME, "Secret expired.");
       }
       if (givenCode == secret.get<std::string>(PARAMETER_KEY_CODE)) {
-        NDN_LOG_TRACE("Correct PIN code. Challenge succeeded.");
+        NDN_LOG_TRACE("PIN is correct, challenge succeeded");
         return returnWithSuccess(request);
       }
       // check rest attempt times
       if (request.challengeState->remainingTries > 1) {
         auto remainTime = m_secretLifetime - (currentTime - request.challengeState->timestamp);
-        NDN_LOG_TRACE("Wrong PIN code provided. Remaining Tries - 1.");
+        NDN_LOG_TRACE("Wrong PIN, remaining tries = " << request.challengeState->remainingTries - 1);
         return returnWithNewChallengeStatus(request, WRONG_CODE, std::move(secret),
                                             request.challengeState->remainingTries - 1,
                                             time::duration_cast<time::seconds>(remainTime));
       }
       else {
-        // run out times
-        NDN_LOG_TRACE("Wrong PIN code provided. Ran out tires. Challenge failed.");
-        return returnWithError(request, ErrorCode::OUT_OF_TRIES, "Ran out tires.");
+        NDN_LOG_TRACE("Wrong PIN, no tries remaining");
+        return returnWithError(request, ErrorCode::OUT_OF_TRIES, "Ran out of tries.");
       }
     }
   }
-  return returnWithError(request, ErrorCode::INVALID_PARAMETER, "Unexpected status or challenge status");
+
+  return returnWithError(request, ErrorCode::INVALID_PARAMETER, "Unexpected challenge status.");
 }
 
 // For Client
@@ -101,7 +103,7 @@
     result.emplace(PARAMETER_KEY_CODE, "Incorrect PIN code, please try again");
   }
   else {
-    NDN_THROW(std::runtime_error("Unexpected status or challenge status."));
+    NDN_THROW(std::runtime_error("Unexpected challenge status"));
   }
   return result;
 }
@@ -116,14 +118,14 @@
   }
   else if (status == Status::CHALLENGE && (challengeStatus == NEED_CODE || challengeStatus == WRONG_CODE)) {
     if (params.size() != 1 || params.find(PARAMETER_KEY_CODE) == params.end()) {
-      NDN_THROW(std::runtime_error("Wrong parameter provided."));
+      NDN_THROW(std::runtime_error("Wrong parameter provided"));
     }
     request.push_back(ndn::makeStringBlock(tlv::SelectedChallenge, CHALLENGE_TYPE));
     request.push_back(ndn::makeStringBlock(tlv::ParameterKey, PARAMETER_KEY_CODE));
     request.push_back(ndn::makeStringBlock(tlv::ParameterValue, params.find(PARAMETER_KEY_CODE)->second));
   }
   else {
-    NDN_THROW(std::runtime_error("Unexpected status or challenge status."));
+    NDN_THROW(std::runtime_error("Unexpected challenge status"));
   }
   request.encode();
   return request;
diff --git a/src/challenge/challenge-possession.cpp b/src/challenge/challenge-possession.cpp
index 2473f29..ae85a8c 100644
--- a/src/challenge/challenge-possession.cpp
+++ b/src/challenge/challenge-possession.cpp
@@ -42,7 +42,7 @@
   : ChallengeModule("Possession", 1, time::seconds(60))
 {
   if (configPath.empty()) {
-    m_configFile = std::string(NDNCERT_SYSCONFDIR) + "/ndncert/challenge-credential.conf";
+    m_configFile = NDNCERT_SYSCONFDIR "/ndncert/challenge-credential.conf";
   }
   else {
     m_configFile = configPath;
@@ -62,7 +62,7 @@
   }
 
   if (config.begin() == config.end()) {
-    NDN_THROW(std::runtime_error("Error processing configuration file: " + m_configFile + " no data"));
+    NDN_THROW(std::runtime_error("Error processing configuration file " + m_configFile + ": no data"));
   }
 
   m_trustAnchors.clear();
@@ -72,7 +72,7 @@
     std::istringstream ss(it->second.get("certificate", ""));
     auto cert = ndn::io::load<Certificate>(ss);
     if (cert == nullptr) {
-      NDN_LOG_ERROR("Cannot load the certificate from config file");
+      NDN_LOG_ERROR("Cannot load certificate from configuration file");
       continue;
     }
     m_trustAnchors.push_back(*cert);
@@ -98,9 +98,8 @@
           credential.wireDecode(elements[i + 1].blockFromValue());
         }
         catch (const std::exception& e) {
-          NDN_LOG_ERROR("Cannot load challenge parameter: credential " << e.what());
-          return returnWithError(request, ErrorCode::INVALID_PARAMETER,
-                                 "Cannot challenge credential: credential."s + e.what());
+          NDN_LOG_ERROR("Cannot decode credential: " << e.what());
+          return returnWithError(request, ErrorCode::INVALID_PARAMETER, "Malformed credential.");
         }
       }
       else if (readString(elements[i]) == PARAMETER_KEY_PROOF) {
@@ -112,11 +111,11 @@
 
   // verify the credential and the self-signed cert
   if (request.status == Status::BEFORE_CHALLENGE) {
-    NDN_LOG_TRACE("Challenge Interest arrives. Check certificate and init the challenge");
+    NDN_LOG_TRACE("Begin challenge");
 
     // check the certificate
     if (!credential.hasContent() || signatureLen != 0) {
-      return returnWithError(request, ErrorCode::BAD_INTEREST_FORMAT, "Cannot find certificate");
+      return returnWithError(request, ErrorCode::BAD_INTEREST_FORMAT, "Cannot find certificate.");
     }
     auto keyLocator = credential.getSignatureInfo().getKeyLocator().getName();
     ndn::security::transform::PublicKey key;
@@ -126,7 +125,7 @@
              ndn::security::verifySignature(credential, anchor);
     });
     if (!checkOK) {
-      return returnWithError(request, ErrorCode::INVALID_PARAMETER, "Certificate cannot be verified");
+      return returnWithError(request, ErrorCode::INVALID_PARAMETER, "Certificate cannot be verified.");
     }
 
     // for the first time, init the challenge
@@ -135,19 +134,19 @@
     JsonSection secretJson;
     secretJson.add(PARAMETER_KEY_NONCE, ndn::toHex(secretCode));
     secretJson.add(PARAMETER_KEY_CREDENTIAL_CERT, ndn::toHex(credential.wireEncode()));
-    NDN_LOG_TRACE("Secret for request " << ndn::toHex(request.requestId) << " : " << ndn::toHex(secretCode));
+    NDN_LOG_TRACE("Secret for request " << ndn::toHex(request.requestId) << " is " << ndn::toHex(secretCode));
     return returnWithNewChallengeStatus(request, NEED_PROOF, std::move(secretJson), m_maxAttemptTimes, m_secretLifetime);
   }
   else if (request.challengeState && request.challengeState->challengeStatus == NEED_PROOF) {
-    NDN_LOG_TRACE("Challenge Interest (proof) arrives. Check the proof");
-    //check the format and load credential
+    NDN_LOG_TRACE("Checking proof");
+    // check the format and load credential
     if (credential.hasContent() || signatureLen == 0) {
-      return returnWithError(request, ErrorCode::BAD_INTEREST_FORMAT, "Cannot find certificate");
+      return returnWithError(request, ErrorCode::BAD_INTEREST_FORMAT, "Cannot find certificate.");
     }
     credential = Certificate(Block(ndn::fromHex(request.challengeState->secrets.get(PARAMETER_KEY_CREDENTIAL_CERT, ""))));
     auto secretCode = *ndn::fromHex(request.challengeState->secrets.get(PARAMETER_KEY_NONCE, ""));
 
-    //check the proof
+    // check the proof
     ndn::security::transform::PublicKey key;
     key.loadPkcs8(credential.getPublicKey());
     if (ndn::security::verifySignature({secretCode}, {signature, signatureLen}, key)) {
@@ -156,8 +155,9 @@
     return returnWithError(request, ErrorCode::INVALID_PARAMETER,
                            "Cannot verify the proof of private key against credential.");
   }
-  NDN_LOG_TRACE("Proof of possession: bad state");
-  return returnWithError(request, ErrorCode::INVALID_PARAMETER, "Fail to recognize the request.");
+
+  NDN_LOG_TRACE("Bad state");
+  return returnWithError(request, ErrorCode::INVALID_PARAMETER, "Cannot recognize the request.");
 }
 
 // For Client
@@ -173,7 +173,7 @@
     result.emplace(PARAMETER_KEY_PROOF, "Please sign a Data packet with request ID as the content.");
   }
   else {
-    NDN_THROW(std::runtime_error("Unexpected status or challenge status."));
+    NDN_THROW(std::runtime_error("Unexpected challenge status"));
   }
   return result;
 }
@@ -185,7 +185,7 @@
   Block request(tlv::EncryptedPayload);
   if (status == Status::BEFORE_CHALLENGE) {
     if (params.size() != 1) {
-      NDN_THROW(std::runtime_error("Wrong parameter provided."));
+      NDN_THROW(std::runtime_error("Wrong parameter provided"));
     }
     request.push_back(ndn::makeStringBlock(tlv::SelectedChallenge, CHALLENGE_TYPE));
     for (const auto& item : params) {
@@ -198,13 +198,13 @@
         request.push_back(valueBlock);
       }
       else {
-        NDN_THROW(std::runtime_error("Wrong parameter provided."));
+        NDN_THROW(std::runtime_error("Wrong parameter provided"));
       }
     }
   }
   else if (status == Status::CHALLENGE && challengeStatus == NEED_PROOF) {
     if (params.size() != 1) {
-      NDN_THROW(std::runtime_error("Wrong parameter provided."));
+      NDN_THROW(std::runtime_error("Wrong parameter provided"));
     }
     for (const auto& item : params) {
       if (std::get<0>(item) == PARAMETER_KEY_PROOF) {
@@ -212,12 +212,12 @@
         request.push_back(ndn::makeStringBlock(tlv::ParameterValue, std::get<1>(item)));
       }
       else {
-        NDN_THROW(std::runtime_error("Wrong parameter provided."));
+        NDN_THROW(std::runtime_error("Wrong parameter provided"));
       }
     }
   }
   else {
-    NDN_THROW(std::runtime_error("Unexpected status or challenge status."));
+    NDN_THROW(std::runtime_error("Unexpected challenge status"));
   }
   request.encode();
   return request;
diff --git a/src/detail/error-encoder.cpp b/src/detail/error-encoder.cpp
index db2b1ca..546ca4f 100644
--- a/src/detail/error-encoder.cpp
+++ b/src/detail/error-encoder.cpp
@@ -27,10 +27,10 @@
 NDN_LOG_INIT(ndncert.encode.error);
 
 Block
-encodeDataContent(ErrorCode errorCode, const std::string& description)
+encodeDataContent(ErrorCode errorCode, std::string_view description)
 {
   Block response(ndn::tlv::Content);
-  response.push_back(ndn::makeNonNegativeIntegerBlock(tlv::ErrorCode, static_cast<size_t>(errorCode)));
+  response.push_back(ndn::makeNonNegativeIntegerBlock(tlv::ErrorCode, static_cast<uint64_t>(errorCode)));
   response.push_back(ndn::makeStringBlock(tlv::ErrorInfo, description));
   response.encode();
   return response;
@@ -68,8 +68,9 @@
       return {ErrorCode::NO_ERROR, ""};
     }
     if (codeCount != 1 || infoCount != 1) {
-      NDN_THROW(std::runtime_error("Error TLV contains " + std::to_string(codeCount) + " error code(s) and " +
-                                   std::to_string(infoCount) + " error info(s), instead of expected 1 time each."));
+      NDN_THROW(std::runtime_error("Error TLV contains " + std::to_string(codeCount) +
+                                   " error code(s) and " + std::to_string(infoCount) +
+                                   " error info(s), instead of expected 1 time each."));
     }
     if (otherCriticalCount > 0) {
       NDN_THROW(std::runtime_error("Unknown critical TLV type in error packet"));
diff --git a/src/detail/error-encoder.hpp b/src/detail/error-encoder.hpp
index d41e6f6..53581f4 100644
--- a/src/detail/error-encoder.hpp
+++ b/src/detail/error-encoder.hpp
@@ -31,7 +31,7 @@
  * Encode error information into a Data content TLV
  */
 Block
-encodeDataContent(ErrorCode errorCode, const std::string& description);
+encodeDataContent(ErrorCode errorCode, std::string_view description);
 
 /**
  * Decode error information from Data content TLV
diff --git a/src/detail/info-encoder.cpp b/src/detail/info-encoder.cpp
index 4c260b4..2d327ba 100644
--- a/src/detail/info-encoder.cpp
+++ b/src/detail/info-encoder.cpp
@@ -20,12 +20,8 @@
 
 #include "detail/info-encoder.hpp"
 
-#include <ndn-cxx/util/logger.hpp>
-
 namespace ndncert::infotlv {
 
-NDN_LOG_INIT(ndncert.encode.info);
-
 Block
 encodeDataContent(const CaProfile& caConfig, const Certificate& certificate)
 {
@@ -45,7 +41,6 @@
   content.push_back(ndn::makeNonNegativeIntegerBlock(tlv::MaxValidityPeriod, caConfig.maxValidityPeriod.count()));
   content.push_back(makeNestedBlock(tlv::CaCertificate, certificate));
   content.encode();
-  NDN_LOG_TRACE("Encoding INFO packet with certificate " << certificate.getFullName());
   return content;
 }
 
diff --git a/src/detail/request-encoder.cpp b/src/detail/request-encoder.cpp
index 1187243..d240209 100644
--- a/src/detail/request-encoder.cpp
+++ b/src/detail/request-encoder.cpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /*
- * Copyright (c) 2017-2022, Regents of the University of California.
+ * Copyright (c) 2017-2024, Regents of the University of California.
  *
  * This file is part of ndncert, a certificate management system based on NDN.
  *
@@ -60,7 +60,7 @@
       ecdhPubCount++;
     }
     else if ((requestType == RequestType::NEW && item.type() == tlv::CertRequest) ||
-               (requestType == RequestType::REVOKE && item.type() == tlv::CertToRevoke)) {
+             (requestType == RequestType::REVOKE && item.type() == tlv::CertToRevoke)) {
       requestPayload = item;
       requestPayloadCount++;
       requestPayload.parse();
@@ -75,9 +75,9 @@
   }
 
   if (ecdhPubCount != 1 || requestPayloadCount != 1) {
-    NDN_THROW(std::runtime_error("Error TLV contains " + std::to_string(ecdhPubCount) + " ecdh public param(s) and " +
-                                 std::to_string(requestPayloadCount) +
-                                 "request payload(s), instead of expected 1 times each."));
+    NDN_THROW(std::runtime_error("TLV contains " + std::to_string(ecdhPubCount) +
+                                 " ecdh public param(s) and " + std::to_string(requestPayloadCount) +
+                                 " request payload(s), instead of expected 1 time each"));
   }
 }
 
@@ -100,9 +100,11 @@
 
 std::list <std::string>
 requesttlv::decodeDataContent(const Block& content, std::vector <uint8_t>& ecdhKey,
-                              std::array<uint8_t, 32>& salt, RequestId& requestId) {
-  std::list<std::string> challenges;
+                              std::array<uint8_t, 32>& salt, RequestId& requestId)
+{
   content.parse();
+
+  std::list<std::string> challenges;
   int ecdhPubCount = 0, saltCount = 0, requestIdCount = 0;
   for (auto const &element : content.elements()) {
     if (element.type() == tlv::Challenge) {
@@ -128,11 +130,13 @@
       //ignore
     }
   }
+
   if (ecdhPubCount != 1 || saltCount != 1 || requestIdCount != 1) {
-    NDN_THROW(std::runtime_error("Error TLV contains " + std::to_string(ecdhPubCount) + " ecdh public param(s), " +
+    NDN_THROW(std::runtime_error("TLV contains " + std::to_string(ecdhPubCount) + " ecdh public param(s), " +
                                  std::to_string(saltCount) + " salt(s) and " + std::to_string(requestIdCount) +
-                                 "request id(s), instead of expected 1 times each."));
+                                 " request id(s), instead of expected 1 time each"));
   }
+
   return challenges;
 }
 
diff --git a/src/redirection/redirection-policy.hpp b/src/redirection/redirection-policy.hpp
index 9e55467..462a721 100644
--- a/src/redirection/redirection-policy.hpp
+++ b/src/redirection/redirection-policy.hpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /*
- * Copyright (c) 2017-2022, Regents of the University of California.
+ * Copyright (c) 2017-2024, Regents of the University of California.
  *
  * This file is part of ndncert, a certificate management system based on NDN.
  *
@@ -21,7 +21,7 @@
 #ifndef NDNCERT_REDIRECTION_POLICY_HPP
 #define NDNCERT_REDIRECTION_POLICY_HPP
 
-#include "detail/ca-request-state.hpp"
+#include "detail/ndncert-common.hpp"
 
 #include <map>
 
@@ -35,10 +35,8 @@
 
   /**
    * @brief The Redirection Policy provided by the CA operator to decide if redirection is suitable.
-   *
-   *
-   * @param vector A list of parameter key-value pair from probe.
-   * @return a boolean that is true if the provided params conform to the configured redirection policy.
+   * @param params A list of parameter key-value pairs from the probe.
+   * @return true if the provided @p params conform to the configured redirection policy.
    */
   virtual bool
   isRedirecting(const std::multimap<std::string, std::string>& params) = 0;