Performance improvements on the PoW miner

This commit is contained in:
Vitor Pamplona 2025-02-18 20:44:24 -05:00
parent af29133272
commit 94e0f4ed02
3 changed files with 21 additions and 15 deletions

View File

@ -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
}
}

View File

@ -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<Char> =

View File

@ -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
}
}
}