Skip to content

Commit

Permalink
labelHash function added (#2140)
Browse files Browse the repository at this point in the history
Signed-off-by: Nischal Sharma <[email protected]>
  • Loading branch information
NickSneo authored Jan 20, 2025
1 parent 2e64ff9 commit bf61f86
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
13 changes: 13 additions & 0 deletions core/src/main/java/org/web3j/ens/NameHash.java
Original file line number Diff line number Diff line change
Expand Up @@ -107,4 +107,17 @@ public static String dnsEncode(String name) throws IOException {

return Numeric.toHexString(outputStream.toByteArray()) + "00";
}

public static String labelHash(String ensName) {
if (ensName.isEmpty()) {
return Numeric.toHexString(EMPTY);
} else {
String normalisedEnsName = normalise(ensName);
return Numeric.toHexString(Hash.sha3(normalisedEnsName.split("\\.")[0].getBytes(StandardCharsets.UTF_8)));
}
}

public static byte[] labelHashAsBytes(String ensName) {
return Numeric.hexStringToByteArray(labelHash(ensName));
}
}
20 changes: 20 additions & 0 deletions core/src/test/java/org/web3j/ens/NameHashTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.web3j.ens.NameHash.labelHash;
import static org.web3j.ens.NameHash.nameHash;
import static org.web3j.ens.NameHash.normalise;

Expand All @@ -42,6 +43,25 @@ void testNameHash() {
("0xf7de5954cda078ee481b14cff677e8066fe805a89b5c87b4a9b866338049b04a"));
}

@Test
void testLabelHash() {
assertEquals(
labelHash(""),
("0x0000000000000000000000000000000000000000000000000000000000000000"));

assertEquals(
labelHash("label"),
("0x1b036544434cea9770a413fd03e0fb240e1ccbd10a452f7dba85c8eca9ca3eda"));

assertEquals(
labelHash("label.eth"),
("0x1b036544434cea9770a413fd03e0fb240e1ccbd10a452f7dba85c8eca9ca3eda"));

assertEquals(
labelHash("\uD83D\uDC8E.gmcafe.art"),
("0xed2cc33b0587afe42a04579d79c23b72b25c5416efcb50c674f3f59e2db9cce6"));
}

@Test
void testNormalise() {
assertEquals(normalise("foo"), ("foo"));
Expand Down

0 comments on commit bf61f86

Please sign in to comment.