├── .npmignore ├── lib ├── version.js ├── miner │ ├── scavenger │ │ ├── scavenger.js │ │ ├── index.js │ │ └── scavenger-config-generator.js │ ├── conqueror │ │ ├── index.js │ │ └── conqueror.js │ ├── index.js │ ├── binary-manager │ │ ├── download.js │ │ └── binary-manager.js │ ├── config-manager │ │ └── config-manager.js │ └── miner.js ├── services │ ├── event-bus.js │ ├── coin-gecko.js │ ├── store.js │ ├── profitability-service.js │ ├── foxy-pool-gateway.js │ ├── logger.js │ ├── cli-dashboard.js │ └── config.js ├── upstream │ ├── base.js │ ├── foxypool.js │ ├── mixins │ │ ├── submit-probability-mixin.js │ │ ├── config-mixin.js │ │ ├── halt-mining-mixin.js │ │ └── outage-detection-mixin.js │ ├── foxy-pool-multi.js │ ├── socketio.js │ └── generic.js ├── currentRound.js ├── plot-file-finder │ ├── plot.js │ └── plot-file-finder.js ├── coin-util.js ├── capacity.js ├── submission.js ├── startup-message.js ├── miningInfo.js ├── idle-program.js ├── output-util.js ├── currentRoundManager.js ├── proxy.js └── first-run-wizard │ └── first-run-wizard.js ├── .github ├── CODEOWNERS ├── dependabot.yml ├── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md └── workflows │ └── ci.yml ├── Dockerfile ├── .gitignore ├── package.json ├── bin └── build-package.js ├── README.md ├── CODE_OF_CONDUCT.md ├── CHANGELOG.md ├── main.js └── LICENSE /.npmignore: -------------------------------------------------------------------------------- 1 | .github 2 | bin 3 | -------------------------------------------------------------------------------- /lib/version.js: -------------------------------------------------------------------------------- 1 | module.exports = require('../package.json').version; 2 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/about-codeowners/ for more info 2 | 3 | * @felixbrucker 4 | -------------------------------------------------------------------------------- /lib/miner/scavenger/scavenger.js: -------------------------------------------------------------------------------- 1 | const Miner = require('../miner'); 2 | 3 | class Scavenger extends Miner {} 4 | 5 | module.exports = Scavenger; 6 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:16-slim 2 | 3 | WORKDIR /app 4 | COPY package.json yarn.lock ./ 5 | RUN yarn install 6 | COPY . . 7 | 8 | ENTRYPOINT ["yarn"] 9 | CMD ["start"] 10 | -------------------------------------------------------------------------------- /lib/miner/conqueror/index.js: -------------------------------------------------------------------------------- 1 | const Conqueror = require('./conqueror'); 2 | 3 | module.exports = { 4 | Miner: Conqueror, 5 | ConfigGenerator: null, 6 | supportsManagement: false, 7 | minerType: 'conqueror', 8 | downloadInfo: null, 9 | }; 10 | -------------------------------------------------------------------------------- /lib/miner/conqueror/conqueror.js: -------------------------------------------------------------------------------- 1 | const Miner = require('../miner'); 2 | 3 | class Conqueror extends Miner { 4 | constructor(binPath, configPath = null, outputToConsole = false) { 5 | super(binPath, configPath, outputToConsole); 6 | this.software = 'conqueror'; 7 | this.roundFinishedString = 'conquest finished'; 8 | } 9 | } 10 | 11 | module.exports = Conqueror; 12 | -------------------------------------------------------------------------------- /lib/services/event-bus.js: -------------------------------------------------------------------------------- 1 | const EventEmitter = require('events'); 2 | 3 | class EventBus { 4 | constructor() { 5 | this.emitter = new EventEmitter(); 6 | } 7 | 8 | publish(topic, ...msg) { 9 | this.emitter.emit(topic, ...msg); 10 | } 11 | 12 | subscribe(topic, cb) { 13 | this.emitter.on(topic, cb); 14 | } 15 | } 16 | 17 | module.exports = new EventBus(); 18 | -------------------------------------------------------------------------------- /lib/upstream/base.js: -------------------------------------------------------------------------------- 1 | const EventEmitter = require('events'); 2 | const submitProbabilityMixin = require('./mixins/submit-probability-mixin'); 3 | const outageDetectionMixin = require('./mixins/outage-detection-mixin'); 4 | const configMixin = require('./mixins/config-mixin'); 5 | const haltMiningMixin = require('./mixins/halt-mining-mixin'); 6 | 7 | module.exports = configMixin(haltMiningMixin(outageDetectionMixin(submitProbabilityMixin(EventEmitter)))); 8 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: npm 4 | directory: "/" 5 | schedule: 6 | interval: weekly 7 | open-pull-requests-limit: 99 8 | versioning-strategy: increase 9 | 10 | - package-ecosystem: github-actions 11 | directory: "/" 12 | schedule: 13 | interval: weekly 14 | 15 | - package-ecosystem: docker 16 | directory: "/" 17 | schedule: 18 | interval: weekly 19 | -------------------------------------------------------------------------------- /lib/miner/scavenger/index.js: -------------------------------------------------------------------------------- 1 | const { type: os } = require('os'); 2 | 3 | const Scavenger = require('./scavenger'); 4 | const ScavengerConfigGenerator = require('./scavenger-config-generator'); 5 | 6 | module.exports = { 7 | Miner: Scavenger, 8 | ConfigGenerator: ScavengerConfigGenerator, 9 | minerType: 'scavenger', 10 | supportsManagement: true, 11 | downloadInfo: { 12 | version: os() === 'Darwin' ? '1.7.8' : '1.9.0', 13 | }, 14 | }; 15 | -------------------------------------------------------------------------------- /lib/currentRound.js: -------------------------------------------------------------------------------- 1 | class CurrentRound { 2 | constructor(upstream, miningInfo, miner) { 3 | this.upstream = upstream; 4 | this.miningInfo = miningInfo; 5 | this.miner = miner; 6 | this.weight = (upstream && (upstream.upstreamConfig.weight || upstream.upstreamConfig.prio || upstream.weight)) || 10; 7 | this.scanDone = false; 8 | this.progress = 0; 9 | } 10 | 11 | start() { 12 | this.miner.publish('new-round', this.miningInfo); 13 | } 14 | 15 | getHeight() { 16 | return this.miningInfo.height; 17 | } 18 | } 19 | 20 | module.exports = CurrentRound; 21 | -------------------------------------------------------------------------------- /lib/upstream/foxypool.js: -------------------------------------------------------------------------------- 1 | const SocketIo = require('./socketio'); 2 | 3 | class FoxyPool extends SocketIo { 4 | async init() { 5 | if (!this.upstreamConfig.url) { 6 | this.upstreamConfig.url = 'http://miner.signa.foxypool.io/mining'; 7 | } 8 | if (this.upstreamConfig.url.endsWith('/')) { 9 | this.upstreamConfig.url = this.upstreamConfig.url.slice(0, -1); 10 | } 11 | if (!this.upstreamConfig.url.endsWith('/mining')) { 12 | this.upstreamConfig.url += '/mining'; 13 | } 14 | await super.init(); 15 | } 16 | } 17 | 18 | module.exports = FoxyPool; 19 | -------------------------------------------------------------------------------- /lib/services/coin-gecko.js: -------------------------------------------------------------------------------- 1 | const superagent = require('superagent'); 2 | 3 | class CoinGecko { 4 | constructor(currency = 'usd') { 5 | this.currency = currency; 6 | this.baseUrl = 'https://api.coingecko.com/api/v3'; 7 | } 8 | 9 | async getRates(symbols) { 10 | return this.doApiCall('simple/price', {vs_currencies: this.currency, ids: symbols.join(',')}); 11 | } 12 | 13 | async doApiCall(endpoint, params = {}) { 14 | const res = await superagent.get(`${this.baseUrl}/${endpoint}`).query(params); 15 | 16 | return res.body; 17 | } 18 | } 19 | 20 | module.exports = CoinGecko; 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: enhancement 6 | assignees: felixbrucker 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /lib/plot-file-finder/plot.js: -------------------------------------------------------------------------------- 1 | const { basename, dirname } = require('path'); 2 | const BigNumber = require('bignumber.js'); 3 | 4 | const plotFileRegex = /^([0-9]+)_([0-9]+)_([0-9]+)$/; 5 | 6 | class Plot { 7 | static isPlot(file) { 8 | return !!file.match(plotFileRegex); 9 | } 10 | 11 | constructor(path) { 12 | this.path = path; 13 | this.directoryPath = dirname(this.path); 14 | this.fileName = basename(this.path); 15 | const parts = this.fileName.match(plotFileRegex); 16 | this.accountId = parts[1]; 17 | this.nonces = parts[3]; 18 | this.sizeInTiB = (new BigNumber(this.nonces)).multipliedBy(256).dividedBy(new BigNumber(1024).exponentiatedBy(3)); 19 | } 20 | } 21 | 22 | module.exports = Plot; 23 | -------------------------------------------------------------------------------- /lib/miner/index.js: -------------------------------------------------------------------------------- 1 | const scavenger = require('./scavenger'); 2 | const conqueror = require('./conqueror'); 3 | 4 | const miner = { 5 | scavenger, 6 | conqueror, 7 | }; 8 | 9 | const moduleExports = { 10 | miner, 11 | getMiner: ({ minerType }) => { 12 | if (!miner[minerType]) { 13 | throw new Error(`Unsupported miner type: ${minerType}`); 14 | } 15 | 16 | return miner[minerType]; 17 | }, 18 | getMinerDownloadInfo: ({ minerType }) => { 19 | const miner = moduleExports.getMiner({ minerType }); 20 | if (!miner.downloadInfo) { 21 | throw new Error(`No download info available for ${minerType}`); 22 | } 23 | 24 | return miner.downloadInfo; 25 | }, 26 | }; 27 | 28 | module.exports = moduleExports; 29 | -------------------------------------------------------------------------------- /lib/coin-util.js: -------------------------------------------------------------------------------- 1 | const coinUtil = { 2 | blockTime(coin) { 3 | switch (coin) { 4 | default: 5 | return 240; 6 | } 7 | }, 8 | blockZeroBaseTarget(coin) { 9 | switch (coin) { 10 | default: 11 | return 18325193796; 12 | } 13 | }, 14 | modifyDeadline(deadline, coin) { 15 | if (coin !== 'BURST' && coin !== 'SIGNA') { 16 | return deadline; 17 | } 18 | 19 | return Math.floor(Math.log(deadline) * (this.blockTime(coin) / Math.log(this.blockTime(coin)))); 20 | }, 21 | modifyNetDiff(netDiff, coin) { 22 | if (coin !== 'BURST' && coin !== 'SIGNA') { 23 | return netDiff; 24 | } 25 | 26 | return Math.round(netDiff / 1.83); 27 | } 28 | }; 29 | 30 | module.exports = coinUtil; 31 | -------------------------------------------------------------------------------- /lib/capacity.js: -------------------------------------------------------------------------------- 1 | class Capacity { 2 | constructor(capacityInGiB) { 3 | this.capacityInGiB = capacityInGiB; 4 | } 5 | 6 | static fromGiB(capacityInGiB) { 7 | return new Capacity(capacityInGiB); 8 | } 9 | 10 | static fromTiB(capacityInTiB) { 11 | return new Capacity(capacityInTiB * 1024); 12 | } 13 | 14 | toString(precision = 2) { 15 | let capacity = this.capacityInGiB; 16 | let unit = 0; 17 | const units = ['GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']; 18 | while (capacity >= 1024) { 19 | capacity /= 1024; 20 | unit += 1; 21 | } 22 | 23 | return `${capacity.toFixed(precision)} ${units[unit]}`; 24 | } 25 | } 26 | 27 | module.exports = Capacity; 28 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug 6 | assignees: felixbrucker 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **System (please complete the following information):** 27 | - OS: [e.g. Windows] 28 | - NodeJs Version [e.g. 10] 29 | 30 | **Additional context** 31 | Add any other context about the problem here. 32 | -------------------------------------------------------------------------------- /lib/upstream/mixins/submit-probability-mixin.js: -------------------------------------------------------------------------------- 1 | const coinUtil = require('../../coin-util'); 2 | 3 | module.exports = (upstreamClass) => class SubmitProbabilityMixin extends upstreamClass { 4 | async init() { 5 | this.useSubmitProbability = !!this.upstreamConfig.submitProbability; 6 | this.targetDLFactor = null; 7 | this.lastCapacity = null; 8 | if (this.useSubmitProbability) { 9 | let submitProbability = this.upstreamConfig.submitProbability > 10 ? this.upstreamConfig.submitProbability / 100 : this.upstreamConfig.submitProbability; 10 | if (submitProbability >= 1) { 11 | submitProbability = 0.999999; 12 | } 13 | this.targetDLFactor = -1 * Math.log(1 - submitProbability) * (this.blockTime); 14 | } 15 | if (super.init) { 16 | await super.init(); 17 | } 18 | } 19 | 20 | get blockTime() { 21 | return coinUtil.blockTime(this.upstreamConfig.coin); 22 | } 23 | }; -------------------------------------------------------------------------------- /lib/services/store.js: -------------------------------------------------------------------------------- 1 | const { homedir } = require('os'); 2 | const { join } = require('path'); 3 | 4 | class Store { 5 | constructor() { 6 | this.useColors = true; 7 | this._logLevel = 'info'; 8 | this._configFilePath = join(this.configDirectory, 'foxy-miner.yaml'); 9 | this._useDashboard = false; 10 | } 11 | 12 | getUseColors() { 13 | return this.useColors; 14 | } 15 | 16 | setUseColors(useColors) { 17 | this.useColors = useColors; 18 | } 19 | 20 | get logLevel() { 21 | return this._logLevel; 22 | } 23 | 24 | set logLevel(logLevel) { 25 | this._logLevel = logLevel; 26 | } 27 | 28 | get configFilePath() { 29 | return this._configFilePath; 30 | } 31 | 32 | set configFilePath(configFilePath) { 33 | this._configFilePath = configFilePath; 34 | } 35 | 36 | get useDashboard() { 37 | return this._useDashboard; 38 | } 39 | 40 | set useDashboard(value) { 41 | this._useDashboard = value; 42 | } 43 | 44 | get configDirectory() { 45 | return join(homedir(), '.config', 'foxy-miner'); 46 | } 47 | } 48 | 49 | module.exports = new Store(); 50 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # next.js build output 61 | .next 62 | 63 | config.yaml 64 | foxy-miner.yaml 65 | 66 | .idea 67 | 68 | build 69 | -------------------------------------------------------------------------------- /lib/submission.js: -------------------------------------------------------------------------------- 1 | const BigNumber = require('bignumber.js'); 2 | 3 | module.exports = class Submission { 4 | constructor(accountId, height, nonce, deadline, secretPhrase = null) { 5 | this._accountId = accountId; 6 | this._height = parseInt(height, 10); 7 | this._nonce = BigNumber(nonce); 8 | this._deadline = BigNumber(deadline); 9 | this._secretPhrase = secretPhrase; 10 | } 11 | 12 | isValid() { 13 | return this.accountId !== '' && !isNaN(this.height) && !this.nonce.isNaN() && (!this.deadline.isNaN() || this.secretPhrase); 14 | } 15 | 16 | get accountId() { 17 | return this._accountId; 18 | } 19 | 20 | get height() { 21 | return this._height; 22 | } 23 | 24 | get deadline() { 25 | return this._deadline; 26 | } 27 | 28 | get nonce() { 29 | return this._nonce; 30 | } 31 | 32 | get secretPhrase() { 33 | return this._secretPhrase; 34 | } 35 | 36 | toObject() { 37 | const obj = { 38 | accountId: this.accountId, 39 | height: this.height, 40 | nonce: this.nonce.toString(), 41 | }; 42 | if (this.secretPhrase) { 43 | obj.secretPhrase = this.secretPhrase; 44 | } else { 45 | obj.deadline = this.deadline.toString() 46 | } 47 | 48 | return obj; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /lib/startup-message.js: -------------------------------------------------------------------------------- 1 | const outputUtil = require('./output-util'); 2 | 3 | module.exports = () => { 4 | console.log(` ${outputUtil.getString('______ ______ __ __ __ __', '#ff4f19')} ${outputUtil.getString('__ __ __ __ __ ______ ______', '#ff7a53')}\n` + 5 | `${outputUtil.getString('/\\ ___\\/\\ __ \\ /\\_\\_\\_\\ /\\ \\_\\ \\', '#ff4f19')} ${outputUtil.getString('/\\ "-./ \\ /\\ \\ /\\ "-.\\ \\ /\\ ___\\ /\\ == \\', '#ff7a53')} \n` + 6 | `${outputUtil.getString('\\ \\ __\\\\ \\ \\/\\ \\\\/_/\\_\\/_\\ \\____ \\', '#ff4f19')} ${outputUtil.getString('\\ \\ \\-./\\ \\\\ \\ \\\\ \\ \\-. \\\\ \\ __\\ \\ \\ __<', '#ff7a53')} \n` + 7 | ` ${outputUtil.getString('\\ \\_\\ \\ \\_____\\ /\\_\\/\\_\\\\/\\_____\\', '#ff4f19')} ${outputUtil.getString('\\ \\_\\ \\ \\_\\\\ \\_\\\\ \\_\\\\"\\_\\\\ \\_____\\\\ \\_\\ \\_\\', '#ff7a53')} \n` + 8 | ` ${outputUtil.getString('\\/_/ \\/_____/ \\/_/\\/_/ \\/_____/', '#ff4f19')} ${outputUtil.getString('\\/_/ \\/_/ \\/_/ \\/_/ \\/_/ \\/_____/ \\/_/ /_/', '#ff7a53')}\n\n` + 9 | ` ${outputUtil.getString('BHD: 33fKEwAHxVwnrhisREFdSNmZkguo76a2ML', '#f99320')}\n` + 10 | ` ${outputUtil.getString('SIGNA: S-BVUD-7VWE-HD7F-6RX4P', '#0099ff')}\n`); 11 | }; 12 | -------------------------------------------------------------------------------- /lib/services/profitability-service.js: -------------------------------------------------------------------------------- 1 | const CoinGecko = require('./coin-gecko'); 2 | 3 | class ProfitabilityService { 4 | constructor() { 5 | this.coinGecko = new CoinGecko(); 6 | this.rates = {}; 7 | } 8 | 9 | getBlockReward(miningInfo, coin) { 10 | switch (coin) { 11 | case 'burst': 12 | case 'signa': 13 | const month = Math.floor(miningInfo.height / 10800); 14 | return Math.floor(10000 * Math.pow(95, month) / Math.pow(100, month)); 15 | } 16 | 17 | return 0; 18 | } 19 | 20 | async init(useEcoBlockRewards) { 21 | this.useEcoBlockRewards = useEcoBlockRewards; 22 | await this.updateRates(); 23 | setInterval(this.updateRates.bind(this), 5 * 60 * 1000); 24 | } 25 | 26 | async updateRates() { 27 | try { 28 | const rates = await this.coinGecko.getRates(['signum']); 29 | this.rates.signa = rates.signum.usd; 30 | this.rates.burst = this.rates.signa; 31 | } catch (err) {} 32 | } 33 | 34 | getRate(symbol) { 35 | return this.rates[symbol]; 36 | } 37 | 38 | getProfitability(miningInfo, coin, blockReward) { 39 | const rate = this.getRate(coin); 40 | if (!rate) { 41 | return 0; 42 | } 43 | 44 | if (!blockReward) { 45 | blockReward = this.getBlockReward(miningInfo, coin); 46 | } 47 | 48 | return Math.round((Math.pow(1024, 2) / miningInfo.netDiff) * 100 * blockReward * rate); 49 | } 50 | } 51 | 52 | module.exports = new ProfitabilityService(); 53 | -------------------------------------------------------------------------------- /lib/upstream/mixins/config-mixin.js: -------------------------------------------------------------------------------- 1 | const { hostname } = require('os'); 2 | const version = require('../../version'); 3 | const outputUtil = require('../../output-util'); 4 | 5 | module.exports = (upstreamClass) => class ConfigMixin extends upstreamClass { 6 | constructor(upstreamConfig, proxyIndex, minerColor) { 7 | super(upstreamConfig, proxyIndex, minerColor); 8 | this.proxyIndex = proxyIndex; 9 | this.minerColor = minerColor; 10 | this.upstreamName = outputUtil.getName(upstreamConfig); 11 | this.fullUpstreamName = proxyIndex ? `${outputUtil.getString(`Miner #${proxyIndex}`, this.minerColor)} | ${this.upstreamName}` : this.upstreamName; 12 | this.upstreamConfig = upstreamConfig; 13 | this.userAgent = `Foxy-Miner ${version}`; 14 | this.defaultMinerName = `${this.userAgent}/${hostname()}`; 15 | this.miningInfo = {height: 0, toObject: () => ({height: 0})}; 16 | this.bestDL = null; 17 | this.roundStart = null; 18 | this.roundProgress = 0; 19 | this.on('new-round', () => { 20 | this.bestDL = null; 21 | this.roundProgress = 0; 22 | this.roundStart = new Date(); 23 | }); 24 | } 25 | 26 | get stats() { 27 | return { 28 | name: this.upstreamConfig.name, 29 | color: this.upstreamConfig.color, 30 | coin: this.upstreamConfig.coin, 31 | miningInfo: this.miningInfo, 32 | bestDL: this.bestDL, 33 | roundStart: this.roundStart, 34 | roundProgress: this.roundProgress, 35 | counter: 1, 36 | lastCapacity: this.lastCapacity || 0, 37 | miners: [], 38 | }; 39 | } 40 | }; -------------------------------------------------------------------------------- /lib/upstream/mixins/halt-mining-mixin.js: -------------------------------------------------------------------------------- 1 | const superagent = require('superagent'); 2 | 3 | module.exports = (upstreamClass) => class HaltMiningMixin extends upstreamClass { 4 | constructor() { 5 | super(); 6 | this.plotterIds = {}; 7 | this.on('new-round', async () => { 8 | await this.updatePlotterIdStates(); 9 | }); 10 | } 11 | 12 | miningCanBeHalted() { 13 | if (Object.keys(this.plotterIds).length === 0) { 14 | return false; 15 | } 16 | 17 | return Object.keys(this.plotterIds) 18 | .map(plotterId => this.plotterIds[plotterId]) 19 | .every(plotterId => plotterId.miningHalted); 20 | } 21 | 22 | async updatePlotterIdStates() { 23 | if (this.upstreamConfig.coin === 'BTB' && !!this.upstreamConfig.walletUrl) { 24 | await Promise.all(Object.keys(this.plotterIds).map(async plotterId => { 25 | this.plotterIds[plotterId].miningHalted = await this.isPlotterIdOverSizeBTB(plotterId); 26 | })); 27 | } 28 | } 29 | 30 | async isPlotterIdOverSizeBTB(plotterId) { 31 | try { 32 | const res = await this.doWalletApiCall('getplottermininginfo', [plotterId]); 33 | 34 | return res.oversize; 35 | } catch (err) { 36 | return null; 37 | } 38 | } 39 | 40 | async doWalletApiCall(method, params = []) { 41 | const res = await superagent.post(this.upstreamConfig.walletUrl).send({ 42 | jsonrpc: '2.0', 43 | id: 0, 44 | method, 45 | params, 46 | }); 47 | 48 | return res.body.result; 49 | } 50 | 51 | submitNonce(submission) { 52 | if (this.plotterIds[submission.accountId]) { 53 | return; 54 | } 55 | this.plotterIds[submission.accountId] = {}; 56 | } 57 | }; -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "foxy-miner", 3 | "version": "2.7.0", 4 | "description": "A scavenger / conqueror wrapper for collision free multi mining.", 5 | "keywords": [ 6 | "burst", 7 | "signa", 8 | "poc", 9 | "scavenger", 10 | "conqueror", 11 | "multi-chain", 12 | "collision-free", 13 | "mining", 14 | "foxyminer", 15 | "foxy", 16 | "foxypool" 17 | ], 18 | "repository": "https://github.com/foxypool/foxy-miner.git", 19 | "bugs": "https://github.com/foxypool/foxy-miner/issues", 20 | "license": "GPL-3.0", 21 | "dependencies": { 22 | "@sentry/integrations": "^7.15.0", 23 | "@sentry/node": "^7.15.0", 24 | "bignumber.js": "^9.1.0", 25 | "bytes": "^3.1.2", 26 | "chalk": "^4.1.2", 27 | "cli-progress": "^3.11.2", 28 | "cli-table3": "^0.6.3", 29 | "commander": "^9.4.1", 30 | "cross-spawn": "^7.0.3", 31 | "decompress": "^4.2.1", 32 | "js-yaml": "^4.1.0", 33 | "koa": "^2.13.4", 34 | "koa-bodyparser": "^4.3.0", 35 | "koa-router": "^12.0.0", 36 | "lodash": "^4.17.21", 37 | "log-update": "^4.0.0", 38 | "mkdirp": "^1.0.4", 39 | "moment": "^2.29.4", 40 | "opencl-info": "^0.3.0", 41 | "ora": "^5.4.1", 42 | "prompts": "^2.4.2", 43 | "request": "^2.88.2", 44 | "request-progress": "^3.0.0", 45 | "rotating-file-stream": "^3.0.4", 46 | "socket.io-client": "^4.5.3", 47 | "strip-ansi": "^6.0.1", 48 | "superagent": "^8.0.2" 49 | }, 50 | "devDependencies": { 51 | "archiver": "^5.3.1", 52 | "pkg": "^5.8.0" 53 | }, 54 | "bin": { 55 | "foxy-miner": "./main.js" 56 | }, 57 | "main": "main.js", 58 | "scripts": { 59 | "start": "node main.js", 60 | "package": "node bin/build-package.js" 61 | }, 62 | "engines": { 63 | "node": ">=14" 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /lib/upstream/mixins/outage-detection-mixin.js: -------------------------------------------------------------------------------- 1 | const eventBus = require('../../services/event-bus'); 2 | 3 | module.exports = (upstreamClass) => class OutageDetectionMixin extends upstreamClass { 4 | constructor() { 5 | super(); 6 | this.connected = true; 7 | this.smoothedConnectionState = this.connected; 8 | this.prevConnectionState = this.connected; 9 | this.connectionStateCounter = 0; 10 | this.connectionOutageCounterThreshold = 2; 11 | } 12 | 13 | async init() { 14 | const updateMiningInfoInterval = this.upstreamConfig.updateMiningInfoInterval ? this.upstreamConfig.updateMiningInfoInterval : 1000; 15 | this.connectionOutageCounterThreshold = Math.round(updateMiningInfoInterval / 1000) * 2; 16 | setInterval(this.detectConnectionOutage.bind(this), 1000); 17 | if (super.init) { 18 | await super.init(); 19 | } 20 | } 21 | 22 | detectConnectionOutage() { 23 | this.prevConnectionState = this.smoothedConnectionState; 24 | 25 | if (this.connected) { 26 | this.smoothedConnectionState = true; 27 | this.connectionStateCounter = 0; 28 | } else if (this.smoothedConnectionState !== this.connected) { 29 | this.connectionStateCounter += 1; 30 | } else { 31 | this.connectionStateCounter = 0; 32 | } 33 | 34 | if (this.connectionStateCounter > this.connectionOutageCounterThreshold) { 35 | this.smoothedConnectionState = this.connected; 36 | this.connectionStateCounter = 0; 37 | } 38 | 39 | if (this.prevConnectionState && !this.smoothedConnectionState) { 40 | eventBus.publish('log/error', `${this.upstreamName} | Connection outage detected ..`); 41 | } else if (!this.prevConnectionState && this.smoothedConnectionState) { 42 | eventBus.publish('log/error', `${this.upstreamName} | Connection outage resolved`); 43 | } 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /lib/miningInfo.js: -------------------------------------------------------------------------------- 1 | const Capacity = require('./capacity'); 2 | const coinUtil = require('./coin-util'); 3 | 4 | module.exports = class MiningInfo { 5 | constructor({ 6 | height, 7 | baseTarget, 8 | generationSignature, 9 | targetDeadline = null, 10 | miningHalted = false, 11 | coin = null, 12 | }) { 13 | this._height = parseInt(height, 10); 14 | this._baseTarget = parseInt(baseTarget, 10); 15 | this._generationSignature = generationSignature; 16 | this._targetDeadline = targetDeadline >= Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : targetDeadline; 17 | this._miningHalted = miningHalted; 18 | this._coin = coin; 19 | } 20 | 21 | get blockZeroBaseTarget() { 22 | return coinUtil.blockZeroBaseTarget(this._coin); 23 | } 24 | 25 | get height() { 26 | return this._height; 27 | } 28 | 29 | get baseTarget() { 30 | return this._baseTarget; 31 | } 32 | 33 | get generationSignature() { 34 | return this._generationSignature; 35 | } 36 | 37 | get targetDeadline() { 38 | return this._targetDeadline; 39 | } 40 | 41 | get netDiff() { 42 | const netDiff = Math.round(this.blockZeroBaseTarget / this.baseTarget); 43 | 44 | return coinUtil.modifyNetDiff(netDiff, this._coin); 45 | } 46 | 47 | get netDiffFormatted() { 48 | return Capacity.fromTiB(this.netDiff).toString(); 49 | } 50 | 51 | get miningHalted() { 52 | return this._miningHalted; 53 | } 54 | 55 | set miningHalted(value) { 56 | this._miningHalted = value; 57 | } 58 | 59 | toObject() { 60 | const obj = { 61 | height: this.height, 62 | baseTarget: this.baseTarget, 63 | generationSignature: this.generationSignature, 64 | }; 65 | if (this.targetDeadline) { 66 | obj.targetDeadline = this.targetDeadline; 67 | } 68 | if (this.miningHalted) { 69 | obj.miningHalted = this.miningHalted; 70 | } 71 | 72 | return obj; 73 | } 74 | }; 75 | -------------------------------------------------------------------------------- /lib/miner/binary-manager/download.js: -------------------------------------------------------------------------------- 1 | const EventEmitter = require('events'); 2 | const { createWriteStream, unlinkSync } = require('fs'); 3 | const { join } = require('path'); 4 | const request = require('request'); 5 | const progress = require('request-progress'); 6 | const decompress = require('decompress'); 7 | const mkdirp = require('mkdirp'); 8 | 9 | class Download { 10 | constructor({ url, destinationDir }) { 11 | this.url = url; 12 | this.destinationDir = destinationDir; 13 | this.filename = this.url.split('/').pop(); 14 | this.downloadFilePath = join(this.destinationDir, this.filename); 15 | this.emitter = new EventEmitter(); 16 | } 17 | 18 | async download() { 19 | mkdirp.sync(this.destinationDir, { mode: 0o770 }); 20 | 21 | return new Promise((resolve, reject) => { 22 | let returned = false; 23 | const download = progress(request(this.url)); 24 | 25 | download.on('progress', (state) => { 26 | this.emitter.emit('download-progress', state); 27 | }); 28 | 29 | download.on('error', (err) => { 30 | if (returned) { 31 | return; 32 | } 33 | returned = true; 34 | reject(err); 35 | }); 36 | 37 | download.on('end', () => { 38 | if (returned) { 39 | return; 40 | } 41 | returned = true; 42 | resolve(); 43 | }); 44 | 45 | download.pipe(createWriteStream(this.downloadFilePath)); 46 | }); 47 | } 48 | 49 | async extract() { 50 | if (this.filename.includes('.tar.gz') || this.filename.includes('.zip')) { 51 | await decompress(this.downloadFilePath, this.destinationDir); 52 | } else { 53 | throw new Error(`No matching extractor found for ${this.filename}`); 54 | } 55 | } 56 | 57 | async removeDownloadFile() { 58 | unlinkSync(this.downloadFilePath); 59 | } 60 | 61 | on(...args) { 62 | return this.emitter.on(...args); 63 | } 64 | } 65 | 66 | module.exports = Download; 67 | -------------------------------------------------------------------------------- /bin/build-package.js: -------------------------------------------------------------------------------- 1 | const { basename, join } = require('path'); 2 | const { createWriteStream, createReadStream, unlinkSync, copyFileSync, existsSync } = require('fs'); 3 | const { exec } = require('pkg'); 4 | const mkdirp = require('mkdirp'); 5 | const archiver = require('archiver'); 6 | 7 | const version = require('../lib/version'); 8 | 9 | const nativeModulePaths = []; 10 | 11 | (async () => { 12 | const buildPath = join(__dirname, '..', 'build'); 13 | mkdirp.sync(buildPath); 14 | const binaryFileName = `foxy-miner${process.platform === 'win32' ? '.exe' : ''}`; 15 | const binaryPath = join(buildPath, binaryFileName); 16 | await exec([ '--output', binaryPath, '.' ]); 17 | const fileList = [ 18 | binaryPath, 19 | ]; 20 | nativeModulePaths.forEach(nativeModulePath => { 21 | const fullNativeModulePath = join(__dirname, '..', 'node_modules', nativeModulePath); 22 | if (!existsSync(fullNativeModulePath)) { 23 | return; 24 | } 25 | const filePath = join(buildPath, basename(nativeModulePath)); 26 | copyFileSync(fullNativeModulePath, filePath); 27 | fileList.push(filePath); 28 | }); 29 | await createZipArchiveForFiles(fileList, join(buildPath, `foxy-miner-${version}-${getZipPlatform()}.zip`)); 30 | })(); 31 | 32 | async function createZipArchiveForFiles(fileList, zipFilePath) { 33 | const zipFileStream = createWriteStream(zipFilePath); 34 | const zipFileClosedPromise = new Promise(resolve => zipFileStream.once('close', resolve)); 35 | const archive = archiver('zip', { zlib: { level: 9 } }); 36 | archive.pipe(zipFileStream); 37 | fileList.forEach(filePath => archive.append(createReadStream(filePath), { 38 | name: basename(filePath), 39 | mode: 0o755, 40 | prefix: `foxy-miner-${version}`, 41 | })); 42 | await archive.finalize(); 43 | await zipFileClosedPromise; 44 | fileList.forEach(filePath => unlinkSync(filePath)); 45 | } 46 | 47 | function getZipPlatform() { 48 | switch (process.platform) { 49 | case 'win32': return 'windows'; 50 | case 'linux': return 'linux'; 51 | case 'darwin': return 'macos'; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /lib/idle-program.js: -------------------------------------------------------------------------------- 1 | const { dirname, basename } = require('path'); 2 | const { exec } = require('child_process'); 3 | const spawn = require('cross-spawn'); 4 | const eventBus = require('./services/event-bus'); 5 | 6 | class IdleProgram { 7 | constructor(binPath, killBinPath = null) { 8 | this.binPath = binPath; 9 | this.bin = `./${basename(this.binPath)}`; 10 | this.cwd = dirname(this.binPath); 11 | this.killBinPath = killBinPath; 12 | this.stopped = true; 13 | } 14 | 15 | async start() { 16 | while (this.stopping) { 17 | await new Promise(resolve => setTimeout(resolve, 500)); 18 | } 19 | this.stopped = false; 20 | const args = []; // Not supported for now 21 | 22 | const options = { 23 | cwd: this.cwd, 24 | stdio: 'pipe', 25 | }; 26 | let bin = this.bin; 27 | if (this.killBinPath) { 28 | delete options.stdio; 29 | options.detached = true; 30 | options.shell = true; 31 | bin = this.binPath; 32 | } 33 | eventBus.publish('log/debug', `${this.constructor.name} | Starting with binary: ${bin}, args: ${args.join(' ')}, cwd: ${this.cwd}`); 34 | this.programRef = spawn(bin, args, options); 35 | if (!this.killBinPath) { 36 | this.programRef.stdout.on('data', (data) => process.stdout.write(data)); 37 | this.programRef.stderr.on('data', (data) => process.stderr.write(data)); 38 | } 39 | this.programRef.on('close', async () => { 40 | if (this.stopped || this.stopping) { 41 | return; 42 | } 43 | await new Promise(resolve => setTimeout(resolve, 500)); 44 | this.start(); 45 | }); 46 | } 47 | 48 | async stop() { 49 | if (!this.programRef || this.stopping) { 50 | return; 51 | } 52 | eventBus.publish('log/debug', `${this.constructor.name} | Stopping ..`); 53 | this.stopping = true; 54 | if (this.killBinPath) { 55 | await new Promise(resolve => exec(this.killBinPath, resolve)); 56 | } 57 | 58 | this.programRef.kill(); 59 | this.programRef = null; 60 | this.stopped = true; 61 | this.stopping = false; 62 | } 63 | } 64 | 65 | module.exports = IdleProgram; 66 | -------------------------------------------------------------------------------- /lib/output-util.js: -------------------------------------------------------------------------------- 1 | const chalk = require('chalk'); 2 | const moment = require('moment'); 3 | const store = require('./services/store'); 4 | const coinUtil = require('./coin-util'); 5 | 6 | module.exports = { 7 | getName(config) { 8 | if (!store.getUseColors()) { 9 | return config.name; 10 | } 11 | 12 | return `${config.color ? chalk.hex(config.color)(config.name) : config.name}`; 13 | }, 14 | getString(text, color) { 15 | if (!store.getUseColors() || !color) { 16 | return text; 17 | } 18 | if (!color.startsWith('#')) { 19 | return chalk[color](text); 20 | } 21 | 22 | return chalk.hex(color)(text); 23 | }, 24 | getFormattedDeadline(deadline) { 25 | const duration = moment.duration(deadline, 'seconds'); 26 | if (duration.years() > 0) { 27 | return `${duration.years()}y ${duration.months()}m ${duration.days()}d ${duration.hours().toString().padStart(2, '0')}:${duration.minutes().toString().padStart(2, '0')}:${duration.seconds().toString().padStart(2, '0')}`; 28 | } else if (duration.months() > 0) { 29 | return `${duration.months()}m ${duration.days()}d ${duration.hours().toString().padStart(2, '0')}:${duration.minutes().toString().padStart(2, '0')}:${duration.seconds().toString().padStart(2, '0')}`; 30 | } else if (duration.days() > 0) { 31 | return `${duration.days()}d ${duration.hours().toString().padStart(2, '0')}:${duration.minutes().toString().padStart(2, '0')}:${duration.seconds().toString().padStart(2, '0')}`; 32 | } 33 | 34 | return `${duration.hours().toString().padStart(2, '0')}:${duration.minutes().toString().padStart(2, '0')}:${duration.seconds().toString().padStart(2, '0')}`; 35 | }, 36 | getDeadlineColor(deadline, coin) { 37 | if (deadline === null) { 38 | return null; 39 | } 40 | const aMonth = 30 * 24 * 60 * 60; 41 | const tenMinutes = 10 * 60; 42 | const limit = coinUtil.modifyDeadline(aMonth, coin); 43 | const lowLimit = coinUtil.modifyDeadline(tenMinutes, coin); 44 | if (deadline <= lowLimit) { 45 | return '#00ffbb'; 46 | } 47 | 48 | const percent = Math.min(Math.max((1 - (deadline / limit)), 0), 1); 49 | if (percent < 0.5) { 50 | return null; 51 | } 52 | const red = Math.max(Math.min(Math.floor(255 - ((percent * 2) - 1) * 255), 255), 0); 53 | const green = Math.max(Math.min(Math.floor(percent * 2 * 255), 255), 0); 54 | 55 | return `#${red.toString(16).padStart(2, '0')}${green.toString(16).padStart(2, '0')}00`; 56 | } 57 | }; -------------------------------------------------------------------------------- /lib/services/foxy-pool-gateway.js: -------------------------------------------------------------------------------- 1 | const EventEmitter = require('events'); 2 | const io = require('socket.io-client'); 3 | 4 | const eventBus = require('./event-bus'); 5 | const config = require('../services/config'); 6 | 7 | class FoxyPoolGateway { 8 | constructor() { 9 | this.url = 'http://miner.foxypool.io/mining'; 10 | this.coins = []; 11 | this.emitter = new EventEmitter(); 12 | this.emitter.setMaxListeners(0); 13 | this.connected = false; 14 | } 15 | 16 | async init() { 17 | const options = { rejectUnauthorized : false }; 18 | if (!config.allowLongPolling) { 19 | options.transports = ['websocket']; 20 | } 21 | this.client = io(this.url, options); 22 | 23 | this.client.on('connect', async () => { 24 | this.connected = true; 25 | this.emitter.emit('connection-state-change'); 26 | eventBus.publish('log/debug', `Foxy-Pool-Gateway | url=${this.url} | Socket.IO connected`); 27 | const result = await this.subscribeToCoins(); 28 | if (result.error) { 29 | eventBus.publish('log/error', `Foxy-Pool-Gateway | Error: ${result.error}`); 30 | } 31 | await Promise.all(this.coins.map(async coin => { 32 | const miningInfo = await this.getMiningInfo(coin); 33 | this.emitter.emit(`${coin}:miningInfo`, miningInfo); 34 | })); 35 | }); 36 | this.client.on('disconnect', () => { 37 | this.connected = false; 38 | this.emitter.emit('connection-state-change'); 39 | eventBus.publish('log/debug', `Foxy-Pool-Gateway | url=${this.url} | Socket.IO disconnected`); 40 | }); 41 | 42 | this.client.on('miningInfo', (coin, miningInfo) => { 43 | this.connected = true; 44 | this.emitter.emit('connection-state-change'); 45 | this.emitter.emit(`${coin}:miningInfo`, miningInfo); 46 | }); 47 | } 48 | 49 | async subscribeToCoins() { 50 | return new Promise(resolve => this.client.emit('subscribe', this.coins, resolve)); 51 | } 52 | 53 | onNewMiningInfo(coin, handler) { 54 | this.emitter.on(`${coin}:miningInfo`, handler); 55 | } 56 | 57 | onConnectionStateChange(handler) { 58 | this.emitter.on('connection-state-change', handler); 59 | } 60 | 61 | async getMiningInfo(coin) { 62 | return new Promise(resolve => this.client.emit('getMiningInfo', coin, resolve)); 63 | } 64 | 65 | async submitNonce(coin, submission, options) { 66 | return new Promise(resolve => this.client.emit('submitNonce', coin, submission, options, resolve)); 67 | } 68 | } 69 | 70 | module.exports = new FoxyPoolGateway(); 71 | -------------------------------------------------------------------------------- /lib/miner/config-manager/config-manager.js: -------------------------------------------------------------------------------- 1 | const { existsSync, writeFileSync, readFileSync } = require('fs'); 2 | const { homedir } = require('os'); 3 | const { join } = require('path'); 4 | const mkdirp = require('mkdirp'); 5 | 6 | const { getMiner } = require('../'); 7 | 8 | class ConfigManager { 9 | ensureMinerConfigExists({ minerType, config = {}, minerIndex = null }) { 10 | const minerConfigPath = this.getMinerConfigPath({ minerType, minerIndex }); 11 | if (existsSync(minerConfigPath)) { 12 | return; 13 | } 14 | const miner = getMiner({ minerType }); 15 | if (!miner.ConfigGenerator) { 16 | throw new Error(`No config generator available for ${minerType}`); 17 | } 18 | const minerConfigs = config.miner || []; 19 | const minerConfig = minerIndex !== null ? minerConfigs[minerIndex] : {}; 20 | 21 | const configGenerator = new miner.ConfigGenerator({ config }); 22 | const minerConfigYaml = configGenerator.generate({ minerConfig, minerIndex }); 23 | 24 | mkdirp.sync(this.configDirectory, { mode: 0o770 }); 25 | writeFileSync(minerConfigPath, minerConfigYaml, 'utf8'); 26 | } 27 | 28 | updateMinerConfig({ minerType, config = {}, minerIndex = null }) { 29 | const minerConfigPath = this.getMinerConfigPath({ minerType, minerIndex }); 30 | if (!existsSync(minerConfigPath)) { 31 | return; 32 | } 33 | const miner = getMiner({ minerType }); 34 | if (!miner.ConfigGenerator) { 35 | throw new Error(`No config generator available for ${minerType}`); 36 | } 37 | const minerConfigs = config.miner || []; 38 | const minerConfig = minerIndex !== null ? minerConfigs[minerIndex] : {}; 39 | 40 | const configGenerator = new miner.ConfigGenerator({ config }); 41 | 42 | const configYaml = readFileSync(minerConfigPath, 'utf8'); 43 | let updatedConfigYaml; 44 | try { 45 | updatedConfigYaml = configGenerator.updateConfig({ configYaml, minerConfig, minerIndex }); 46 | } catch (err) { 47 | updatedConfigYaml = configGenerator.generate({ minerConfig, minerIndex }); 48 | } 49 | if (configYaml !== updatedConfigYaml) { 50 | writeFileSync(minerConfigPath, updatedConfigYaml, 'utf8'); 51 | } 52 | } 53 | 54 | getMinerConfigPath({ minerType, minerIndex = null }) { 55 | return join(this.configDirectory, this.getMinerConfigName({ minerType, minerIndex })); 56 | } 57 | 58 | getMinerConfigName({ minerType, minerIndex = null }) { 59 | if (minerIndex !== null) { 60 | return `${minerType}-${minerIndex + 1}.yaml`; 61 | } 62 | 63 | return `${minerType}.yaml`; 64 | } 65 | 66 | get configDirectory() { 67 | return join(homedir(), '.config', 'foxy-miner', 'miner', 'configs'); 68 | } 69 | } 70 | 71 | module.exports = new ConfigManager(); 72 | -------------------------------------------------------------------------------- /lib/currentRoundManager.js: -------------------------------------------------------------------------------- 1 | const CurrentRound = require('./currentRound'); 2 | const config = require('./services/config'); 3 | 4 | class CurrentRoundManager { 5 | 6 | constructor(miner) { 7 | this.miner = miner; 8 | this.roundQueue = []; 9 | this.currentRound = {scanDone: true, prio: 9999}; 10 | this.miner.subscribe('round-finished', (height) => { 11 | // Ignore round endings for previous rounds 12 | if (this.currentRound.miningInfo.height !== height) { 13 | return; 14 | } 15 | this.currentRound.scanDone = true; 16 | this.currentRound.progress = 100; 17 | this.updateCurrentRound(); 18 | if (!this.currentRound.scanDone) { 19 | return; 20 | } 21 | this.miner.publish('all-rounds-finished'); 22 | }); 23 | } 24 | 25 | getMiningInfo() { 26 | if (!this.currentRound.miningInfo) { 27 | return { 28 | error: 'No miningInfo available!', 29 | }; 30 | } 31 | return this.currentRound.miningInfo.toObject(); 32 | } 33 | 34 | updateCurrentRound() { 35 | if (this.roundQueue.length === 0) { 36 | return; 37 | } 38 | this.currentRound = this.roundQueue.shift(); 39 | this.currentRound.start(); 40 | } 41 | 42 | removeOldRoundsFromUpstream(upstream) { 43 | this.roundQueue = this.roundQueue.filter(currRound => currRound.upstream !== upstream); 44 | } 45 | 46 | addNewRound(upstream, miningInfo) { 47 | const currentRound = new CurrentRound(upstream, miningInfo, this.miner); 48 | this.removeOldRoundsFromUpstream(upstream); 49 | 50 | this.roundQueue.push(currentRound); 51 | this.roundQueue.sort((a, b) => b.weight - a.weight); 52 | if (config.maxNumberOfChains && this.roundQueue.length > config.maxNumberOfChains) { 53 | this.roundQueue = this.roundQueue.slice(0, config.maxNumberOfChains); 54 | } 55 | 56 | // Remove old round directly if from same upstream 57 | if (this.currentRound.upstream === upstream) { 58 | this.currentRound = this.roundQueue.shift(); 59 | this.currentRound.start(); 60 | return; 61 | } 62 | 63 | // Do not interrupt almost finished rounds 64 | const doNotInterruptAbovePercent = this.currentRound.upstream && this.currentRound.upstream.upstreamConfig.doNotInterruptAbovePercent; 65 | if (!!doNotInterruptAbovePercent && !this.currentRound.scanDone && this.currentRound.progress >= doNotInterruptAbovePercent) { 66 | return; 67 | } 68 | 69 | // new high prio round, use it now and get back to the other one later if it was still running 70 | if (this.currentRound.weight < this.roundQueue[0].weight) { 71 | if (!this.currentRound.scanDone) { 72 | this.roundQueue.push(this.currentRound); 73 | this.roundQueue.sort((a, b) => b.weight - a.weight); 74 | } 75 | this.currentRound = this.roundQueue.shift(); 76 | this.currentRound.start(); 77 | } 78 | 79 | // init 80 | if (this.currentRound.scanDone) { 81 | this.updateCurrentRound(); 82 | } 83 | } 84 | 85 | getCurrentRound() { 86 | return this.currentRound; 87 | } 88 | } 89 | 90 | module.exports = CurrentRoundManager; 91 | -------------------------------------------------------------------------------- /lib/plot-file-finder/plot-file-finder.js: -------------------------------------------------------------------------------- 1 | const { join } = require('path'); 2 | const { existsSync, promises: fs } = require('fs'); 3 | const EventEmitter = require('events'); 4 | const BigNumber = require('bignumber.js'); 5 | 6 | const Plot = require('./plot'); 7 | 8 | class PlotFileFinder { 9 | constructor() { 10 | this.plots = []; 11 | this.directoriesScanned = 0; 12 | 13 | this.maxDepth = 2; 14 | this.directoryBlacklist = new Set([ 15 | 'appdata', 16 | 'program files', 17 | 'program files (x86)', 18 | 'windows', 19 | 'system volume information', 20 | '$recycle.bin', 21 | ]); 22 | this.directoryWhitelist = [ 23 | 'burst', 24 | 'signa', 25 | 'signum', 26 | 'bhd', 27 | 'plot', 28 | 'disk', 29 | 'disc', 30 | 'chassis', 31 | ]; 32 | const alphabet = [...Array(26)].map((_, i) => String.fromCharCode('A'.charCodeAt(0) + i)); 33 | this.windowsDrives = alphabet.map(char => `${char}:\\`); 34 | this.linuxMountDirectories = [ 35 | '/mnt', 36 | '/media', 37 | ]; 38 | this.appleMountDirectories = [ 39 | '/Volumes', 40 | ]; 41 | 42 | this.emitter = new EventEmitter(); 43 | } 44 | 45 | async findPlots() { 46 | this.plots = []; 47 | this.directoriesScanned = 0; 48 | 49 | const rootDirs = [].concat(this.windowsDrives, this.linuxMountDirectories, this.appleMountDirectories).filter(path => existsSync(path)); 50 | 51 | await Promise.all(rootDirs.map(rootDir => this.scan(rootDir, 0))); 52 | } 53 | 54 | async scan(dir, currentDepth) { 55 | let files = null; 56 | try { 57 | files = await fs.readdir(dir); 58 | } catch(err) { 59 | return; 60 | } 61 | this.directoriesScanned += 1; 62 | this.emitter.emit('directory-scanned', { 63 | directory: dir, 64 | }); 65 | await Promise.all(files.map(async file => { 66 | let localDepth = currentDepth; 67 | const filePath = join(dir, file); 68 | let stats = null; 69 | try { 70 | stats = await fs.stat(filePath); 71 | } catch (err) { 72 | return; 73 | } 74 | if (stats.isDirectory()) { 75 | if (this.directoryBlacklist.has(file.toLowerCase())) { 76 | return; 77 | } 78 | // Scan whitelisted dirs as far as it goes 79 | if (this.directoryWhitelist.some(dir => filePath.toLowerCase().indexOf(dir) !== -1)) { 80 | localDepth = 0; 81 | } 82 | if (localDepth < this.maxDepth) { 83 | await this.scan(filePath, localDepth + 1); 84 | } 85 | return; 86 | } 87 | if (!Plot.isPlot(file)) { 88 | return; 89 | } 90 | const plot = new Plot(filePath); 91 | this.plots.push(plot); 92 | this.emitter.emit('plot-found', { 93 | plot, 94 | }); 95 | })); 96 | } 97 | 98 | get plotDirectories() { 99 | return [...new Set(this.plots.map(plot => plot.directoryPath))].sort(); 100 | } 101 | 102 | get totalPlotSizeInTiB() { 103 | return this.plots.reduce((acc, curr) => acc.plus(curr.sizeInTiB), new BigNumber(0)); 104 | } 105 | 106 | on(...args) { 107 | return this.emitter.on(...args); 108 | } 109 | } 110 | 111 | module.exports = PlotFileFinder; 112 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Foxy-Miner 2 | ====== 3 | 4 | [![Software License](https://img.shields.io/badge/license-GPL--3.0-brightgreen.svg?style=flat-square)](LICENSE) 5 | [![npm](https://img.shields.io/npm/v/foxy-miner.svg?style=flat-square)](https://www.npmjs.com/package/foxy-miner) 6 | [![npm weekly downloads](https://img.shields.io/npm/dw/foxy-miner.svg?style=flat-square)](https://www.npmjs.com/package/foxy-miner) 7 | [![Discord](https://img.shields.io/discord/582180216747720723.svg?label=Discord&style=flat-square&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAAN1wAADdcBQiibeAAABUlJREFUWMO911uMXWUVB/Dft89lOreWMrT0RgutabFWi1JoaxM1EIk2mjQUbeSpKCQqiVFjovbFxBijKMUXo5AgxUu8oWlQgmk0PghW6IPQcHGMrRULDNSZ6UzndDpzZu/lw57pTDO3qtSV7OyTvb5v/f/rv9a39j4JYt9uuBl34+s4giJ99RfeCIvdq6lUM82RrSK+QPo2cSgdfEUaB4fP4Rt4CQ/gQfTAf0skPryWxgD11hWiuFPEXVglpc8r8nt0Xi6bsv7a8ftqfBmPYg/aYt9uU4jOD3zHO8SulYw129VablcUj4r4ElaNL3mzze+hOXKeQB3Lp8TIcAMewgFsRXYxJOLWqzjTV8F2Rf6wiAeJ68djTtgyLz5VV+Sq4w8qaJ8hXis+hHeNl+T+2Le7gfWkdZrnupx4PtMc6SUdk1K3iA5jox8XcQeWzswy2uRjVYxOEAjkcyR2Jb6IXRjBm4h2ZCKICKIh0jGiBRuQZg+XCikFzivQRO886iZsnMPXQWyet0bl6j7V+qgiP1+XHN0XtfmNsW6NgVylKptyxJ7E8P8BfJj0hFpd+unfLujMP41fl9jS07J0WCqhpxI4jf3ov4Top6W0Xz7Wr1afJDClDI/hO5cu+XS/1vZfq9Sknx2fpgDlQLrmEipwtdFz9akPMkwds9uw85LBR7xfnm9X5OJjN86owG1Y9D+izOVcSNzmilXJwGvTCKzATbPtbBTJnxsVI3PEH47M4dFOQ5HNvijiJr2vrJDn0wi8FWtny+mx/qr9r9b9qr+qGdNXjETmB2e77Btc6ZHhxXOpcI2It4miJBCf3ml8nm8RsaD8feGOhPWthYWVcLCv5plGZdqkf2K0ww/PXq4rG7Opem6mzCmCiBZii2ZTfHSzqj0fZM3KzJGjmwyeoX+A04OcGyk3pRLpurbcXUs5ejazvrWYRnJz7axbW0/bUR+ypd6YdBRBtcLCdpZcxpLFXNa5yY4tFSdezlM8ewA6tdQPSWmb5hhDDXpO8Y+TnOojz0lJoFC+u0FzhL8/V96VL5RsXDERtNRZs5z1q1lxBe2tVDPCU5rFLaTBqiwrCUR0oWS7eFF5rVvNyR6e/yu9/VJKk+Az2AW+Ncu5YSOrllKrlIpNlIEuKXVisFpKHO2mfpDEuL61GmtXs7SLZ17g+EuTvllZZLx9Aze+hbaWErCYtqdd0gFVRYF4Tco+JcXVUtqAzVK6FgtF0NHO1uuoVuk+Njt4SmzZyLZNpZKTwINCN46iWzghj56JBp9M/MgDjIwmCzsXqmSbpGyPLN0+LlnZmH94mpd7SrCpPRBR1vp926nXJpTqE34s/EThOSMxoCrSLfsvOGEzWjx7gKFGZvGij8iy76JDSvS8zu8PM9qcJDB6jrYF7Ho3K5dMZN4QPmE4fqSeinTzvTPizDqy0ua9dHYUmmMHRTx5vjeWdLFsyYW9EMFVy7iya1L28Ee5X84FPicBlMextaUh4hHlCSxru3zp+flQRkmsWVb6SivwczUNw8WcEHMSSO/8ZCl1Xjwu4oXxzDQXLfJ61LzazPwzrzmZtRldvMiU6fSiwuNy0gfum5NA1Xw2MsqSrpcNNb4npW9Ksh513+pZYHAonOpbpbXGV7I26yayDw9pSyediXnDZ/MtSNffyeAZ8vz7In4DedCfJ31jmd6ioreoTP6pCIcUHjYc0nvvnS/8/ATAwBmq1V5F8VkRv0WRkITyTpR1/53wGZl/zVf7/4hA2nE3g0NUKt3qlb2DQ+e+ljieUspTSkXixMDQ2D1aKntl/iKvSDvvu5jQ/g1HtBu+eMyiaAAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAxOS0wNC0zMFQxMjozNzoxMC0wNDowMH0cFvgAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMTktMDQtMzBUMTI6Mzc6MTAtMDQ6MDAMQa5EAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAABJRU5ErkJggg==)](https://discord.gg/gNHhn9y) 8 | 9 | ## Prerequisites 10 | 11 | - nodejs >= 14, see [here](https://docs.foxypool.io/general/installing-nodejs/) how to install it 12 | 13 | ## Getting started 14 | 15 | Check out the [Docs](https://docs.foxypool.io/foxy-miner/). 16 | 17 | ## Setup 18 | 19 | ```bash 20 | npm i -g foxy-miner 21 | foxy-miner 22 | ``` 23 | 24 | ## Updating the miner 25 | 26 | ```bash 27 | npm update -g foxy-miner 28 | ``` 29 | 30 | ## Donate 31 | 32 | - BHD: 33fKEwAHxVwnrhisREFdSNmZkguo76a2ML 33 | - SIGNA: S-BVUD-7VWE-HD7F-6RX4P 34 | - PP: https://www.paypal.me/felixbrucker 35 | 36 | ## Changelog 37 | 38 | A Changelog can be found [here](https://github.com/foxypool/foxy-miner/blob/master/CHANGELOG.md) 39 | 40 | ## License 41 | 42 | GNU GPLv3 (see [LICENSE](https://github.com/foxypool/foxy-miner/blob/master/LICENSE)) 43 | -------------------------------------------------------------------------------- /lib/miner/binary-manager/binary-manager.js: -------------------------------------------------------------------------------- 1 | const { existsSync } = require('fs'); 2 | const { type: os, homedir, arch } = require('os'); 3 | const { join } = require('path'); 4 | const cliProgress = require('cli-progress'); 5 | const bytes = require('bytes'); 6 | 7 | const Download = require('./download'); 8 | const { miner, getMinerDownloadInfo } = require('../'); 9 | 10 | class BinaryManager { 11 | async ensureMinerDownloaded({ minerType, isCpuOnly }) { 12 | if (minerType !== miner.scavenger.minerType) { 13 | throw new Error('Only scavenger supported at this time'); 14 | } 15 | const downloadInfo = getMinerDownloadInfo({ minerType }); 16 | const minerBinPath = this.getMinerBinaryPath({ minerType, isCpuOnly, version: downloadInfo.version }); 17 | if (existsSync(minerBinPath)) { 18 | return; 19 | } 20 | const downloadProgressBar = new cliProgress.SingleBar({ 21 | format: `Downloading ${minerType}: {bar} | {percentage}% | Speed: {speed}`, 22 | barCompleteChar: '\u2588', 23 | barIncompleteChar: '\u2591', 24 | hideCursor: true, 25 | clearOnComplete: true, 26 | }); 27 | const downloadUrl = this.getMinerDownloadUrl({ minerType, isCpuOnly, version: downloadInfo.version }); 28 | const minerDownload = new Download({ url: downloadUrl, destinationDir: this.binaryDirectory }); 29 | downloadProgressBar.start(100, 0, { 30 | speed: 'N/A', 31 | }); 32 | minerDownload.on('download-progress', (state) => { 33 | downloadProgressBar.update(state.percent * 100, { 34 | speed: `${bytes(state.speed)}/s`, 35 | }); 36 | }); 37 | await minerDownload.download(); 38 | downloadProgressBar.update(100, { 39 | speed: 'N/A', 40 | }); 41 | downloadProgressBar.stop(); 42 | await minerDownload.extract(); 43 | await minerDownload.removeDownloadFile(); 44 | } 45 | 46 | getMinerBinaryPath({ minerType, isCpuOnly, version = getMinerDownloadInfo({ minerType }).version }) { 47 | return join(this.binaryDirectory, this.getMinerBinaryName({ minerType, isCpuOnly, version })); 48 | } 49 | 50 | getMinerBinaryName({ minerType, isCpuOnly, version }) { 51 | let name = `${minerType}-${version}`; 52 | switch (os()) { 53 | case 'Linux': 54 | name += '-linux'; 55 | switch (arch()) { 56 | case 'arm64': 57 | case 'arm': 58 | name += '-armv7'; 59 | break; 60 | default: 61 | name += '-x86_64'; 62 | } 63 | break; 64 | case 'Windows_NT': 65 | name += '-windows-x86_64'; 66 | break; 67 | case 'Darwin': 68 | name += '-apple-x86_64'; 69 | break; 70 | } 71 | switch (arch()) { 72 | case 'arm64': 73 | name += '-cpu-only'; 74 | break; 75 | default: 76 | name += isCpuOnly ? '-cpu-only' : '-cpu-gpu'; 77 | } 78 | if (os() === 'Windows_NT') { 79 | name += '.exe' 80 | } 81 | 82 | return name; 83 | } 84 | 85 | getMinerDownloadUrl({ minerType, isCpuOnly, version }) { 86 | const binaryName = this.getMinerBinaryName({ minerType, isCpuOnly, version }); 87 | 88 | return `${this.minerDownloadBaseUrl}/${binaryName}.zip`; 89 | } 90 | 91 | get minerDownloadBaseUrl() { 92 | return 'https://github.com/foxypool/foxy-miner/releases/download/0.0.0'; 93 | } 94 | 95 | get binaryDirectory() { 96 | return join(homedir(), '.config', 'foxy-miner', 'miner', 'binaries'); 97 | } 98 | } 99 | 100 | module.exports = new BinaryManager(); 101 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at contact@felixbrucker.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /lib/upstream/foxy-pool-multi.js: -------------------------------------------------------------------------------- 1 | const Base = require('./base'); 2 | const foxyPoolGateway = require('../services/foxy-pool-gateway'); 3 | 4 | const eventBus = require('../services/event-bus'); 5 | const config = require('../services/config'); 6 | const MiningInfo = require('../miningInfo'); 7 | const outputUtil = require('../output-util'); 8 | 9 | class FoxyPoolMulti extends Base { 10 | async init() { 11 | await super.init(); 12 | this.coin = this.upstreamConfig.coin.toUpperCase(); 13 | this.connected = foxyPoolGateway.connected; 14 | 15 | foxyPoolGateway.onConnectionStateChange(() => { 16 | this.connected = foxyPoolGateway.connected; 17 | }); 18 | foxyPoolGateway.onNewMiningInfo(this.coin, this.onNewMiningInfo.bind(this)); 19 | 20 | const miningInfo = await foxyPoolGateway.getMiningInfo(this.coin); 21 | await this.onNewMiningInfo(miningInfo); 22 | } 23 | 24 | async onNewMiningInfo(para) { 25 | if (this.upstreamConfig.sendTargetDL) { 26 | para.targetDeadline = this.upstreamConfig.sendTargetDL; 27 | } 28 | const miningInfo = new MiningInfo({ 29 | height: para.height, 30 | baseTarget: para.baseTarget, 31 | generationSignature: para.generationSignature, 32 | targetDeadline: para.targetDeadline, 33 | miningHalted: para.miningHalted, 34 | coin: this.upstreamConfig.coin, 35 | }); 36 | if (this.miningInfo && this.miningInfo.height === miningInfo.height && this.miningInfo.baseTarget === miningInfo.baseTarget) { 37 | return; 38 | } 39 | 40 | this.dynamicTargetDeadline = null; 41 | if (this.useSubmitProbability && this.lastCapacity) { 42 | const totalCapacityInTiB = this.lastCapacity / 1024; 43 | this.dynamicTargetDeadline = Math.round(this.targetDLFactor * miningInfo.netDiff / totalCapacityInTiB); 44 | const dynamicTargetDeadlineFormatted = config.humanizeDeadlines ? outputUtil.getFormattedDeadline(this.dynamicTargetDeadline) : this.dynamicTargetDeadline; 45 | eventBus.publish('log/debug', `${this.fullUpstreamName} | Submit Probability | Using targetDL ${dynamicTargetDeadlineFormatted}`); 46 | } 47 | 48 | if (this.miningCanBeHalted()) { 49 | miningInfo.miningHalted = true; 50 | } 51 | 52 | this.miningInfo = miningInfo; 53 | this.emit('new-round', miningInfo); 54 | let newBlockLine = `${this.fullUpstreamName} | ${outputUtil.getString(`New block ${miningInfo.height}, baseTarget ${miningInfo.baseTarget}, netDiff ${miningInfo.netDiffFormatted}`, 'green')}`; 55 | if (miningInfo.targetDeadline) { 56 | newBlockLine += outputUtil.getString(`, targetDL: ${miningInfo.targetDeadline}`, 'green'); 57 | } 58 | eventBus.publish('log/info', newBlockLine); 59 | } 60 | 61 | async submitNonce(submission, minerSoftware, options) { 62 | super.submitNonce(submission); 63 | 64 | const optionsToSubmit = { 65 | minerName: this.upstreamConfig.minerName || options.minerName || this.defaultMinerName, 66 | userAgent: `${this.userAgent} | ${minerSoftware}`, 67 | capacity: options.capacity, 68 | payoutAddress: this.upstreamConfig.payoutAddress || this.upstreamConfig.accountKey, 69 | accountName: this.upstreamConfig.accountName || options.accountName || null, 70 | distributionRatio: this.upstreamConfig.distributionRatio || null, 71 | }; 72 | 73 | const result = await foxyPoolGateway.submitNonce(this.coin, submission.toObject(), optionsToSubmit); 74 | 75 | return { 76 | error: null, 77 | result, 78 | }; 79 | } 80 | 81 | getMiningInfo() { 82 | return this.miningInfo.toObject(); 83 | } 84 | } 85 | 86 | module.exports = FoxyPoolMulti; 87 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | on: push 2 | name: CI 3 | 4 | jobs: 5 | build: 6 | name: Build 7 | strategy: 8 | fail-fast: false 9 | matrix: 10 | node-version: [ 14.x ] 11 | os: [ ubuntu-latest, macos-latest, windows-latest ] 12 | 13 | runs-on: ${{ matrix.os }} 14 | steps: 15 | - name: Checkout repository 16 | uses: actions/checkout@v3 17 | 18 | - name: Set up Node.js ${{ matrix.node-version }} 19 | uses: actions/setup-node@v3 20 | with: 21 | node-version: ${{ matrix.node-version }} 22 | 23 | - name: yarn install 24 | run: yarn install 25 | 26 | - name: Package release archive 27 | run: yarn run package 28 | 29 | - name: Save release archive 30 | uses: actions/upload-artifact@v3 31 | with: 32 | name: release-archive-${{ matrix.os }} 33 | path: build/*.zip 34 | 35 | build-and-push-image: 36 | name: Build and push image 37 | needs: build 38 | if: startsWith(github.ref, 'refs/tags/') 39 | runs-on: ubuntu-latest 40 | permissions: 41 | contents: read 42 | packages: write 43 | env: 44 | REGISTRY: ghcr.io 45 | IMAGE_NAME: ${{ github.repository }} 46 | steps: 47 | - name: Checkout repository 48 | uses: actions/checkout@v3 49 | 50 | - name: Log in to the Container registry 51 | uses: docker/login-action@v2 52 | with: 53 | registry: ${{ env.REGISTRY }} 54 | username: ${{ github.actor }} 55 | password: ${{ secrets.GITHUB_TOKEN }} 56 | 57 | - name: Extract metadata for Docker 58 | id: meta 59 | uses: docker/metadata-action@v4 60 | with: 61 | images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} 62 | tags: | 63 | type=semver,pattern={{version}} 64 | type=semver,pattern={{major}}.{{minor}} 65 | type=semver,pattern={{major}} 66 | 67 | - name: Build and push Docker image 68 | uses: docker/build-push-action@v3 69 | with: 70 | context: . 71 | push: ${{ startsWith(github.ref, 'refs/tags/') }} 72 | tags: ${{ steps.meta.outputs.tags }} 73 | labels: ${{ steps.meta.outputs.labels }} 74 | 75 | publish-release: 76 | name: Publish release 77 | needs: build 78 | if: startsWith(github.ref, 'refs/tags/') 79 | runs-on: ubuntu-latest 80 | steps: 81 | - name: Checkout the repo 82 | uses: actions/checkout@v3 83 | - name: Set up Node.js 14.x 84 | uses: actions/setup-node@v3 85 | with: 86 | node-version: 14.x 87 | registry-url: 'https://registry.npmjs.org' 88 | - name: Publish to npm 89 | env: 90 | NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH_TOKEN }} 91 | run: npm publish --access public 92 | - name: Fetch release archives 93 | uses: actions/download-artifact@v3 94 | - name: Get the tag name 95 | id: tag 96 | run: echo ::set-output name=TAG::${GITHUB_REF/refs\/tags\//} 97 | - name: Create github release 98 | uses: felixbrucker/github-actions/publish-release@master 99 | env: 100 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 101 | with: 102 | args: --name Foxy-Miner 103 | - uses: AButler/upload-release-assets@v2.0 104 | with: 105 | files: 'release-archive-*/*.zip' 106 | repo-token: ${{ secrets.GITHUB_TOKEN }} 107 | release-tag: ${{ steps.tag.outputs.TAG }} 108 | - name: Post to Discord 109 | uses: felixbrucker/github-actions/post-release-in-discord@master 110 | env: 111 | FOXY_DISCORD_WEBHOOK_ID: ${{ secrets.FOXY_DISCORD_WEBHOOK_ID }} 112 | FOXY_DISCORD_WEBHOOK_TOKEN: ${{ secrets.FOXY_DISCORD_WEBHOOK_TOKEN }} 113 | -------------------------------------------------------------------------------- /lib/services/logger.js: -------------------------------------------------------------------------------- 1 | const chalk = require('chalk'); 2 | const moment = require('moment'); 3 | const { homedir } = require('os'); 4 | const { join } = require('path'); 5 | const rfs = require('rotating-file-stream'); 6 | const mkdirp = require('mkdirp'); 7 | const stripAnsi = require('strip-ansi'); 8 | const readline = require('readline'); 9 | 10 | const eventBus = require('./event-bus'); 11 | const store = require('./store'); 12 | 13 | class Logger { 14 | static getLogLevelNumber(logLevel) { 15 | switch (logLevel) { 16 | case 'trace': return 1; 17 | case 'debug': return 2; 18 | case 'info': return 3; 19 | case 'error': return 4; 20 | } 21 | } 22 | 23 | constructor() { 24 | this.lastLogLine = { 25 | isMinerLog: false, 26 | }; 27 | this.logResetCounter = 0; 28 | eventBus.subscribe('log/trace', (msg, options = {}) => this.onLogs('trace', msg, options)); 29 | eventBus.subscribe('log/debug', (msg, options = {}) => this.onLogs('debug', msg, options)); 30 | eventBus.subscribe('log/info', (msg, options = {}) => this.onLogs('info', msg, options)); 31 | eventBus.subscribe('log/error', (msg, options = {}) => this.onLogs('error', msg, options)); 32 | } 33 | 34 | onLogs(logLevel, msg, { isMinerLog = false } = {}) { 35 | if (Logger.getLogLevelNumber(store.logLevel) > Logger.getLogLevelNumber(logLevel)) { 36 | return; 37 | } 38 | let logLine = `${moment().format('YYYY-MM-DD HH:mm:ss.SSS')} [${logLevel.toUpperCase()}] ${msg}`; 39 | if (this.logWriter && !isMinerLog) { 40 | this.logWriter.write(`${stripAnsi(logLine)}\n`); 41 | } 42 | if (store.useDashboard) { 43 | return; 44 | } 45 | if (this.lastLogLine.isMinerLog) { 46 | if (isMinerLog && this.logResetCounter > 10) { 47 | readline.clearLine(process.stdout, 0); 48 | this.logResetCounter = 0; 49 | } else if (!isMinerLog) { 50 | readline.clearLine(process.stdout, 0); 51 | } 52 | readline.cursorTo(process.stdout, 0); 53 | } 54 | if (isMinerLog && this.lastLogLine.isMinerLog) { 55 | this.logResetCounter += 1; 56 | } else { 57 | this.logResetCounter = 0; 58 | } 59 | this.lastLogLine.isMinerLog = isMinerLog; 60 | 61 | switch (logLevel) { 62 | case 'trace': 63 | case 'debug': 64 | if (isMinerLog) { 65 | process.stdout.write(store.getUseColors() ? chalk.grey(logLine) : logLine); 66 | } else { 67 | console.log(store.getUseColors() ? chalk.grey(logLine) : logLine); 68 | } 69 | break; 70 | case 'info': 71 | if (isMinerLog) { 72 | process.stdout.write(logLine); 73 | } else { 74 | console.log(logLine); 75 | } 76 | break; 77 | case 'error': 78 | if (isMinerLog) { 79 | process.stderr.write(store.getUseColors() ? chalk.red(logLine) : logLine); 80 | } else { 81 | console.error(store.getUseColors() ? chalk.red(logLine) : logLine); 82 | } 83 | break; 84 | } 85 | } 86 | 87 | enableFileLogging() { 88 | if (this.logWriter) { 89 | return; 90 | } 91 | mkdirp.sync(this.logDirectory, { mode: 0o770 }); 92 | 93 | const loggerOptions = { 94 | size: '10M', 95 | interval: '1d', 96 | path: this.logDirectory, 97 | maxFiles: 10, 98 | }; 99 | 100 | this.logWriter = rfs.createStream(Logger.logFileGenerator, loggerOptions); 101 | this.logWriter.write('\n\n'); 102 | } 103 | 104 | static logFileGenerator(time, index) { 105 | const fileName = 'foxy-miner.log'; 106 | if (!time) { 107 | return fileName; 108 | } 109 | 110 | return `${moment(time).format('YYYY-MM-DD')}-foxy-miner.${index}.log`; 111 | } 112 | 113 | get logDirectory() { 114 | return join(homedir(), '.config', 'foxy-miner', 'logs'); 115 | } 116 | } 117 | 118 | module.exports = new Logger(); 119 | -------------------------------------------------------------------------------- /lib/upstream/socketio.js: -------------------------------------------------------------------------------- 1 | const io = require('socket.io-client'); 2 | const eventBus = require('../services/event-bus'); 3 | const config = require('../services/config'); 4 | const MiningInfo = require('../miningInfo'); 5 | const outputUtil = require('../output-util'); 6 | const Base = require('./base'); 7 | 8 | class SocketIo extends Base { 9 | async init() { 10 | await super.init(); 11 | this.connected = false; 12 | const options = { rejectUnauthorized : false }; 13 | if (!config.allowLongPolling) { 14 | options.transports = ['websocket']; 15 | } 16 | this.client = io(this.upstreamConfig.url, options); 17 | 18 | this.client.on('connect', () => { 19 | this.connected = true; 20 | eventBus.publish('log/debug', `${this.fullUpstreamName} | url=${this.upstreamConfig.url} | socketio opened`); 21 | }); 22 | this.client.on('disconnect', () => { 23 | this.connected = false; 24 | eventBus.publish('log/debug', `${this.fullUpstreamName} | url=${this.upstreamConfig.url} | socketio closed`); 25 | }); 26 | 27 | this.client.on('miningInfo', this.onNewRound.bind(this)); 28 | this.client.on('connect', () => this.client.emit('getMiningInfo', this.onNewRound.bind(this))); 29 | this.client.emit('getMiningInfo', this.onNewRound.bind(this)); 30 | } 31 | 32 | async onNewRound(para) { 33 | this.connected = true; 34 | if (this.upstreamConfig.sendTargetDL) { 35 | para.targetDeadline = this.upstreamConfig.sendTargetDL; 36 | } 37 | const miningInfo = new MiningInfo({ 38 | height: para.height, 39 | baseTarget: para.baseTarget, 40 | generationSignature: para.generationSignature, 41 | targetDeadline: para.targetDeadline, 42 | miningHalted: para.miningHalted, 43 | coin: this.upstreamConfig.coin, 44 | }); 45 | if (this.miningInfo && this.miningInfo.height === miningInfo.height && this.miningInfo.baseTarget === miningInfo.baseTarget) { 46 | return; 47 | } 48 | 49 | this.dynamicTargetDeadline = null; 50 | if (this.useSubmitProbability && this.lastCapacity) { 51 | const totalCapacityInTiB = this.lastCapacity / 1024; 52 | this.dynamicTargetDeadline = Math.round(this.targetDLFactor * miningInfo.netDiff / totalCapacityInTiB); 53 | const dynamicTargetDeadlineFormatted = config.humanizeDeadlines ? outputUtil.getFormattedDeadline(this.dynamicTargetDeadline) : this.dynamicTargetDeadline; 54 | eventBus.publish('log/debug', `${this.fullUpstreamName} | Submit Probability | Using targetDL ${dynamicTargetDeadlineFormatted}`); 55 | } 56 | 57 | if (this.miningCanBeHalted()) { 58 | miningInfo.miningHalted = true; 59 | } 60 | 61 | this.miningInfo = miningInfo; 62 | this.emit('new-round', miningInfo); 63 | let newBlockLine = `${this.fullUpstreamName} | ${outputUtil.getString(`New block ${miningInfo.height}, baseTarget ${miningInfo.baseTarget}, netDiff ${miningInfo.netDiffFormatted}`, 'green')}`; 64 | if (miningInfo.targetDeadline) { 65 | newBlockLine += outputUtil.getString(`, targetDL: ${miningInfo.targetDeadline}`, 'green'); 66 | } 67 | eventBus.publish('log/info', newBlockLine); 68 | } 69 | 70 | async submitNonce(submission, minerSoftware, options) { 71 | super.submitNonce(submission); 72 | const result = await new Promise(resolve => this.client.emit('submitNonce', submission.toObject(), { 73 | minerName: this.upstreamConfig.minerName || options.minerName || this.defaultMinerName, 74 | userAgent: `${this.userAgent} | ${minerSoftware}`, 75 | capacity: options.capacity, 76 | accountKey: this.upstreamConfig.accountKey, 77 | payoutAddress: this.upstreamConfig.payoutAddress || this.upstreamConfig.accountKey, 78 | maxScanTime: this.upstreamConfig.maxScanTime, 79 | accountName: this.upstreamConfig.accountName || options.accountName || null, 80 | distributionRatio: this.upstreamConfig.distributionRatio || null, 81 | color: this.upstreamConfig.minerColor || options.color || null, 82 | }, resolve)); 83 | 84 | return { 85 | error: null, 86 | result, 87 | }; 88 | } 89 | 90 | getMiningInfo() { 91 | return this.miningInfo.toObject(); 92 | } 93 | } 94 | 95 | module.exports = SocketIo; 96 | -------------------------------------------------------------------------------- /lib/upstream/generic.js: -------------------------------------------------------------------------------- 1 | const superagent = require('superagent'); 2 | const eventBus = require('../services/event-bus'); 3 | const config = require('../services/config'); 4 | const MiningInfo = require('../miningInfo'); 5 | const outputUtil = require('../output-util'); 6 | const Base = require('./base'); 7 | 8 | class GenericUpstream extends Base { 9 | static hasUnicode(str) { 10 | for (let i = 0; i < str.length; i++) { 11 | if (str.charCodeAt(i) > 127) { 12 | return true; 13 | } 14 | } 15 | return false; 16 | } 17 | 18 | async init() { 19 | await super.init(); 20 | this.connected = false; 21 | await this.updateMiningInfo(); 22 | const interval = this.upstreamConfig.updateMiningInfoInterval ? this.upstreamConfig.updateMiningInfoInterval : 1000; 23 | setInterval(this.updateMiningInfo.bind(this), interval); 24 | } 25 | 26 | async updateMiningInfo() { 27 | try { 28 | let request = superagent.get(`${this.upstreamConfig.url}/burst`).timeout({ 29 | response: 20 * 1000, 30 | deadline: 30 * 1000, 31 | }).set('User-Agent', this.userAgent); 32 | 33 | let {text: result} = await request.query({requestType: 'getMiningInfo'}); 34 | result = JSON.parse(result); 35 | this.connected = true; 36 | const miningInfo = new MiningInfo({ 37 | height: result.height, 38 | baseTarget: result.baseTarget, 39 | generationSignature: result.generationSignature, 40 | targetDeadline: result.targetDeadline, 41 | miningHalted: result.miningHalted, 42 | coin: this.upstreamConfig.coin, 43 | }); 44 | if (miningInfo.height === this.miningInfo.height && miningInfo.baseTarget === this.miningInfo.baseTarget) { 45 | return; 46 | } 47 | 48 | this.dynamicTargetDeadline = null; 49 | if (this.useSubmitProbability && this.lastCapacity) { 50 | const totalCapacityInTiB = this.lastCapacity / 1024; 51 | this.dynamicTargetDeadline = Math.round(this.targetDLFactor * miningInfo.netDiff / totalCapacityInTiB); 52 | const dynamicTargetDeadlineFormatted = config.humanizeDeadlines ? outputUtil.getFormattedDeadline(this.dynamicTargetDeadline) : this.dynamicTargetDeadline; 53 | eventBus.publish('log/debug', `${this.fullUpstreamName} | Submit Probability | Using targetDL ${dynamicTargetDeadlineFormatted}`); 54 | } 55 | 56 | if (this.miningCanBeHalted()) { 57 | miningInfo.miningHalted = true; 58 | } 59 | 60 | this.miningInfo = miningInfo; 61 | this.emit('new-round', miningInfo); 62 | let newBlockLine = `${this.upstreamName} | ${outputUtil.getString(`New block ${miningInfo.height}, baseTarget ${miningInfo.baseTarget}, netDiff ${miningInfo.netDiffFormatted}`, 'green')}`; 63 | if (miningInfo.targetDeadline) { 64 | newBlockLine += outputUtil.getString(`, targetDL: ${miningInfo.targetDeadline}`, 'green'); 65 | } 66 | eventBus.publish('log/info', newBlockLine); 67 | } catch (err) { 68 | const message = (err.timeout || err.message === 'Aborted') ? 'getMiningInfo request timed out' : err.message; 69 | eventBus.publish('log/debug', `${this.fullUpstreamName} | Error: ${message}`); 70 | this.connected = false; 71 | } 72 | } 73 | 74 | async submitNonce(submission, minerSoftware, options) { 75 | super.submitNonce(submission); 76 | const queryParams = { 77 | requestType: 'submitNonce', 78 | accountId: submission.accountId, 79 | nonce: submission.nonce.toString(), 80 | blockheight: submission.height, 81 | }; 82 | if (submission.secretPhrase) { 83 | queryParams.secretPhrase = submission.secretPhrase; 84 | } else { 85 | queryParams.deadline = submission.deadline.toString() 86 | } 87 | 88 | try { 89 | let request = superagent.post(`${this.upstreamConfig.url}/burst`) 90 | .query(queryParams) 91 | .timeout({ 92 | response: 30 * 1000, 93 | deadline: 45 * 1000, 94 | }) 95 | .set('User-Agent', `${this.userAgent} | ${minerSoftware}`) 96 | .set('X-Capacity', options.capacity) 97 | .set('X-Miner', this.defaultMinerName) 98 | .set('X-MinerName', this.upstreamConfig.minerName || options.minerName || this.defaultMinerName) 99 | .set('X-Plotfile', `${this.defaultMinerName}`); 100 | 101 | const accountKey = options.accountKey || this.upstreamConfig.accountKey; 102 | if (accountKey) { 103 | request = request.set('X-Account', accountKey); 104 | request = request.set('X-AccountKey', accountKey); 105 | } 106 | let accountName = this.upstreamConfig.accountName || options.accountName || null; 107 | if (accountName) { 108 | if (GenericUpstream.hasUnicode(accountName)) { 109 | accountName = encodeURI(accountName); 110 | } 111 | request = request.set('X-AccountName', accountName); 112 | } 113 | if (this.upstreamConfig.distributionRatio) { 114 | request = request.set('X-DistributionRatio', this.upstreamConfig.distributionRatio); 115 | } 116 | const minerColor = this.upstreamConfig.minerColor || options.color || null; 117 | if (minerColor) { 118 | request = request.set('X-Color', minerColor); 119 | } 120 | 121 | let {text: result} = await request.retry(5, (err) => { 122 | if (!err) { 123 | return; 124 | } 125 | eventBus.publish('log/debug', `${this.fullUpstreamName} | Error: Failed submitting DL ${submission.deadline.toString()}, retrying ..`); 126 | return true; 127 | }); 128 | result = JSON.parse(result); 129 | 130 | return { 131 | error: null, 132 | result, 133 | }; 134 | } catch (err) { 135 | let error = { 136 | message: 'error reaching upstream', 137 | code: 3, 138 | }; 139 | if (err.response && err.response.error && err.response.error.text) { 140 | try { 141 | error = JSON.parse(err.response.error.text); 142 | } catch (e) {} 143 | } 144 | 145 | return { 146 | error, 147 | }; 148 | } 149 | } 150 | 151 | getMiningInfo() { 152 | return this.miningInfo.toObject(); 153 | } 154 | } 155 | 156 | module.exports = GenericUpstream; 157 | -------------------------------------------------------------------------------- /lib/services/cli-dashboard.js: -------------------------------------------------------------------------------- 1 | const chalk = require('chalk'); 2 | const logUpdate = require('log-update'); 3 | const moment = require('moment'); 4 | const Table = require('cli-table3'); 5 | const { flatten } = require('lodash'); 6 | const eventBus = require('./event-bus'); 7 | const store = require('./store'); 8 | const config = require('./config'); 9 | const version = require('../version'); 10 | const Capacity = require('../capacity'); 11 | const outputUtil = require('../output-util'); 12 | 13 | class Dashboard { 14 | static getLogLevelNumber(logLevel) { 15 | switch (logLevel) { 16 | case 'trace': return 1; 17 | case 'debug': return 2; 18 | case 'info': return 3; 19 | case 'error': return 4; 20 | } 21 | } 22 | 23 | static getTimeElapsedSinceLastBlock(blockStart) { 24 | const duration = moment.duration(moment().diff(moment(blockStart))); 25 | 26 | return `${duration.hours().toString().padStart(2, '0')}:${duration.minutes().toString().padStart(2, '0')}:${duration.seconds().toString().padStart(2, '0')}`; 27 | } 28 | 29 | static getBestDeadlineString(bestDL) { 30 | if (bestDL === null) { 31 | return 'N/A'; 32 | } 33 | 34 | return outputUtil.getFormattedDeadline(bestDL); 35 | }; 36 | 37 | constructor() { 38 | this.maxLogLines = 16; 39 | this.lastLogLines= []; 40 | } 41 | 42 | init() { 43 | eventBus.subscribe('log/trace', (msg) => this.onLogs('trace', msg)); 44 | eventBus.subscribe('log/debug', (msg) => this.onLogs('debug', msg)); 45 | eventBus.subscribe('log/info', (msg) => this.onLogs('info', msg)); 46 | eventBus.subscribe('log/error', (msg) => this.onLogs('error', msg)); 47 | } 48 | 49 | onLogs(logLevel, msg) { 50 | const logLine = `${moment().format('YYYY-MM-DD HH:mm:ss.SSS')} [${logLevel.toUpperCase()}] ${msg}`; 51 | if (Dashboard.getLogLevelNumber(store.logLevel) > Dashboard.getLogLevelNumber(logLevel)) { 52 | return; 53 | } 54 | switch (logLevel) { 55 | case 'trace': 56 | case 'debug': 57 | this.lastLogLines.push(store.getUseColors() ? chalk.grey(logLine) : logLine); 58 | break; 59 | case 'info': 60 | this.lastLogLines.push(logLine); 61 | break; 62 | case 'error': 63 | this.lastLogLines.push(store.getUseColors() ? chalk.red(logLine) : logLine); 64 | break; 65 | } 66 | if (this.lastLogLines.length > this.maxLogLines) { 67 | this.lastLogLines = this.lastLogLines.slice(this.maxLogLines * -1); 68 | } 69 | this.render(); 70 | } 71 | 72 | buildTable() { 73 | const table = new Table({ 74 | head: ['Upstream', 'Block #', 'NetDiff', 'Elapsed', 'Best DL', 'Capacity', 'Progress'], 75 | style: { head: ['cyan'] }, 76 | }); 77 | if (!this.proxies || this.proxies.some(proxy => !proxy.upstreams)) { 78 | return table.toString(); 79 | } 80 | const upstreams = flatten(this.proxies.map(proxy => proxy.upstreams.map(upstream => upstream.stats))).reduce((acc, curr) => { 81 | let upstream = acc.find(data => data.name === curr.name); 82 | if (!upstream) { 83 | acc.push(curr); 84 | return acc; 85 | } 86 | if (upstream.bestDL === null || (curr.bestDL !== null && upstream.bestDL > curr.bestDL)) { 87 | upstream.bestDL = curr.bestDL; 88 | } 89 | upstream.roundProgress += curr.roundProgress; 90 | upstream.lastCapacity += curr.lastCapacity; 91 | upstream.counter += 1; 92 | return acc; 93 | }, []); 94 | upstreams.forEach(upstream => upstream.roundProgress /= upstream.counter); 95 | this.proxies.forEach(proxy => { 96 | const minerStats = proxy.miner.stats; 97 | const upstream = upstreams.find(upstream => upstream.miningInfo.height === minerStats.currentBlockScanning && minerStats.progress !== 100); 98 | if (!upstream) { 99 | return; 100 | } 101 | 102 | upstream.miners.push(minerStats); 103 | }); 104 | upstreams.forEach(upstream => { 105 | const roundProgressRounding = upstream.roundProgress === 100 ? 0 : 2; 106 | let roundProgressText = 'Interrupted'; 107 | if (upstream.miners.length === 0) { 108 | if (upstream.roundProgress === 0) { 109 | roundProgressText = 'Waiting'; 110 | } else if (upstream.roundProgress === 100) { 111 | roundProgressText = 'Done'; 112 | } 113 | roundProgressText += ` (${upstream.roundProgress.toFixed(roundProgressRounding)} %)`; 114 | } else { 115 | roundProgressText = this.isSingleMiner ? '' : `${upstream.roundProgress.toFixed(roundProgressRounding)} %\n`; 116 | roundProgressText += upstream.miners.map(minerStats => { 117 | const minerNameString = this.isSingleMiner ? '' : `${outputUtil.getString(`Miner #${minerStats.proxyIndex}`, minerStats.color)} | `; 118 | 119 | return `${minerNameString}Scanning with ${minerStats.scanSpeed}, ${minerStats.remainingTime} (${minerStats.progress} %)`; 120 | }).join('\n'); 121 | } 122 | 123 | upstream.roundProgressText = roundProgressText; 124 | 125 | table.push([ 126 | outputUtil.getName(upstream), 127 | upstream.miningInfo.height, 128 | upstream.miningInfo.netDiff ? `${Capacity.fromTiB(upstream.miningInfo.netDiff).toString(2)}` : 'N/A', 129 | Dashboard.getTimeElapsedSinceLastBlock(upstream.roundStart), 130 | outputUtil.getString(Dashboard.getBestDeadlineString(upstream.bestDL), outputUtil.getDeadlineColor(upstream.bestDL, upstream.coin)), 131 | upstream.lastCapacity ? Capacity.fromGiB(upstream.lastCapacity).toString() : 'N/A', 132 | roundProgressText, 133 | ]); 134 | }); 135 | 136 | return table.toString(); 137 | } 138 | 139 | buildLogs() { 140 | return this.lastLogLines.join('\n'); 141 | } 142 | 143 | render() { 144 | logUpdate([ 145 | chalk.bold.blueBright(`Foxy-Miner ${version}`), 146 | this.buildTable(), 147 | '', 148 | 'Last log lines:', 149 | this.buildLogs(), 150 | ].join('\n')); 151 | } 152 | 153 | start() { 154 | this.maxLogLines = config.dashboardLogLines; 155 | this.render(); 156 | this.timer = setInterval(this.render.bind(this), 1000); 157 | } 158 | 159 | stop() { 160 | clearInterval(this.timer); 161 | } 162 | 163 | get proxies() { 164 | return this._proxies; 165 | } 166 | 167 | set proxies(proxies) { 168 | this._proxies = proxies; 169 | this.isSingleMiner = proxies.length === 1; 170 | } 171 | } 172 | 173 | module.exports = new Dashboard(); 174 | -------------------------------------------------------------------------------- /lib/proxy.js: -------------------------------------------------------------------------------- 1 | const BigNumber = require('bignumber.js'); 2 | const GenericUpstream = require('./upstream/generic'); 3 | const SocketIo = require('./upstream/socketio'); 4 | const FoxyPool = require('./upstream/foxypool'); 5 | const FoxyPoolMulti = require('./upstream/foxy-pool-multi'); 6 | const Submission = require('./submission'); 7 | const CurrentRoundManager = require('./currentRoundManager'); 8 | const config = require('./services/config'); 9 | const profitabilityService = require('./services/profitability-service'); 10 | const eventBus = require('./services/event-bus'); 11 | const outputUtil = require('./output-util'); 12 | const coinUtil = require('./coin-util'); 13 | 14 | class Proxy { 15 | static getUpstreamClass(upstreamConfig) { 16 | if (upstreamConfig.type === 'foxypool' && upstreamConfig.url) { 17 | return FoxyPool; 18 | } else if (upstreamConfig.type === 'foxypool' && upstreamConfig.coin) { 19 | return FoxyPoolMulti; 20 | } else if (upstreamConfig.type === 'socketio') { 21 | return SocketIo; 22 | } 23 | 24 | return GenericUpstream; 25 | } 26 | 27 | constructor({upstreamConfigs, proxyIndex, miner, showProxyIndex, minerConfig}) { 28 | this.proxyIndex = proxyIndex; 29 | this.miner = miner; 30 | this.minerConfig = minerConfig; 31 | this.minerColor = minerConfig.minerColor; 32 | this.showProxyIndex = showProxyIndex; 33 | this.upstreamConfigs = upstreamConfigs; 34 | this.currentRoundManager = new CurrentRoundManager(this.miner); // Default Round Manager 35 | const assumeScannedAfter = this.minerConfig.assumeScannedAfter || config.config.assumeScannedAfter; 36 | if (assumeScannedAfter) { 37 | let timeout = null; 38 | this.miner.subscribe('new-round', async (miningInfo) => { 39 | if (timeout) { 40 | clearTimeout(timeout); 41 | timeout = null; 42 | } 43 | timeout = setTimeout(() => { 44 | this.miner.publish('round-finished', miningInfo.height); 45 | timeout = null; 46 | }, assumeScannedAfter * 1000); 47 | }); 48 | } 49 | this.miner.subscribe('log', this.onMinerLog.bind(this)); 50 | } 51 | 52 | onMinerLog(logLevel, msg, options = {}) { 53 | const fullMessage = this.showProxyIndex ? `${outputUtil.getString(`Miner #${this.proxyIndex}`, this.minerColor)} | ${msg}` : msg; 54 | eventBus.publish(`log/${logLevel}`, fullMessage, options); 55 | } 56 | 57 | async init() { 58 | this.upstreams = await Promise.all(this.upstreamConfigs.map(async upstreamConfig => { 59 | const upstreamClass = Proxy.getUpstreamClass(upstreamConfig); 60 | const upstream = new upstreamClass(upstreamConfig, this.showProxyIndex ? this.proxyIndex : false, this.minerColor); 61 | 62 | upstream.on('new-round', (miningInfo) => { 63 | this.currentRoundManager.removeOldRoundsFromUpstream(upstream); 64 | if (config.useProfitability) { 65 | upstream.weight = profitabilityService.getProfitability(upstream.miningInfo, upstream.upstreamConfig.coin.toLowerCase(), upstream.upstreamConfig.blockReward); 66 | eventBus.publish('log/debug', `${upstream.fullUpstreamName} | Profitability-Service | Got weight ${upstream.weight}`); 67 | } 68 | if (upstream.upstreamConfig.allowMiningToBeHalted && miningInfo.miningHalted) { 69 | eventBus.publish('log/info', `${upstream.fullUpstreamName} | Not queuing new block because mining is halted for this round`); 70 | return; 71 | } 72 | const weight = (upstreamConfig.weight || upstreamConfig.prio || upstream.weight) || 10; 73 | if (upstreamConfig.minWeight && upstreamConfig.minWeight > weight) { 74 | eventBus.publish('log/info', `${upstream.fullUpstreamName} | Not queuing new block because minWeight is set to ${upstreamConfig.minWeight} and the weight is too low`); 75 | return; 76 | } 77 | if (this.upstreams && config.maxNumberOfChains) { 78 | const upstreamsWithWeight = this.upstreams 79 | .map(upstream => [upstream, (upstream.upstreamConfig.weight || upstream.upstreamConfig.prio || upstream.weight) || 10]) 80 | .sort((a, b) => b[1] - a[1]) 81 | .slice(0, config.maxNumberOfChains) 82 | .reverse(); 83 | if (!upstreamsWithWeight.some(upstreamWithWeight => upstreamWithWeight[0] === upstream) && weight <= upstreamsWithWeight[0][1]) { 84 | eventBus.publish('log/info', `${upstream.fullUpstreamName} | Not queuing new block because maxNumberOfChains is set to ${config.maxNumberOfChains} and the weight is too low`); 85 | return; 86 | } 87 | } 88 | this.currentRoundManager.addNewRound(upstream, miningInfo); 89 | }); 90 | 91 | await upstream.init(); 92 | 93 | return upstream; 94 | })); 95 | } 96 | 97 | getMiningInfo() { 98 | return this.currentRoundManager.getMiningInfo(); 99 | } 100 | 101 | getUpstreamForHeight(height) { 102 | return this.upstreams.find(upstream => upstream.getMiningInfo().height === height); 103 | } 104 | 105 | async submitNonce(submissionObj, options) { 106 | const blockHeight = submissionObj.blockheight || this.currentRoundManager.getMiningInfo().height; 107 | const submission = new Submission( 108 | submissionObj.accountId, 109 | blockHeight, 110 | submissionObj.nonce, 111 | submissionObj.deadline, 112 | submissionObj.secretPhrase 113 | ); 114 | const minerSoftware = options.userAgent || options.miner || 'unknown'; 115 | 116 | if (!submission.isValid()) { 117 | return { 118 | error: { 119 | message: 'submission has wrong format', 120 | code: 1, 121 | }, 122 | }; 123 | } 124 | const upstream = this.getUpstreamForHeight(submission.height); 125 | if (!upstream) { 126 | return { 127 | error: { 128 | message: 'submission is for different round', 129 | code: 2, 130 | }, 131 | }; 132 | } 133 | 134 | upstream.lastCapacity = options.capacity; 135 | const adjustedDL = submission.deadline.dividedBy(upstream.miningInfo.baseTarget).integerValue(BigNumber.ROUND_FLOOR); 136 | const modifiedAdjustedDL = coinUtil.modifyDeadline(adjustedDL.toNumber(), upstream.upstreamConfig.coin); 137 | if (upstream.bestDL === null || modifiedAdjustedDL < upstream.bestDL) { 138 | upstream.bestDL = modifiedAdjustedDL; 139 | } 140 | if (upstream.upstreamConfig.targetDL && adjustedDL > upstream.upstreamConfig.targetDL) { 141 | return { 142 | result: 'success', 143 | deadline: adjustedDL.toNumber(), 144 | }; 145 | } 146 | if (upstream.dynamicTargetDeadline && adjustedDL.toNumber() > upstream.dynamicTargetDeadline) { 147 | return { 148 | result: 'success', 149 | deadline: adjustedDL.toNumber(), 150 | }; 151 | } 152 | 153 | const result = await upstream.submitNonce(submission, minerSoftware, options); 154 | if (result.error) { 155 | return { 156 | error: result.error, 157 | }; 158 | } 159 | 160 | return result.result; 161 | } 162 | } 163 | 164 | module.exports = Proxy; 165 | -------------------------------------------------------------------------------- /lib/services/config.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const YAML = require('js-yaml'); 3 | 4 | const eventBus = require('./event-bus'); 5 | const outputUtil = require('../output-util'); 6 | const store = require('./store'); 7 | 8 | class Config { 9 | static logErrorAndExit(error) { 10 | eventBus.publish('log/error', `There is an error with your config file: ${error}`); 11 | process.exit(1); 12 | } 13 | 14 | constructor() { 15 | this.validMinerTypes = [ 16 | 'scavenger', 17 | 'conqueror', 18 | ]; 19 | this.upstreamTypesWithoutUrl = [ 20 | 'foxypool', 21 | ]; 22 | } 23 | 24 | async init() { 25 | this.filePath = store.configFilePath; 26 | this.loadedFilePath = this.filePath; 27 | const result = await this.loadFromFile(); 28 | if (result === null) { 29 | return null; 30 | } 31 | this.validateConfig(); 32 | store.setUseColors(this.useColors); 33 | store.logLevel = this.logLevel; 34 | store.configFilePath = this.loadedFilePath 35 | } 36 | 37 | validateConfig() { 38 | if (!this.config.isManaged && !this.minerBinPath && !this.miner) { 39 | Config.logErrorAndExit('No valid miner bin path specified!'); 40 | } 41 | if ((!this.minerType || !this.validMinerTypes.some(minerType => this.minerType === minerType)) && !this.miner) { 42 | Config.logErrorAndExit('No valid miner type specified!'); 43 | } 44 | if ((!this.upstreams || !Array.isArray(this.upstreams) || this.upstreams.length === 0) && !this.miner) { 45 | Config.logErrorAndExit(`No upstreams defined!`); 46 | } 47 | if (this.upstreams) { 48 | this.upstreams.forEach(upstream => { 49 | if (!upstream.name) { 50 | Config.logErrorAndExit(`At least one upstream does not have a name!`); 51 | } 52 | if (!this.upstreamTypesWithoutUrl.some(type => type === upstream.type) && !upstream.url) { 53 | Config.logErrorAndExit(`Upstream ${outputUtil.getName(upstream)}: No url defined!`); 54 | } 55 | if (this.useProfitability && !upstream.coin) { 56 | Config.logErrorAndExit(`Upstream ${outputUtil.getName(upstream)}: No coin defined!`); 57 | } 58 | }); 59 | } 60 | if (this.miner) { 61 | this.miner.forEach(miner => { 62 | if (!miner.minerType || !this.validMinerTypes.some(minerType => miner.minerType === minerType)) { 63 | Config.logErrorAndExit('No valid miner type specified!'); 64 | } 65 | if (!miner.upstreams || !Array.isArray(miner.upstreams) || miner.upstreams.length === 0) { 66 | Config.logErrorAndExit(`No upstreams defined!`); 67 | } 68 | miner.upstreams.forEach(upstream => { 69 | if (!upstream.name) { 70 | Config.logErrorAndExit(`At least one upstream does not have a name!`); 71 | } 72 | if (!this.upstreamTypesWithoutUrl.some(type => type === upstream.type) && !upstream.url) { 73 | Config.logErrorAndExit(`Upstream ${outputUtil.getName(upstream)}: No url defined!`); 74 | } 75 | if (this.useProfitability && !upstream.coin) { 76 | Config.logErrorAndExit(`Upstream ${outputUtil.getName(upstream)}: No coin defined!`); 77 | } 78 | }); 79 | }); 80 | } 81 | } 82 | 83 | async loadFromFile() { 84 | const file = this.loadFromFiles([ 85 | this.filePath, 86 | 'foxy-miner.yaml', 87 | 'config.yaml', 88 | ]); 89 | if (file === null) { 90 | return null; 91 | } 92 | let configObject = null; 93 | try { 94 | configObject = YAML.load(file); 95 | } catch (err) { 96 | Config.logErrorAndExit(err); 97 | } 98 | this.initFromObject(configObject); 99 | return true; 100 | } 101 | 102 | loadFromFiles(filePaths) { 103 | for (let filePath of filePaths) { 104 | try { 105 | const content = fs.readFileSync(filePath); 106 | this.loadedFilePath = filePath; 107 | 108 | return content; 109 | } catch (err) {} 110 | } 111 | 112 | return null; 113 | } 114 | 115 | save() { 116 | const yaml = YAML.dump(this.config, { 117 | lineWidth: 140, 118 | }); 119 | fs.writeFileSync(this.loadedFilePath, yaml, 'utf8'); 120 | } 121 | 122 | initFromObject(configObject) { 123 | this._config = configObject; 124 | this.patchConfig(); 125 | } 126 | 127 | patchConfig() { 128 | let updated = false; 129 | if (this.config.minerConfig && this.config.minerConfig.plotDirs && typeof this.config.minerConfig.plotDirs === 'string') { 130 | this.config.minerConfig.plotDirs = [this.config.minerConfig.plotDirs]; 131 | updated = true; 132 | } 133 | if (!this.config.listenAddr 134 | || this.config.listenAddr.indexOf('http') === 0 135 | || this.config.listenAddr.split(':').length < 2 136 | || this.listenPort < 1 137 | || this.listenPort > 65535 138 | ) { 139 | this.config.listenAddr = '127.0.0.1:5000'; 140 | updated = true; 141 | } 142 | if (updated) { 143 | this.save(); 144 | } 145 | } 146 | 147 | get upstreams() { 148 | return this.config.upstreams; 149 | } 150 | 151 | get listenAddr() { 152 | return this.config.listenAddr; 153 | } 154 | 155 | get listenHost() { 156 | const parts = this.config.listenAddr.split(':'); 157 | parts.pop(); 158 | return parts.join(':'); 159 | } 160 | 161 | get listenPort() { 162 | const parts = this.config.listenAddr.split(':'); 163 | return parseInt(parts.pop(), 10); 164 | } 165 | 166 | get config() { 167 | return this._config; 168 | } 169 | 170 | get logLevel() { 171 | return this.config.logLevel; 172 | } 173 | 174 | get logToFile() { 175 | return this.config.logToFile; 176 | } 177 | 178 | get useColors() { 179 | return !this.config.noColors; 180 | } 181 | 182 | get minerBinPath() { 183 | return this.config.minerBinPath; 184 | } 185 | 186 | get minerType() { 187 | return this.config.minerType; 188 | } 189 | 190 | get minerConfigPath() { 191 | return this.config.minerConfigPath; 192 | } 193 | 194 | get useProfitability() { 195 | return !!this.config.useProfitability; 196 | } 197 | 198 | get maxNumberOfChains() { 199 | return this.config.maxNumberOfChains; 200 | } 201 | 202 | get humanizeDeadlines() { 203 | return !!this.config.humanizeDeadlines; 204 | } 205 | 206 | get allowLongPolling() { 207 | return !!this.config.allowLongPolling; 208 | } 209 | 210 | get miner() { 211 | return this.config.miner; 212 | } 213 | 214 | getAccountColor(account) { 215 | if (!this.config.accountColors || !this.config.accountColors[account]) { 216 | return null; 217 | } 218 | 219 | return this.config.accountColors[account]; 220 | } 221 | 222 | get dashboardLogLines() { 223 | return this.config.dashboardLogLines || 16; 224 | } 225 | 226 | get useEcoBlockRewardsForProfitability() { 227 | return !!this.config.useEcoBlockRewards; 228 | } 229 | 230 | get minerOutputToConsole() { 231 | return !!this.config.minerOutputToConsole; 232 | } 233 | 234 | get hideScanProgress() { 235 | return !!this.config.hideScanProgress; 236 | } 237 | } 238 | 239 | module.exports = new Config(); 240 | -------------------------------------------------------------------------------- /lib/miner/scavenger/scavenger-config-generator.js: -------------------------------------------------------------------------------- 1 | const YAML = require('js-yaml'); 2 | const { isEqual } = require('lodash') 3 | 4 | class ScavengerConfigGenerator { 5 | constructor({ config }) { 6 | this.config = config; 7 | } 8 | 9 | generate({ minerConfig, minerIndex = null }) { 10 | let listenAddr = this.config.listenAddr; 11 | if (this.config.listenHost === '0.0.0.0') { 12 | listenAddr = `127.0.0.1:${this.config.listenPort}`; 13 | } 14 | let url = `http://${listenAddr}`; 15 | if (minerIndex !== null) { 16 | url += `/${minerIndex + 1}`; 17 | } 18 | const plotDirs = this.getFromMinerConfig(minerConfig, { key: 'plotDirs', defaultValue: [] }); 19 | const isCpuOnly = this.getFromConfig(minerConfig, { key: 'isCpuOnly', defaultValue: true }); 20 | 21 | const generatedConfig = { 22 | plot_dirs: plotDirs, 23 | url, 24 | hdd_reader_thread_count: 0, 25 | hdd_use_direct_io: this.getFromMinerConfig(minerConfig, { key: 'useHddDirectIo', defaultValue: true }), 26 | hdd_wakeup_after: 240, 27 | 28 | cpu_threads: 0, 29 | cpu_worker_task_count: this.getFromMinerConfig(minerConfig, { key: 'cpuWorkers', defaultValue: isCpuOnly ? 4 : 0 }), 30 | cpu_nonces_per_cache: 65536, 31 | cpu_thread_pinning: this.getFromMinerConfig(minerConfig, { key: 'useCpuThreadPinning', defaultValue: false }), 32 | 33 | gpu_platform: this.getFromMinerConfig(minerConfig, { key: 'gpuPlatform', defaultValue: 0 }), 34 | gpu_device: this.getFromMinerConfig(minerConfig, { key: 'gpuDevice', defaultValue: 0 }), 35 | gpu_threads: this.getFromMinerConfig(minerConfig, { key: 'gpuThreads', defaultValue: isCpuOnly ? 0 : 1 }), 36 | gpu_worker_task_count: this.getFromMinerConfig(minerConfig, { key: 'gpuWorkers', defaultValue: isCpuOnly ? 0 : 12 }), 37 | gpu_nonces_per_cache: this.getFromMinerConfig(minerConfig, { key: 'gpuNoncesPerCache', defaultValue: 262144 }), 38 | 39 | gpu_mem_mapping: this.getFromMinerConfig(minerConfig, { key: 'useGpuMemMapping', defaultValue: false }), 40 | gpu_async: this.getFromMinerConfig(minerConfig, { key: 'useGpuAsyncCompute', defaultValue: !isCpuOnly }), 41 | 42 | target_deadline: this.getFromConfig(minerConfig, { key: 'targetDL', defaultValue: 31536000 }), 43 | get_mining_info_interval: 500, 44 | timeout: 5000, 45 | send_proxy_details: true, 46 | 47 | console_log_level: 'info', 48 | logfile_log_level: 'off', 49 | logfile_max_count: 10, 50 | logfile_max_size: 20, 51 | console_log_pattern: '{({d(%H:%M:%S)} [{l}]):16.16} {m}{n}', 52 | logfile_log_pattern: '{({d(%Y-%m-%d %H:%M:%S)} [{l}]):26.26} {m}{n}', 53 | 54 | show_progress: true, 55 | show_drive_stats: false, 56 | benchmark_only: 'disabled', 57 | }; 58 | 59 | return YAML.dump(generatedConfig, { lineWidth: 140 }); 60 | } 61 | 62 | updateConfig({ configYaml, minerConfig, minerIndex = null }) { 63 | const config = YAML.load(configYaml); 64 | let listenAddr = this.config.listenAddr; 65 | if (this.config.listenHost === '0.0.0.0') { 66 | listenAddr = `127.0.0.1:${this.config.listenPort}`; 67 | } 68 | let url = `http://${listenAddr}`; 69 | if (minerIndex !== null) { 70 | url += `/${minerIndex + 1}`; 71 | } 72 | if (config.url !== url) { 73 | config.url = url; 74 | } 75 | const plotDirs = this.getFromMinerConfig(minerConfig, { key: 'plotDirs', defaultValue: null }); 76 | if (plotDirs !== null && (!Array.isArray(config.plot_dirs) || !isEqual(config.plot_dirs.sort(), plotDirs.sort()))) { 77 | config.plot_dirs = plotDirs; 78 | } 79 | if (plotDirs !== null && config.hdd_reader_thread_count !== 0) { 80 | config.hdd_reader_thread_count = 0; 81 | } 82 | const useDirectIo = this.getFromMinerConfig(minerConfig, { key: 'useHddDirectIo', defaultValue: null }); 83 | if (useDirectIo !== null && config.hdd_use_direct_io !== useDirectIo) { 84 | config.hdd_use_direct_io = useDirectIo; 85 | } 86 | const cpuWorkers = this.getFromMinerConfig(minerConfig, { key: 'cpuWorkers', defaultValue: null }); 87 | if (cpuWorkers !== null && config.cpu_worker_task_count !== cpuWorkers) { 88 | config.cpu_worker_task_count = cpuWorkers; 89 | } 90 | const useCpuThreadPinning = this.getFromMinerConfig(minerConfig, { key: 'useCpuThreadPinning', defaultValue: null }); 91 | if (useCpuThreadPinning !== null && config.cpu_thread_pinning !== useCpuThreadPinning) { 92 | config.cpu_thread_pinning = useCpuThreadPinning; 93 | } 94 | const gpuPlatform = this.getFromMinerConfig(minerConfig, { key: 'gpuPlatform', defaultValue: null }); 95 | if (gpuPlatform !== null && config.gpu_platform !== gpuPlatform) { 96 | config.gpu_platform = gpuPlatform; 97 | } 98 | const gpuDevice = this.getFromMinerConfig(minerConfig, { key: 'gpuDevice', defaultValue: null }); 99 | if (gpuDevice !== null && config.gpu_device !== gpuDevice) { 100 | config.gpu_device = gpuDevice; 101 | } 102 | const gpuThreads = this.getFromMinerConfig(minerConfig, { key: 'gpuThreads', defaultValue: null }); 103 | if (gpuThreads !== null && config.gpu_threads !== gpuThreads) { 104 | config.gpu_threads = gpuThreads; 105 | } 106 | const gpuWorkers = this.getFromMinerConfig(minerConfig, { key: 'gpuWorkers', defaultValue: null }); 107 | if (gpuWorkers !== null && config.gpu_worker_task_count !== gpuWorkers) { 108 | config.gpu_worker_task_count = gpuWorkers; 109 | } 110 | const gpuNoncesPerCache = this.getFromMinerConfig(minerConfig, { key: 'gpuNoncesPerCache', defaultValue: null }); 111 | if (gpuNoncesPerCache !== null && config.gpu_nonces_per_cache !== gpuNoncesPerCache) { 112 | config.gpu_nonces_per_cache = gpuNoncesPerCache; 113 | } 114 | const useGpuMemMapping = this.getFromMinerConfig(minerConfig, { key: 'useGpuMemMapping', defaultValue: null }); 115 | if (useGpuMemMapping !== null && config.gpu_mem_mapping !== useGpuMemMapping) { 116 | config.gpu_mem_mapping = useGpuMemMapping; 117 | } 118 | const useGpuAsyncCompute = this.getFromMinerConfig(minerConfig, { key: 'useGpuAsyncCompute', defaultValue: null }); 119 | if (useGpuAsyncCompute !== null && config.gpu_async !== useGpuAsyncCompute) { 120 | config.gpu_async = useGpuAsyncCompute; 121 | } 122 | const targetDL = this.getFromConfig(minerConfig, { key: 'targetDL', defaultValue: null }); 123 | if (targetDL !== null && config.target_deadline !== targetDL) { 124 | config.target_deadline = targetDL; 125 | } 126 | 127 | return YAML.dump(config, { lineWidth: 140 }); 128 | } 129 | 130 | getFromMinerConfig(minerConfig, { key, defaultValue = null }) { 131 | if (minerConfig.minerConfig && minerConfig.minerConfig[key] !== undefined) { 132 | return minerConfig.minerConfig[key]; 133 | } 134 | if (this.config.minerConfig && this.config.minerConfig[key] !== undefined) { 135 | return this.config.minerConfig[key]; 136 | } 137 | 138 | return defaultValue; 139 | } 140 | 141 | getFromConfig(minerConfig, { key, defaultValue = null }) { 142 | if (minerConfig && minerConfig[key] !== undefined) { 143 | return minerConfig[key]; 144 | } 145 | if (this.config && this.config[key] !== undefined) { 146 | return this.config[key]; 147 | } 148 | 149 | return defaultValue; 150 | } 151 | } 152 | 153 | module.exports = ScavengerConfigGenerator; 154 | -------------------------------------------------------------------------------- /lib/miner/miner.js: -------------------------------------------------------------------------------- 1 | const { dirname, basename } = require('path'); 2 | const EventEmitter = require('events'); 3 | const spawn = require('cross-spawn'); 4 | const { flatten } = require('lodash'); 5 | const eventBus = require('../services/event-bus'); 6 | const config = require('../services/config'); 7 | const store = require('../services/store'); 8 | const outputUtil = require('../output-util'); 9 | const coinUtil = require('../coin-util'); 10 | 11 | class Miner { 12 | constructor(binPath, configPath = null, outputToConsole = false) { 13 | this.binPath = binPath; 14 | this.bin = `./${basename(this.binPath)}`; 15 | this.cwd = dirname(this.binPath); 16 | this.configPath = configPath; 17 | this.stopped = true; 18 | this.currentBlockScanning = null; 19 | this.roundFinishedString = 'round finished'; 20 | this.newRoundRegex = /new block: height=([0-9]+)/; 21 | this.versionRegex = /v\.([0-9]+\.[0-9]+\.[0-9]+)/; 22 | this.deadlineRegex = /deadline=([0-9]+)/; 23 | this.accountRegex = /account=([0-9]+)/; 24 | this.progressRegex = /([0-9]+\.?[0-9]*) %/; 25 | this.scanSpeedRegex = /([0-9]+\.?[0-9]* [KMG]B\/s)/; 26 | this.remainingTimeRegex = /([0-9]+[s,m])/; 27 | this.timestampRegex = /(([0-9]+:[0-9]+:[0-9]+)(\.[0-9]+)?( \[(.+)\])?) +/; 28 | this.progressIndicator = ' % '; 29 | this.version = null; 30 | this.software = 'scavenger'; 31 | this.emitter = new EventEmitter(); 32 | this.outputToConsole = outputToConsole; 33 | } 34 | 35 | static getFormattedDeadline(deadline) { 36 | if (!config.humanizeDeadlines) { 37 | return deadline.toString(); 38 | } 39 | 40 | return outputUtil.getFormattedDeadline(deadline); 41 | } 42 | 43 | modifyDeadline(data) { 44 | if (data.indexOf('deadline=') === -1) { 45 | return data; 46 | } 47 | 48 | const upstream = this.proxy.currentRoundManager.getCurrentRound() ? this.proxy.currentRoundManager.getCurrentRound().upstream : null; 49 | const coin = upstream && upstream.upstreamConfig.coin; 50 | 51 | return data.replace(this.deadlineRegex, (match, deadline) => { 52 | deadline = coinUtil.modifyDeadline(parseInt(deadline, 10), coin); 53 | 54 | return `deadline=${outputUtil.getString(Miner.getFormattedDeadline(deadline), outputUtil.getDeadlineColor(deadline, coin))}`; 55 | }); 56 | } 57 | 58 | async start() { 59 | this.stopped = false; 60 | let args = []; 61 | if (this.configPath) { 62 | args = args.concat(['-c', this.configPath]); 63 | } 64 | eventBus.publish('log/debug', `${this.fullMinerName} | Starting with binary: ${this.bin}, args: ${args.join(' ')}, cwd: ${this.cwd}`); 65 | try { 66 | this.minerRef = spawn(this.bin, args, { 67 | cwd: this.cwd, 68 | stdio: 'pipe', 69 | }); 70 | } catch (err) { 71 | eventBus.publish('log/error', `An error occurred while starting the miner binary ${this.binPath}, exiting ..`); 72 | process.exit(1); 73 | } 74 | this.minerRef.on('error', (err) => { 75 | if (err.message.indexOf('ENOENT') !== -1) { 76 | eventBus.publish('log/error', `Invalid miner binary path, could not start ${this.constructor.name}, exiting ..`); 77 | process.exit(1); 78 | } 79 | if (err.message.indexOf('EACCES') !== -1) { 80 | eventBus.publish('log/error', `The miner binary ${this.binPath} might not be marked as executable or you are missing the required rights to start it, exiting ..`); 81 | process.exit(1); 82 | } 83 | }); 84 | this.minerRef.stdout.on('data', (data) => { 85 | data = data.toString(); 86 | 87 | const lines = flatten(data.trim().split('\n').map(line => line.trim().split('\r'))); 88 | 89 | lines.forEach(line => { 90 | let logLevel = 'info'; 91 | line = line.replace(this.timestampRegex, (match, all, time, ms, levelFull, level) => { 92 | if (level) { 93 | logLevel = level.toLowerCase(); 94 | } 95 | 96 | return ''; 97 | }); 98 | 99 | if (line.indexOf(this.progressIndicator) !== -1) { 100 | let matches = line.match(this.progressRegex); 101 | if (matches && matches.length > 1) { 102 | this.progress = parseFloat(matches[1]); 103 | } 104 | matches = line.match(this.scanSpeedRegex); 105 | this.scanSpeed = matches ? matches[1] : '0B/s'; 106 | matches = line.match(this.remainingTimeRegex); 107 | this.remainingTime = matches ? matches[1] : null; 108 | if (this.proxy.currentRoundManager.getCurrentRound() && this.proxy.currentRoundManager.getCurrentRound().upstream) { 109 | this.proxy.currentRoundManager.getCurrentRound().upstream.roundProgress = this.progress; 110 | this.proxy.currentRoundManager.getCurrentRound().progress = this.progress; 111 | } 112 | if (store.useDashboard || this.outputToConsole || config.hideScanProgress) { 113 | return; 114 | } 115 | this.publish('log', logLevel, line, { isMinerLog: true }); 116 | return; 117 | } else if (line.indexOf(this.roundFinishedString) !== -1) { 118 | this.progress = 100; 119 | this.scanSpeed = null; 120 | this.remainingTime = null; 121 | if (this.proxy.currentRoundManager.getCurrentRound() && this.proxy.currentRoundManager.getCurrentRound().upstream) { 122 | this.proxy.currentRoundManager.getCurrentRound().upstream.roundProgress = this.progress; 123 | this.proxy.currentRoundManager.getCurrentRound().progress = this.progress; 124 | } 125 | this.publish('round-finished', this.currentBlockScanning); 126 | } 127 | 128 | if (line.indexOf('account=') !== -1) { 129 | line = line.replace(this.accountRegex, (match, account) => { 130 | return `account=${outputUtil.getString(account, config.getAccountColor(account))}`; 131 | }); 132 | } 133 | 134 | line = this.modifyDeadline(line); 135 | 136 | const newRoundMatches = line.match(this.newRoundRegex); 137 | if (newRoundMatches) { 138 | this.currentBlockScanning = parseInt(newRoundMatches[1], 10); 139 | if (this.proxy.currentRoundManager.getCurrentRound() && this.proxy.currentRoundManager.getCurrentRound().upstream) { 140 | line = `Starting scan of ${line} (${this.proxy.currentRoundManager.getCurrentRound().upstream.upstreamName})`; 141 | } 142 | } 143 | 144 | if (!this.outputToConsole) { 145 | this.publish('log', logLevel, line); 146 | } 147 | }); 148 | 149 | if (this.outputToConsole) { 150 | process.stdout.write(data); 151 | } 152 | }); 153 | this.minerRef.stdout.once('data', (data) => { 154 | const text = data.toString().trim(); 155 | const matches = text.match(this.versionRegex); 156 | if (matches) { 157 | this.version = matches[1]; 158 | } 159 | }); 160 | this.minerRef.stderr.on('data', (data) => { 161 | data = data.toString(); 162 | 163 | if (this.outputToConsole) { 164 | process.stderr.write(data); 165 | return; 166 | } 167 | 168 | const lines = flatten(data.trim().split('\n').map(line => line.trim().split('\r'))); 169 | lines.forEach(line => { 170 | let logLevel = 'error'; 171 | line = line.replace(this.timestampRegex, (match, all, time, ms, levelFull, level) => { 172 | if (level) { 173 | logLevel = level.toLowerCase(); 174 | } 175 | return ''; 176 | }); 177 | line = this.modifyDeadline(line); 178 | this.publish('log', logLevel, line, { isMinerLog: true }); 179 | }); 180 | }); 181 | this.minerRef.on('close', async () => { 182 | await new Promise(resolve => setTimeout(resolve, 2000)); 183 | if (this.stopped) { 184 | return; 185 | } 186 | this.start(); 187 | }); 188 | } 189 | 190 | async stop() { 191 | this.stopped = true; 192 | if (!this.minerRef) { 193 | return; 194 | } 195 | this.minerRef.kill(); 196 | this.minerRef = null; 197 | } 198 | 199 | publish(topic, ...msg) { 200 | this.emitter.emit(topic, ...msg); 201 | } 202 | 203 | subscribe(topic, cb) { 204 | this.emitter.on(topic, cb); 205 | } 206 | 207 | get proxy() { 208 | return this._proxy; 209 | } 210 | 211 | set proxy(proxy) { 212 | this._proxy = proxy; 213 | this.color = proxy.minerColor; 214 | this.fullMinerName = proxy.showProxyIndex ? `${outputUtil.getString(`Miner #${proxy.proxyIndex}`, this.color)} | ${this.constructor.name}` : this.constructor.name; 215 | } 216 | 217 | get stats() { 218 | return { 219 | software: this.software, 220 | version: this.version, 221 | progress: this.progress, 222 | scanSpeed: this.scanSpeed, 223 | remainingTime: this.remainingTime, 224 | currentBlockScanning: this.currentBlockScanning, 225 | proxyIndex: this.proxy.proxyIndex, 226 | color: this.color, 227 | }; 228 | } 229 | } 230 | 231 | module.exports = Miner; 232 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 2.7.0 / 2023-06-18 2 | ================== 3 | 4 | * Drop BHD as it transitions to CHIA plots. 5 | 6 | 2.6.0 / 2022-02-05 7 | ================== 8 | 9 | * Update managed scavenger installs to 1.9.0 10 | * Fix multi managed miner bootstrapping 11 | 12 | 2.5.0 / 2022-02-05 13 | ================== 14 | 15 | * Require at least node 14 16 | * Update dependencies 17 | * Remove bitmart and coinpaprika api 18 | 19 | 2.4.1 / 2021-07-27 20 | ================== 21 | 22 | * Fix the shown DL and NetDiff values for SIGNA. 23 | 24 | 2.4.0 / 2021-07-18 25 | ================== 26 | 27 | * Use SIGNA throughout instead of BURST 28 | * Drop HDD, LHD and XHD from the first run wizard 29 | 30 | 2.3.0 / 2021-06-23 31 | ================== 32 | 33 | * Update socket.io to v4 and enforce websocket transports 34 | * Add config option `allowLongPolling` to allow the use of long polling as socket.io transport 35 | * Fix missing config validation for `minerBinPath` in unmanaged mode 36 | 37 | 2.2.0 / 2021-04-02 38 | ================== 39 | 40 | * Automatically fix all sorts of invalid and broken scavenger configs 41 | * Set `useGpuMemMapping` and `useGpuAsyncCompute` based on the detected gpu 42 | * The native module is now included in the binary, no more extra files 43 | * Fix invalid log message when loading the config from a custom location 44 | 45 | 2.1.0 / 2021-03-11 46 | ================== 47 | 48 | * Automatically fix invalid `plotDirs` and `listenAddr` config values 49 | 50 | 2.0.1 / 2021-03-09 51 | ================== 52 | 53 | * Fix a bug that could cause the miner to crash on startup on certain systems 54 | 55 | 2.0.0 / 2021-03-06 56 | ================== 57 | 58 | * Foxy-Miner will now manage scavenger binaries and configs itself, all config is done through the Foxy-Miner config. This applies to new configs created by the first run wizard only. Existing configs will continue to function and are not migrated 59 | * The Foxy-Miner config file is now stored in the home directory of the user, eg: `C:\Users\\.config\foxy-miner\foxy-miner.yaml`. If this file does not exist Foxy-Miner will search for the config file in the current directory 60 | * Auto-detect plot files in first run wizard 61 | * Auto-detect GPU availability in first run wizard and adjust `gpuWorkers` based on found plot files and max memory of the GPU 62 | * Auto-detect CPU cores and set `cpuWorkers` based on found plot files and max cores of the CPU when no GPU is found 63 | * Bundle the required native module for gpu detection with the release binary in a versioned release zip archive instead of plain binaries 64 | * Add support for logging to file via a `logToFile` option 65 | * Fix miner scan progress output glitches 66 | 67 | 1.20.0 / 2020-10-29 68 | ================== 69 | 70 | * Remove `listenAddress` from first run wizard 71 | * Include the upstream name in scan start log lines 72 | * Update dependencies 73 | 74 | 1.19.0 / 2020-08-30 75 | ================== 76 | 77 | * Add support for listening on an ipv6 address 78 | 79 | 1.18.0 / 2020-08-08 80 | ================== 81 | 82 | * Use fixed indexes for multi miner setups. This means if you run a multi miner setup and have one miner disabled the other miners endpoints are still counted as if it were enabled, the index is just skipped. This can be a breaking change, please adjust your miner config accordingly. 83 | * Add support for auto-downloading a Mac OS X compiled scavenger 1.7.8 binary 84 | * Remove DISC from the first run wizard as well as the profitability service 85 | * Use the foxypool.io domain 86 | 87 | 1.17.0 / 2020-07-26 88 | ================== 89 | 90 | * Add support for showing SODIUM deadlines and netDiff (@zyzzyva99) 91 | * Drop BOOM and LAVA from profitability calculations 92 | * Remove AETH and BTB Foxy-Pools from First Run Wizard 93 | * Fix obscure connection issues with the miner-gateway and websocket transports 94 | 95 | 1.16.1 / 2020-04-06 96 | ================== 97 | 98 | * Remove LAVA from first run wizard 99 | 100 | 1.16.0 / 2020-04-04 101 | ================== 102 | 103 | * Add auto download and configuration of scavenger in first run wizard 104 | 105 | 1.15.1 / 2020-04-03 106 | ================== 107 | 108 | * Fix: Only connect to the gateway if no url set 109 | 110 | 1.15.0 / 2020-04-03 111 | ================== 112 | 113 | * Add support for single connection foxy-pool upstreams which do not require an url to be configured 114 | 115 | 1.14.2 / 2020-04-01 116 | ================== 117 | 118 | * Use new mining endpoints for config generation 119 | 120 | 1.14.1 / 2020-03-25 121 | ================== 122 | 123 | * Fix `assumeScannedAfter` marking unfinished rounds as finished 124 | 125 | 1.14.0 / 2020-03-22 126 | ================== 127 | 128 | * Rename the default config file to foxy-miner.yaml 129 | * Add AETH to pool list for setup wizard 130 | * Listen on /1 for single miner setups as well 131 | * Fix `assumeScannedAfter` option 132 | * Fix old rounds of unused upstreams never getting removed if they were never fully scanned 133 | * Fix configured weight not favored over profitability based weight in some cases 134 | 135 | 1.13.0 / 2020-01-15 136 | ================== 137 | 138 | * Add support for nodejs v12. 139 | * Favor configured weight over profitability based weight. 140 | * Add `minWeight` config option to only mine coins above a minimum weight. 141 | * Add support for halting BTB mining when supplying a BTB `walletUrl` and the plotterId is over capacity. 142 | 143 | 1.12.1 / 2019-11-30 144 | ================== 145 | 146 | * Fix `minerConfigPath` for single miner configs. 147 | 148 | 1.12.0 / 2019-11-22 149 | ================== 150 | 151 | * Add `allowMiningToBeHalted` upstream config option for foxy-pools. 152 | * Add XHD and BTB pools to setup wizard. 153 | * Fix multi miner bestDL aggregation for live dashboard. 154 | * Fix `submitProbability` for greater 100% 155 | 156 | 1.11.0 / 2019-10-17 157 | ================== 158 | 159 | * Allow setting distributionRatio via a config option for foxy-pools. 160 | * Add LAVA pool to setup wizard. 161 | * Fix interruption for same upstream when using `doNotInterruptAbovePercent`. 162 | * Fix netDiff for BHD. 163 | 164 | 1.10.0 / 2019-10-07 165 | ================== 166 | 167 | * Remove pool DR selection in first install wizard as the pool handles that now. 168 | * Drop hdpool support. 169 | * Add support for HDD. 170 | * Auto remove trailing slash in foxypool url if detected. 171 | * Fix BHD rate for profitability based switching. 172 | * Fix dynamic TargetDL for LHD. 173 | * Fix error when no speed information can be found in the miners output. 174 | 175 | 1.9.0 / 2019-09-07 176 | ================== 177 | 178 | * Add support for LHD mining on hdpool. 179 | * Fix "new" backwards incompatible mining api of hdpool. 180 | 181 | 1.8.0 / 2019-09-05 182 | ================== 183 | 184 | * Add `doNotInterruptAbovePercent` upstream option. 185 | * Add `hideScanProgress` config option. 186 | 187 | 1.7.1 / 2019-09-05 188 | ================== 189 | 190 | * Fix missing scan progress. 191 | 192 | 1.7.0 / 2019-09-05 193 | ================== 194 | 195 | * Add config switch to toggle full/eco block rewards for profitability calculation. 196 | * Add DISC and LHD profitability data. 197 | * Add submit probability. 198 | * Adapt profitability calculation to use new BHD block rewards. 199 | * Use LHD genesis base target for netDiff calculation. 200 | * Add cli-dashboard for live stats. 201 | * Add support for multiple scav/conqueror instances. 202 | 203 | 1.6.0 / 2019-08-22 204 | ================== 205 | 206 | * Add LHD to the setup wizard. 207 | * Add targetDL support. 208 | * Show fallback weight in case of no profitability data. 209 | 210 | 1.5.1 / 2019-08-14 211 | ================== 212 | 213 | * Fix typo in setup wizard. 214 | 215 | 1.5.0 / 2019-08-06 216 | ================== 217 | 218 | * Add setup wizard. 219 | * Add support for `humanizeDeadlines` option. 220 | * Add support for HDPool. 221 | * Add dynamic deadline colors. 222 | * Add support for accountId colors. 223 | * Add support for prebuilt binaries. 224 | 225 | 1.4.1 / 2019-07-26 226 | ================== 227 | 228 | * Fix BOOM rate not being updated correctly. 229 | * Rename minerAlias to accountName. 230 | 231 | 1.4.0 / 2019-07-25 232 | ================== 233 | 234 | * Add support for BOOM rates. 235 | * Automatically add '/mining' to Foxy-Pool URLs if missing. 236 | 237 | 1.3.0 / 2019-07-15 238 | ================== 239 | 240 | * Add support for `assumeScannedAfter` to force chain switches. 241 | * Add support for `maxNumberOfChains`. 242 | * Add support for connection outage detection. 243 | * Add experimental support for running a program when idling. 244 | * Fix unicode minerAlias in header when using http upstreams. 245 | 246 | 1.2.0 / 2019-07-02 247 | ================== 248 | 249 | * Add support for dynamic prio's based on profitability. 250 | * Add support for disabling upstreams. 251 | * Fix possibly outdated miningInfo after reconnecting through socket.io. 252 | * Rename prio to weight in config to clarify precedence. 253 | 254 | 1.1.0 / 2019-06-30 255 | ================== 256 | 257 | * Add support for conqueror. 258 | * Add support for custom miner colors in Foxy-Proxy. 259 | * Fix starting the miner on linux. 260 | 261 | 1.0.0 / 2019-06-04 262 | ================== 263 | 264 | * Initial release. 265 | -------------------------------------------------------------------------------- /lib/first-run-wizard/first-run-wizard.js: -------------------------------------------------------------------------------- 1 | const {writeFileSync } = require('fs'); 2 | const YAML = require('js-yaml'); 3 | const chalk = require('chalk'); 4 | const prompts = require('prompts'); 5 | const ora = require('ora'); 6 | const { cpus } = require('os'); 7 | const { flatMap } = require('lodash'); 8 | const BigNumber = require('bignumber.js'); 9 | 10 | const eventBus = require('../services/event-bus'); 11 | const startupMessage = require('../startup-message'); 12 | const binaryManager = require('../miner/binary-manager/binary-manager'); 13 | const configManager = require('../miner/config-manager/config-manager'); 14 | const { miner } = require('../miner'); 15 | const PlotFileFinder = require('../plot-file-finder/plot-file-finder'); 16 | 17 | let getPlatformInfo = null; 18 | let OpenclUnavailableError = null; 19 | try { 20 | const openclInfo = require('opencl-info'); 21 | getPlatformInfo = openclInfo.getPlatformInfo; 22 | OpenclUnavailableError = openclInfo.OpenclUnavailableError; 23 | } catch (err) {} 24 | 25 | class FirstRunWizard { 26 | constructor(configFilePath) { 27 | this.configFilePath = configFilePath; 28 | } 29 | 30 | async run() { 31 | startupMessage(); 32 | eventBus.publish('log/info', `First start detected, starting the first run wizard ..`); 33 | let platformInfo = null; 34 | let isCpuOnly = null; 35 | if (getPlatformInfo !== null) { 36 | try { 37 | platformInfo = getPlatformInfo(); 38 | isCpuOnly = false; 39 | } catch (err) { 40 | if (!(err instanceof OpenclUnavailableError)) { 41 | isCpuOnly = true; 42 | } 43 | } 44 | } 45 | if (isCpuOnly === null) { 46 | const result = await prompts([{ 47 | type: 'select', 48 | name: 'isCpuOnly', 49 | message: 'Do you want to mine with your CPU or GPU?', 50 | choices: [{ 51 | title: 'CPU', 52 | description: 'CPU only', 53 | value: true, 54 | }, { 55 | title: 'CPU/GPU', 56 | description: 'CPU and/or GPU', 57 | value: false, 58 | }], 59 | initial: 0, 60 | }]); 61 | isCpuOnly = result.isCpuOnly; 62 | this.logCancelFirstRunWizardAndExit(isCpuOnly); 63 | } 64 | let selectedGpu = null; 65 | if (!isCpuOnly && platformInfo !== null) { 66 | const devices = flatMap(platformInfo, platform => platform.devices.map(device => ({ 67 | ...device, 68 | platform: { 69 | id: platform.id, 70 | name: platform.name, 71 | }, 72 | }))); 73 | const gpus = devices.filter(device => device.type !== 'CPU'); 74 | if (gpus.length === 1) { 75 | selectedGpu = gpus[0]; 76 | ora().succeed(`Only one GPU detected, using ${selectedGpu.vendor} - ${selectedGpu.name}`); 77 | } else if (gpus.length > 1) { 78 | const { selectedGpuSelection } = await prompts([{ 79 | type: 'select', 80 | name: 'selectedGpuSelection', 81 | message: 'Please select the GPU you want to use', 82 | choices: gpus.map(gpu => ({ 83 | title: `${gpu.vendor} - ${gpu.name}`, 84 | value: gpu, 85 | })), 86 | initial: 0, 87 | }]); 88 | this.logCancelFirstRunWizardAndExit(selectedGpuSelection); 89 | selectedGpu = selectedGpuSelection; 90 | } 91 | } 92 | const minerType = miner.scavenger.minerType; 93 | await binaryManager.ensureMinerDownloaded({ minerType, isCpuOnly }); 94 | const { coins } = await prompts([{ 95 | type: 'multiselect', 96 | name: 'coins', 97 | message: 'Which coins do you want to mine?', 98 | choices: this.coins.map(coin => ({ 99 | title: coin, 100 | value: coin, 101 | selected: coin === 'SIGNA', 102 | })), 103 | min: 1, 104 | }]); 105 | this.logCancelFirstRunWizardAndExit(coins); 106 | let pools = []; 107 | for (let coin of coins) { 108 | const pool = { 109 | name: `FoxyPool ${coin}`, 110 | type: 'foxypool', 111 | color: this.coinColors[coin], 112 | coin, 113 | distributionRatio: '0-100', 114 | }; 115 | const { 116 | payoutAddress, 117 | accountName, 118 | minerName, 119 | } = await prompts([{ 120 | type: 'text', 121 | name: 'payoutAddress', 122 | message: `[${chalk.hex(pool.color)(pool.name)}] Please enter your ${coin} payout address`, 123 | validate: (input) => !!input ? true : 'No payout address entered!', 124 | }, { 125 | type: 'text', 126 | name: 'accountName', 127 | message: `[${chalk.hex(pool.color)(pool.name)}] Which account name to you want to use? (optional)`, 128 | }, { 129 | type: 'text', 130 | name: 'minerName', 131 | message: `[${chalk.hex(pool.color)(pool.name)}] Which miner name to you want to use? (optional)`, 132 | }]); 133 | this.logCancelFirstRunWizardAndExit(payoutAddress); 134 | this.logCancelFirstRunWizardAndExit(accountName); 135 | this.logCancelFirstRunWizardAndExit(minerName); 136 | pool.payoutAddress = payoutAddress.trim(); 137 | if (accountName.trim()) { 138 | pool.accountName = accountName.trim(); 139 | } 140 | if (minerName.trim()) { 141 | pool.minerName = minerName.trim(); 142 | } 143 | pools.push(pool); 144 | } 145 | let unselectedPools = pools.slice(); 146 | for (let i = 1; i <= pools.length; i += 1) { 147 | const weight = 31 - i; 148 | const { selectedPool } = await prompts({ 149 | type: 'autocomplete', 150 | name: 'selectedPool', 151 | message: `Select your number ${i} priority coin:`, 152 | choices: unselectedPools.map(pool => ({ 153 | title: pool.coin, 154 | value: pool, 155 | })), 156 | }); 157 | this.logCancelFirstRunWizardAndExit(selectedPool); 158 | selectedPool.weight = weight; 159 | unselectedPools = unselectedPools.filter(pool => pool !== selectedPool); 160 | } 161 | pools.sort((a, b) => b.weight - a.weight); 162 | 163 | const plotFileFinder = new PlotFileFinder(); 164 | const spinner = ora('Searching for plot files .. Found plots: 0 | Scanned directories: 0').start(); 165 | 166 | let lastScannedDirectory = null; 167 | plotFileFinder.on('directory-scanned', ({ directory }) => { 168 | lastScannedDirectory = directory; 169 | spinner.text = `Searching for plot files in ${lastScannedDirectory}. Found plots: ${plotFileFinder.plots.length} | Scanned directories: ${plotFileFinder.directoriesScanned}`; 170 | }); 171 | plotFileFinder.on('plot-found', () => { 172 | spinner.text = `Searching for plot files in ${lastScannedDirectory}. Found plots: ${plotFileFinder.plots.length} | Scanned directories: ${plotFileFinder.directoriesScanned}`; 173 | }); 174 | await plotFileFinder.findPlots(); 175 | spinner.succeed(`Finished searching for plots. Found plots: ${plotFileFinder.plots.length} (${plotFileFinder.totalPlotSizeInTiB.toFixed(2)} TiB) | Scanned directories: ${plotFileFinder.directoriesScanned}`); 176 | const plotDirs = plotFileFinder.plotDirectories; 177 | 178 | let gpuPlatform = 0; 179 | let gpuDevice = 0; 180 | let gpuWorkers = isCpuOnly ? 0 : 12; 181 | let gpuNoncesPerCache = 262144; 182 | let useGpuMemMapping = false; 183 | let useGpuAsyncCompute = false; 184 | if (selectedGpu !== null) { 185 | gpuPlatform = selectedGpu.platform.id; 186 | gpuDevice = selectedGpu.id; 187 | gpuWorkers = Math.max(plotDirs.length, gpuWorkers); 188 | const threadMemInMib = new BigNumber(45).multipliedBy(2); 189 | const nonceMemInMib = new BigNumber(gpuNoncesPerCache).multipliedBy(64).dividedBy(new BigNumber(1024).pow(2)); 190 | const gpuMemoryInMib = new BigNumber(selectedGpu.memory).dividedBy(new BigNumber(1024).pow(2)); 191 | const maxGpuWorkers = gpuMemoryInMib.minus(threadMemInMib).dividedBy(nonceMemInMib).integerValue(BigNumber.ROUND_FLOOR); 192 | gpuWorkers = BigNumber.min(gpuWorkers, maxGpuWorkers).toNumber(); 193 | const isIntel = selectedGpu.vendor.toLowerCase().indexOf('intel') !== -1; 194 | useGpuAsyncCompute = !isIntel; 195 | useGpuMemMapping = isIntel; 196 | } 197 | let cpuWorkers = isCpuOnly ? 4 : 0; 198 | if (isCpuOnly) { 199 | cpuWorkers = Math.min(Math.max(plotDirs.length, cpuWorkers), (cpus().length * 4)); 200 | } 201 | 202 | const config = { 203 | logLevel: 'info', 204 | logToFile: true, 205 | humanizeDeadlines: true, 206 | isCpuOnly, 207 | upstreams: pools, 208 | minerConfig: { 209 | useHddDirectIo: true, 210 | cpuWorkers, 211 | useCpuThreadPinning: false, 212 | gpuPlatform, 213 | gpuDevice, 214 | gpuThreads: isCpuOnly ? 0 : 1, 215 | gpuWorkers, 216 | gpuNoncesPerCache, 217 | useGpuMemMapping, 218 | useGpuAsyncCompute, 219 | plotDirs, 220 | }, 221 | listenAddr: '127.0.0.1:5000', 222 | isManaged: true, 223 | minerType, 224 | }; 225 | this.saveToFile(config); 226 | configManager.ensureMinerConfigExists({ minerType, config }); 227 | 228 | let text = `The first run wizard completed successfully and the config has been written to ${this.configFilePath}!`; 229 | text += chalk.cyan(`\n\nPlease add any missing plot file paths to the config (${this.configFilePath}).`); 230 | text += chalk.green('\n\nPress enter to exit the program.'); 231 | 232 | await prompts({ 233 | type: 'text', 234 | name: 'exit', 235 | message: chalk.green(text), 236 | }); 237 | process.exit(0); 238 | } 239 | 240 | saveToFile(config) { 241 | const yaml = YAML.dump(config, { 242 | lineWidth: 140, 243 | }); 244 | writeFileSync(this.configFilePath, yaml, 'utf8'); 245 | } 246 | 247 | get coins() { 248 | return Object.keys(this.coinColors); 249 | } 250 | 251 | get coinColors() { 252 | return { 253 | SIGNA: '#0099ff', 254 | }; 255 | } 256 | 257 | logCancelFirstRunWizardAndExit(value) { 258 | if (value !== undefined) { 259 | return; 260 | } 261 | eventBus.publish('log/info', `You canceled the first run wizard, exiting ..`); 262 | process.exit(0); 263 | } 264 | } 265 | 266 | module.exports = FirstRunWizard; 267 | -------------------------------------------------------------------------------- /main.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const bodyParser = require('koa-bodyparser'); 4 | const chalk = require('chalk'); 5 | const http = require('http'); 6 | const Integrations = require('@sentry/integrations'); 7 | const Koa = require('koa'); 8 | const Router = require('koa-router'); 9 | const Sentry = require('@sentry/node'); 10 | const { program } = require('commander'); 11 | const { flatten } = require('lodash'); 12 | const { arch, platform, release } = require('os'); 13 | 14 | const eventBus = require('./lib/services/event-bus'); 15 | const logger = require('./lib/services/logger'); 16 | const config = require('./lib/services/config'); 17 | const Proxy = require('./lib/proxy'); 18 | const store = require('./lib/services/store'); 19 | const version = require('./lib/version'); 20 | const { getMiner } = require('./lib/miner'); 21 | const IdleProgram = require('./lib/idle-program'); 22 | const startupMessage = require('./lib/startup-message'); 23 | const profitabilityService = require('./lib/services/profitability-service'); 24 | const dashboard = require('./lib/services/cli-dashboard'); 25 | const foxyPoolGateway = require('./lib/services/foxy-pool-gateway'); 26 | const binaryManager = require('./lib/miner/binary-manager/binary-manager'); 27 | const configManager = require('./lib/miner/config-manager/config-manager'); 28 | const FirstRunWizard = require('./lib/first-run-wizard/first-run-wizard'); 29 | 30 | program 31 | .version(version) 32 | .option('--config ', 'The custom foxy miner config.yaml file path') 33 | .option('--live', 'Show a live dashboard with stats') 34 | .parse(process.argv); 35 | 36 | if (program.opts().config) { 37 | store.configFilePath = program.opts().config; 38 | } 39 | if (program.opts().live) { 40 | store.useDashboard = true; 41 | dashboard.init(); 42 | } 43 | 44 | (async () => { 45 | const result = await config.init(); 46 | if (result === null) { 47 | const firstRunWizard = new FirstRunWizard(store.configFilePath); 48 | await firstRunWizard.run(); 49 | process.exit(0); 50 | } 51 | if (config.logToFile) { 52 | logger.enableFileLogging(); 53 | } 54 | 55 | startupMessage(); 56 | 57 | eventBus.publish('log/info', `Config loaded from ${store.configFilePath} successfully`); 58 | 59 | Sentry.init({ 60 | dsn: 'https://2c5b7b184ad44ed99fc457f4442386e9@sentry.io/1462805', 61 | release: `Foxy-Miner@${version}`, 62 | integrations: [ 63 | new Integrations.Dedupe(), 64 | new Integrations.ExtraErrorData(), 65 | new Integrations.Transaction(), 66 | ], 67 | ignoreErrors: [ 68 | /ENOSYS/ 69 | ], 70 | }); 71 | 72 | Sentry.configureScope((scope) => { 73 | scope.setTag('os.arch', arch()); 74 | scope.setTag('os.platform', platform()); 75 | scope.setTag('os.release', release()); 76 | scope.setContext('Config', { 77 | 'Foxy-Miner': JSON.stringify(config.config, null, 2), 78 | }); 79 | }); 80 | 81 | process.on('unhandledRejection', (err) => { 82 | eventBus.publish('log/error', `Error: ${err.message}`); 83 | }); 84 | process.on('uncaughtException', (err) => { 85 | eventBus.publish('log/error', `Error: ${err.message}`); 86 | }); 87 | 88 | const app = new Koa(); 89 | app.on('error', err => { 90 | eventBus.publish('log/error', `Error: ${err.message}`); 91 | }); 92 | 93 | const router = new Router(); 94 | app.use(bodyParser()); 95 | 96 | if (config.useProfitability) { 97 | await profitabilityService.init(config.useEcoBlockRewardsForProfitability); 98 | } 99 | 100 | let minerConfigs; 101 | if (config.miner) { 102 | minerConfigs = config.miner 103 | .map((minerConfig, index) => ({ 104 | ...minerConfig, 105 | index, 106 | })) 107 | .filter(minerConfig => !minerConfig.disabled); 108 | } else { 109 | minerConfigs = [{ 110 | upstreams: config.upstreams, 111 | minerBinPath: config.minerBinPath, 112 | minerConfigPath: config.minerConfigPath, 113 | minerType: config.minerType, 114 | minerOutputToConsole: config.minerOutputToConsole, 115 | assumeScannedAfter: config.config.assumeScannedAfter, 116 | isCpuOnly: config.config.isCpuOnly, 117 | isManaged: config.config.isManaged, 118 | }]; 119 | } 120 | 121 | const singleProxy = minerConfigs.length === 1; 122 | const managedMiners = minerConfigs 123 | .map(minerConfig => ({ 124 | miner: getMiner({ minerType: minerConfig.minerType }), 125 | minerConfig, 126 | })) 127 | .filter(({ miner, minerConfig }) => miner.supportsManagement && minerConfig.isManaged); 128 | const groupedManagedMiners = managedMiners.reduce((acc, curr) => { 129 | const identifier = `${curr.minerConfig.minerType}/${curr.minerConfig.isCpuOnly}`; 130 | if (!acc[identifier]) { 131 | acc[identifier] = curr; 132 | } 133 | 134 | return acc; 135 | }, {}); 136 | await Promise.all(Object.values(groupedManagedMiners).map(async ({ minerConfig }) => { 137 | try { 138 | await binaryManager.ensureMinerDownloaded({ minerType: minerConfig.minerType, isCpuOnly: minerConfig.isCpuOnly }); 139 | } catch (err) { 140 | eventBus.publish('log/error', `Failed to download the miner binary for type ${minerConfig.minerType} with error: ${err}`); 141 | process.exit(0); 142 | } 143 | })); 144 | const proxies = await Promise.all(minerConfigs.map(async (minerConfig) => { 145 | const proxyIndex = (minerConfig.index || 0) + 1; 146 | 147 | const miner = getMiner({ minerType: minerConfig.minerType }); 148 | if (miner.supportsManagement && minerConfig.isManaged) { 149 | configManager.ensureMinerConfigExists({ 150 | minerType: minerConfig.minerType, 151 | config: config.config, 152 | minerIndex: !!config.miner ? minerConfig.index : null, 153 | }); 154 | configManager.updateMinerConfig({ 155 | minerType: minerConfig.minerType, 156 | config: config.config, 157 | minerIndex: !!config.miner ? minerConfig.index : null, 158 | }); 159 | const minerBinPath = binaryManager.getMinerBinaryPath({ minerType: minerConfig.minerType, isCpuOnly: minerConfig.isCpuOnly }); 160 | const minerConfigPath = configManager.getMinerConfigPath({ 161 | minerType: minerConfig.minerType, 162 | minerIndex: !!config.miner ? minerConfig.index : null, 163 | }); 164 | minerConfig.minerBinPath = minerBinPath; 165 | minerConfig.minerConfigPath = minerConfigPath; 166 | } 167 | const minerInstance = new miner.Miner( 168 | minerConfig.minerBinPath, 169 | minerConfig.minerConfigPath, 170 | minerConfig.minerOutputToConsole 171 | ); 172 | 173 | const enabledUpstreams = minerConfig.upstreams.filter(upstreamConfig => !upstreamConfig.disabled); 174 | const proxy = new Proxy({ 175 | upstreamConfigs: enabledUpstreams, 176 | proxyIndex, 177 | showProxyIndex: !singleProxy, 178 | miner: minerInstance, 179 | minerConfig: minerConfig, 180 | }); 181 | minerInstance.proxy = proxy; 182 | 183 | const endpoints = [`/${proxyIndex}/burst`]; 184 | if (singleProxy) { 185 | endpoints.unshift('/burst'); 186 | } 187 | for (let endpoint of endpoints) { 188 | router.get(endpoint, (ctx) => { 189 | const requestType = ctx.query.requestType; 190 | switch (requestType) { 191 | case 'getMiningInfo': 192 | ctx.body = proxy.getMiningInfo(); 193 | break; 194 | default: 195 | eventBus.publish('log/error', `Unknown requestType ${requestType} with data: ${JSON.stringify(ctx.params)}. Please message this info to the creator of this software.`); 196 | ctx.status = 400; 197 | ctx.body = { 198 | error: { 199 | message: 'unknown request type', 200 | code: 4, 201 | }, 202 | }; 203 | } 204 | }); 205 | router.post(endpoint, async (ctx) => { 206 | const requestType = ctx.query.requestType; 207 | switch (requestType) { 208 | case 'getMiningInfo': 209 | ctx.body = proxy.getMiningInfo(); 210 | break; 211 | case 'submitNonce': 212 | const options = { 213 | ip: ctx.request.ip, 214 | maxScanTime: ctx.params.maxScanTime, 215 | minerName: ctx.req.headers['x-minername'] || ctx.req.headers['x-miner'], 216 | userAgent: ctx.req.headers['user-agent'], 217 | miner: ctx.req.headers['x-miner'], 218 | capacity: parseInt(ctx.req.headers['x-capacity']), 219 | accountKey: ctx.req.headers['x-account'], 220 | accountName: ctx.req.headers['x-accountname'] || ctx.req.headers['x-mineralias'] || null, 221 | color: ctx.req.headers['x-color'] || null, 222 | }; 223 | const submissionObj = { 224 | accountId: ctx.query.accountId, 225 | blockheight: ctx.query.blockheight, 226 | nonce: ctx.query.nonce, 227 | deadline: ctx.query.deadline, 228 | secretPhrase: ctx.query.secretPhrase !== '' ? ctx.query.secretPhrase : null, 229 | }; 230 | ctx.body = await proxy.submitNonce(submissionObj, options); 231 | if (ctx.body.error) { 232 | ctx.status = 400; 233 | } 234 | break; 235 | default: 236 | eventBus.publish('log/error', `Unknown requestType ${requestType} with data: ${JSON.stringify(ctx.params)}. Please message this info to the creator of this software.`); 237 | ctx.status = 400; 238 | ctx.body = { 239 | error: { 240 | message: 'unknown request type', 241 | code: 4, 242 | }, 243 | }; 244 | } 245 | }); 246 | } 247 | 248 | return { 249 | miner: minerInstance, 250 | proxy, 251 | }; 252 | })); 253 | 254 | if (store.useDashboard) { 255 | dashboard.proxies = proxies.map(({proxy}) => proxy); 256 | dashboard.start(); 257 | } 258 | 259 | const coins = [...new Set(flatten(proxies.map(({proxy}) => 260 | proxy.upstreamConfigs 261 | .filter(upstreamConfig => upstreamConfig.type === 'foxypool' && upstreamConfig.coin && !upstreamConfig.url) 262 | .map(upstreamConfig => upstreamConfig.coin.toUpperCase()) 263 | )))]; 264 | if (coins.length > 0) { 265 | foxyPoolGateway.coins = coins; 266 | await foxyPoolGateway.init(); 267 | } 268 | 269 | await Promise.all(proxies.map(({proxy}) => proxy.init())); 270 | 271 | app.use(router.routes()); 272 | app.use(router.allowedMethods()); 273 | 274 | const server = http.createServer(app.callback()); 275 | 276 | server.on('error', (err) => { 277 | eventBus.publish('log/error', `Error: ${err.message}`); 278 | if (err.code === 'EADDRINUSE' || err.code === 'EACCES') { 279 | process.exit(1); 280 | } 281 | }); 282 | 283 | server.listen(config.listenPort, config.listenHost); 284 | 285 | const startupLine = `Foxy-Miner ${version} initialized`; 286 | eventBus.publish('log/info', store.getUseColors() ? chalk.green(startupLine) : startupLine); 287 | proxies.map(({ proxy }) => { 288 | const listenLine = `Accepting connections on http://${config.listenAddr}${singleProxy ? '' : '/' + (proxy.proxyIndex)}`; 289 | eventBus.publish('log/info', store.getUseColors() ? chalk.blueBright(listenLine) : listenLine); 290 | }); 291 | 292 | await Promise.all(proxies.map(({miner}) => miner.start())); 293 | 294 | if (config.config.runIdleBinPath && singleProxy) { 295 | const idleProgram = new IdleProgram(config.config.runIdleBinPath, config.config.runIdleKillBinPath); 296 | proxies[0].miner.subscribe('new-round', () => idleProgram.stop()); 297 | proxies[0].miner.subscribe('all-rounds-finished', () => idleProgram.start()); 298 | } 299 | })(); 300 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------