From ab4021dd0ee37af0af4137dc772911ea8ec52bb2 Mon Sep 17 00:00:00 2001
From: Adam Ierymenko <adam.ierymenko@gmail.com>
Date: Fri, 18 Nov 2016 11:09:19 -0800
Subject: [PATCH] Do packet MAC check before locallyValidate(), and add timing
 measurement in selftest.

---
 node/IncomingPacket.cpp | 15 ++++++++-------
 selftest.cpp            | 12 ++++++++----
 2 files changed, 16 insertions(+), 11 deletions(-)

diff --git a/node/IncomingPacket.cpp b/node/IncomingPacket.cpp
index c6346346e..ee4d62c08 100644
--- a/node/IncomingPacket.cpp
+++ b/node/IncomingPacket.cpp
@@ -275,7 +275,7 @@ bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR,const bool alreadyAut
 
 					// Continue at // VALID
 				}
-			} // else continue at // VALID
+			} // else if alreadyAuthenticated then continue at // VALID
 		} else {
 			// We don't already have an identity with this address -- validate and learn it
 
@@ -285,18 +285,19 @@ bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR,const bool alreadyAut
 				return true;
 			}
 
+			// Check packet integrity and MAC
+			SharedPtr<Peer> newPeer(new Peer(RR,RR->identity,id));
+			if (!dearmor(newPeer->key())) {
+				TRACE("rejected HELLO from %s(%s): packet failed authentication",id.address().toString().c_str(),_path->address().toString().c_str());
+				return true;
+			}
+
 			// Check that identity's address is valid as per the derivation function
 			if (!id.locallyValidate()) {
 				TRACE("dropped HELLO from %s(%s): identity invalid",id.address().toString().c_str(),_path->address().toString().c_str());
 				return true;
 			}
 
-			// Check packet integrity and authentication
-			SharedPtr<Peer> newPeer(new Peer(RR,RR->identity,id));
-			if (!dearmor(newPeer->key())) {
-				TRACE("rejected HELLO from %s(%s): packet failed authentication",id.address().toString().c_str(),_path->address().toString().c_str());
-				return true;
-			}
 			peer = RR->topology->addPeer(newPeer);
 
 			// Continue at // VALID
diff --git a/selftest.cpp b/selftest.cpp
index 7ca4ac3b1..9992d7575 100644
--- a/selftest.cpp
+++ b/selftest.cpp
@@ -376,11 +376,15 @@ static int testIdentity()
 		std::cout << "FAIL (1)" << std::endl;
 		return -1;
 	}
-	if (!id.locallyValidate()) {
-		std::cout << "FAIL (2)" << std::endl;
-		return -1;
+	const uint64_t vst = OSUtils::now();
+	for(int k=0;k<10;++k) {
+		if (!id.locallyValidate()) {
+			std::cout << "FAIL (2)" << std::endl;
+			return -1;
+		}
 	}
-	std::cout << "PASS" << std::endl;
+	const uint64_t vet = OSUtils::now();
+	std::cout << "PASS (" << ((double)(vet - vst) / 10.0) << "ms per validation)" << std::endl;
 
 	std::cout << "[identity] Validate known-bad identity... "; std::cout.flush();
 	if (!id.fromString(KNOWN_BAD_IDENTITY)) {