Skip to content

Instantly share code, notes, and snippets.

@odds-get-evened
Created December 20, 2021 22:14
Show Gist options
  • Save odds-get-evened/756ea3c3650761becc7be796b81ddb0f to your computer and use it in GitHub Desktop.
Save odds-get-evened/756ea3c3650761becc7be796b81ddb0f to your computer and use it in GitHub Desktop.
Simple Proof-of-Work
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
class PoW {
private int bitsNeeded = 0;
private int nonce = 0;
private long timestamp;
private String hash;
public PoW(byte[] msg, int numZeroes) throws NoSuchAlgorithmException {
bitsNeeded = numZeroes;
timestamp = Instant.now().toEpochMilli();
work(msg);
System.out.println("Work factor " + nonce);
}
private void work(byte[] msg) throws NoSuchAlgorithmException {
String prefix = StringUtils.repeat("0", bitsNeeded);
String hexMsg = Hex.encodeHexString(msg);
hash = DigestUtils.sha256Hex(reMessage(hexMsg));
while(!hash.startsWith(prefix)) {
timestamp = Instant.now().toEpochMilli();
nonce += 1;
hash = DigestUtils.sha256Hex(reMessage(hexMsg));
}
}
private String reMessage(String msg) {
StringBuilder sb = new StringBuilder(String.valueOf(timestamp));
sb.append(msg);
sb.append(nonce);
return sb.toString();
}
public static void main(String[] args) throws NoSuchAlgorithmException {
PoW pow1 = new PoW("0000000Hello worlds this is kitty mew mew!".getBytes(StandardCharsets.UTF_8), 4);
PoW pow2 = new PoW("RAWR me hangry value is soul".getBytes(StandardCharsets.UTF_8), 3);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment