From 215800fb67ca05e8c3d7df8ad4e3b5a0b7384660 Mon Sep 17 00:00:00 2001 From: CalDescent Date: Fri, 1 Jul 2022 22:36:51 +0100 Subject: [PATCH] Added optional "timeout" parameter to MemoryPoW.compute2(). This can be used to give up after the specified number of milliseconds. --- .../java/org/qortal/crypto/MemoryPoW.java | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/src/main/java/org/qortal/crypto/MemoryPoW.java b/src/main/java/org/qortal/crypto/MemoryPoW.java index 01f4f6fd..f27c8f7a 100644 --- a/src/main/java/org/qortal/crypto/MemoryPoW.java +++ b/src/main/java/org/qortal/crypto/MemoryPoW.java @@ -1,10 +1,44 @@ package org.qortal.crypto; +import org.qortal.utils.NTP; + import java.nio.ByteBuffer; +import java.util.concurrent.TimeoutException; public class MemoryPoW { + /** + * Compute a MemoryPoW nonce + * + * @param data + * @param workBufferLength + * @param difficulty + * @return + * @throws TimeoutException + */ public static Integer compute2(byte[] data, int workBufferLength, long difficulty) { + try { + return MemoryPoW.compute2(data, workBufferLength, difficulty, null); + + } catch (TimeoutException e) { + // This won't happen, because above timeout is null + return null; + } + } + + /** + * Compute a MemoryPoW nonce, with optional timeout + * + * @param data + * @param workBufferLength + * @param difficulty + * @param timeout maximum number of milliseconds to compute for before giving up,
or null if no timeout + * @return + * @throws TimeoutException + */ + public static Integer compute2(byte[] data, int workBufferLength, long difficulty, Long timeout) throws TimeoutException { + long startTime = NTP.getTime(); + // Hash data with SHA256 byte[] hash = Crypto.digest(data); @@ -33,6 +67,13 @@ public class MemoryPoW { if (Thread.currentThread().isInterrupted()) return -1; + if (timeout != null) { + long now = NTP.getTime(); + if (now > startTime + timeout) { + throw new TimeoutException("Timeout reached"); + } + } + seed *= seedMultiplier; // per nonce state[0] = longHash[0] ^ seed;