apow-cli 0.9.0 → 0.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +9 -5
- package/dist/build.js +229 -0
- package/dist/clawrouter.js +96 -0
- package/dist/config.js +4 -3
- package/dist/errors.js +16 -0
- package/dist/grinder-native.js +71 -2
- package/dist/grinder.js +14 -0
- package/dist/index.js +29 -5
- package/dist/miner.js +77 -29
- package/dist/preflight.js +17 -2
- package/dist/smhl.js +56 -0
- package/local/gpu/Makefile +39 -0
- package/local/gpu/grinder-cpu.c +241 -0
- package/local/gpu/grinder-cuda.cu +322 -0
- package/local/gpu/grinder.m +191 -0
- package/local/gpu/keccak.metal +143 -0
- package/package.json +9 -3
- package/skill.md +46 -29
package/dist/miner.js
CHANGED
|
@@ -240,11 +240,11 @@ async function startMining(tokenId) {
|
|
|
240
240
|
abi: agentCoinAbi,
|
|
241
241
|
functionName: "getMiningChallenge",
|
|
242
242
|
}));
|
|
243
|
-
|
|
244
|
-
const smhl = (0, smhl_1.normalizeSmhlChallenge)(
|
|
243
|
+
let [challengeNumber, target] = [miningChallenge[0], miningChallenge[1]];
|
|
244
|
+
const smhl = (0, smhl_1.normalizeSmhlChallenge)(miningChallenge[2]);
|
|
245
245
|
// Solve SMHL algorithmically (sub-millisecond)
|
|
246
246
|
const smhlStart = process.hrtime();
|
|
247
|
-
|
|
247
|
+
let smhlSolution = (0, smhl_1.solveSmhlAlgorithmic)(smhl);
|
|
248
248
|
const smhlIssues = (0, smhl_1.validateSmhlSolution)(smhlSolution, smhl);
|
|
249
249
|
if (smhlIssues.length > 0) {
|
|
250
250
|
throw new Error(`SMHL generation failed: ${smhlIssues.join(", ")}`);
|
|
@@ -252,36 +252,84 @@ async function startMining(tokenId) {
|
|
|
252
252
|
const smhlElapsed = elapsedSeconds(smhlStart);
|
|
253
253
|
console.log(` ${ui.dim(`SMHL solved (${(smhlElapsed * 1000).toFixed(1)}ms)`)}`);
|
|
254
254
|
// Grind nonce — native GPU/CPU if available, JS fallback
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
255
|
+
// Abort and re-fetch challenge every STALE_CHECK_INTERVAL_MS to avoid
|
|
256
|
+
// grinding a dead nonce after another miner wins the block.
|
|
257
|
+
const STALE_CHECK_INTERVAL_MS = 20_000;
|
|
258
|
+
let grind = null;
|
|
259
|
+
while (!grind) {
|
|
260
|
+
const abortController = new AbortController();
|
|
261
|
+
const nonceSpinner = ui.spinner(`Grinding nonce (${modeLabel})...`);
|
|
262
|
+
// Background staleness checker — polls challenge every 20s
|
|
263
|
+
const staleTimer = setInterval(async () => {
|
|
264
|
+
try {
|
|
265
|
+
const fresh = (await wallet_1.publicClient.readContract({
|
|
266
|
+
address: config_1.config.agentCoinAddress,
|
|
267
|
+
abi: agentCoinAbi,
|
|
268
|
+
functionName: "getMiningChallenge",
|
|
269
|
+
}));
|
|
270
|
+
if (fresh[0] !== challengeNumber) {
|
|
271
|
+
nonceSpinner.stop("Challenge changed — restarting grind");
|
|
272
|
+
abortController.abort();
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
catch {
|
|
276
|
+
// RPC hiccup — don't abort, just skip this check
|
|
277
|
+
}
|
|
278
|
+
}, STALE_CHECK_INTERVAL_MS);
|
|
258
279
|
try {
|
|
259
|
-
|
|
280
|
+
if (useNative) {
|
|
281
|
+
try {
|
|
282
|
+
grind = await (0, grinder_native_1.grindNonceNative)(challengeNumber, target, account.address, grinderInfo, abortController.signal);
|
|
283
|
+
}
|
|
284
|
+
catch (err) {
|
|
285
|
+
if (abortController.signal.aborted)
|
|
286
|
+
throw err; // re-throw abort
|
|
287
|
+
nonceSpinner.update("Native grinder failed — falling back to JS...");
|
|
288
|
+
grind = await (0, grinder_1.grindNonceParallel)({
|
|
289
|
+
challengeNumber,
|
|
290
|
+
target,
|
|
291
|
+
minerAddress: account.address,
|
|
292
|
+
threads: config_1.config.minerThreads,
|
|
293
|
+
signal: abortController.signal,
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
else {
|
|
298
|
+
grind = await (0, grinder_1.grindNonceParallel)({
|
|
299
|
+
challengeNumber,
|
|
300
|
+
target,
|
|
301
|
+
minerAddress: account.address,
|
|
302
|
+
threads: config_1.config.minerThreads,
|
|
303
|
+
signal: abortController.signal,
|
|
304
|
+
onProgress: (attempts, hashrate) => {
|
|
305
|
+
const khs = (hashrate / 1000).toFixed(0);
|
|
306
|
+
nonceSpinner.update(`Grinding nonce (JS)... ${khs}k H/s (${attempts.toLocaleString()} attempts)`);
|
|
307
|
+
},
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
clearInterval(staleTimer);
|
|
311
|
+
const khs = grind.hashrate > 0 ? (grind.hashrate / 1000).toFixed(0) : "?";
|
|
312
|
+
nonceSpinner.stop(`Nonce found (${grind.elapsed.toFixed(1)}s${grind.hashrate > 0 ? `, ${khs}k H/s` : ""})`);
|
|
260
313
|
}
|
|
261
|
-
catch {
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
314
|
+
catch (err) {
|
|
315
|
+
clearInterval(staleTimer);
|
|
316
|
+
if (abortController.signal.aborted) {
|
|
317
|
+
// Challenge went stale — re-fetch and retry
|
|
318
|
+
const freshChallenge = (await wallet_1.publicClient.readContract({
|
|
319
|
+
address: config_1.config.agentCoinAddress,
|
|
320
|
+
abi: agentCoinAbi,
|
|
321
|
+
functionName: "getMiningChallenge",
|
|
322
|
+
}));
|
|
323
|
+
[challengeNumber, target] = [freshChallenge[0], freshChallenge[1]];
|
|
324
|
+
const freshSmhl = (0, smhl_1.normalizeSmhlChallenge)(freshChallenge[2]);
|
|
325
|
+
smhlSolution = (0, smhl_1.solveSmhlAlgorithmic)(freshSmhl);
|
|
326
|
+
console.log(` ${ui.dim("SMHL re-solved, grinding fresh challenge...")}`);
|
|
327
|
+
grind = null; // loop again
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
throw err; // non-abort error — propagate
|
|
269
331
|
}
|
|
270
332
|
}
|
|
271
|
-
else {
|
|
272
|
-
grind = await (0, grinder_1.grindNonceParallel)({
|
|
273
|
-
challengeNumber,
|
|
274
|
-
target,
|
|
275
|
-
minerAddress: account.address,
|
|
276
|
-
threads: config_1.config.minerThreads,
|
|
277
|
-
onProgress: (attempts, hashrate) => {
|
|
278
|
-
const khs = (hashrate / 1000).toFixed(0);
|
|
279
|
-
nonceSpinner.update(`Grinding nonce (JS)... ${khs}k H/s (${attempts.toLocaleString()} attempts)`);
|
|
280
|
-
},
|
|
281
|
-
});
|
|
282
|
-
}
|
|
283
|
-
const khs = grind.hashrate > 0 ? (grind.hashrate / 1000).toFixed(0) : "?";
|
|
284
|
-
nonceSpinner.stop(`Nonce found (${grind.elapsed.toFixed(1)}s${grind.hashrate > 0 ? `, ${khs}k H/s` : ""})`);
|
|
285
333
|
// Submit transaction with spinner
|
|
286
334
|
const txSpinner = ui.spinner("Submitting transaction...");
|
|
287
335
|
const txHash = await walletClient.writeContract({
|
package/dist/preflight.js
CHANGED
|
@@ -97,7 +97,7 @@ async function runPreflight(level) {
|
|
|
97
97
|
results.push({
|
|
98
98
|
label: "No USDC balance — QuickNode x402 requires USDC on Base",
|
|
99
99
|
passed: false,
|
|
100
|
-
fix: `Send USDC to ${wallet_1.account.address} on Base (~$10
|
|
100
|
+
fix: `Send USDC to ${wallet_1.account.address} on Base (~$10 covers ${config_1.config.llmProvider === "clawrouter" ? "both RPC and LLM calls" : "~1M RPC calls"}). Run \`apow fund\` to bridge from Solana.`,
|
|
101
101
|
});
|
|
102
102
|
}
|
|
103
103
|
else {
|
|
@@ -184,7 +184,22 @@ async function runPreflight(level) {
|
|
|
184
184
|
}
|
|
185
185
|
// Check 5: LLM key set (only required for minting, not mining)
|
|
186
186
|
if (level === "wallet") {
|
|
187
|
-
if (config_1.config.llmProvider === "
|
|
187
|
+
if (config_1.config.llmProvider === "clawrouter") {
|
|
188
|
+
if (!wallet_1.account) {
|
|
189
|
+
results.push({
|
|
190
|
+
label: "ClawRouter requires PRIVATE_KEY (wallet signs x402 payments)",
|
|
191
|
+
passed: false,
|
|
192
|
+
fix: "Set PRIVATE_KEY in .env",
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
else {
|
|
196
|
+
results.push({
|
|
197
|
+
label: `LLM provider: clawrouter (x402, same wallet as mining)`,
|
|
198
|
+
passed: true,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
else if (config_1.config.llmProvider === "ollama") {
|
|
188
203
|
results.push({ label: `LLM provider: ollama (${config_1.config.ollamaUrl})`, passed: true });
|
|
189
204
|
}
|
|
190
205
|
else if (config_1.config.llmProvider === "claude-code" || config_1.config.llmProvider === "codex") {
|
package/dist/smhl.js
CHANGED
|
@@ -1,4 +1,37 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
2
35
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
36
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
37
|
};
|
|
@@ -286,6 +319,27 @@ async function requestQwenSolution(prompt) {
|
|
|
286
319
|
}, { timeout: 15_000 });
|
|
287
320
|
return response.choices[0]?.message.content ?? "";
|
|
288
321
|
}
|
|
322
|
+
async function requestClawRouterSolution(prompt) {
|
|
323
|
+
const { ensureClawRouter, getClawRouterBaseUrl } = await Promise.resolve().then(() => __importStar(require("./clawrouter")));
|
|
324
|
+
const { requirePrivateKey } = await Promise.resolve().then(() => __importStar(require("./config")));
|
|
325
|
+
await ensureClawRouter(requirePrivateKey());
|
|
326
|
+
const client = new openai_1.default({
|
|
327
|
+
apiKey: "x402",
|
|
328
|
+
baseURL: `${getClawRouterBaseUrl()}/v1`,
|
|
329
|
+
});
|
|
330
|
+
const response = await client.chat.completions.create({
|
|
331
|
+
model: config_1.config.llmModel || "blockrun/eco",
|
|
332
|
+
temperature: 0.7,
|
|
333
|
+
messages: [
|
|
334
|
+
{
|
|
335
|
+
role: "system",
|
|
336
|
+
content: "You generate short lowercase word sequences that match exact constraints. Return only the words separated by spaces. Nothing else.",
|
|
337
|
+
},
|
|
338
|
+
{ role: "user", content: prompt },
|
|
339
|
+
],
|
|
340
|
+
}, { timeout: 15_000 });
|
|
341
|
+
return response.choices[0]?.message.content ?? "";
|
|
342
|
+
}
|
|
289
343
|
async function requestClaudeCodeSolution(prompt) {
|
|
290
344
|
return new Promise((resolve, reject) => {
|
|
291
345
|
const escaped = prompt.replace(/'/g, "'\\''");
|
|
@@ -325,6 +379,8 @@ async function requestProviderSolution(prompt) {
|
|
|
325
379
|
return requestDeepSeekSolution(prompt);
|
|
326
380
|
case "qwen":
|
|
327
381
|
return requestQwenSolution(prompt);
|
|
382
|
+
case "clawrouter":
|
|
383
|
+
return requestClawRouterSolution(prompt);
|
|
328
384
|
case "openai":
|
|
329
385
|
default:
|
|
330
386
|
return requestOpenAiSolution(prompt);
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# APoW GPU Nonce Grinder — Build Targets
|
|
2
|
+
#
|
|
3
|
+
# Metal (macOS Apple Silicon): make metal
|
|
4
|
+
# CUDA (Vast.ai RTX 4090): make cuda
|
|
5
|
+
# CPU (reference/fallback): make cpu
|
|
6
|
+
|
|
7
|
+
.PHONY: all metal cuda cpu clean
|
|
8
|
+
|
|
9
|
+
# ── Metal (macOS only) ──
|
|
10
|
+
metal: grinder-gpu
|
|
11
|
+
|
|
12
|
+
grinder-gpu: grinder.m keccak.metal
|
|
13
|
+
clang -O2 -framework Metal -framework Foundation grinder.m -o grinder-gpu
|
|
14
|
+
|
|
15
|
+
# ── CUDA (Linux, requires nvcc + CUDA toolkit) ──
|
|
16
|
+
# sm_89 = Ada Lovelace (RTX 4090). Change for other GPUs:
|
|
17
|
+
# sm_86 = Ampere (RTX 3090), sm_90 = Hopper (H100)
|
|
18
|
+
CUDA_ARCH ?= sm_89
|
|
19
|
+
|
|
20
|
+
cuda: grinder-cuda
|
|
21
|
+
|
|
22
|
+
grinder-cuda: grinder-cuda.cu
|
|
23
|
+
nvcc grinder-cuda.cu -o grinder-cuda -std=c++17 -O3 -arch=$(CUDA_ARCH)
|
|
24
|
+
|
|
25
|
+
# ── CPU (portable reference) ──
|
|
26
|
+
cpu: grinder-cpu
|
|
27
|
+
|
|
28
|
+
grinder-cpu: grinder-cpu.c
|
|
29
|
+
clang -O2 -pthread grinder-cpu.c -o grinder-cpu
|
|
30
|
+
|
|
31
|
+
# ── Test harness (Metal, verifies GPU vs CPU keccak) ──
|
|
32
|
+
test: test_keccak
|
|
33
|
+
|
|
34
|
+
test_keccak: test_keccak.m
|
|
35
|
+
clang -O2 -framework Metal -framework Foundation test_keccak.m -o test_keccak
|
|
36
|
+
|
|
37
|
+
# ── Cleanup ──
|
|
38
|
+
clean:
|
|
39
|
+
rm -f grinder-gpu grinder-cuda grinder-cpu test_keccak *.metallib
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* APoW PoW Nonce Grinder — Multi-threaded keccak256
|
|
3
|
+
* Usage: ./grinder <challenge_hex> <address_hex> <target_hex> [threads]
|
|
4
|
+
* Output: <nonce_decimal> <attempts>
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
#include <stdio.h>
|
|
8
|
+
#include <stdlib.h>
|
|
9
|
+
#include <string.h>
|
|
10
|
+
#include <stdint.h>
|
|
11
|
+
#include <unistd.h>
|
|
12
|
+
#include <pthread.h>
|
|
13
|
+
#include <time.h>
|
|
14
|
+
|
|
15
|
+
/* ─── Keccak-256 (compact implementation) ──────────────────── */
|
|
16
|
+
|
|
17
|
+
#define KECCAK_ROUNDS 24
|
|
18
|
+
|
|
19
|
+
static const uint64_t RC[24] = {
|
|
20
|
+
0x0000000000000001ULL, 0x0000000000008082ULL, 0x800000000000808aULL,
|
|
21
|
+
0x8000000080008000ULL, 0x000000000000808bULL, 0x0000000080000001ULL,
|
|
22
|
+
0x8000000080008081ULL, 0x8000000000008009ULL, 0x000000000000008aULL,
|
|
23
|
+
0x0000000000000088ULL, 0x0000000080008009ULL, 0x000000008000000aULL,
|
|
24
|
+
0x000000008000808bULL, 0x800000000000008bULL, 0x8000000000008089ULL,
|
|
25
|
+
0x8000000000008003ULL, 0x8000000000008002ULL, 0x8000000000000080ULL,
|
|
26
|
+
0x000000000000800aULL, 0x800000008000000aULL, 0x8000000080008081ULL,
|
|
27
|
+
0x8000000000008080ULL, 0x0000000080000001ULL, 0x8000000080008008ULL
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
static const int ROTC[24] = {
|
|
31
|
+
1,3,6,10,15,21,28,36,45,55,2,14,27,41,56,8,25,43,62,18,39,61,20,44
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
static const int PILN[24] = {
|
|
35
|
+
10,7,11,17,18,3,5,16,8,21,24,4,15,23,19,13,12,2,20,14,22,9,6,1
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
static inline uint64_t rotl64(uint64_t x, int n) {
|
|
39
|
+
return (x << n) | (x >> (64 - n));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
static void keccak_f1600(uint64_t st[25]) {
|
|
43
|
+
uint64_t bc[5];
|
|
44
|
+
for (int r = 0; r < KECCAK_ROUNDS; r++) {
|
|
45
|
+
// Theta
|
|
46
|
+
for (int i = 0; i < 5; i++)
|
|
47
|
+
bc[i] = st[i] ^ st[i+5] ^ st[i+10] ^ st[i+15] ^ st[i+20];
|
|
48
|
+
for (int i = 0; i < 5; i++) {
|
|
49
|
+
uint64_t t = bc[(i+4)%5] ^ rotl64(bc[(i+1)%5], 1);
|
|
50
|
+
for (int j = 0; j < 25; j += 5) st[j+i] ^= t;
|
|
51
|
+
}
|
|
52
|
+
// Rho + Pi
|
|
53
|
+
uint64_t t = st[1];
|
|
54
|
+
for (int i = 0; i < 24; i++) {
|
|
55
|
+
int j = PILN[i];
|
|
56
|
+
uint64_t tmp = st[j];
|
|
57
|
+
st[j] = rotl64(t, ROTC[i]);
|
|
58
|
+
t = tmp;
|
|
59
|
+
}
|
|
60
|
+
// Chi
|
|
61
|
+
for (int j = 0; j < 25; j += 5) {
|
|
62
|
+
uint64_t tmp[5];
|
|
63
|
+
for (int i = 0; i < 5; i++) tmp[i] = st[j+i];
|
|
64
|
+
for (int i = 0; i < 5; i++)
|
|
65
|
+
st[j+i] = tmp[i] ^ ((~tmp[(i+1)%5]) & tmp[(i+2)%5]);
|
|
66
|
+
}
|
|
67
|
+
// Iota
|
|
68
|
+
st[0] ^= RC[r];
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
static void keccak256(const uint8_t *in, size_t inlen, uint8_t *out) {
|
|
73
|
+
uint64_t st[25] = {0};
|
|
74
|
+
const int rate = 136; // (1600 - 256*2) / 8
|
|
75
|
+
|
|
76
|
+
// Absorb
|
|
77
|
+
while (inlen >= (size_t)rate) {
|
|
78
|
+
for (int i = 0; i < rate/8; i++)
|
|
79
|
+
st[i] ^= ((const uint64_t*)in)[i];
|
|
80
|
+
keccak_f1600(st);
|
|
81
|
+
in += rate;
|
|
82
|
+
inlen -= rate;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Final block (pad with aligned copy)
|
|
86
|
+
uint8_t tmp[136] = {0};
|
|
87
|
+
memcpy(tmp, in, inlen);
|
|
88
|
+
tmp[inlen] = 0x01; // Keccak padding (NOT SHA3 which uses 0x06)
|
|
89
|
+
tmp[rate - 1] |= 0x80;
|
|
90
|
+
|
|
91
|
+
for (int i = 0; i < rate/8; i++)
|
|
92
|
+
st[i] ^= ((uint64_t*)tmp)[i];
|
|
93
|
+
keccak_f1600(st);
|
|
94
|
+
|
|
95
|
+
// Squeeze (32 bytes)
|
|
96
|
+
memcpy(out, st, 32);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/* ─── Hex parsing ──────────────────────────────────────────── */
|
|
100
|
+
|
|
101
|
+
static int hex2byte(char c) {
|
|
102
|
+
if (c >= '0' && c <= '9') return c - '0';
|
|
103
|
+
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
|
|
104
|
+
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
|
|
105
|
+
return -1;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
static int parse_hex(const char *hex, uint8_t *out, int len) {
|
|
109
|
+
if (hex[0] == '0' && hex[1] == 'x') hex += 2;
|
|
110
|
+
for (int i = 0; i < len; i++) {
|
|
111
|
+
int hi = hex2byte(hex[i*2]);
|
|
112
|
+
int lo = hex2byte(hex[i*2+1]);
|
|
113
|
+
if (hi < 0 || lo < 0) return -1;
|
|
114
|
+
out[i] = (hi << 4) | lo;
|
|
115
|
+
}
|
|
116
|
+
return 0;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/* ─── Worker thread ────────────────────────────────────────── */
|
|
120
|
+
|
|
121
|
+
typedef struct {
|
|
122
|
+
uint8_t base[84]; // challenge(32) + address(20) + nonce_template(32)
|
|
123
|
+
uint8_t target[32];
|
|
124
|
+
uint64_t start;
|
|
125
|
+
uint64_t range;
|
|
126
|
+
uint64_t found_nonce;
|
|
127
|
+
volatile int *global_found;
|
|
128
|
+
uint64_t attempts;
|
|
129
|
+
} WorkerArgs;
|
|
130
|
+
|
|
131
|
+
static void *grind_worker(void *arg) {
|
|
132
|
+
WorkerArgs *a = (WorkerArgs *)arg;
|
|
133
|
+
uint8_t buf[84];
|
|
134
|
+
uint8_t hash[32];
|
|
135
|
+
memcpy(buf, a->base, 52); // challenge + address
|
|
136
|
+
memset(buf + 52, 0, 24); // Zero first 24 bytes of nonce area
|
|
137
|
+
|
|
138
|
+
for (uint64_t n = a->start; n < a->start + a->range; n++) {
|
|
139
|
+
if (*a->global_found) return NULL;
|
|
140
|
+
|
|
141
|
+
// Write nonce as big-endian in last 8 bytes (buf[76..83])
|
|
142
|
+
buf[76] = (n >> 56) & 0xff;
|
|
143
|
+
buf[77] = (n >> 48) & 0xff;
|
|
144
|
+
buf[78] = (n >> 40) & 0xff;
|
|
145
|
+
buf[79] = (n >> 32) & 0xff;
|
|
146
|
+
buf[80] = (n >> 24) & 0xff;
|
|
147
|
+
buf[81] = (n >> 16) & 0xff;
|
|
148
|
+
buf[82] = (n >> 8) & 0xff;
|
|
149
|
+
buf[83] = n & 0xff;
|
|
150
|
+
|
|
151
|
+
keccak256(buf, 84, hash);
|
|
152
|
+
|
|
153
|
+
// Compare hash < target (MSB first)
|
|
154
|
+
int less = 0;
|
|
155
|
+
for (int i = 0; i < 32; i++) {
|
|
156
|
+
if (hash[i] < a->target[i]) { less = 1; break; }
|
|
157
|
+
if (hash[i] > a->target[i]) break;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (less) {
|
|
161
|
+
a->found_nonce = n;
|
|
162
|
+
a->attempts = n - a->start + 1;
|
|
163
|
+
__sync_val_compare_and_swap(a->global_found, 0, 1);
|
|
164
|
+
return NULL;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
a->attempts = a->range;
|
|
168
|
+
return NULL;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/* ─── Main ─────────────────────────────────────────────────── */
|
|
172
|
+
|
|
173
|
+
int main(int argc, char *argv[]) {
|
|
174
|
+
if (argc < 4) {
|
|
175
|
+
fprintf(stderr, "Usage: %s <challenge_hex> <address_hex> <target_hex> [threads]\n", argv[0]);
|
|
176
|
+
return 1;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
uint8_t challenge[32], address[20], target[32];
|
|
180
|
+
if (parse_hex(argv[1], challenge, 32) < 0 ||
|
|
181
|
+
parse_hex(argv[2], address, 20) < 0 ||
|
|
182
|
+
parse_hex(argv[3], target, 32) < 0) {
|
|
183
|
+
fprintf(stderr, "Invalid hex input\n");
|
|
184
|
+
return 1;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
int nthreads = argc > 4 ? atoi(argv[4]) : 8;
|
|
188
|
+
if (nthreads < 1) nthreads = 1;
|
|
189
|
+
if (nthreads > 64) nthreads = 64;
|
|
190
|
+
|
|
191
|
+
// Build base buffer
|
|
192
|
+
uint8_t base[84] = {0};
|
|
193
|
+
memcpy(base, challenge, 32);
|
|
194
|
+
memcpy(base + 32, address, 20);
|
|
195
|
+
|
|
196
|
+
// Random start nonce
|
|
197
|
+
srand((unsigned)time(NULL) ^ (unsigned)getpid());
|
|
198
|
+
uint64_t start = ((uint64_t)rand() << 32) | rand();
|
|
199
|
+
uint64_t range_per_thread = 500000000ULL; // 500M per thread max
|
|
200
|
+
|
|
201
|
+
volatile int found = 0;
|
|
202
|
+
pthread_t threads[64];
|
|
203
|
+
WorkerArgs args[64];
|
|
204
|
+
|
|
205
|
+
struct timespec t0, t1;
|
|
206
|
+
clock_gettime(CLOCK_MONOTONIC, &t0);
|
|
207
|
+
|
|
208
|
+
for (int i = 0; i < nthreads; i++) {
|
|
209
|
+
args[i] = (WorkerArgs){
|
|
210
|
+
.start = start + i * range_per_thread,
|
|
211
|
+
.range = range_per_thread,
|
|
212
|
+
.found_nonce = 0,
|
|
213
|
+
.global_found = &found,
|
|
214
|
+
.attempts = 0
|
|
215
|
+
};
|
|
216
|
+
memcpy(args[i].base, base, 84);
|
|
217
|
+
memcpy(args[i].target, target, 32);
|
|
218
|
+
pthread_create(&threads[i], NULL, grind_worker, &args[i]);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Wait for completion
|
|
222
|
+
for (int i = 0; i < nthreads; i++)
|
|
223
|
+
pthread_join(threads[i], NULL);
|
|
224
|
+
|
|
225
|
+
clock_gettime(CLOCK_MONOTONIC, &t1);
|
|
226
|
+
double elapsed = (t1.tv_sec - t0.tv_sec) + (t1.tv_nsec - t0.tv_nsec) / 1e9;
|
|
227
|
+
|
|
228
|
+
// Find the winning thread
|
|
229
|
+
uint64_t total_attempts = 0;
|
|
230
|
+
for (int i = 0; i < nthreads; i++) {
|
|
231
|
+
total_attempts += args[i].attempts;
|
|
232
|
+
if (args[i].found_nonce && found) {
|
|
233
|
+
printf("%llu %llu %.3f\n", args[i].found_nonce, total_attempts, elapsed);
|
|
234
|
+
fflush(stdout);
|
|
235
|
+
return 0;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
fprintf(stderr, "No nonce found after %llu attempts (%.1fs)\n", total_attempts, elapsed);
|
|
240
|
+
return 1;
|
|
241
|
+
}
|