Skip to content

Commit

Permalink
perf(NameRegistry): optimize by checking for good case in _validateNa…
Browse files Browse the repository at this point in the history
…me (#123)
  • Loading branch information
varunsrin authored Sep 13, 2022
1 parent 7aec133 commit 1c6bfac
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 19 deletions.
8 changes: 4 additions & 4 deletions .gas-snapshot
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
BundleRegistryGasUsageTest:testGasRegister() (gas: 2099140)
BundleRegistryGasUsageTest:testGasTrustedRegister() (gas: 1792448)
BundleRegistryGasUsageTest:testGasRegister() (gas: 2081200)
BundleRegistryGasUsageTest:testGasTrustedRegister() (gas: 1783478)
IDRegistryGasUsageTest:testGasRegisterAndRecover() (gas: 2077004)
IDRegistryGasUsageTest:testGasRegisterFromTrustedCaller() (gas: 838954)
NameRegistryGasUsageTest:testGasRegisterUsage() (gas: 2322626)
NameRegistryGasUsageTest:testGasTrustedRegisterUsage() (gas: 1167366)
NameRegistryGasUsageTest:testGasRegisterUsage() (gas: 2308274)
NameRegistryGasUsageTest:testGasTrustedRegisterUsage() (gas: 1158396)
34 changes: 19 additions & 15 deletions src/NameRegistry.sol
Original file line number Diff line number Diff line change
Expand Up @@ -1182,7 +1182,7 @@ contract NameRegistry is
// solhint-disable-next-line code-complexity
function _validateName(bytes16 fname) internal pure {
uint256 length = fname.length;
bool nameEnded = false;
bool nameEnded;

/**
* Iterate over the bytes16 fname one char at a time, ensuring that:
Expand All @@ -1197,40 +1197,44 @@ contract NameRegistry is
for (uint256 i = 0; i < length; ) {
uint8 charInt = uint8(fname[i]);

unchecked {
// Safety: i can never overflow because length is guaranteed to be <= 16
i++;
}

if (nameEnded) {
// Only NULL characters are allowed after a name has ended
if (charInt != 0) {
revert InvalidName();
}
} else {
// Only valid ASCII characters [45, 48-57, 97-122] are allowed before the name ends
if ((charInt >= 1 && charInt <= 44)) {
revert InvalidName();
}

if ((charInt >= 46 && charInt <= 47)) {
revert InvalidName();
// Check if the character is a-z
if ((charInt >= 97 && charInt <= 122)) {
continue;
}

if ((charInt >= 58 && charInt <= 96)) {
revert InvalidName();
// Check if the character is 0-9
if ((charInt >= 48 && charInt <= 57)) {
continue;
}

if (charInt >= 123) {
revert InvalidName();
// Check if the character is a hyphen
if ((charInt == 45)) {
continue;
}

// On seeing the first NULL char in the name, revert if is the first char in the
// name, otherwise mark the name as ended
if (charInt == 0) {
if (i == 0) revert InvalidName();
// We check i==1 instead of i==0 because i is incremented before the check
if (i == 1) revert InvalidName();
nameEnded = true;
continue;
}
}

unchecked {
// Safety: i can never overflow because length is guaranteed to be <= 16
i++;
revert InvalidName();
}
}
}
Expand Down

0 comments on commit 1c6bfac

Please sign in to comment.