-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.java
More file actions
186 lines (160 loc) · 6.63 KB
/
Copy pathClient.java
File metadata and controls
186 lines (160 loc) · 6.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import java.util.List;
import java.util.Random;
import java.nio.ByteBuffer;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.layered.TFramedTransport;
import org.apache.thrift.transport.TTransportFactory;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import org.bitcoinj.base.Difficulty;
import org.bitcoinj.base.Sha256Hash;
import org.bitcoinj.core.Block;
import org.bitcoinj.core.Transaction;
public class Client {
private static volatile boolean miningStarted = false;
private static volatile boolean shouldExit = false;
private static volatile long lastCancelTime = 0;
private static final Object lock = new Object();
public static void main(String [] args) {
if (args.length != 2) {
System.err.println("Usage: java Client host port");
System.exit(-1);
}
final String host = args[0];
final int port = Integer.parseInt(args[1]);
Thread cancelThread = new Thread(new Runnable() {
@Override
public void run() {
try {
TSocket cancelSock = new TSocket(host, port);
TTransport cancelTransport = new TFramedTransport(cancelSock);
TProtocol cancelProtocol = new TBinaryProtocol(cancelTransport);
MiningPoolService.Client cancelClient = new MiningPoolService.Client(cancelProtocol);
cancelTransport.open();
while (!shouldExit) {
synchronized (lock) {
while (!miningStarted && !shouldExit) {
try {
lock.wait();
} catch (InterruptedException e) {
return;
}
}
}
if (shouldExit) break;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
break;
}
if (!shouldExit && miningStarted) {
try {
cancelClient.cancel();
lastCancelTime = System.currentTimeMillis();
System.out.println("[CANCEL] Sent cancel request at " + lastCancelTime);
} catch (TException e) {
System.err.println("[CANCEL] Error: " + e.getMessage());
}
}
synchronized (lock) {
while (miningStarted && !shouldExit) {
try {
lock.wait();
} catch (InterruptedException e) {
return;
}
}
}
}
cancelTransport.close();
} catch (TException x) {
System.err.println("[CANCEL] Connection error: " + x.getMessage());
}
}
});
cancelThread.setDaemon(true);
cancelThread.start();
try {
TSocket sock = new TSocket(host, port);
TTransport transport = new TFramedTransport(sock);
TProtocol protocol = new TBinaryProtocol(transport);
MiningPoolService.Client client = new MiningPoolService.Client(protocol);
transport.open();
int version = 1;
Random random = new Random();
int runs = 50;
long totalMs = 0;
int successfulRuns = 0;
long firstRunStart = 0;
long lastRunEnd = 0;
for (int i = 0; i < runs; i++) {
byte[] bytes1 = new byte[32];
random.nextBytes(bytes1);
Sha256Hash prevBlockHash = Sha256Hash.wrap(bytes1);
byte[] bytes2 = new byte[32];
random.nextBytes(bytes2);
Sha256Hash merkleRootHash = Sha256Hash.wrap(bytes2);
Instant time = Instant.now().truncatedTo(ChronoUnit.SECONDS);
Difficulty difficulty = Difficulty.ofCompact(0x1e290000);
long nonce = 0;
List<Transaction> txns = null;
Block b = new Block(version, prevBlockHash, merkleRootHash, time, difficulty, nonce, txns);
lastCancelTime = 0;
synchronized (lock) {
miningStarted = true;
lock.notifyAll();
}
long start = System.currentTimeMillis();
if (i == 0) firstRunStart = start;
try {
ByteBuffer buf1 = ByteBuffer.wrap(bytes1);
ByteBuffer buf2 = ByteBuffer.wrap(bytes2);
nonce = client.mineBlock(version, buf1, buf2, time.getEpochSecond(), difficulty.compact());
} catch (Exception e) {
System.out.println("Exception check: exception thrown");
}
long end = System.currentTimeMillis();
long dur = end - start;
lastRunEnd = end;
boolean wasCancelled = (lastCancelTime > 0 && lastCancelTime >= start && lastCancelTime <= end);
if (!wasCancelled) {
totalMs += dur;
b.setNonce(nonce);
Sha256Hash hash = b.getHash();
boolean ok = Difficulty.ofCompact(0x1e290000).isMetByWork(hash);
if (ok) {
successfulRuns++;
}
System.out.println("Run " + (i+1) + "/" + runs + ": duration=" + dur + " ms, nonce=" + nonce + ", ok=" + ok);
} else {
System.out.println("Run " + (i+1) + "/" + runs + ": cancelled (duration=" + dur + " ms, skipping validation)");
}
synchronized (lock) {
miningStarted = false;
lock.notifyAll();
}
}
double avgDuration = totalMs / (double) successfulRuns;
long totalElapsedTime = lastRunEnd - firstRunStart;
double totalElapsedSec = totalElapsedTime / 1000.0;
double throughput = successfulRuns / totalElapsedSec;
System.out.println("\n========== RESULTS ==========");
System.out.println("Total runs: " + runs);
System.out.println("Successful runs: " + successfulRuns + " (correct nonce + not cancelled)");
System.out.println("Cancelled runs: " + (runs - successfulRuns));
System.out.println("Total elapsed time: " + totalElapsedSec + " seconds");
System.out.println("Average duration: " + avgDuration + " ms (successful runs only)");
System.out.println("THROUGHPUT: " + String.format("%.2f", throughput) + " blocks/s");
System.out.println("=============================\n");
shouldExit = true;
transport.close();
} catch (TException x) {
System.err.println("[MAIN] Error: " + x.getMessage());
shouldExit = true;
}
}
}