-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathconfig_examples.go
More file actions
342 lines (313 loc) · 13.3 KB
/
Copy pathconfig_examples.go
File metadata and controls
342 lines (313 loc) · 13.3 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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
package main
import (
"errors"
"fmt"
"os"
"path/filepath"
"github.com/pelletier/go-toml"
)
func ensureExampleFiles(dataDir string) {
if dataDir == "" {
dataDir = defaultDataDir
}
examplesDir := filepath.Join(dataDir, "config", "examples")
if err := os.MkdirAll(examplesDir, 0o755); err != nil {
logger.Warn("create examples directory for example configs failed", "dir", examplesDir, "error", err)
return
}
configExamplePath := filepath.Join(examplesDir, "config.toml.example")
ensureExampleFile(configExamplePath, exampleConfigBytes())
ensureExampleFile(filepath.Join(examplesDir, "secrets.toml.example"), secretsConfigExample)
ensureExampleFile(filepath.Join(examplesDir, "services.toml.example"), exampleServicesConfigBytes())
ensureExampleFile(filepath.Join(examplesDir, "policy.toml.example"), examplePolicyConfigBytes())
ensureExampleFile(filepath.Join(examplesDir, "tuning.toml.example"), exampleTuningConfigBytes())
ensureExampleFile(filepath.Join(examplesDir, "version_bits.toml.example"), exampleVersionBitsConfigBytes())
}
func ensureExampleFile(path string, contents []byte) {
if len(contents) == 0 {
return
}
if err := os.WriteFile(path, contents, 0o644); err != nil {
logger.Warn("write example config failed", "path", path, "error", err)
}
}
func withPrependedTOMLComments(data []byte, parts ...[]byte) []byte {
total := len(data)
for _, part := range parts {
total += len(part)
}
out := make([]byte, 0, total)
for _, part := range parts {
out = append(out, part...)
}
out = append(out, data...)
return out
}
func exampleHeader(text string) []byte {
return fmt.Appendf(nil, "# Generated %s example (copy to a real config and edit as needed)\n\n", text)
}
func generatedConfigFileHeader() []byte {
return []byte(`# goPool config.toml
# This file is read on startup.
# goPool may rewrite it (keeping a .bak) when it needs to persist settings.
#
`)
}
func generatedPolicyFileHeader() []byte {
return []byte(`# goPool policy.toml
# Optional policy/security overrides loaded after config.toml on startup.
# Keep this file absent unless you need to override defaults.
#
`)
}
func generatedServicesFileHeader() []byte {
return []byte(`# goPool services.toml
# Optional services/integrations settings loaded after config.toml on startup.
# Keep this file absent unless you need to override defaults.
#
`)
}
func generatedTuningFileHeader() []byte {
return []byte(`# goPool tuning.toml
# Optional tuning/capacity overrides loaded after config.toml on startup.
# Keep this file absent unless you need to override defaults.
#
`)
}
func baseConfigDocComments() []byte {
return []byte(`# Key notes
# - [server].pool_listen: Stratum TCP listener for miners (requires restart).
# - [server].status_listen: HTTP listener for status UI (requires restart).
# - [server].status_tls_listen: HTTPS listener; "" disables TLS (requires restart).
# - [server].status_public_url: Canonical public URL for redirects/cookies; empty = auto-detect.
# - [stratum].stratum_tls_listen: Optional Stratum-over-TLS listener (requires restart).
# - [stratum].stratum_password_enabled: Require miners to send a password on authorize (requires restart).
# - [stratum].stratum_password: Password string checked against mining.authorize params (requires restart).
# - [stratum].stratum_password_public: Show the stratum password on the public connect panel (requires restart).
# - [stratum].safe_mode: Force conservative compatibility/safety behavior (disables unsafe debug/public-RPC toggles).
# - Runtime override: --safe-mode=true/false
#
# Logging
# - [logging].level: debug, info, warn, error (requires restart).
#
# Advanced settings can be split across services.toml, policy.toml, and tuning.toml.
#
`)
}
func servicesConfigDocComments() []byte {
return []byte(`# Services / Integrations
# - [auth]: Clerk/OIDC endpoints and session cookie settings.
# - [backblaze_backup]: Cloud backup service toggle, bucket, prefix, and cadence.
# - [discord]: Discord integration endpoints/channels and worker notification threshold.
# - [status]: UI external links (mempool_address_url, github_url).
#
`)
}
func tuningConfigDocComments() []byte {
return []byte(`# Rate limits ([rate_limits])
# - max_conns: Maximum simultaneous Stratum connections allowed (checked on accept; requires restart).
# - disable_connect_rate_limits: Disable accept/connect throttling entirely (intended for local-only pools on trusted networks; requires restart).
# - auto_accept_rate_limits: When true, computes accept throttles from max_conns on startup (overrides explicit accept_* values; requires restart).
# - max_accepts_per_second: Accepts/sec during the initial restart/reconnect window (requires restart).
# - max_accept_burst: Token bucket burst size for accepts (requires restart).
# - accept_reconnect_window: Target seconds for all miners to reconnect after restart (used for auto_accept_rate_limits).
# - accept_burst_window: Initial burst window (seconds) after restart (used for auto_accept_rate_limits).
# - accept_steady_state_window: Seconds after startup before switching to steady-state throttles (requires restart).
# - accept_steady_state_rate: Accepts/sec once steady-state mode activates (requires restart).
# - accept_steady_state_reconnect_percent: Expected % of miners reconnecting during normal operation (used for auto_accept_rate_limits; requires restart).
# - accept_steady_state_reconnect_window: Seconds to spread expected steady-state reconnects across (used for auto_accept_rate_limits; requires restart).
# - stratum_messages_per_minute: Per-connection Stratum messages/min before disconnect (0 disables; requires restart).
#
# Difficulty ([difficulty])
# - default_difficulty: Fallback difficulty if no suggest_* arrives during the startup delay; 0 means "use min_difficulty" (or the built-in minimum if min_difficulty=0).
# - target_shares_per_min: VarDiff target share cadence used for difficulty adjustment and hashrate EMA sample window sizing.
# - min_difficulty / max_difficulty: VarDiff clamp for miner connections; 0 disables that clamp (no limit; requires restart).
# - lock_suggested_difficulty: If true, the first mining.suggest_difficulty / mining.suggest_target locks that connection to the suggested difficulty (disables VarDiff; requires restart).
# - enforce_suggested_difficulty_limits: If true, ban/disconnect when miner-suggested difficulty is outside min_difficulty/max_difficulty.
#
# Mining ([mining])
# - extranonce2_size: Per-share extranonce2 byte length used for submit parsing and validation; 4 is the broadest compatibility default, and 2-16 is the supported compatibility range (requires restart).
# - template_extra_nonce2_size: Template extranonce2 byte length used in generated jobs (requires restart).
# - job_entropy: Entropy bytes added to per-job coinbase tags (requires restart).
# - coinbase_scriptsig_max_bytes: Maximum allowed coinbase scriptSig size in bytes (2-100; requires restart).
#
# Hashrate ([hashrate])
# - hashrate_ema_tau_seconds: EMA time constant for per-connection hashrate smoothing (seconds; requires restart).
# - hashrate_cumulative_enabled: Blend per-connection EMA with cumulative hashrate for per-worker display (requires restart).
# - hashrate_recent_cumulative_enabled: Allow short-window cumulative (vardiff window) to influence per-worker display (requires restart).
# - saved_worker_history_flush_interval_seconds: Periodic flush cadence for saved-worker history snapshot persistence. The whole snapshot file is rewritten each flush, so use a long interval to reduce drive wear (default: 10800 / 3h).
#
# Peer cleaning ([peer_cleaning])
# - enabled/max_ping_ms/min_peers: Optional cleanup of high-latency peers.
#
# Stratum tuning ([stratum])
# - tcp_read_buffer_bytes / tcp_write_buffer_bytes: Socket buffer sizes in bytes (0 = OS default; restart to apply).
#
#
`)
}
func policyConfigDocComments() []byte {
return []byte(`# Stratum policy ([stratum])
# - ckpool_emulate: CKPool-style subscribe response compatibility shape.
#
# Mining policy ([mining])
# - share_job_freshness_mode: 0=off, 1=job_id, 2=job_id+prevhash.
# - share_check_ntime_window: Enforce nTime policy window.
# - share_check_version_rolling: Enforce version-rolling policy.
# - share_require_authorized_connection: Require authorized connection for submit.
# - share_check_param_format: Enforce submit parameter format checks.
# - share_require_worker_match: Require submit worker matches authorized worker.
# - submit_process_inline: Process mining.submit inline on connection goroutine.
# - share_check_duplicate: Enable duplicate share checks.
#
# Hashrate policy ([hashrate])
# - share_ntime_max_forward_seconds: max allowed forward nTime skew.
#
# Version policy ([version])
# - min_version_bits: minimum version-rolling bit count advertised/negotiated with miners; not a per-share changed-bit requirement.
# - share_allow_out_of_mask_version_bits: allow legacy miners to submit version
# bits outside the negotiated version-rolling mask.
# - share_allow_degraded_version_bits: retained compatibility flag; in-mask BIP310 submits are accepted even when fewer bits change on a single share.
#
# Timeouts ([timeouts])
# - connection_timeout_seconds: Miner idle timeout in seconds; 0 disables idle disconnects.
#
# Bans ([bans])
# - invalid-submit and reconnect ban thresholds/windows.
#
`)
}
func exampleConfigBytes() []byte {
cfg := defaultConfig()
cfg.PayoutAddress = "YOUR_POOL_WALLET_ADDRESS_HERE"
cfg.PoolDonationAddress = "OPTIONAL_POOL_DONATION_WALLET"
cfg.PoolEntropy = "" // Don't set a default - auto-generated on first run
fc := buildBaseFileConfig(cfg)
data, err := toml.Marshal(fc)
if err != nil {
logger.Warn("encode config example failed", "error", err)
return nil
}
return withPrependedTOMLComments(data, exampleHeader("base config"), baseConfigDocComments())
}
func exampleTuningConfigBytes() []byte {
cfg := defaultConfig()
pf := buildTuningFileConfig(cfg)
data, err := toml.Marshal(pf)
if err != nil {
logger.Warn("encode tuning config example failed", "error", err)
return nil
}
return withPrependedTOMLComments(data, exampleHeader("tuning config"), tuningConfigDocComments())
}
func examplePolicyConfigBytes() []byte {
cfg := defaultConfig()
pf := buildPolicyFileConfig(cfg)
data, err := toml.Marshal(pf)
if err != nil {
logger.Warn("encode policy config example failed", "error", err)
return nil
}
return withPrependedTOMLComments(data, exampleHeader("policy config"), policyConfigDocComments())
}
func exampleServicesConfigBytes() []byte {
cfg := defaultConfig()
sf := buildServicesFileConfig(cfg)
data, err := toml.Marshal(sf)
if err != nil {
logger.Warn("encode services config example failed", "error", err)
return nil
}
return withPrependedTOMLComments(data, exampleHeader("services config"), servicesConfigDocComments())
}
func exampleVersionBitsConfigBytes() []byte {
return []byte(`# Generated version bits config example (copy to ../version_bits.toml and edit as needed)
#
# This file is READ ONLY from goPool's perspective:
# - goPool never rewrites version_bits.toml.
# - Entries are applied in order; later entries for the same bit win.
# - Overrides here are applied directly to the node's template version.
#
# Format:
# [[bits]]
# bit = <0..31>
# enabled = true|false
# Add one [[bits]] block per bit you want to override.
# To set multiple bits, repeat [[bits]] for each bit.
#
# WARNING:
# - Do not flip version bits unless you have a specific, validated reason.
# - This file only modifies bits from the node's getblocktemplate version.
# - In normal operation, leave node-provided bits unchanged.
# - Improper changes can cause found (winning) blocks to be rejected.
#
# Example: force bit 5 on.
#
[[bits]]
bit = 5
enabled = true
# Example: force bit 1 on.
[[bits]]
bit = 1
enabled = true
# Example: force bit 0 off.
[[bits]]
bit = 0
enabled = false
`)
}
func rewriteConfigFile(path string, cfg Config) error {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o755); err != nil {
return fmt.Errorf("mkdir %s: %w", dir, err)
}
fc := buildBaseFileConfig(cfg)
data, err := toml.Marshal(fc)
if err != nil {
return fmt.Errorf("encode config: %w", err)
}
data = withPrependedTOMLComments(data, generatedConfigFileHeader(), baseConfigDocComments())
tmpFile, err := os.CreateTemp(dir, "config-*.tmp")
if err != nil {
return fmt.Errorf("create temp config: %w", err)
}
tmpName := tmpFile.Name()
removeTemp := true
defer func() {
if tmpFile != nil {
_ = tmpFile.Close()
}
if removeTemp {
_ = os.Remove(tmpName)
}
}()
if _, err := tmpFile.Write(data); err != nil {
return fmt.Errorf("write temp config: %w", err)
}
if err := tmpFile.Sync(); err != nil {
return fmt.Errorf("sync temp config: %w", err)
}
if err := tmpFile.Close(); err != nil {
return fmt.Errorf("close temp config: %w", err)
}
tmpFile = nil
if err := os.Chmod(tmpName, 0o644); err != nil {
return fmt.Errorf("chmod %s: %w", tmpName, err)
}
bakPath := path + ".bak"
if _, err := os.Stat(path); err == nil {
if err := os.Remove(bakPath); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("remove %s: %w", bakPath, err)
}
if err := os.Rename(path, bakPath); err != nil {
return fmt.Errorf("rename %s to %s: %w", path, bakPath, err)
}
} else if !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("stat %s: %w", path, err)
}
if err := os.Rename(tmpName, path); err != nil {
return fmt.Errorf("rename %s to %s: %w", tmpName, path, err)
}
removeTemp = false
return nil
}