diff --git a/quartz/src/main/java/com/vitorpamplona/quartz/nip13Pow/miner/ByteArrayExt.kt b/quartz/src/main/java/com/vitorpamplona/quartz/nip13Pow/miner/ByteArrayExt.kt index b4dfbc714..f931ecdeb 100644 --- a/quartz/src/main/java/com/vitorpamplona/quartz/nip13Pow/miner/ByteArrayExt.kt +++ b/quartz/src/main/java/com/vitorpamplona/quartz/nip13Pow/miner/ByteArrayExt.kt @@ -37,13 +37,3 @@ fun ByteArray.indexOf(sequence: ByteArray): Int { } return -1 } - -fun ByteArray.set( - value: ByteArray, - startIndex: Int, -) { - var index = startIndex - for (byte in value) { - this[index++] = byte - } -} diff --git a/quartz/src/main/java/com/vitorpamplona/quartz/nip13Pow/miner/PoWMiner.kt b/quartz/src/main/java/com/vitorpamplona/quartz/nip13Pow/miner/PoWMiner.kt index 3169e49e6..bd3984e9e 100644 --- a/quartz/src/main/java/com/vitorpamplona/quartz/nip13Pow/miner/PoWMiner.kt +++ b/quartz/src/main/java/com/vitorpamplona/quartz/nip13Pow/miner/PoWMiner.kt @@ -32,8 +32,9 @@ class PoWMiner( val desiredPoW: Int, ) { val hasher = Sha256Hasher() + val emptyBytesForDesiredPoW = desiredPoW / 8 - fun rank(byteArray: ByteArray) = PoWRankEvaluator.calculatePowRankOf(hasher.hash(byteArray)) + fun reachedDesiredPoW(byteArray: ByteArray) = PoWRankEvaluator.atLeastPowRank(hasher.hash(byteArray), desiredPoW, emptyBytesForDesiredPoW) fun run() = runDigit(buffer.nonceStarts) @@ -42,15 +43,17 @@ class PoWMiner( // replaces the background base by the nonce integers buffer.bytes[index] = testByte - if (rank(buffer.bytes) >= desiredPoW) return true - - if (index + 1 < buffer.nonceEnds && runDigit(index + 1)) return true + if (index + 1 < buffer.nonceEnds) { + if (runDigit(index + 1)) return true + } else { + if (reachedDesiredPoW(buffer.bytes)) return true + } } return false } companion object { - private val STARTING_NONCE_SIZE = 5 + private const val STARTING_NONCE_SIZE = 5 // make sure these chars are not escaped by the JSON stringifier private val VALID_CHARS: List = diff --git a/quartz/src/main/java/com/vitorpamplona/quartz/nip13Pow/miner/PoWRankEvaluator.kt b/quartz/src/main/java/com/vitorpamplona/quartz/nip13Pow/miner/PoWRankEvaluator.kt index 0a65d591f..5b521b180 100644 --- a/quartz/src/main/java/com/vitorpamplona/quartz/nip13Pow/miner/PoWRankEvaluator.kt +++ b/quartz/src/main/java/com/vitorpamplona/quartz/nip13Pow/miner/PoWRankEvaluator.kt @@ -103,5 +103,18 @@ class PoWRankEvaluator { } return rank } + + @JvmStatic + fun atLeastPowRank( + id: ByteArray, + minPoW: Int, + emptyBytes: Int, + ): Boolean { + for (index in 0 until emptyBytes) { + if (id[index] != R8) return false + } + + return calculatePowRankOf(id) >= minPoW + } } }