Java: Generate Bitcoin & Ethereum Target from Difficulty
The other day I was making a small CPU miner for Ethereum using Java. I decided to implement the stratum protocol and I came to the following... difficulty.
Stratum does not send the target directly to the miner as the Getwork protocol does. Stratum sends a double data type that holds the difficulty and the miner have to generate the target from that.
Stratum example message of mining difficulty:
The code is written in simple Java and does not need any external libraries.
Stratum does not send the target directly to the miner as the Getwork protocol does. Stratum sends a double data type that holds the difficulty and the miner have to generate the target from that.
Stratum example message of mining difficulty:
{ "id": null, "method": "mining.set_difficulty", "params": [ 0.5 ] }\n
The Java Solution!
As I read online the conversion between difficulty and target is done the same way as with Bitcoin but it is not very clear how can someone do that so... I decided to post my code and maybe make the life of others a bit easier.The code is written in simple Java and does not need any external libraries.
public static void main(String[] args) { String target = GetTargetFromDifficulty(1); System.out.println("Target for difficulty 1 is " + target); } private static String GetTargetFromDifficulty(double difficulty) { // Note: difficulty of 1 is transformed to target being in HEX: // 00000000ffff0000000000000000000000000000000000000000000000000000 long m; int k; byte[] target = new byte[8 * 4]; for (k = 6; k > 0 && difficulty > 1.0; k--) { difficulty /= 4294967296.0; } m = (long) (4294901760.0 / difficulty); if (m == 0 && k == 6) { Arrays.fill(target, (byte) 0xff); } else { Arrays.fill(target, (byte) 0); for (int i = 0; i < 8; i++) { target[k * 4 + i] = (byte) ((m >> (i * 8)) & 0xff); } } String tmp = toHexString(target); String reverse = new StringBuffer(tmp).reverse().toString(); return reverse; } private static String toHexString(byte[] b) { StringBuilder sb = new StringBuilder(80); for (int i = 0; i < b.length; i++) { sb.append(Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); }
Your music is amazing. You have some very talented artists. I wish you the best of success.
ReplyDeleteEthereum
Cool stuff you have got and you keep update all of us. ethereum
ReplyDelete