From bf61f86a4c2e06f7d952b3d9f9ccf8fb275aeb9b Mon Sep 17 00:00:00 2001 From: Nischal Sharma Date: Mon, 20 Jan 2025 14:40:37 +0530 Subject: [PATCH] labelHash function added (#2140) Signed-off-by: Nischal Sharma --- .../src/main/java/org/web3j/ens/NameHash.java | 13 ++++++++++++ .../test/java/org/web3j/ens/NameHashTest.java | 20 +++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/core/src/main/java/org/web3j/ens/NameHash.java b/core/src/main/java/org/web3j/ens/NameHash.java index 9e24de122..85cbe80df 100644 --- a/core/src/main/java/org/web3j/ens/NameHash.java +++ b/core/src/main/java/org/web3j/ens/NameHash.java @@ -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)); + } } diff --git a/core/src/test/java/org/web3j/ens/NameHashTest.java b/core/src/test/java/org/web3j/ens/NameHashTest.java index 186577113..baa1aa105 100644 --- a/core/src/test/java/org/web3j/ens/NameHashTest.java +++ b/core/src/test/java/org/web3j/ens/NameHashTest.java @@ -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; @@ -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"));