Troubleshoot miner Workers
Fix common MDK miner Worker startup, mock, and registration issues.
TL;DR
- Most mock failures are a wrong port, a stale mock still holding it, or two Kernels sharing
~/.mdk - A telemetry check that fails prints its error: read a failed check maps each one, route errors included, to its cause
- To run examples side by side, give each its own
HOMEandTMPDIR:HOME=/tmp/mdk-a TMPDIR=/tmp/mdk-a node avalon-dev.js. Two Kernels sharing~/.mdk, or two copies of one script sharingTMPDIR, fail withFile descriptor could not be locked.
Overview
This page covers the mock runs in the Antminer, Whatsminer, Avalon,
Antspace, and Bitdeer Worker guides. Each guide runs its Worker with mdk run, which starts
the Worker's bundled mock with it. The Avalon, Antspace, and Bitdeer guides also show a host script that runs the Worker in
your own Node.js process, with the mock started by npm run mock. A guide whose real device takes a password keeps it
in the project's .env, and this page also covers a password that is missing or arrives cut short.
Expected output
Under mdk run, each Worker prints a line once the Kernel accepts it, and the run ends with Stack running. Press Ctrl+C to stop.
Expected output includes:
✔ worker avalon ready 98edeb00a6142891In a project set up with mdk onboard, mdk status, from a second terminal in the project directory, needs no sign-in.
Right after boot the health can read UNKNOWN and the command exits 5 until the first report arrives; wait a few
seconds, or run mdk status --wait. Expected output ends with:
Stack
Running foreground, PID <pid>
Kernel up <kernel key>
Gateway up http://127.0.0.1:3847
Workers 1/1 registered 1 device
Apps 0/0 running
WORKER REGISTERED STATE HEALTH DEVICES
avalon yes READY HEALTHY 1
✔ Health: healthyExpected output from a host script in the guides:
Worker registered: <worker id>
Kernel HRPC key: <hex key>
Ctrl+C to stop.Each of these proves the Kernel accepted the Worker. None of them reaches a device: with the mock stopped, or a device on the wrong port, the output is the same. Only a telemetry read reports the failure, as Worker is healthy but devices show no data describes.
Check a device reports telemetry
This check reads one device's live telemetry through the Kernel and the device's Worker, and returns each channel's value
or its error. It reads the device now; for a Worker that collects its own telemetry, the stored series is a separate read,
pullSnapshot.
The Kernel only answers a caller its policy lets read devices. Who that caller is depends on what booted the Kernel: under
mdk run, an app route reads the device for the signed-in user; in
a script of your own, such as a guide's development script, the script boots its
Kernel with a service account that may read devices.
Under mdk run
mdk run serves apps behind the Gateway, so the check is an app route. Set it up once, from the project directory:
-
Scaffold an app:
mdk create app fleet -
Let the app read devices. In
apps/fleet/mdk-app.yaml, add adevicesrule topermissions:permissions: [{ resources: [workers], verbs: [list] }, { resources: [devices], verbs: [read] }]Then grant the app what it now requests:
mdk add app fleet --accept-permissions -
Add this route to the
routesarray inapps/fleet/plugin/mdk-plugin.json:{ "id": "fleet.device-telemetry", "description": "Every telemetry channel of one device, read live from its Worker as the signed-in user.", "handler": "./controllers/device-telemetry.js", "safety": "read-only", "http": { "method": "GET", "path": "/api/fleet/devices/{deviceId}/telemetry", "parameters": [ { "in": "path", "name": "deviceId", "required": true, "schema": { "type": "string" } } ] } } -
Save its controller as
apps/fleet/plugin/controllers/device-telemetry.js:'use strict' module.exports = async function deviceTelemetry (req) { return req.mdk.pullTelemetry(req.params.deviceId) }req.mdkreads as the signed-in user, so the Kernel checks the user's access as well as the app's. Routes and controllers covers both files in full. -
Start the stack with
mdk run, or restart it if it runs: an app loads its routes when it starts. -
If the project has no user yet, create the first operator with
mdk user add <name> --admin. Then sign in over HTTP for an access token inTOKEN. -
Read a device, by the ID
mdk.yamldeclares for it, from a second terminal:curl -sS -H "Authorization: Bearer $TOKEN" http://localhost:3847/apps/fleet/api/fleet/devices/<device id>/telemetry
The route reads once and answers with the device's channels under metrics: each holds a value, or { "error": ... } for a
channel the device could not answer. At least one value proves the device answers; anything else is
a failed check. The port is spec.gateway.port in mdk.yaml. The access token lasts minutes, so sign
in again when the read answers ERR_AUTH_UNAUTHORIZED.
In a script that boots its own Kernel
The check boots the
Kernel on a store of its own under the temporary directory and registers both there. Your Kernel's policy, service
accounts, and key file stay as they were. Save this module as check-telemetry.js next to the script that boots your
Kernel, and outside this repository add @tetherto/mdk-client and @tetherto/mdk-identity to your dependencies, beside the
@tetherto/mdk-core the script already uses to boot the Kernel:
'use strict'
const os = require('os')
const path = require('path')
const { createMdkClient } = require('@tetherto/mdk-client')
const { generateCredential } = require('@tetherto/mdk-identity')
const { callerKeyPair } = require('@tetherto/mdk-core/lib/local-discovery')
// A service account that may read devices and nothing else. The Kernel only
// registers service accounts at boot, so spread checkKernelOpts into getKernel().
// The Kernel boots on a store of its own, so the policy and account set here
// never replace the ones in your Kernel's store.
const ACCOUNT = 'telemetry-check'
const credential = generateCredential()
const checkKernelOpts = {
root: path.join(os.tmpdir(), 'mdk-dev', 'telemetry-check-kernel'),
keyFile: false,
rbac: {
enforcement: 'deny',
roles: [{ name: 'device-reader', rules: [{ resources: ['devices'], verbs: ['read'] }] }],
bindings: [{ role: 'device-reader', subjects: [{ kind: 'ServiceAccount', name: ACCOUNT }] }]
},
serviceAccounts: [{ name: ACCOUNT, publicKey: credential.publicKey }]
}
// Read one device's live telemetry through the Kernel, retrying until the device
// answers or timeoutMs passes, then print each single-value channel or its error.
async function checkTelemetry (kernel, deviceId, { timeoutMs = 60000 } = {}) {
const caller = callerKeyPair(path.join(os.tmpdir(), 'mdk-dev', 'telemetry-check'))
kernel.allowKey(caller.publicKey)
const client = createMdkClient({
kernelKey: kernel.getPublicKey(),
kernelKeyPair: caller,
kernelCredential: { name: ACCOUNT, privateKey: credential.privateKeyPem }
})
// A channel the device could not answer holds { error }; the device has answered
// once at least one channel holds a single value.
const answered = (reading) => Object.values(reading.metrics || {}).some((value) => typeof value !== 'object')
try {
const deadline = Date.now() + timeoutMs
let reading = await client.pullTelemetry(deviceId)
// Once the Worker has registered, these two never clear: fail now, not after timeoutMs.
if (/^ERR_(DEVICE_NOT_FOUND|WORKER_NOT_ROUTABLE)\b/.test(reading.error)) throw new Error(reading.error)
while (!answered(reading) && Date.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, 2000))
reading = await client.pullTelemetry(deviceId)
}
if (!answered(reading)) throw new Error(`ERR_NO_TELEMETRY ${deviceId}: ${JSON.stringify(reading)}`)
console.log(`Telemetry from ${deviceId}:`)
for (const [name, value] of Object.entries(reading.metrics)) {
if (typeof value !== 'object') console.log(` ${name}: ${value}`)
else if (value && value.error) console.log(` ${name}: ${value.error}`)
}
} finally {
await client.close()
}
}
module.exports = { checkKernelOpts, checkTelemetry }Then spread checkKernelOpts into your script's getKernel call, and call checkTelemetry once the Worker is
registered, with the device ID your script declares:
const { checkKernelOpts, checkTelemetry } = require('./check-telemetry')
const kernel = await getKernel({ ...checkKernelOpts })
// ...start and register the Worker...
await checkTelemetry(kernel, '<device id>')A device that answers prints one line per single-value channel. A check that gets no answer within a minute fails with
ERR_NO_TELEMETRY, followed by the last reading. A device that never answers at all, rather than
refusing the connection, can end the check sooner with ERR_MDK_CLIENT_UNAVAILABLE: CHANNEL_DESTROYED.
The Kernel the check boots is a development Kernel, apart from yours. Remove checkKernelOpts from getKernel to go
back to your own Kernel store. While it is in, the script doesn't write ~/.mdk/.kernel-key, so a Gateway started separately
with startGateway() reads the key of the last Kernel that did, or fails with ERR_KERNEL_KEY_FILE_NOT_FOUND if none has.
Read a failed check
The route answers with the error in its body; a script prints it.
| Output | Cause |
|---|---|
Each channel holds an error, such as ERR_MINER_UNREACHABLE: connect ECONNREFUSED <host>:<port> | The Worker cannot reach the device |
ERR_DEVICE_NOT_FOUND | No Worker declares that device ID |
ERR_WORKER_NOT_ROUTABLE | The Worker that owns the device has not connected since the Kernel started: it isn't running, was removed from mdk.yaml, or failed to register. Check mdk status and the mdk run output. |
ERR_MDK_CLIENT_UNAVAILABLE: CHANNEL_DESTROYED: channel destroyed, after about 10 seconds | The device did not answer before the request timed out: an unreachable host, or a firewall dropping the traffic. Check its address, then retry. |
ERR_KERNEL_ACTION_FORBIDDEN: app:fleet may not read devices ... | The app's role doesn't grant devices: read. Add the rule to mdk-app.yaml, run mdk add app fleet --accept-permissions, then mdk rbac apply. The running stack picks it up without a restart. |
ERR_KERNEL_ACTION_FORBIDDEN from a script | The policy the script's Kernel boots with does not let the account read devices |
ERR_AUTH_FORBIDDEN: <user> may not get fleet/api/fleet/devices/:deviceId/telemetry | The signed-in user has no role that may call the route. Bind the user to a role that may call it. |
ERR_AUTH_UNAUTHORIZED | The request carries no access token, or it has expired. Sign in again. |
Route GET:/apps/fleet/... not found | The path names another app or route, or the stack started before the route was added. Check the path, then restart mdk run. |
curl: (7) Failed to connect to localhost port 3847 | No stack runs, or the Gateway listens on another port: check spec.gateway.port in mdk.yaml |
Worker is not registered with the Kernel
mdk run prints ! worker <name> not registered with the Kernel (<error>) in place of the ready line, with a warning or hint
that says what to check. mdk status then shows the Worker as REGISTERED no and ends with ! Health: degraded. A host script
from the guides stops with Error: Worker not registered: <error> and a stack trace, and exits 1. The Kernel's
error table gives the fix for each code:
ERR_CHANNEL_NOT_CONNECTEDorERR_WORKER_IDENTITY_UNAVAILABLE: the Kernel could not reach the Worker; run the network checksERR_WORKER_DEVICE_CONFLICT: another Worker ID already owns one of the device IDs, as when a host script'sworkerIdchanges while its device stays the same. Worker bindings covers releasing the old ownerERR_WORKER_CONTRACT_INVALID: the Worker'smdk-contract.jsonfails validation;mdk validate workernames the problem
Network checks
Same-process examples register Worker public keys directly and do not use DHT topic discovery. Runtime traffic still uses HRPC, which relies on HyperDHT to establish encrypted peer connections. The machine therefore needs outbound UDP access to its configured DHT bootstrap nodes even when Kernel and the Worker share a process or host.
If outbound access or network-interface inspection is blocked, a host script may stop responding or fail before it prints
anything. A machine with no outbound access runs the local and air-gapped profile instead: a private bootstrap on
127.0.0.1 that every component joins. A project mdk onboard created already has that setting, spec.network.dht; the hint
mdk run prints names it for an older project.
Check:
- The machine has outbound network access.
- Local security tooling, containers, or sandboxes are not blocking UDP/network-interface access.
- A host script runs from the repository root.
- Dependencies have been installed with
npm installat the repository root.
Worker is healthy but devices show no data
READY and HEALTHY describe the Worker process, not the devices behind it: Kernel's health ping is answered by the Worker from
memory and never reaches a device, so a Worker with every miner unplugged still reports both
(Worker health is not device liveness). mdk status shows the same READY HEALTHY row and ✔ Health: healthy.
Check:
- Check one device reports telemetry and read each channel's error; an unreachable
device surfaces there as
ERR_MINER_UNREACHABLEor a connection error, not in the Worker state. - Compare the device's
optswith the keys the package's own example config sets, as every reading fails describes. - Confirm the device is reachable from the Worker host on its native port (real miners).
- For a command, read
verification.statefromcommand.status; onlyVERIFIEDproves the device reached the requested state.
mdk run warns that a Worker may be missing device options
warning: worker "<name>" may be missing device options: its package's smoke.config.js sets <keys> means the device's opts
in mdk.yaml lack keys the package's example config sets. It does not stop the Worker. Against the bundled mock the run works
without them; against hardware, a missing credential fails every reading, as every reading fails covers.
mdk.yaml fails to load because a variable is not set
mdk run, mdk validate, mdk rbac, or another command that reads mdk.yaml stops with:
error: <project>/mdk.yaml: `spec.workers[0].config.devices[0].opts.password` references ${ANTMINER_PASSWORD}, which is not set.
Set ANTMINER_PASSWORD in the environment or the project's .env, or write $${ANTMINER_PASSWORD} if the plugin expects the text
${ANTMINER_PASSWORD} itself.mdk status doesn't stop: it reports mdk.yaml as invalid and shows the same message.
The placeholder at that path has no value in the environment or in the project's .env. Add it to .env as
writing a value in .env describes, then run the command again. When a plugin expects the text ${...} itself,
write $${...} in mdk.yaml instead.
A device refuses a password set in .env
.env can cut a value short without an error, so the device receives only part of the password:
Line in .env | Value the CLI reads | Fix |
|---|---|---|
PASSWORD=ab#cd | ab | Quote the value, as writing a value in .env describes |
PASSWORD="a'b`c\"d" | a'b`c\ | Write it unquoted, PASSWORD=a'b`c"d, if it has no # and doesn't start with a quote; otherwise change the password |
.env has no escape for a quote, so a value with all three quote characters can't be quoted, and an unquoted value loses
leading and trailing spaces.
Find the right port
Mock runs and real miners use different sources for ports.
Mock runs
Under mdk run, each device's port in mdk.yaml is the port its mock listens on, and the Worker reaches the mock there. For
Antminer and Whatsminer, mdk add worker writes that port when it adds the Worker.
A host script's mock listens on the port you pass to npm run mock, and the Worker reaches it through the port in that
device's config in the script. The two must match: the Avalon guide's host script uses 4028 for both.
Run npm run mock with no arguments to list every mock device and its types.
The cross-worker manifest also records the expected mock type and default port for each variant: workers manifest.
Real miners
Real devices use their native APIs:
- Antminer: HTTP, usually port
80, with digest-auth credentials. - Whatsminer: encrypted TCP with the API password, plus the API
accounton API v3 (superwhen unset). With noportset, the plugin probes API v3 on4433first, then API v2 on4028. Set either port to pin that version. - Avalon: CGMiner TCP API, usually port
4028, with the device password. Reads are unauthenticated and writes send the password, but the Worker refuses to start with a device registered without one:mdk runstops withERR_INSTANCE_HANDLER_LOAD_FAILED: <device>: … ERR_DEVICE_CONFIG_INVALID: address and password are required.
Before registering a real miner, confirm the miner is reachable from the machine or container running the Worker.
Antminer or Whatsminer installs an unexpected dependency
antminer-mdk-worker and whatsminer-mdk-worker are git dependencies, not
versioned npm packages. mdk add worker writes the commit it installed into package.json as github:<owner>/<repo>#<sha>, and
package-lock.json records the same commit, so npm ci reinstalls exactly that commit. The lockfile spells each entry
git+ssh://git@github.com/...; that is npm's own form for a GitHub dependency, and the install still fetches over HTTPS, so no SSH
key is needed. The same spelling appears in npm warn skipping integrity check for git dependency ssh://git@github.com/..., which
npm prints when it adds the plugin, and again on npm ci: npm records an integrity hash for a git dependency but does not check it,
and the commit pins it instead.
If git diff shows the resolved commit for either entry changed, a pin moved. Review that change, then reinstall from the
committed lockfile:
npm cinpm ci fails on a lockfile/package.json mismatch instead of drifting.
whatsminer-mdk-worker declares a dependency on the deprecated crypto-js, so npm prints a deprecation warning when it installs
the plugin into your project. Inside the MDK repository, npm ls crypto-js from the repository root, or an npm audit run, shows
crypto-js resolving to mdk-crypto-lib instead: MDK overrides it at install time with a drop-in replacement built on Node's own
node:crypto. Neither is a broken install.
Clean up a mock port
If a run exits with EADDRINUSE or says a port is already in use, find the process using that port. A second npm run mock
on a taken port also prints EADDRINUSE, but npm still exits 0, so read its output. Under mdk run, a busy mock port is moved
for you, with a notice such as mock port 14030 is in use — … moved to 14031. lsof is not installed on every system, so add
it first if needed:
lsof -nP -iTCP:<port> -sTCP:LISTENReplace <port> with the mock port for your Worker. The output includes a process ID (PID). If the process is an old miner mock
or example that you no longer need, stop it:
kill <pid>Run lsof again to confirm the port is free before starting again.
File lock or key file errors
The host scripts call getKernel() with default local paths: the Kernel's store under ~/.mdk/store and its key file at
~/.mdk/.kernel-key. Each script's Worker also keeps a store under the system temporary directory (os.tmpdir()). A second
process using either store fails with File descriptor could not be locked, and a client can pick up the wrong Kernel key from
the shared key file.
Stop stale example processes before starting another example. To run examples side by side, give each process its own home directory and its own temporary directory:
HOME=/tmp/mdk-a TMPDIR=/tmp/mdk-a node avalon-dev.jsWorker exits with ERR_WORKER_ALLOWED_KEYS_REQUIRED
A Worker hosted outside mdk run names no RPC caller, so start() refuses to run. mdk run passes the key itself. Pass the
Kernel's client key to WorkerRuntimeV2:
const kernel = await getKernel()
const runtime = new WorkerRuntimeV2(pkgDir, {
workerId: 'avalon-rack-1',
storeDir: './store/avalon-rack-1',
allowedKeys: [kernel.getClientPublicKey()],
devices: [ /* ... */ ]
})allowAll: true also lets the Worker start, for a local check only: the runtime logs a warning and accepts any caller. An adapter
passes both options on to WorkerRuntimeV2; the Antminer and Whatsminer adapters in examples/mvp-site/backend forward each one.
Still blocked
When asking for help on Discord or GitHub issues collect:
- The exact command
- The model and mock port
- The full
stdoutandstderr, and themdk statusoutput node --versionandnpm --version- Any process currently listening on the mock port