Adds an event id hash check that doesn't create a separate bytearray to compare between the incoming hex from the relay and the recalculated byte array from SHA256.

This commit is contained in:
Vitor Pamplona
2025-09-16 17:06:01 -04:00
parent 80c884a4d1
commit 83e87c2cf4
4 changed files with 39 additions and 2 deletions

View File

@@ -43,6 +43,13 @@ class HexBenchmark {
fr.acinq.secp256k1.Hex
.decode(hex)
@Test
fun hexIsEqual() {
r.measureRepeated {
assert(Hex.isEqual(hex, bytes))
}
}
@Test
fun hexDecodeOurs() {
r.measureRepeated {

View File

@@ -30,7 +30,7 @@ fun Event.generateId(): String = EventHasher.hashId(pubKey, createdAt, kind, tag
fun Event.verifyId(): Boolean {
if (id.isEmpty()) return false
return id == generateId()
return EventHasher.hashIdEquals(id, pubKey, createdAt, kind, tags, content)
}
fun Event.verifySignature(): Boolean {

View File

@@ -25,6 +25,7 @@ import com.fasterxml.jackson.databind.node.JsonNodeFactory
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
import com.vitorpamplona.quartz.nip01Core.jackson.JsonMapper
import com.vitorpamplona.quartz.utils.Hex
import com.vitorpamplona.quartz.utils.sha256.sha256
class EventHasher {
@@ -80,5 +81,17 @@ class EventHasher {
tags: Array<Array<String>>,
content: String,
): String = hashIdBytes(pubKey, createdAt, kind, tags, content).toHexKey()
fun hashIdEquals(
id: HexKey,
pubKey: HexKey,
createdAt: Long,
kind: Int,
tags: Array<Array<String>>,
content: String,
): Boolean {
val outId = hashIdBytes(pubKey, createdAt, kind, tags, content)
return Hex.isEqual(id, outId)
}
}
}
}

View File

@@ -74,4 +74,21 @@ object Hex {
}
return String(out)
}
fun isEqual(
id: String,
ourId: ByteArray,
): Boolean {
var charIndex = 0
for (i in 0 until ourId.size) {
val chars = byteToHex[ourId[i].toInt() and 0xFF]
if (
id[charIndex++] != (chars shr 8).toChar() ||
id[charIndex++] != (chars and 0xFF).toChar()
) {
return false
}
}
return true
}
}