├── .nvmrc ├── .gitignore ├── index.js ├── .travis.yml ├── dockerfiles ├── storjshare-daemon-alpine.dockerfile ├── storjshare-daemon-ubuntu.dockerfile ├── get_dep_ver.ps1 └── storjshare-daemon-win.dockerfile ├── snap └── snapcraft.yaml ├── lib ├── config │ ├── daemon.js │ └── farmer.js ├── utils.js └── api.js ├── ISSUE_TEMPLATE.md ├── example ├── daemon.config.json └── farmer.config.json ├── .jshintrc ├── bin ├── storjshare-killall.js ├── storjshare-stop.js ├── storjshare-destroy.js ├── storjshare.js ├── storjshare-save.js ├── storjshare-load.js ├── storjshare-restart.js ├── storjshare-daemon.js ├── storjshare-start.js ├── storjshare-logs.js ├── storjshare-status.js └── storjshare-create.js ├── CONTRIBUTING.md ├── package.json ├── script └── farmer.js ├── test ├── utils.unit.js └── api.unit.js ├── README.md └── LICENSE /.nvmrc: -------------------------------------------------------------------------------- 1 | lts/* 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.snap 2 | parts/ 3 | stage/ 4 | prime/ 5 | node_modules/ 6 | coverage/ 7 | *.swp 8 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @module storj-share 4 | * @license (AGPL-3.0) 5 | */ 6 | 7 | 'use strict'; 8 | 9 | /** {@link module:utils} */ 10 | exports.utils = require('./lib/utils'); 11 | 12 | /** {@link RPC} */ 13 | exports.RPC = require('./lib/api'); 14 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | 2 | language: node_js 3 | compiler: 4 | - gcc 5 | - clang 6 | addons: 7 | apt: 8 | sources: 9 | - ubuntu-toolchain-r-test 10 | packages: 11 | - gcc-4.8 12 | - g++-4.8 13 | - clang 14 | node_js: 15 | - "8" 16 | before_install: 17 | - export CXX="g++-4.8" CC="gcc-4.8" 18 | after_script: 19 | - npm run coverage 20 | - cat ./coverage/lcov.info | ./node_modules/.bin/coveralls 21 | -------------------------------------------------------------------------------- /dockerfiles/storjshare-daemon-alpine.dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:alpine 2 | MAINTAINER Storj Labs (storj.io) 3 | 4 | RUN apk add --no-cache bash g++ git make openssl-dev python vim && \ 5 | node --version && \ 6 | npm --version && \ 7 | python --version && \ 8 | npm install --global storjshare-daemon && \ 9 | npm cache clean && \ 10 | apk del git openssl-dev python vim && \ 11 | rm -rf /var/cache/apk/* && \ 12 | rm -rf /tmp/npm* && \ 13 | storjshare --version 14 | 15 | EXPOSE 4000 16 | EXPOSE 4001 17 | EXPOSE 4002 18 | EXPOSE 4003 19 | -------------------------------------------------------------------------------- /snap/snapcraft.yaml: -------------------------------------------------------------------------------- 1 | name: storjshare 2 | version: git 3 | summary: farm data on the Storj network. 4 | description: | 5 | Earn money by sharing your hard drive space. 6 | Daemon + CLI for farming data on the Storj network. 7 | 8 | grade: stable 9 | confinement: strict 10 | 11 | apps: 12 | storjshare: 13 | command: bin/storjshare 14 | plugs: [network, network-bind, home] 15 | 16 | parts: 17 | storjshare-daemon: 18 | source-subdir: .. 19 | plugin: nodejs 20 | node-engine: '8.9.0' 21 | install: npm install 22 | build-packages: [git, python, build-essential] 23 | stage-packages: [nano] 24 | -------------------------------------------------------------------------------- /lib/config/daemon.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @module config 3 | */ 4 | 5 | 'use strict'; 6 | 7 | const mkdirp = require('mkdirp'); 8 | const path = require('path'); 9 | const {homedir} = require('os'); 10 | const datadir = path.join(homedir(), '.config', 'storjshare'); 11 | 12 | mkdirp.sync(datadir); 13 | mkdirp.sync(path.join(datadir, 'logs')); 14 | mkdirp.sync(path.join(datadir, 'shares')); 15 | mkdirp.sync(path.join(datadir, 'configs')); 16 | 17 | module.exports = require('rc')('storjshare', { 18 | daemonRpcPort: 45015, 19 | daemonRpcAddress: '127.0.0.1', 20 | daemonLogFilePath: path.join(datadir, 'logs', 'daemon.log'), 21 | daemonLogVerbosity: 3 22 | }); 23 | -------------------------------------------------------------------------------- /ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### Package Versions 2 | 3 | Replace the values below using the output from `storjshare --version`. 4 | 5 | ``` 6 | 2.0.3 7 | ``` 8 | 9 | Replace the values below using the output from `node --version`. 10 | 11 | ``` 12 | v8.x.x 13 | ``` 14 | 15 | ### Expected Behavior 16 | 17 | Please describe the program's expected behavior. 18 | 19 | ### Actual Behavior 20 | 21 | Please describe the program's actual behavior. Please include any stack traces 22 | or log output in the back ticks below. 23 | 24 | ``` 25 | 26 | ``` 27 | 28 | ### Steps to Reproduce 29 | 30 | Please include the steps the reproduce the issue, numbered below. Include as 31 | much detail as possible. 32 | 33 | 1. ... 34 | 2. ... 35 | 3. ... 36 | -------------------------------------------------------------------------------- /dockerfiles/storjshare-daemon-ubuntu.dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:latest 2 | MAINTAINER Storj Labs (www.storj.io) 3 | 4 | RUN apt-get update && \ 5 | apt-get -y install apt-utils curl && \ 6 | curl -sL https://deb.nodesource.com/setup_8.x | bash - && \ 7 | apt-get -y install build-essential git libssl-dev nodejs python vim && \ 8 | npm install --global storjshare-daemon --unsafe-perm && \ 9 | apt-get --purge remove -y apt-utils build-essential curl git libssl-dev python vim && \ 10 | apt autoremove -y && \ 11 | apt-get clean -y && \ 12 | rm -rf /var/lib/apt/lists/* && \ 13 | rm -rf /tmp/npm* && \ 14 | echo npm --version; npm --version && \ 15 | echo storjshare --version; storjshare --version 16 | 17 | EXPOSE 4000 18 | EXPOSE 4001 19 | EXPOSE 4002 20 | EXPOSE 4003 21 | -------------------------------------------------------------------------------- /example/daemon.config.json: -------------------------------------------------------------------------------- 1 | { 2 | // Bind Dnode RPC server to this port 3 | "daemonRpcPort": 45015, 4 | // Interface to bind Dnode RPC server, if your host is public, be sure to 5 | // leave this as "127.0.0.1" to prevent others from controlling your nodes 6 | // You can set this to a public address if you'd like to control your shares 7 | // remotely, however you must secure access on your own - you have been 8 | // warned 9 | "daemonRpcAddress": "127.0.0.1", 10 | // Path to write daemon log file to disk, leave blank to default to: 11 | // $HOME/.config/storjshare/logs/daemon.log 12 | "daemonLogFilePath": "", 13 | // Determines how much detail is shown in the log: 14 | // 4 - DEBUG | 3 - INFO | 2 - WARN | 1 - ERROR | 0 - SILENT 15 | "daemonLogVerbosity": 3 16 | } 17 | -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "laxbreak": true, 3 | "bitwise": false, 4 | "browser": true, 5 | "camelcase": false, 6 | "curly": true, 7 | "devel": false, 8 | "eqeqeq": true, 9 | "esnext": true, 10 | "freeze": true, 11 | "immed": true, 12 | "indent": 2, 13 | "latedef": true, 14 | "newcap": false, 15 | "noarg": true, 16 | "node": true, 17 | "noempty": true, 18 | "nonew": true, 19 | "quotmark": "single", 20 | "regexp": true, 21 | "smarttabs": false, 22 | "strict": true, 23 | "trailing": true, 24 | "undef": true, 25 | "unused": true, 26 | "maxparams": 4, 27 | "maxstatements": 20, 28 | "maxcomplexity": 6, 29 | "maxdepth": 3, 30 | "maxlen": 80, 31 | "multistr": true, 32 | "predef": [ 33 | "after", 34 | "afterEach", 35 | "before", 36 | "beforeEach", 37 | "describe", 38 | "exports", 39 | "it", 40 | "module", 41 | "require" 42 | ] 43 | } 44 | -------------------------------------------------------------------------------- /bin/storjshare-killall.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | 'use strict'; 4 | 5 | const config = require('../lib/config/daemon'); 6 | const utils = require('../lib/utils'); 7 | const storjshare_killall = require('commander'); 8 | 9 | storjshare_killall 10 | .description('destroys all running nodes and stop daemon') 11 | .option('-r, --remote ', 12 | 'hostname and optional port of the daemon') 13 | .parse(process.argv); 14 | 15 | let port = config.daemonRpcPort; 16 | let address = null; 17 | if (storjshare_killall.remote) { 18 | address = storjshare_killall.remote.split(':')[0]; 19 | if (storjshare_killall.remote.split(':').length > 1) { 20 | port = parseInt(storjshare_killall.remote.split(':')[1], 10); 21 | } 22 | } 23 | 24 | utils.connectToDaemon(port, function(rpc, sock) { 25 | sock.on('end', () => console.info('\n * daemon has stopped')); 26 | rpc.killall(() => sock.end()); 27 | }, address); 28 | -------------------------------------------------------------------------------- /lib/config/farmer.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const mkdirp = require('mkdirp'); 4 | const path = require('path'); 5 | const {homedir} = require('os'); 6 | const datadir = path.join(homedir(), '.config', 'storjshare'); 7 | 8 | mkdirp.sync(datadir); 9 | mkdirp.sync(path.join(datadir, 'logs')); 10 | 11 | const config = require('rc')('storjfarmer', { 12 | // NB: These properties are passed directly to Farmer 13 | paymentAddress: null, 14 | opcodeSubscriptions: [ 15 | '0f01020202', 16 | '0f02020202', 17 | '0f03020202' 18 | ], 19 | seedList: [], 20 | rpcAddress: '127.0.0.1', 21 | rpcPort: 4000, 22 | doNotTraverseNat: true, 23 | maxTunnels: 3, 24 | maxConnections: 150, 25 | tunnelGatewayRange: { 26 | min: 4001, 27 | max: 4003 28 | }, 29 | joinRetry: { 30 | times: 3, 31 | interval: 5000 32 | }, 33 | offerBackoffLimit: 4, 34 | // NB: These properties are processed before given to Farmer 35 | networkPrivateKey: null, 36 | loggerVerbosity: 3, 37 | loggerOutputFile: null, 38 | storagePath: null, 39 | storageAllocation: '2GB' 40 | }); 41 | 42 | if (!config.loggerOutputFile) { 43 | config.loggerOutputFile = path.join(homedir(),'.config/storjshare/logs'); 44 | } 45 | 46 | module.exports = config; 47 | -------------------------------------------------------------------------------- /bin/storjshare-stop.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | 'use strict'; 4 | 5 | const config = require('../lib/config/daemon'); 6 | const utils = require('../lib/utils'); 7 | const storjshare_stop = require('commander'); 8 | 9 | storjshare_stop 10 | .description('stops the running node specified') 11 | .option('-i, --nodeid ', 'id of the running node') 12 | .option('-r, --remote ', 13 | 'hostname and optional port of the daemon') 14 | .parse(process.argv); 15 | 16 | if (!storjshare_stop.nodeid) { 17 | console.error('\n missing node id, try --help'); 18 | process.exit(1); 19 | } 20 | 21 | let port = config.daemonRpcPort; 22 | let address = null; 23 | if (storjshare_stop.remote) { 24 | address = storjshare_stop.remote.split(':')[0]; 25 | if (storjshare_stop.remote.split(':').length > 1) { 26 | port = parseInt(storjshare_stop.remote.split(':')[1], 10); 27 | } 28 | } 29 | 30 | utils.connectToDaemon(port, function(rpc, sock) { 31 | rpc.stop(storjshare_stop.nodeid, (err) => { 32 | if (err) { 33 | console.error(`\n cannot stop node, reason: ${err.message}`); 34 | return sock.end(); 35 | } 36 | console.info(`\n * share ${storjshare_stop.nodeid} stopped`); 37 | return sock.end(); 38 | }); 39 | }, address); 40 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Contributing 2 | ============ 3 | 4 | Want to contribute? Read on! 5 | 6 | Contributor License Agreement 7 | ----------------------------- 8 | 9 | By submitting pull requests, you agree that your work may be licensed under GNU Affero General Public License Version 3 (or later). 10 | You also assert that you have completed the [Contributor License Agreement](https://storj.io/cla). 11 | 12 | Pull Requests for Swag 13 | ---------------------- 14 | We love pull requests, so to encourage more of them we are offering 15 | awesome swag. Only significant pull requests count. Fixing a comma 16 | doesn’t count, but fixing a bug, adding more test coverage, or writing 17 | guides and documentation does. 18 | 19 | - Make 1x pull requests to get into the contributors list and website 20 | - Make 2x pull requests and we will send you a packet of stickers 21 | - Make 5x pull requests and we will send you a t-shirt and more stickers 22 | - Make 10x pull requests, and you'll get a job interview + other swag 23 | 24 | If we miss a milestone, just let us know so we can get you your swag. 25 | 26 | Style Guide 27 | ----------- 28 | We adhere to 29 | [Felix's Node.js Style Guide](https://github.com/felixge/node-style-guide). 30 | Please take the time to review the style guide and take care to follow it. 31 | -------------------------------------------------------------------------------- /bin/storjshare-destroy.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | 'use strict'; 4 | 5 | const config = require('../lib/config/daemon'); 6 | const utils = require('../lib/utils'); 7 | const storjshare_destroy = require('commander'); 8 | 9 | storjshare_destroy 10 | .description('stops a running node and removes it from status') 11 | .option('-i, --nodeid ', 'id of the managed node') 12 | .option('-r, --remote ', 13 | 'hostname and optional port of the daemon') 14 | .parse(process.argv); 15 | 16 | if (!storjshare_destroy.nodeid) { 17 | console.error('\n missing node id, try --help'); 18 | process.exit(1); 19 | } 20 | 21 | let port = config.daemonRpcPort; 22 | let address = null; 23 | if (storjshare_destroy.remote) { 24 | address = storjshare_destroy.remote.split(':')[0]; 25 | if (storjshare_destroy.remote.split(':').length > 1) { 26 | port = parseInt(storjshare_destroy.remote.split(':')[1], 10); 27 | } 28 | } 29 | 30 | utils.connectToDaemon(port, function(rpc, sock) { 31 | rpc.destroy(storjshare_destroy.nodeid, (err) => { 32 | if (err) { 33 | console.error(`\n cannot destroy node, reason: ${err.message}`); 34 | return sock.end(); 35 | } 36 | console.info(`\n * share ${storjshare_destroy.nodeid} destroyed`); 37 | sock.end(); 38 | }); 39 | }, address); 40 | -------------------------------------------------------------------------------- /bin/storjshare.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | 'use strict'; 4 | 5 | const storjshare = require('commander'); 6 | const {version, bin} = require('../package'); 7 | const {software: core, protocol} = require('storj-lib').version; 8 | 9 | function checkIfValidSubcommand() { 10 | if (process.argv.length > 2) { 11 | for (var prop in bin) { 12 | if (bin[prop].replace('bin/storjshare-','') 13 | .replace('.js','') === process.argv[2]) { 14 | return true; 15 | } 16 | } 17 | } 18 | return false; 19 | } 20 | 21 | storjshare 22 | .version(`daemon: ${version}, core: ${core}, protocol: ${protocol}`) 23 | .command('start', 'start a farming node') 24 | .command('stop', 'stop a farming node') 25 | .command('restart', 'restart a farming node') 26 | .command('status', 'check status of node(s)') 27 | .command('logs', 'tail the logs for a node') 28 | .command('create', 'create a new configuration') 29 | .command('save', 'snapshot the currently managed node') 30 | .command('load', 'load a snapshot of previously managed nodes') 31 | .command('destroy', 'kills the farming node') 32 | .command('killall', 'kills all nodes and stops the daemon') 33 | .command('daemon', 'starts the daemon') 34 | .parse(process.argv); 35 | 36 | if (!checkIfValidSubcommand()) { 37 | storjshare.help(); 38 | } 39 | -------------------------------------------------------------------------------- /bin/storjshare-save.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | 'use strict'; 4 | 5 | const os = require('os'); 6 | const path = require('path'); 7 | const config = require('../lib/config/daemon'); 8 | const utils = require('../lib/utils'); 9 | const storjshare_save = require('commander'); 10 | 11 | storjshare_save 12 | .description('saves a snapshot of nodes') 13 | .option('-s, --snapshot ', 'path to write the snapshot file') 14 | .option('-r, --remote ', 15 | 'hostname and optional port of the daemon') 16 | .parse(process.argv); 17 | 18 | if (!storjshare_save.snapshot) { 19 | storjshare_save.snapshot = path.join( 20 | os.homedir(), 21 | '.config/storjshare/snapshot' 22 | ); 23 | } 24 | 25 | if (!path.isAbsolute(storjshare_save.snapshot)) { 26 | storjshare_save.snapshot = path.join(process.cwd(), 27 | storjshare_save.snapshot); 28 | } 29 | 30 | let port = config.daemonRpcPort; 31 | let address = null; 32 | if (storjshare_save.remote) { 33 | address = storjshare_save.remote.split(':')[0]; 34 | if (storjshare_save.remote.split(':').length > 1) { 35 | port = parseInt(storjshare_save.remote.split(':')[1], 10); 36 | } 37 | } 38 | 39 | utils.connectToDaemon(port, function(rpc, sock) { 40 | rpc.save(storjshare_save.snapshot, (err) => { 41 | if (err) { 42 | console.error(`\n cannot save snapshot, reason: ${err.message}`); 43 | return sock.end(); 44 | } 45 | console.info(`\n * snapshot ${storjshare_save.snapshot} saved`); 46 | sock.end(); 47 | }); 48 | }, address); 49 | -------------------------------------------------------------------------------- /bin/storjshare-load.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | 'use strict'; 4 | 5 | const os = require('os'); 6 | const path = require('path'); 7 | const config = require('../lib/config/daemon'); 8 | const utils = require('../lib/utils'); 9 | const storjshare_load = require('commander'); 10 | 11 | storjshare_load 12 | .description('loads a snapshot of nodes and starts all of them') 13 | .option('-s, --snapshot ', 'path to load the snapshot file') 14 | .option('-r, --remote ', 15 | 'hostname and optional port of the daemon') 16 | .parse(process.argv); 17 | 18 | if (!storjshare_load.snapshot) { 19 | storjshare_load.snapshot = path.join( 20 | os.homedir(), 21 | '.config/storjshare/snapshot' 22 | ); 23 | } 24 | 25 | if (!path.isAbsolute(storjshare_load.snapshot)) { 26 | storjshare_load.snapshot = path.join(process.cwd(), 27 | storjshare_load.snapshot); 28 | } 29 | 30 | let port = config.daemonRpcPort; 31 | let address = null; 32 | if (storjshare_load.remote) { 33 | address = storjshare_load.remote.split(':')[0]; 34 | if (storjshare_load.remote.split(':').length > 1) { 35 | port = parseInt(storjshare_load.remote.split(':')[1], 10); 36 | } 37 | } 38 | 39 | utils.connectToDaemon(port, function(rpc, sock) { 40 | rpc.load(storjshare_load.snapshot, (err) => { 41 | if (err) { 42 | console.error(`\n cannot load snapshot, reason: ${err.message}`); 43 | return sock.end(); 44 | } 45 | console.info(`\n * snapshot ${storjshare_load.snapshot} loaded`); 46 | sock.end(); 47 | }); 48 | }, address); 49 | -------------------------------------------------------------------------------- /bin/storjshare-restart.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | 'use strict'; 4 | 5 | const config = require('../lib/config/daemon'); 6 | const utils = require('../lib/utils'); 7 | const storjshare_restart = require('commander'); 8 | 9 | storjshare_restart 10 | .description('restarts the running node specified') 11 | .option('-i, --nodeid ', 'id of the running node') 12 | .option('-a, --all', 'restart all running nodes') 13 | .option('-r, --remote ', 14 | 'hostname and optional port of the daemon') 15 | .parse(process.argv); 16 | 17 | if (!storjshare_restart.nodeid && !storjshare_restart.all) { 18 | console.error('\n missing node id, try --help'); 19 | process.exit(1); 20 | } 21 | 22 | let port = config.daemonRpcPort; 23 | let address = null; 24 | if (storjshare_restart.remote) { 25 | address = storjshare_restart.remote.split(':')[0]; 26 | if (storjshare_restart.remote.split(':').length > 1) { 27 | port = parseInt(storjshare_restart.remote.split(':')[1], 10); 28 | } 29 | } 30 | 31 | utils.connectToDaemon(port, function(rpc, sock) { 32 | if (storjshare_restart.all) { 33 | console.info('\n * restarting all managed nodes'); 34 | } 35 | 36 | rpc.restart(storjshare_restart.nodeid || '*', (err) => { 37 | if (err) { 38 | console.error(`\n cannot restart node, reason: ${err.message}`); 39 | return sock.end(); 40 | } 41 | 42 | if (storjshare_restart.nodeid) { 43 | console.info(`\n * share ${storjshare_restart.nodeid} restarted`); 44 | } else { 45 | console.info('\n * all nodes restarted successfully'); 46 | } 47 | 48 | sock.end(); 49 | }); 50 | }, address); 51 | -------------------------------------------------------------------------------- /dockerfiles/get_dep_ver.ps1: -------------------------------------------------------------------------------- 1 | $uri = 'https://github.com/git-for-windows/git/releases/latest' 2 | 3 | if($(invoke-webrequest $uri -DisableKeepAlive -UseBasicParsing -Method head).BaseResponse.ResponseUri) { 4 | $url = $(invoke-webrequest $uri -DisableKeepAlive -UseBasicParsing -Method head).BaseResponse.ResponseUri.ToString() 5 | Write-Host $url 6 | } 7 | 8 | if($(invoke-webrequest $uri -DisableKeepAlive -UseBasicParsing -Method head).BaseResponse.RequestMessage) { 9 | $url = $(invoke-webrequest $uri -DisableKeepAlive -UseBasicParsing -Method head).BaseResponse.RequestMessage.RequestUri.ToString(); 10 | Write-Host $url 11 | } 12 | 13 | $version = $url.Substring(0,$url.Length-".windows.1".Length) 14 | $pos = $version.IndexOf("v") 15 | $version = $version.Substring($pos+1) 16 | 17 | Write-Host "Found Latest Version of Git for Windows - ${version}" 18 | $env:MINGIT_VERSION = "${version}" 19 | 20 | $node_base_ver = 8 21 | $arch_ver = "-x64" 22 | $uri = "https://nodejs.org/dist/latest-v${node_base_ver}.x/" 23 | $site = invoke-webrequest $uri -DisableKeepAlive -UseBasicParsing 24 | 25 | $found=0 26 | $site.Links | Foreach { 27 | $url_items = $_.href 28 | 29 | if($url_items -like "*${arch_ver}.msi") { 30 | $filename=$url_items 31 | $found=1 32 | } 33 | } 34 | 35 | if($found -ne 1) { 36 | Write-Host "Unable to gather Node.js Version"; 37 | } 38 | 39 | $url="${url}$filename" 40 | $version = $filename.Substring(0,$filename.Length-"${arch_ver}.msi".Length) 41 | $pos = $version.IndexOf("v") 42 | $version = $version.Substring($pos+1) 43 | 44 | Write-Host "Found Latest Version of Node - ${version}" 45 | $env:NODE_VERSION = "${version}" 46 | -------------------------------------------------------------------------------- /bin/storjshare-daemon.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | 'use strict'; 4 | 5 | const daemonize = require('daemon'); 6 | const dnode = require('dnode'); 7 | const RPC = require('../lib/api'); 8 | const utils = require('../lib/utils'); 9 | const config = require('../lib/config/daemon'); 10 | const { createWriteStream } = require('fs'); 11 | const logFile = createWriteStream(config.daemonLogFilePath, { flags: 'a' }); 12 | const storjshare_daemon = require('commander'); 13 | 14 | storjshare_daemon 15 | .option('--status', 'print the status of the daemon and exit') 16 | .option('-F, --foreground', 'keeps the process in the foreground') 17 | .option('-r, --remote ', 18 | 'hostname and optional port of the daemon ' + 19 | 'to connect to when using --status') 20 | .parse(process.argv); 21 | 22 | const api = new RPC({ 23 | logVerbosity: config.daemonLogVerbosity 24 | }); 25 | 26 | function startDaemonRpcServer() { 27 | dnode(api.methods) 28 | .on('error', (err) => api.jsonlogger.warn(err.message)) 29 | .listen(config.daemonRpcPort, config.daemonRpcAddress); 30 | } 31 | 32 | let port = config.daemonRpcPort; 33 | let address = null; 34 | if (storjshare_daemon.remote) { 35 | address = storjshare_daemon.remote.split(':')[0]; 36 | if (storjshare_daemon.remote.split(':').length > 1) { 37 | port = parseInt(storjshare_daemon.remote.split(':')[1], 10); 38 | } 39 | } 40 | 41 | utils.checkDaemonRpcStatus(port, (isRunning) => { 42 | if (storjshare_daemon.status) { 43 | console.info(`\n * daemon ${isRunning ? 'is' : 'is not'} running`); 44 | process.exitCode = isRunning ? 0 : 3; 45 | } else if (isRunning) { 46 | return console.info('\n * daemon is already running'); 47 | } else { 48 | if (storjshare_daemon.foreground) { 49 | console.info('\n * starting daemon in foreground\n'); 50 | api.jsonlogger.pipe(process.stdout); 51 | startDaemonRpcServer(); 52 | } else { 53 | console.info('\n * starting daemon in background'); 54 | daemonize(); 55 | api.jsonlogger.pipe(logFile); 56 | startDaemonRpcServer(); 57 | } 58 | } 59 | }, address); 60 | -------------------------------------------------------------------------------- /bin/storjshare-start.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | 'use strict'; 4 | 5 | const {spawn} = require('child_process'); 6 | const utils = require('../lib/utils'); 7 | const path = require('path'); 8 | const config = require('../lib/config/daemon'); 9 | const storjshare_start = require('commander'); 10 | 11 | storjshare_start 12 | .description('starts a new network node') 13 | .option('-c, --config ', 'specify the configuration path') 14 | .option('-d, --detached', 'run node without management from daemon') 15 | .option('-u, --unsafe', 'ignore system resource guards') 16 | .option('-r, --remote ', 17 | 'hostname and optional port of the daemon') 18 | .parse(process.argv); 19 | 20 | if (!storjshare_start.config) { 21 | console.error('\n no config file was given, try --help'); 22 | process.exit(1); 23 | } 24 | 25 | const configPath = path.isAbsolute(storjshare_start.config) ? 26 | path.normalize(storjshare_start.config) : 27 | path.join(process.cwd(), storjshare_start.config); 28 | 29 | let port = config.daemonRpcPort; 30 | let address = null; 31 | if (storjshare_start.remote) { 32 | address = storjshare_start.remote.split(':')[0]; 33 | if (storjshare_start.remote.split(':').length > 1) { 34 | port = parseInt(storjshare_start.remote.split(':')[1], 10); 35 | } 36 | } 37 | 38 | function runDetachedShare() { 39 | const scriptPath = path.join(__dirname, '../script/farmer.js'); 40 | const shareProc = spawn(scriptPath, ['--config', configPath]); 41 | 42 | process.stdin.pipe(shareProc.stdin); 43 | shareProc.stdout.pipe(process.stdout); 44 | shareProc.stderr.pipe(process.stderr); 45 | shareProc.on('exit', (code) => process.exit(code)); 46 | } 47 | 48 | function runManagedShare() { 49 | utils.connectToDaemon(port, function(rpc, sock) { 50 | rpc.start(configPath, (err) => { 51 | if (err) { 52 | console.error(`\n failed to start node, reason: ${err.message}`); 53 | return sock.end(); 54 | } 55 | console.info(`\n * starting node with config at ${configPath}`); 56 | sock.end(); 57 | }, storjshare_start.unsafe); 58 | }, address); 59 | } 60 | 61 | if (storjshare_start.detached) { 62 | runDetachedShare(); 63 | } else { 64 | runManagedShare(); 65 | } 66 | -------------------------------------------------------------------------------- /dockerfiles/storjshare-daemon-win.dockerfile: -------------------------------------------------------------------------------- 1 | FROM microsoft/windowsservercore 2 | MAINTAINER Storj Labs (www.storj.io) 3 | SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop';"] 4 | 5 | ENV NPM_CONFIG_LOGLEVEL info 6 | 7 | ADD https://raw.githubusercontent.com/Storj/storjshare-daemon/master/dockerfiles/get_dep_ver.ps1 get_dep_ver.ps1 8 | 9 | RUN .\get_dep_ver.ps1; \ 10 | Invoke-WebRequest $('https://nodejs.org/dist/v{0}/node-v{0}-win-x64.zip' -f $env:NODE_VERSION) -OutFile 'node.zip' -UseBasicParsing ; \ 11 | Expand-Archive node.zip -DestinationPath C:\ ; \ 12 | Rename-Item -Path $('C:\node-v{0}-win-x64' -f $env:NODE_VERSION) -NewName 'C:\nodejs' ; \ 13 | New-Item $($env:APPDATA + '\npm') ; \ 14 | $env:PATH = 'C:\nodejs;{0}\npm;{1}' -f $env:APPDATA, $env:PATH ; \ 15 | Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\' -Name Path -Value $env:PATH ; \ 16 | Remove-Item -Path node.zip; \ 17 | \ 18 | Invoke-WebRequest $('https://github.com/git-for-windows/git/releases/download/v{0}.windows.1/MinGit-{0}-64-bit.zip' -f $env:MINGIT_VERSION) -OutFile 'mingit.zip' -UseBasicParsing ; \ 19 | Expand-Archive mingit.zip -DestinationPath C:\mingit ; \ 20 | $keepPath = $env:PATH; \ 21 | $env:PATH = 'C:\mingit\cmd;{0}' -f $env:PATH ; \ 22 | Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\' -Name Path -Value $env:PATH ; \ 23 | Remove-Item -Path mingit.zip; \ 24 | \ 25 | Write-Host npm install --global windows-build-tools; npm install --global windows-build-tools; \ 26 | Write-Host npm install --global storjshare-daemon --unsafe-perm; npm install --global storjshare-daemon --unsafe-perm; \ 27 | Write-Host npm uninstall --global windows-build-tools; npm uninstall --global windows-build-tools; \ 28 | Remove-Item -Path C:\mingit -Recurse -Force; \ 29 | $env:PATH = $keepPath; \ 30 | Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\' -Name Path -Value $env:PATH ; \ 31 | Remove-Item *.log -Force; \ 32 | Remove-Item *.ps1 -Force; \ 33 | Remove-Item -recurse -force "C:\Windows\Temp\*.*"; \ 34 | Get-Childitem "$env:Temp" -Recurse | ForEach-Object { Remove-Item $_.FullName -Recurse -Force -ErrorAction SilentlyContinue }; \ 35 | Remove-Item -recurse -force "$env:UserProfile\.node-gyp"; \ 36 | Remove-Item -recurse -force "$env:UserProfile\.windows-build-tools"; \ 37 | Write-Host npm --version; npm --version; \ 38 | Write-Host storjshare --version; storjshare --version; 39 | 40 | EXPOSE 4000 41 | EXPOSE 4001 42 | EXPOSE 4002 43 | EXPOSE 4003 44 | CMD [""] 45 | ENTRYPOINT ["powershell"] 46 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "storjshare-daemon", 3 | "version": "5.3.1", 4 | "description": "daemon + process manager for sharing space on the storj network", 5 | "main": "index.js", 6 | "bin": { 7 | "storjshare": "bin/storjshare.js", 8 | "storjshare-start": "bin/storjshare-start.js", 9 | "storjshare-stop": "bin/storjshare-stop.js", 10 | "storjshare-restart": "bin/storjshare-restart.js", 11 | "storjshare-status": "bin/storjshare-status.js", 12 | "storjshare-logs": "bin/storjshare-logs.js", 13 | "storjshare-save": "bin/storjshare-save.js", 14 | "storjshare-load": "bin/storjshare-load.js", 15 | "storjshare-killall": "bin/storjshare-killall.js", 16 | "storjshare-destroy": "bin/storjshare-destroy.js", 17 | "storjshare-daemon": "bin/storjshare-daemon.js", 18 | "storjshare-create": "bin/storjshare-create.js" 19 | }, 20 | "directories": { 21 | "test": "test", 22 | "lib": "lib" 23 | }, 24 | "scripts": { 25 | "test": "npm run testsuite && npm run linter", 26 | "testsuite": "STORJ_ALLOW_LOOPBACK=1 ./node_modules/.bin/mocha test/** --recursive", 27 | "coverage": "STORJ_ALLOW_LOOPBACK=1 ./node_modules/.bin/istanbul cover ./node_modules/.bin/_mocha -- --recursive", 28 | "linter": "./node_modules/.bin/jshint --config .jshintrc ./index.js ./lib ./test ./bin" 29 | }, 30 | "preferGlobal": true, 31 | "repository": { 32 | "type": "git", 33 | "url": "git+https://github.com/storj/storjshare-daemon.git" 34 | }, 35 | "keywords": [ 36 | "storj", 37 | "farmer", 38 | "storjshare", 39 | "share" 40 | ], 41 | "author": "Alexander Leitner ", 42 | "contributors": [ 43 | { 44 | "name": "Gordon Hall", 45 | "email": "gordon@storj.io" 46 | }, 47 | { 48 | "name": "littleskunk", 49 | "url": "https://github.com/littleskunk" 50 | }, 51 | { 52 | "name": "Steve Ashman", 53 | "url": "https://github.com/ssa3512" 54 | } 55 | ], 56 | "license": "AGPL-3.0", 57 | "bugs": { 58 | "url": "https://github.com/storj/storjshare-daemon/issues" 59 | }, 60 | "homepage": "https://github.com/storj/storjshare-daemon#readme", 61 | "dependencies": { 62 | "async": "^2.5.0", 63 | "blindfold": "0.0.1", 64 | "bytes": "^3.0.0", 65 | "cli-table": "^0.3.1", 66 | "colors": "^1.1.2", 67 | "commander": "^2.11.0", 68 | "daemon": "github:zipang/daemon.node#48d0977c26fb3a6a44ae99aae3471b9d5a761085", 69 | "diskusage": "^0.2.4", 70 | "dnode": "^1.2.2", 71 | "du": "^0.1.0", 72 | "editor": "^1.0.0", 73 | "fslogger": "^2.0.2", 74 | "kad-logger-json": "^0.1.2", 75 | "mkdirp": "^0.5.1", 76 | "moment": "^2.19.3", 77 | "pretty-ms": "^3.0.1", 78 | "rc": "^1.2.2", 79 | "storj-lib": "^8.7.2", 80 | "strip-json-comments": "^2.0.1", 81 | "tail": "^1.2.3", 82 | "touch": "3.1.0", 83 | "web3-utils": "^1.0.0-beta" 84 | }, 85 | "devDependencies": { 86 | "chai": "^2.2.0", 87 | "coveralls": "^2.11.2", 88 | "istanbul": "^0.3.13", 89 | "jshint": "2.8.0", 90 | "mocha": "^2.2.4", 91 | "proxyquire": "^1.7.3", 92 | "sinon": "^1.14.1" 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /example/farmer.config.json: -------------------------------------------------------------------------------- 1 | { 2 | // Set the STORJ/ERC20 wallet address for receiving contract payments 3 | "paymentAddress": "", 4 | // Subscribes to the given contract topics 5 | // See https://storj.github.io/core/tutorial-contract-topics.html 6 | "opcodeSubscriptions": [ 7 | "0f01020202", 8 | "0f02020202", 9 | "0f03020202" 10 | ], 11 | // An array of bridges to connect and accept contracts, 12 | // send exchange reports and discover network seeds. 13 | "bridges":[ 14 | { 15 | "url": "https://api.storj.io", 16 | "extendedKey": "xpub6AHweYHAxk1EhJSBctQD1nLWPog6Sy2eTpKQLExR1hfzTyyZQWvU4EYNXv1NJN7GpLYXnDLt4PzN874g6zSjAQdFCHZN7U7nbYKYVDUzD42" 17 | } 18 | ], 19 | // Known preferred seeds in form of a storj URI 20 | // Example: "storj://[ip.or.hostname]:[port]/[nodeid]" 21 | "seedList": [], 22 | // Interface to bind RPC server, use 0.0.0.0 for all interfaces or if you 23 | // have a public address, use that, else leave 127.0.0.1 and Storj Share 24 | // will try to determine your address 25 | "rpcAddress": "127.0.0.1", 26 | // Port to bind for RPC server, make sure this is forwarded if behind a 27 | // NAT or firewall - otherwise Storj Share will try to punch out 28 | "rpcPort": 4000, 29 | // doNotTraverseNat: true requires you to have an external ip address. 30 | // You can use a proxy to gain an external IP address. 31 | // doNotTraverseNat: false Enables NAT traversal strategies 32 | // first UPnP, then reverse HTTP tunnel 33 | // if that fails. Disable if you are public or using dynamic DNS 34 | "doNotTraverseNat": false, 35 | // Maximum number of tunnels to provide to the network 36 | // Tunnels help nodes with restrictive network configurations participate 37 | "maxTunnels": 0, 38 | // Maximum number of concurrent connections to allow 39 | "maxConnections": 150, 40 | // If providing tunnels, the starting and ending port range to open for 41 | // them 42 | "tunnelGatewayRange": { 43 | "min": 0, 44 | "max": 0 45 | }, 46 | // Number of times to retry joining the network and the wait time between 47 | "joinRetry": { 48 | "times": 3, 49 | "interval": 5000 50 | }, 51 | // Temporarily stop sending OFFER messages if more than this number of shard 52 | // transfers are active 53 | "offerBackoffLimit": 4, 54 | // ECDSA private key for your network identity, your Node ID is derived from 55 | // this and it is used to sign and verify messages 56 | "networkPrivateKey": "", 57 | // Determines how much detail is shown in the log: 58 | // 4 - DEBUG | 3 - INFO | 2 - WARN | 1 - ERROR | 0 - SILENT 59 | "loggerVerbosity": 3, 60 | // Path to write the log file to disk, leave empty to default to: 61 | // $HOME/.config/storjshare/logs/[nodeid]_date.log 62 | "loggerOutputFile": "", 63 | // Directory path to store contracts and shards 64 | "storagePath": "", 65 | // Amount of space to lease to the network, as human readable string 66 | // Valid units are B, KB, MB, GB, TB 67 | "storageAllocation": "2GB" 68 | // Max size of shards that will be accepted and stored 69 | // Use this and make this lower if you don't have a strong internet connection 70 | // "maxShardSize": "100MB" 71 | } 72 | -------------------------------------------------------------------------------- /bin/storjshare-logs.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | 'use strict'; 4 | 5 | const config = require('../lib/config/daemon'); 6 | const utils = require('../lib/utils'); 7 | const {Tail} = require('tail'); 8 | const colors = require('colors/safe'); 9 | const storjshare_logs = require('commander'); 10 | const fs = require('fs'); 11 | const path = require('path'); 12 | const FsLogger = require('fslogger'); 13 | 14 | storjshare_logs 15 | .description('tails the logs for the given node id') 16 | .option('-i, --nodeid ', 'id of the running node') 17 | .option('-l, --lines ', 'lines back to print') 18 | .option('-r, --remote ', 19 | 'hostname and optional port of the daemon') 20 | .parse(process.argv); 21 | 22 | if (!storjshare_logs.nodeid) { 23 | console.error('\n missing node id, try --help'); 24 | process.exit(1); 25 | } 26 | 27 | function getLastLines(filename, lines, callback) { 28 | let chunk = ''; 29 | let size = Math.max(0, fs.statSync(filename).size - (lines * 200)); 30 | 31 | fs.createReadStream(filename, { start: size }) 32 | .on('data', function(data) { 33 | chunk += data.toString(); 34 | }) 35 | .on('end', function() { 36 | chunk = chunk.split('\n').slice(-(lines + 1)); 37 | chunk.pop(); 38 | callback(chunk); 39 | }); 40 | } 41 | 42 | function prettyLog(line) { 43 | var output = ' '; 44 | 45 | try { 46 | line = JSON.parse(line); 47 | } catch (err) { 48 | return; 49 | } 50 | 51 | switch (line.level) { 52 | case 'debug': 53 | output += colors.magenta('[ debug ] '); 54 | break; 55 | case 'info': 56 | output += colors.cyan('[ info ] '); 57 | break; 58 | case 'warn': 59 | output += colors.yellow('[ warn ] '); 60 | break; 61 | case 'error': 62 | output += colors.red('[ error ] '); 63 | break; 64 | default: 65 | // noop 66 | } 67 | 68 | output += colors.gray( `[ ${line.timestamp} ]\n [ `); 69 | output += `${line.message}`; 70 | console.log(output); 71 | } 72 | 73 | let port = config.daemonRpcPort; 74 | let address = null; 75 | if (storjshare_logs.remote) { 76 | address = storjshare_logs.remote.split(':')[0]; 77 | if (storjshare_logs.remote.split(':').length > 1) { 78 | port = parseInt(storjshare_logs.remote.split(':')[1], 10); 79 | } 80 | } 81 | 82 | utils.connectToDaemon(port, function(rpc, sock) { 83 | process.on('exit', () => { 84 | sock.end(); 85 | process.exit(0); 86 | }); 87 | 88 | rpc.status((err, shares) => { 89 | if (err) { 90 | console.error(`\n cannot get status, reason: ${err.message}`); 91 | return sock.end(); 92 | } 93 | 94 | let logFileDir = null; 95 | 96 | for (let i = 0; i < shares.length; i++) { 97 | if (shares[i].id === storjshare_logs.nodeid) { 98 | logFileDir = shares[i].config.loggerOutputFile; 99 | break; 100 | } 101 | } 102 | 103 | try { 104 | if (!fs.statSync(logFileDir).isDirectory()) { 105 | logFileDir = path.dirname(logFileDir); 106 | } 107 | } catch (err) { 108 | logFileDir = path.dirname(logFileDir); 109 | } 110 | 111 | const fslogger = new FsLogger(logFileDir, storjshare_logs.nodeid); 112 | 113 | let currentFile = null; 114 | let logTail = null; 115 | 116 | setInterval(function() { 117 | if (currentFile !== fslogger._todaysFile()) { 118 | if (logTail instanceof Tail) { 119 | logTail.unwatch(); 120 | } 121 | 122 | currentFile = fslogger._todaysFile(); 123 | if (!utils.existsSync(fslogger._todaysFile())) { 124 | console.error(`\n no logs to show for ${storjshare_logs.nodeid}`); 125 | return sock.end(); 126 | } 127 | 128 | logTail = new Tail(fslogger._todaysFile()); 129 | let numLines = storjshare_logs.lines 130 | ? parseInt(storjshare_logs.lines) 131 | : 20; 132 | 133 | getLastLines(fslogger._todaysFile(), numLines, (lines) => { 134 | lines.forEach((line) => prettyLog(line)); 135 | logTail.on('line', (line) => prettyLog(line)); 136 | }); 137 | } 138 | 139 | }, 1000); 140 | 141 | }); 142 | }, address); 143 | -------------------------------------------------------------------------------- /script/farmer.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | 'use strict'; 4 | 5 | const utils = require('../lib/utils'); 6 | const storj = require('storj-lib'); 7 | const Logger = require('kad-logger-json'); 8 | const config = JSON.parse(JSON.stringify(require('../lib/config/farmer'))); 9 | const bytes = require('bytes'); 10 | const processIsManaged = typeof process.send === 'function'; 11 | 12 | let spaceAllocation = bytes.parse(config.storageAllocation); 13 | let farmerState = { 14 | bridges: {}, 15 | bridgesConnectionStatus: 0, 16 | percentUsed: '...', 17 | spaceUsed: '...', 18 | totalPeers: 0, 19 | lastActivity: Date.now(), 20 | contractCount: 0, 21 | dataReceivedCount: 0, 22 | portStatus: { 23 | listenPort: '...', 24 | connectionStatus: -1, 25 | connectionType: '' 26 | }, 27 | ntpStatus: { 28 | delta: '...', 29 | status: -1 30 | } 31 | }; 32 | 33 | config.keyPair = new storj.KeyPair(config.networkPrivateKey); 34 | config.logger = new Logger(config.loggerVerbosity); 35 | config.maxShardSize = config.maxShardSize ? bytes.parse(config.maxShardSize) : null; 36 | config.storageManager = new storj.StorageManager( 37 | new storj.EmbeddedStorageAdapter(config.storagePath), 38 | { 39 | maxCapacity: spaceAllocation, 40 | logger: config.logger 41 | } 42 | ); 43 | 44 | const farmer = storj.Farmer(config); 45 | 46 | config.logger.on('log', () => farmerState.lastActivity = Date.now()); 47 | config.logger.pipe(process.stdout); 48 | 49 | farmer.join((err) => { 50 | if (err) { 51 | config.logger.error(err.message); 52 | process.exit(1); 53 | } 54 | }) 55 | farmer.on('bridgeConnected', (bridge) => { 56 | farmerState.bridges[bridge.extendedKey] = bridge; 57 | config.logger.info('Connected to bridge: %s', bridge.url); 58 | }); 59 | farmer.connectBridges(); 60 | farmer.on('bridgesConnecting', function() { 61 | farmerState.bridgesConnectionStatus = 1; 62 | }); 63 | farmer.on('bridgeChallenge', (bridge) => { 64 | farmerState.bridgesConnectionStatus = 2; 65 | }); 66 | farmer.on('bridgesConnected', function() { 67 | farmerState.bridgesConnectionStatus = 3; 68 | }); 69 | 70 | function transportInitialized() { 71 | return farmer.transport._requiresTraversal !== undefined 72 | && farmer.transport._portOpen !== undefined; 73 | } 74 | 75 | function getPort() { 76 | if (transportInitialized()) { 77 | return farmer.transport._contact.port; 78 | } 79 | return '...'; 80 | } 81 | 82 | function getConnectionType() { 83 | if(!transportInitialized()) { 84 | return ''; 85 | } 86 | if (farmer._tunneled) { 87 | return '(Tunnel)'; 88 | } 89 | if (!farmer.transport._requiresTraversal 90 | && !farmer.transport._publicIp) { 91 | return '(Private)'; 92 | } 93 | return farmer.transport._requiresTraversal ? '(uPnP)' : '(TCP)'; 94 | } 95 | 96 | function getConnectionStatus() { 97 | if (!transportInitialized()) { 98 | return -1; 99 | } 100 | if (farmer.transport._portOpen) { 101 | return 0; 102 | } 103 | if (farmer._tunneled) { 104 | return 1; 105 | } 106 | if (!farmer.transport._requiresTraversal 107 | && !farmer.transport._publicIp) { 108 | return 2; 109 | } 110 | return -1; 111 | } 112 | 113 | function sendFarmerState() { 114 | farmerState.portStatus.listenPort = getPort(); 115 | farmerState.portStatus.connectionType = getConnectionType(); 116 | farmerState.portStatus.connectionStatus = getConnectionStatus(); 117 | farmerState.totalPeers = farmer.router.length; 118 | farmerState.contractCount = farmer._contractCount || 0; 119 | farmerState.dataReceivedCount = farmer._dataReceivedCount || 0; 120 | process.send(farmerState); 121 | } 122 | 123 | function updatePercentUsed() { 124 | config.storageManager._storage.size((err, result) => { 125 | if (result) { 126 | farmerState.spaceUsed = bytes(result); 127 | farmerState.spaceUsedBytes = result; 128 | farmerState.percentUsed = ((result / spaceAllocation) * 100).toFixed(); 129 | } 130 | }); 131 | } 132 | 133 | function updateNtpDelta() { 134 | storj.utils.getNtpTimeDelta(function(err, delta) { 135 | if (err) { 136 | farmerState.ntpStatus.delta = '...'; 137 | farmerState.ntpStatus.status = -1; 138 | } 139 | else { 140 | farmerState.ntpStatus.delta = delta + 'ms'; 141 | if (delta > 9999 || delta < -9999) { 142 | farmerState.ntpStatus.delta = '>9999ms'; 143 | } 144 | if (delta <= 500 && delta >= -500) { 145 | farmerState.ntpStatus.status = 0; 146 | } 147 | else { 148 | farmerState.ntpStatus.status = 2; 149 | } 150 | } 151 | }); 152 | } 153 | 154 | updatePercentUsed(); 155 | setInterval(updatePercentUsed, 10 * 60 * 1000); // Update space every 10 mins 156 | 157 | if (processIsManaged) { 158 | updateNtpDelta(); 159 | setInterval(updateNtpDelta, 10 * 60 * 1000); // Update ntp delta every 10 mins 160 | 161 | sendFarmerState(); 162 | setInterval(sendFarmerState, 10 * 1000); // Update state every 10 secs 163 | } 164 | -------------------------------------------------------------------------------- /bin/storjshare-status.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | 'use strict'; 4 | 5 | const prettyMs = require('pretty-ms'); 6 | const config = require('../lib/config/daemon'); 7 | const utils = require('../lib/utils'); 8 | const Table = require('cli-table'); 9 | const colors = require('colors/safe'); 10 | const storjshare_status = require('commander'); 11 | 12 | storjshare_status 13 | .description('prints the status of all managed nodes') 14 | .option('-r, --remote ', 15 | 'hostname and optional port of the daemon') 16 | .option('-j, --json', 17 | 'JSON formatted status of all managed nodes') 18 | .parse(process.argv); 19 | 20 | function getColoredValue(status, value) { 21 | switch (status) { 22 | case 0: 23 | // good to go 24 | return colors.green(value); 25 | case 1: 26 | //mark Tunnel Connections as bad 27 | return colors.red(value); 28 | case 2: 29 | //Not Connected - Private NET 30 | return colors.red(value); 31 | default: 32 | return value; 33 | } 34 | } 35 | 36 | function fixContractValue(contractCount) { 37 | contractCount = contractCount || 0; 38 | if (contractCount > 99999999) { 39 | return '>99999999'; 40 | } 41 | return contractCount; 42 | } 43 | 44 | let port = config.daemonRpcPort; 45 | let address = null; 46 | if (storjshare_status.remote) { 47 | address = storjshare_status.remote.split(':')[0]; 48 | if (storjshare_status.remote.split(':').length > 1) { 49 | port = parseInt(storjshare_status.remote.split(':')[1], 10); 50 | } 51 | } 52 | 53 | // Prepare json formatted status for each share 54 | function prepareJson(shares) { 55 | /*jshint maxcomplexity:11 */ 56 | /*jshint maxstatements:23 */ 57 | let json = []; 58 | 59 | for (let i = 0; i < shares.length; i++) { 60 | let share = shares[i]; 61 | 62 | json[i] = {}; 63 | json[i].id = share.id; 64 | 65 | let status = '?'; 66 | 67 | switch (share.state) { 68 | case 0: 69 | status = 'stopped'; 70 | break; 71 | case 1: 72 | status = 'running'; 73 | break; 74 | case 2: 75 | status = 'errored'; 76 | break; 77 | default: 78 | status = 'unknown'; 79 | } 80 | 81 | json[i].status = status; 82 | json[i].configPath = share.config.storagePath; 83 | json[i].uptime = prettyMs(share.meta.uptimeMs); 84 | json[i].restarts = share.meta.numRestarts || 0; 85 | json[i].peers = share.meta.farmerState.totalPeers || 0; 86 | json[i].allocs = fixContractValue( 87 | share.meta.farmerState.contractCount 88 | ); 89 | json[i].dataReceivedCount = fixContractValue( 90 | share.meta.farmerState.dataReceivedCount 91 | ); 92 | json[i].delta = share.meta.farmerState.ntpStatus.delta; 93 | json[i].port = share.meta.farmerState.portStatus.listenPort; 94 | json[i].shared = share.meta.farmerState.spaceUsed; 95 | json[i].sharedPercent = share.meta.farmerState.percentUsed; 96 | 97 | var bridgeCxStat = share.meta.farmerState.bridgesConnectionStatus; 98 | switch (bridgeCxStat) { 99 | case 0: 100 | json[i].bridgeConnectionStatus = 'disconnected'; 101 | break; 102 | case 1: 103 | json[i].bridgeConnectionStatus = 'connecting'; 104 | break; 105 | case 2: 106 | json[i].bridgeConnectionStatus = 'confirming'; 107 | break; 108 | case 3: 109 | json[i].bridgeConnectionStatus = 'connected'; 110 | break; 111 | default: 112 | break; 113 | } 114 | } 115 | 116 | return JSON.stringify(json); 117 | } 118 | 119 | utils.connectToDaemon(port, function(rpc, sock) { 120 | /*jshint maxcomplexity:10 */ 121 | rpc.status(function(err, shares) { 122 | if (storjshare_status.json) { 123 | // Print out json formatted share statuses 124 | const json = prepareJson(shares); 125 | console.log(json); 126 | } else { 127 | let table = new Table({ 128 | head: ['Node', 'Status', 'Uptime', 'Restarts', 'Peers', 129 | 'Allocs', 'Delta', 'Port', 'Shared', 'Bridges'], 130 | style: { 131 | head: ['cyan', 'bold'], 132 | border: [] 133 | }, 134 | colWidths: [45, 9, 10, 10, 9, 15, 9, 10, 11, 14] 135 | }); 136 | shares.forEach((share) => { 137 | let status = '?'; 138 | 139 | switch (share.state) { 140 | case 0: 141 | status = colors.gray('stopped'); 142 | break; 143 | case 1: 144 | status = colors.green('running'); 145 | break; 146 | case 2: 147 | status = colors.red('errored'); 148 | break; 149 | default: 150 | status = 'unknown'; 151 | } 152 | 153 | let portStatus = share.meta.farmerState.portStatus; 154 | let port = getColoredValue(portStatus.connectionStatus, 155 | portStatus.listenPort); 156 | let connectionType = getColoredValue(portStatus.connectionStatus, 157 | portStatus.connectionType); 158 | 159 | let ntpStatus = getColoredValue(share.meta.farmerState.ntpStatus.status, 160 | share.meta.farmerState.ntpStatus.delta); 161 | 162 | let contracts = fixContractValue(share.meta.farmerState.contractCount); 163 | let dataReceived = fixContractValue( 164 | share.meta.farmerState.dataReceivedCount); 165 | 166 | var bridgeCxStat = share.meta.farmerState.bridgesConnectionStatus; 167 | var bridgeCxString = '...'; 168 | switch (bridgeCxStat) { 169 | case 0: 170 | bridgeCxString = colors.gray('disconnected'); 171 | break; 172 | case 1: 173 | bridgeCxString = colors.yellow('connecting'); 174 | break; 175 | case 2: 176 | bridgeCxString = colors.orange('confirming'); 177 | break; 178 | case 3: 179 | bridgeCxString = colors.green('connected'); 180 | break; 181 | default: 182 | break; 183 | } 184 | 185 | table.push([ 186 | `${share.id}\n → ${share.config.storagePath}`, 187 | status, 188 | prettyMs(share.meta.uptimeMs), 189 | share.meta.numRestarts || 0, 190 | share.meta.farmerState.totalPeers || 0, 191 | contracts + '\n' + `${dataReceived} received`, 192 | ntpStatus, 193 | port + '\n' + connectionType, 194 | share.meta.farmerState.spaceUsed + '\n' + 195 | `(${share.meta.farmerState.percentUsed}%)`, 196 | bridgeCxString 197 | ]); 198 | }); 199 | console.log('\n' + table.toString()); 200 | } 201 | sock.end(); 202 | }); 203 | }, address); 204 | -------------------------------------------------------------------------------- /bin/storjshare-create.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | 'use strict'; 4 | 5 | const blindfold = require('blindfold'); 6 | const editor = require('editor'); 7 | const {homedir} = require('os'); 8 | const fs = require('fs'); 9 | const storj = require('storj-lib'); 10 | const path = require('path'); 11 | const mkdirp = require('mkdirp'); 12 | const stripJsonComments = require('strip-json-comments'); 13 | const storjshare_create = require('commander'); 14 | const {execSync} = require('child_process'); 15 | const utils = require('../lib/utils'); 16 | const touch = require('touch'); 17 | 18 | const defaultConfig = JSON.parse(stripJsonComments(fs.readFileSync( 19 | path.join(__dirname, '../example/farmer.config.json') 20 | ).toString())); 21 | 22 | function whichEditor() { 23 | 24 | const editors = ['vi', 'nano']; 25 | 26 | function checkIsInstalled(editor) { 27 | try { 28 | execSync('which ' + editor); 29 | } catch (err) { 30 | return false; 31 | } 32 | 33 | return true; 34 | } 35 | 36 | for (let i = 0; i < editors.length; i++) { 37 | if (checkIsInstalled(editors[i])) { 38 | return editors[i]; 39 | } 40 | } 41 | 42 | return null; 43 | } 44 | 45 | storjshare_create 46 | .description('generates a new node configuration') 47 | .option('--storj ', 'specify the STORJ address (required)') 48 | .option('--key ', 'specify the private key') 49 | .option('--storage ', 'specify the storage path') 50 | .option('--size ', 'specify node size (ex: 10GB, 1TB)') 51 | .option('--rpcport ', 'specify the rpc port number') 52 | .option('--rpcaddress ', 'specify the rpc address') 53 | .option('--maxtunnels ', 'specify the max tunnels') 54 | .option('--tunnelportmin ', 'specify min gateway port') 55 | .option('--tunnelportmax ', 'specify max gateway port') 56 | .option('--manualforwarding', 'do not use nat traversal strategies') 57 | .option('--verbosity ', 'specify the logger verbosity') 58 | .option('--logdir ', 'specify the log directory') 59 | .option('--noedit', 'do not open generated config in editor') 60 | .option('-o, --outfile ', 'write config to path') 61 | .parse(process.argv); 62 | 63 | if (!storjshare_create.storj) { 64 | console.error('\n no payment address was given, try --help'); 65 | process.exit(1); 66 | } 67 | 68 | if (!utils.isValidEthereumAddress(storjshare_create.storj)) { 69 | console.error('\n SJCX addresses are no longer supported. \ 70 | Please enter ERC20 compatible ETH wallet address'); 71 | process.exit(1); 72 | } 73 | 74 | if (!storjshare_create.key) { 75 | storjshare_create.key = storj.KeyPair().getPrivateKey(); 76 | } 77 | 78 | if (!storjshare_create.storage) { 79 | storjshare_create.storage = path.join( 80 | homedir(), 81 | '.config/storjshare/shares', 82 | storj.KeyPair(storjshare_create.key).getNodeID() 83 | ); 84 | mkdirp.sync(storjshare_create.storage); 85 | } 86 | 87 | if (!storjshare_create.outfile) { 88 | const configDir = path.join(homedir(), '.config/storjshare/configs'); 89 | storjshare_create.outfile = path.join( 90 | configDir, storj.KeyPair(storjshare_create.key).getNodeID() + '.json' 91 | ); 92 | mkdirp.sync(configDir); 93 | touch.sync(storjshare_create.outfile); 94 | } 95 | 96 | if (!storjshare_create.logdir) { 97 | storjshare_create.logdir = path.join( 98 | homedir(), 99 | '.config/storjshare/logs' 100 | ); 101 | mkdirp.sync(storjshare_create.logdir); 102 | } 103 | 104 | if (storjshare_create.size && 105 | !storjshare_create.size.match(/[0-9]+(T|M|G|K)?B/g)) { 106 | console.error('\n Invalid storage size specified: '+ 107 | storjshare_create.size); 108 | process.exit(1); 109 | } 110 | 111 | let exampleConfigPath = path.join(__dirname, '../example/farmer.config.json'); 112 | let exampleConfigString = fs.readFileSync(exampleConfigPath).toString(); 113 | 114 | function getDefaultConfigValue(prop) { 115 | return { 116 | value: blindfold(defaultConfig, prop), 117 | type: typeof blindfold(defaultConfig, prop) 118 | }; 119 | } 120 | 121 | function replaceDefaultConfigValue(prop, value) { 122 | let defaultValue = getDefaultConfigValue(prop); 123 | 124 | function toStringReplace(prop, value, type) { 125 | switch (type) { 126 | case 'string': 127 | value = value.split('\\').join('\\\\'); // NB: Hack windows paths 128 | return`"${prop}": "${value}"`; 129 | case 'boolean': 130 | case 'number': 131 | return `"${prop}": ${value}`; 132 | default: 133 | return ''; 134 | } 135 | } 136 | 137 | let validVerbosities = new RegExp(/^[0-4]$/); 138 | if (storjshare_create.verbosity && 139 | !validVerbosities.test(storjshare_create.verbosity)) { 140 | console.error('\n * Invalid verbosity.\n * Accepted values: 4 - DEBUG | \ 141 | 3 - INFO | 2 - WARN | 1 - ERROR | 0 - SILENT\n * Default value of %s \ 142 | will be used.', getDefaultConfigValue('loggerVerbosity').value); 143 | storjshare_create.verbosity = null; 144 | } 145 | 146 | prop = prop.split('.').pop(); 147 | exampleConfigString = exampleConfigString.replace( 148 | toStringReplace(prop, defaultValue.value, defaultValue.type), 149 | toStringReplace(prop, value, defaultValue.type) 150 | ); 151 | } 152 | 153 | replaceDefaultConfigValue('paymentAddress', storjshare_create.storj); 154 | replaceDefaultConfigValue('networkPrivateKey', storjshare_create.key); 155 | replaceDefaultConfigValue('storagePath', 156 | path.normalize(storjshare_create.storage)); 157 | replaceDefaultConfigValue('loggerOutputFile', 158 | path.normalize(storjshare_create.logdir)); 159 | 160 | const optionalReplacements = [ 161 | { option: storjshare_create.size, name: 'storageAllocation' }, 162 | { option: storjshare_create.rpcaddress, name: 'rpcAddress' }, 163 | { option: storjshare_create.rpcport, name: 'rpcPort' }, 164 | { option: storjshare_create.maxtunnels, name: 'maxTunnels' }, 165 | { option: storjshare_create.tunnelportmin, name: 'tunnelGatewayRange.min' }, 166 | { option: storjshare_create.tunnelportmax, name: 'tunnelGatewayRange.max' }, 167 | { option: storjshare_create.manualforwarding, name: 'doNotTraverseNat' }, 168 | { option: storjshare_create.verbosity, name: 'loggerVerbosity' } 169 | ]; 170 | 171 | optionalReplacements.forEach((repl) => { 172 | if (repl.option) { 173 | replaceDefaultConfigValue(repl.name, repl.option); 174 | } 175 | }); 176 | 177 | let outfile = path.isAbsolute(storjshare_create.outfile) ? 178 | path.normalize(storjshare_create.outfile) : 179 | path.join(process.cwd(), storjshare_create.outfile); 180 | 181 | try { 182 | fs.writeFileSync(outfile, exampleConfigString); 183 | } catch (err) { 184 | console.log (`\n failed to write config, reason: ${err.message}`); 185 | process.exit(1); 186 | } 187 | 188 | console.log(`\n * configuration written to ${outfile}`); 189 | 190 | if (!storjshare_create.noedit) { 191 | console.log(' * opening in your favorite editor to tweak before running'); 192 | editor(outfile, { 193 | // NB: Not all distros ship with vim, so let's use GNU Nano 194 | editor: process.platform === 'win32' 195 | ? null 196 | : whichEditor() 197 | }, () => { 198 | console.log(' ...'); 199 | console.log(` * use new config: storjshare start --config ${outfile}`); 200 | }); 201 | } 202 | -------------------------------------------------------------------------------- /lib/utils.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @module utils 3 | */ 4 | 5 | 'use strict'; 6 | 7 | const dnode = require('dnode'); 8 | const net = require('net'); 9 | const fs = require('fs'); 10 | const storj = require('storj-lib'); 11 | const {bitcore} = storj.deps; 12 | const du = require('du'); // Get amount used 13 | const disk = require('diskusage'); // Get amount free 14 | const assert = require('assert'); 15 | const bytes = require('bytes'); 16 | const web3utils = require('web3-utils'); 17 | 18 | /** 19 | * Validate the given payout address 20 | * @param {String} address 21 | */ 22 | exports._isValidPayoutAddress = function(address) { 23 | return bitcore.Address.isValid(address) || 24 | bitcore.Address.isValid(address, bitcore.Networks.testnet) || 25 | this.isValidEthereumAddress(address); 26 | }; 27 | 28 | /** 29 | * Validate the given payout address is an Ethereum address 30 | * @param {String} address 31 | */ 32 | exports.isValidEthereumAddress = function(address) { 33 | //Disallow contract and contract owner addresses 34 | //Stops users from accidentally copying the wrong address 35 | const disallowAddresses = [ 36 | '0xb64ef51c888972c908cfacf59b47c1afbc0ab8ac', 37 | '0x00f6bf3c5033e944feddb3dc8ffb4d47af17ef0b' 38 | ]; 39 | if (typeof address !== 'string') { 40 | return false; 41 | } else if (disallowAddresses.indexOf(address.toLowerCase()) >= 0) { 42 | return false; 43 | } 44 | return /^0x/.test(address) && web3utils.isAddress(address); 45 | }; 46 | 47 | /** 48 | * Validate the given dataserv directory 49 | * @param {String} directory 50 | */ 51 | exports._isValidDirectory = function(directory) { 52 | return this.existsSync(directory); 53 | }; 54 | 55 | /** 56 | * Validate the given size 57 | * @param {String} size 58 | */ 59 | exports._isValidSize = function(size) { 60 | return typeof size === 'number' 61 | && size >= 0 62 | && size <= 8 * Math.pow(2, 40); // 8TiB 63 | }; 64 | 65 | /** 66 | * Validates a given tab config 67 | * @param {Object} config 68 | */ 69 | exports.validate = function(config) { 70 | assert(this._isValidPayoutAddress(config.paymentAddress), 71 | 'Invalid payout address'); 72 | assert(this._isValidDirectory(config.storagePath), `Invalid directory: \ 73 | ${config.storagePath} does not exist`); 74 | assert(this._isValidSize(bytes.parse(config.storageAllocation)), 75 | 'Invalid storage size'); 76 | assert(this._isValidDirectory(config.storagePath), 77 | 'Could not create Shard Directory'); 78 | }; 79 | 80 | /** 81 | * Attempts to apply common fixes to a config 82 | * @param {Object} config 83 | */ 84 | exports.repairConfig = function(config) { 85 | // Check to see if the size is not using a storage unit 86 | if(!isNaN(parseInt(config.storageAllocation)) 87 | && this._isValidSize(config.storageAllocation)) { 88 | config.storageAllocation = config.storageAllocation.toString() + 'B'; 89 | } 90 | return config; 91 | }; 92 | 93 | /** 94 | * Validates the space being allocated exists 95 | * @param {Object} config 96 | */ 97 | exports.validateAllocation = function(conf, callback) { 98 | const self = this; 99 | 100 | if (!self._isValidStorageAllocationFormat(conf.storageAllocation)) { 101 | if (isNaN(conf.storageAllocation)) { 102 | return callback( 103 | new Error('Invalid storage size specified: '+ conf.storageAllocation) 104 | ); 105 | } 106 | 107 | conf.storageAllocation = conf.storageAllocation.toString() + 'B'; 108 | } 109 | 110 | callback(null); 111 | }; 112 | 113 | /** 114 | * Check if file exists 115 | * @param {String} file - Path to file 116 | */ 117 | exports.existsSync = function(file) { 118 | try { 119 | fs.statSync(file); 120 | } catch(err) { 121 | return !(err); 122 | } 123 | 124 | return true; 125 | }; 126 | 127 | /** 128 | * Check if StorageAllocation is formatted properly (Size + Unit) 129 | * @param {String} storage - storage Allocation from config 130 | */ 131 | exports._isValidStorageAllocationFormat = function(storageAllocation) { 132 | if (!storageAllocation.toString().match( 133 | /[0-9]+([Tt]|[Mm]|[Gg]|[Kk])?[Bb]/g) 134 | ) { 135 | return false; 136 | } 137 | 138 | return true; 139 | }; 140 | 141 | /** 142 | * Recursively determines the size of a directory 143 | * @param {String} dir - Directory to traverse 144 | * @param {Function} callback 145 | */ 146 | exports.getDirectorySize = function(dir, callback) { 147 | /* istanbul ignore next */ 148 | du(dir, { 149 | filter: function(f) { 150 | return f.indexOf('contracts.db') !== -1 || 151 | f.indexOf('sharddata.kfs') !== -1; 152 | } 153 | }, callback); 154 | }; 155 | 156 | /** 157 | * Get free space on disk of path 158 | * @param {String} path 159 | */ 160 | /* istanbul ignore next */ 161 | exports.getFreeSpace = function(path, callback) { 162 | if (!exports.existsSync(path)) { 163 | return callback(null, 0); 164 | } 165 | 166 | disk.check(path, function(err, info) { 167 | if (err) { 168 | return callback(err); 169 | } 170 | 171 | return callback(null, info.available); 172 | }); 173 | }; 174 | 175 | /** 176 | * Checks whether a port is currently in use or open 177 | * Callback is of form (err, result) 178 | * @param {Number} port 179 | * @param {Function} callback 180 | */ 181 | exports.portIsAvailable = function(port, callback) { 182 | if(typeof port !== 'number' || port < 0 || port > 65535) { 183 | return callback('Invalid port'); 184 | } else if (port <= 1024) { 185 | return callback( 186 | 'Using a port in the well-known range is strongly discouraged'); 187 | } 188 | let testServer = net.createServer() 189 | .once('error', function() { 190 | testServer.once('close', function() { 191 | callback(null, false); 192 | }) 193 | .close(); 194 | }) 195 | .once('listening', function() { 196 | testServer.once('close', function() { 197 | callback(null, true); 198 | }) 199 | .close(); 200 | }) 201 | .listen(port); 202 | }; 203 | 204 | /** 205 | * Checks the status of the daemon RPC server 206 | * @param {Number} port 207 | * @param {Function} callback 208 | * @param {String} hostname - optional 209 | */ 210 | exports.checkDaemonRpcStatus = function(port, callback, hostname = null) { 211 | if (!hostname) { 212 | hostname = '127.0.0.1'; 213 | } 214 | const sock = net.connect(port, hostname); 215 | 216 | sock.once('error', function() { 217 | callback(false); 218 | }); 219 | 220 | sock.once('connect', () => { 221 | sock.end(); 222 | callback(true); 223 | }); 224 | }; 225 | 226 | /** 227 | * Connects to the daemon and callback with rpc 228 | * @param {Number} port 229 | * @param {Function} callback 230 | * @param {String} hostname - optional 231 | */ 232 | exports.connectToDaemon = function(port, callback, hostname = null) { 233 | if (!hostname) { 234 | hostname = '127.0.0.1'; 235 | } 236 | const sock = dnode.connect(hostname, port); 237 | 238 | sock.on('error', function() { 239 | process.exitCode = 1; 240 | console.error('\n daemon is not running, try: storjshare daemon'); 241 | }); 242 | 243 | sock.on('remote', (rpc) => callback(rpc, sock)); 244 | }; 245 | 246 | /** 247 | * Get node Id by Private Key 248 | * @param {String} privateKey 249 | */ 250 | exports.getNodeID = function(privateKey) { 251 | let nodeId = null; 252 | try { 253 | nodeId = storj.KeyPair(privateKey).getNodeID(); 254 | } catch (err) { 255 | return null; 256 | } 257 | 258 | return nodeId; 259 | }; 260 | -------------------------------------------------------------------------------- /test/utils.unit.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const utils = require('../lib/utils'); 4 | const proxyquire = require('proxyquire'); 5 | const sinon = require('sinon'); 6 | const {expect} = require('chai'); 7 | const {EventEmitter} = require('events'); 8 | const net = require('net'); 9 | 10 | describe('module:utils', function() { 11 | 12 | describe('#_isValidPayoutAddress', function() { 13 | 14 | it('should return true for valid mainnet', function() { 15 | expect(utils._isValidPayoutAddress( 16 | '1ATyTAjFpeU2RrwVzk9YEa2vxQJos4xdqX' 17 | )).to.equal(true); 18 | }); 19 | 20 | it('should return true for valid testnet', function() { 21 | expect(utils._isValidPayoutAddress( 22 | '2MsP1UsraqLpY7A1ZeegT7H7okWWkBbk2AS' 23 | )).to.equal(true); 24 | }); 25 | 26 | it('should return false for invalid address', function() { 27 | expect(utils._isValidPayoutAddress( 28 | '1234 Fake Street' 29 | )).to.equal(false); 30 | }); 31 | 32 | }); 33 | 34 | describe('#isValidEthereumAddress', function() { 35 | 36 | it('should return true for checksumed address', function() { 37 | expect(utils.isValidEthereumAddress( 38 | '0xC2D7CF95645D33006175B78989035C7c9061d3F9' 39 | )).to.equal(true); 40 | }); 41 | 42 | it('should return true for normalized address', function() { 43 | expect(utils.isValidEthereumAddress( 44 | '0xc2d7cf95645d33006175b78989035c7c9061d3f9' 45 | )).to.equal(true); 46 | }); 47 | 48 | it('should return true for uppercase address', function() { 49 | expect(utils.isValidEthereumAddress( 50 | '0xC2D7CF95645D33006175B78989035C7C9061D3F9' 51 | )).to.equal(true); 52 | }); 53 | 54 | it('should return false for invalid checksum', function() { 55 | expect(utils.isValidEthereumAddress( 56 | '0xC2D7Cf95645D33006175B78989035C7c9061d3F9' 57 | )).to.equal(false); 58 | }); 59 | 60 | it('should return false for public key hash digest', function() { 61 | expect(utils.isValidEthereumAddress( 62 | 'C2D7CF95645D33006175B78989035C7c9061d3F9' 63 | )).to.equal(false); 64 | }); 65 | 66 | it('should return false for invalid address', function() { 67 | expect(utils.isValidEthereumAddress( 68 | '1234 Fake Street' 69 | )).to.equal(false); 70 | }); 71 | 72 | it('should return false for contract address', function() { 73 | expect(utils.isValidEthereumAddress( 74 | '0xb64ef51c888972c908cfacf59b47c1afbc0ab8ac' 75 | )).to.equal(false); 76 | }); 77 | 78 | it('should return false for contract owner address', function() { 79 | expect(utils.isValidEthereumAddress( 80 | '0x00f6bf3c5033e944feddb3dc8ffb4d47af17ef0b' 81 | )).to.equal(false); 82 | }); 83 | 84 | }); 85 | 86 | describe('#_isValidDirectory', function() { 87 | 88 | it('should return the the result of existsSync', function() { 89 | let existsSync = sinon.stub(utils, 'existsSync').returns(true); 90 | expect(utils._isValidDirectory('some/directory/path')).to.equal(true); 91 | existsSync.restore(); 92 | }); 93 | 94 | it('should return the the result of existsSync', function() { 95 | let existsSync = sinon.stub(utils, 'existsSync').returns(false); 96 | expect(utils._isValidDirectory('some/directory/path')).to.equal(false); 97 | existsSync.restore(); 98 | }); 99 | 100 | }); 101 | 102 | describe('#_isValidSize', function() { 103 | 104 | it('should return true for positive numbers', function() { 105 | expect(utils._isValidSize(1)).to.equal(true); 106 | }); 107 | 108 | it('should return false for less than 0', function() { 109 | expect(utils._isValidSize(0)).to.equal(true); 110 | expect(utils._isValidSize(-1)).to.equal(false); 111 | }); 112 | 113 | it('should return false for undefined', function() { 114 | expect(utils._isValidSize()).to.equal(false); 115 | }); 116 | 117 | }); 118 | 119 | describe('#validate', function() { 120 | 121 | it('should not throw if valid', function() { 122 | let _isValidDirectory = sinon.stub( 123 | utils, 124 | '_isValidDirectory' 125 | ).returns(true); 126 | expect(function() { 127 | utils.validate({ 128 | paymentAddress: '2MsP1UsraqLpY7A1ZeegT7H7okWWkBbk2AS', 129 | storagePath: 'some/directory/path', 130 | storageAllocation: '1KB' 131 | }); 132 | }).to.not.throw(Error); 133 | _isValidDirectory.restore(); 134 | }); 135 | 136 | it('should throw if not valid', function() { 137 | let _isValidDirectory = sinon.stub( 138 | utils, 139 | '_isValidDirectory' 140 | ).returns(false); 141 | expect(function() { 142 | utils.validate({ 143 | paymentAddress: '2MsP1UsraqLpY7A1ZeegT7H7okWWkBbk2AS', 144 | storagePath: 'some/directory/path', 145 | storageAllocation: '1KB' 146 | }); 147 | }).to.throw(Error); 148 | _isValidDirectory.restore(); 149 | }); 150 | 151 | }); 152 | 153 | describe('#repairConfig', function() { 154 | 155 | it('should convert an unspecified size to bytes', function() { 156 | let dummyConfig = { 157 | storageAllocation: 1048576 158 | }; 159 | utils.repairConfig(dummyConfig); 160 | expect(dummyConfig.storageAllocation).to.equal('1048576B'); 161 | }); 162 | 163 | }); 164 | 165 | describe('#validateAllocation', function() { 166 | 167 | it('should callback null if valid', function(done) { 168 | let getFreeSpace = sinon.stub( 169 | utils, 170 | 'getFreeSpace' 171 | ).callsArgWith(1, null, 1024); 172 | let getDirectorySize = sinon.stub( 173 | utils, 174 | 'getDirectorySize' 175 | ).callsArgWith(1, null, 512); 176 | utils.validateAllocation({ 177 | storageAllocation: '512B', 178 | storagePath: 'some/directory/path' 179 | }, function(err) { 180 | getFreeSpace.restore(); 181 | getDirectorySize.restore(); 182 | expect(err).to.equal(null); 183 | done(); 184 | }); 185 | }); 186 | 187 | }); 188 | 189 | describe('#portIsAvailable', function() { 190 | 191 | it('should callback error if argument is not a valid port', function(done) { 192 | utils.portIsAvailable('Not a port number', function(err, result) { 193 | expect(err).to.equal('Invalid port'); 194 | expect(result).to.equal(undefined); 195 | done(); 196 | }); 197 | }); 198 | 199 | it('should callback error if port is in well-known range', function(done) { 200 | utils.portIsAvailable(77, function(err, result) { 201 | expect(err).to.equal( 202 | 'Using a port in the well-known range is strongly discouraged'); 203 | done(); 204 | expect(result).to.equal(undefined); 205 | }); 206 | }); 207 | 208 | it('should hopefully return true on this semi-random port', function(done) { 209 | utils.portIsAvailable(17026, function(err, result) { 210 | expect(err).to.equal(null); 211 | expect(result).to.equal(true); 212 | done(); 213 | }); 214 | }); 215 | 216 | it('should return false on a port already in use', function(done) { 217 | const server = net.createServer(); 218 | server.once('error', function(err) { 219 | done(err); 220 | }) 221 | .once('listening', function() { 222 | utils.portIsAvailable(17027, function(err, result) { 223 | expect(err).to.equal(null); 224 | expect(result).to.equal(false); 225 | server.once('close', function() { 226 | done(); 227 | }).close(); 228 | }); 229 | }) 230 | .listen(17027); 231 | }); 232 | 233 | }); 234 | 235 | describe('#existsSync', function() { 236 | 237 | it('should return true if statSync success', function() { 238 | let _utils = proxyquire('../lib/utils', { 239 | fs: { 240 | statSync: sinon.stub().returns({}) 241 | } 242 | }); 243 | expect(_utils.existsSync('some/directory/path')).to.equal(true); 244 | }); 245 | 246 | it('should return false if statSync false', function() { 247 | let _utils = proxyquire('../lib/utils', { 248 | fs: { 249 | statSync: sinon.stub().throws(new Error('')) 250 | } 251 | }); 252 | expect(_utils.existsSync('some/directory/path')).to.equal(false); 253 | }); 254 | 255 | }); 256 | 257 | describe('#checkDaemonRpcStatus', function() { 258 | 259 | it('should callback true if connect', function(done) { 260 | let sock = new EventEmitter(); 261 | sock.end = sinon.stub(); 262 | let _utils = proxyquire('../lib/utils', { 263 | net: { 264 | connect: () => { 265 | setTimeout(() => sock.emit('connect'), 50); 266 | return sock; 267 | } 268 | } 269 | }); 270 | _utils.checkDaemonRpcStatus(45015, (isRunning) => { 271 | expect(isRunning).to.equal(true); 272 | done(); 273 | }); 274 | }); 275 | 276 | it('should callback false if error', function(done) { 277 | let sock = new EventEmitter(); 278 | sock.end = sinon.stub(); 279 | let _utils = proxyquire('../lib/utils', { 280 | net: { 281 | connect: () => { 282 | setTimeout(() => sock.emit('error', 283 | new Error('ECONNREFUSED')), 50); 284 | return sock; 285 | } 286 | } 287 | }); 288 | _utils.checkDaemonRpcStatus(45015, (isRunning) => { 289 | expect(isRunning).to.equal(false); 290 | done(); 291 | }); 292 | }); 293 | 294 | }); 295 | 296 | describe('#connectToDaemon', function() { 297 | 298 | it('should set the process exit code and log error', function(done) { 299 | let socket = new EventEmitter(); 300 | let error = sinon.stub(console, 'error'); 301 | let _utils = proxyquire('../lib/utils', { 302 | dnode: { 303 | connect: () => socket 304 | } 305 | }); 306 | _utils.connectToDaemon(45015, () => null); 307 | setImmediate(() => { 308 | socket.emit('error', new Error('Failed to connect')); 309 | setImmediate(() => { 310 | error.restore(); 311 | expect(process.exitCode).to.equal(1); 312 | process.exitCode = 0; 313 | done(); 314 | }); 315 | }); 316 | }); 317 | 318 | it('should callback with remote object and socket', function(done) { 319 | let socket = new EventEmitter(); 320 | let rpc = {}; 321 | let _utils = proxyquire('../lib/utils', { 322 | dnode: { 323 | connect: () => socket 324 | } 325 | }); 326 | _utils.connectToDaemon(45015, (_rpc, sock) => { 327 | expect(_rpc).to.equal(rpc); 328 | expect(sock).to.equal(socket); 329 | done(); 330 | }); 331 | setImmediate(() => socket.emit('remote', rpc)); 332 | }); 333 | 334 | }); 335 | 336 | }); 337 | -------------------------------------------------------------------------------- /lib/api.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const async = require('async'); 4 | const fs = require('fs'); 5 | const {statSync, readFileSync} = require('fs'); 6 | const stripJsonComments = require('strip-json-comments'); 7 | const FsLogger = require('fslogger'); 8 | const JsonLogger = require('kad-logger-json'); 9 | const {fork} = require('child_process'); 10 | const utils = require('./utils'); 11 | const path = require('path'); 12 | const { cpus } = require('os'); 13 | const {homedir} = require('os'); 14 | 15 | /** Class representing a local RPC API's handlers */ 16 | class RPC { 17 | 18 | /** 19 | * Creates a environment to manage node processes 20 | * @param {Object} options 21 | * @param {Number} options.logVerbosity 22 | */ 23 | constructor(options={}) { 24 | this.jsonlogger = new JsonLogger(options.logVerbosity); 25 | this.shares = new Map(); 26 | } 27 | 28 | /** 29 | * Logs the message by pushing it out the stream 30 | * @param {String} message 31 | * @param {String} level 32 | */ 33 | _log(msg, level='info') { 34 | this.jsonlogger[level](msg); 35 | } 36 | 37 | /** 38 | * Handles IPC messages from a running node 39 | * @private 40 | */ 41 | _processShareIpc(share, msg) { 42 | // NB: We receive a complete state object from nodes when an event 43 | // NB: occurs that updates the state object 44 | share.meta.farmerState = msg; 45 | } 46 | 47 | /** 48 | * Reads the config file and returns the parsed version 49 | * @private 50 | */ 51 | _readConfig(configPath) { 52 | let config = null; 53 | 54 | try { 55 | statSync(configPath); 56 | } catch (err) { 57 | throw new Error(`failed to read config at ${configPath}`); 58 | } 59 | 60 | try { 61 | config = JSON.parse(stripJsonComments( 62 | readFileSync(configPath).toString() 63 | )); 64 | } catch (err) { 65 | throw new Error(`failed to parse config at ${configPath}`); 66 | } 67 | 68 | config = utils.repairConfig(config); 69 | 70 | try { 71 | utils.validate(config); 72 | } catch (err) { 73 | throw new Error(err.message.toLowerCase()); 74 | } 75 | 76 | return config; 77 | } 78 | 79 | /** 80 | * Starts a share process with the given configuration 81 | * @param {String} configPath 82 | * @param {Boolean} unsafeFlag 83 | * @param {RPC~startCallback} 84 | * @see https://storj.github.io/core/FarmerInterface.html 85 | */ 86 | start(configPath, callback, unsafeFlag=false) { 87 | /*jshint maxcomplexity:7 */ 88 | let config = null; 89 | 90 | if (this.running >= cpus().length && !unsafeFlag) { 91 | return callback(new Error('insufficient system resources available')); 92 | } 93 | 94 | try { 95 | config = this._readConfig(configPath); 96 | } catch (err) { 97 | return callback(err); 98 | } 99 | 100 | const nodeId = utils.getNodeID(config.networkPrivateKey); 101 | if (nodeId === null) { 102 | return callback(new Error('Invalid Private Key')); 103 | } 104 | 105 | const share = this.shares.get(nodeId) || { 106 | config: config, 107 | meta: { 108 | uptimeMs: 0, 109 | farmerState: {}, 110 | numRestarts: 0 111 | }, 112 | process: null, 113 | readyState: 0, 114 | path: configPath 115 | }; 116 | 117 | this._log(`attempting to start node with config at path ${configPath}`); 118 | 119 | if (this.shares.has(nodeId) && this.shares.get(nodeId).readyState === 1) { 120 | return callback(new Error(`node ${nodeId} is already running`)); 121 | } 122 | 123 | utils.validateAllocation(share.config, (err) => { 124 | if (err) { 125 | return callback(new Error(err.message.toLowerCase())); 126 | } 127 | 128 | share.meta.uptimeMs = 0; 129 | /* istanbul ignore next */ 130 | let uptimeCounter = setInterval(() => share.meta.uptimeMs += 1000, 1000); 131 | 132 | // NB: Fork the actual farmer process, passing it the configuration 133 | share.process = fork( 134 | path.join(__dirname, '../script/farmer.js'), 135 | ['--config', configPath], 136 | { 137 | stdio: [0, 'pipe', 'pipe', 'ipc'] 138 | } 139 | ); 140 | share.readyState = RPC.SHARE_STARTED; 141 | 142 | let loggerOutputFile = !share.config.loggerOutputFile 143 | ? path.join(homedir(), '.config/storjshare/logs') 144 | : share.config.loggerOutputFile; 145 | 146 | try { 147 | if (!fs.statSync(loggerOutputFile).isDirectory()) { 148 | loggerOutputFile = path.dirname(loggerOutputFile); 149 | } 150 | } catch (err) { 151 | loggerOutputFile = path.dirname(loggerOutputFile); 152 | } 153 | 154 | const fslogger = new FsLogger(loggerOutputFile, nodeId); 155 | 156 | fslogger.setLogLevel(config.logVerbosity); 157 | 158 | share.process.stderr.on('data', function(data) { 159 | fslogger.write(data); 160 | }); 161 | 162 | share.process.stdout.on('data', function(data) { 163 | fslogger.write(data); 164 | }); 165 | 166 | // NB: Listen for state changes to update the node's record 167 | share.process.on('error', (err) => { 168 | share.readyState = RPC.SHARE_ERRORED; 169 | this._log(err.message, 'error'); 170 | clearInterval(uptimeCounter); 171 | }); 172 | 173 | // NB: Listen for exits and restart the node if not stopped manually 174 | share.process.on('exit', (code, signal) => { 175 | let maxRestartsReached = share.meta.numRestarts >= RPC.MAX_RESTARTS; 176 | share.readyState = RPC.SHARE_STOPPED; 177 | 178 | this._log(`node ${nodeId} exited with code ${code}`); 179 | clearInterval(uptimeCounter); 180 | 181 | if (signal !== 'SIGINT' && 182 | !maxRestartsReached && 183 | share.meta.uptimeMs >= 5000 184 | ) { 185 | share.meta.numRestarts++; 186 | this.restart(nodeId, () => null); 187 | } 188 | }); 189 | 190 | share.process.on('message', (msg) => this._processShareIpc(share, msg)); 191 | this.shares.set(nodeId, share); 192 | callback(null); 193 | }); 194 | } 195 | /** 196 | * @callback RPC~startCallback 197 | * @param {Error|null} error 198 | */ 199 | 200 | /** 201 | * Stops the node process for the given node ID 202 | * @param {String} nodeId 203 | * @param {RPC~stopCallback} 204 | */ 205 | stop(nodeId, callback) { 206 | this._log(`attempting to stop node with node id ${nodeId}`); 207 | 208 | if (!this.shares.has(nodeId) || !this.shares.get(nodeId).readyState) { 209 | return callback(new Error(`node ${nodeId} is not running`)); 210 | } 211 | 212 | this.shares.get(nodeId).process.kill('SIGINT'); 213 | 214 | //reset share status 215 | if (this.shares.has(nodeId) 216 | && 'meta' in this.shares.get(nodeId)) { 217 | this.shares.get(nodeId).meta.uptimeMs = 0; 218 | this.shares.get(nodeId).meta.numRestarts = 0; 219 | this.shares.get(nodeId).meta.peers = 0; 220 | } 221 | if (this.shares.has(nodeId) 222 | && 'meta' in this.shares.get(nodeId) 223 | && 'farmerState' in this.shares.get(nodeId).meta) { 224 | this.shares.get(nodeId).meta.farmerState.bridgesConnectionStatus = 0; 225 | this.shares.get(nodeId).meta.farmerState.totalPeers = 0; 226 | } 227 | if (this.shares.has(nodeId) 228 | && 'meta' in this.shares.get(nodeId) 229 | && 'farmerState' in this.shares.get(nodeId).meta 230 | && 'ntpStatus' in this.shares.get(nodeId).meta.farmerState) { 231 | this.shares.get(nodeId).meta.farmerState.ntpStatus.delta = 0; 232 | } 233 | 234 | setTimeout(() => callback(null), 1000); 235 | } 236 | /** 237 | * @callback RPC~stopCallback 238 | * @param {Error|null} error 239 | */ 240 | 241 | /** 242 | * Restarts the share process for the given node ID 243 | * @param {String} nodeId 244 | * @param {RPC~restartCallback} 245 | */ 246 | restart(nodeId, callback) { 247 | this._log(`attempting to restart node with node id ${nodeId}`); 248 | 249 | if (nodeId === '*') { 250 | return async.eachSeries( 251 | this.shares.keys(), 252 | (nodeId, next) => this.restart(nodeId, next), 253 | callback 254 | ); 255 | } 256 | 257 | this.stop(nodeId, () => { 258 | this.start(this.shares.get(nodeId).path, callback); 259 | }); 260 | } 261 | /** 262 | * @callback RPC~restartCallback 263 | * @param {Error|null} error 264 | */ 265 | 266 | /** 267 | * Returns status information about the running nodes 268 | * @param {RPC~statusCallback} 269 | */ 270 | status(callback) { 271 | const statuses = []; 272 | 273 | this._log(`got status query`); 274 | this.shares.forEach((share, nodeId) => { 275 | statuses.push({ 276 | id: nodeId, 277 | config: share.config, 278 | state: share.readyState, 279 | meta: share.meta, 280 | path: share.path 281 | }); 282 | }); 283 | 284 | callback(null, statuses); 285 | } 286 | /** 287 | * @callback RPC~statusCallback 288 | * @param {Error|null} error 289 | * @param {Object} status 290 | */ 291 | 292 | /** 293 | * Simply kills the daemon and all managed proccesses 294 | */ 295 | killall(callback) { 296 | this._log(`received kill signal, destroying running nodes`); 297 | 298 | for (let nodeId of this.shares.keys()) { 299 | this.destroy(nodeId, () => null); 300 | } 301 | 302 | callback(); 303 | setTimeout(() => process.exit(0), 1000); 304 | } 305 | 306 | /** 307 | * Kills the node with the given node ID 308 | * @param {String} nodeId 309 | * @param {RPC~destroyCallback} 310 | */ 311 | destroy(nodeId, callback) { 312 | this._log(`received destroy command for ${nodeId}`); 313 | 314 | if (!this.shares.has(nodeId) || !this.shares.get(nodeId).process) { 315 | return callback(new Error(`node ${nodeId} is not running`)); 316 | } 317 | 318 | let share = this.shares.get(nodeId); 319 | 320 | share.process.kill('SIGINT'); 321 | this.shares.delete(nodeId); 322 | callback(null); 323 | } 324 | /** 325 | * @callback RPC~destroyCallback 326 | * @param {Error|null} error 327 | */ 328 | 329 | /** 330 | * Saves the current nodes configured 331 | * @param {String} writePath 332 | * @param {RPC~saveCallback} 333 | */ 334 | save(writePath, callback) { 335 | const snapshot = []; 336 | 337 | this.shares.forEach((val, nodeId) => { 338 | snapshot.push({ 339 | path: val.path, 340 | id: nodeId 341 | }); 342 | }); 343 | 344 | fs.writeFile(writePath, JSON.stringify(snapshot, null, 2), (err) => { 345 | if (err) { 346 | return callback( 347 | new Error(`failed to write snapshot, reason: ${err.message}`) 348 | ); 349 | } 350 | 351 | callback(null); 352 | }); 353 | } 354 | /** 355 | * @callback RPC~saveCallback 356 | * @param {Error|null} error 357 | */ 358 | 359 | /** 360 | * Loads a state snapshot file 361 | * @param {String} readPath 362 | * @param {RPC~loadCallback} 363 | */ 364 | load(readPath, callback) { 365 | fs.readFile(readPath, (err, buffer) => { 366 | if (err) { 367 | return callback( 368 | new Error(`failed to read snapshot, reason: ${err.message}`) 369 | ); 370 | } 371 | 372 | let snapshot = null; 373 | 374 | try { 375 | snapshot = JSON.parse(buffer.toString()); 376 | } catch (err) { 377 | return callback(new Error('failed to parse snapshot')); 378 | } 379 | 380 | async.eachLimit(snapshot, 1, (share, next) => { 381 | this.start(share.path, (err) => { 382 | /* istanbul ignore if */ 383 | if (err) { 384 | this._log(err.message, 'warn'); 385 | } 386 | 387 | next(); 388 | }); 389 | }, callback); 390 | }); 391 | } 392 | /** 393 | * @callback RPC~loadCallback 394 | * @param {Error|null} error 395 | */ 396 | 397 | /** 398 | * Returns the number of nodes currently running 399 | * @private 400 | */ 401 | get running() { 402 | let i = 0; 403 | 404 | for (let [, share] of this.shares) { 405 | if (share.readyState !== 1) { 406 | continue; 407 | } else { 408 | i++; 409 | } 410 | } 411 | 412 | return i; 413 | } 414 | 415 | get methods() { 416 | return { 417 | start: this.start.bind(this), 418 | stop: this.stop.bind(this), 419 | restart: this.restart.bind(this), 420 | status: this.status.bind(this), 421 | killall: this.killall.bind(this), 422 | destroy: this.destroy.bind(this), 423 | save: this.save.bind(this), 424 | load: this.load.bind(this) 425 | }; 426 | } 427 | 428 | } 429 | 430 | RPC.SHARE_STARTED = 1; 431 | RPC.SHARE_STOPPED = 0; 432 | RPC.SHARE_ERRORED = 2; 433 | RPC.MAX_RESTARTS = 30; 434 | 435 | module.exports = RPC; 436 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | _**Notice**: Development on this repo is on pause until we finish our v3 rearchitecture. Please see https://github.com/storj/storj for ongoing v3 development._ 2 | 3 | Storj Share Daemon 4 | ================== 5 | 6 | [![Build Status](https://img.shields.io/travis/Storj/storjshare-daemon.svg?style=flat-square)](https://travis-ci.org/Storj/storjshare-daemon) 7 | [![Coverage Status](https://img.shields.io/coveralls/Storj/storjshare-daemon.svg?style=flat-square)](https://coveralls.io/r/Storj/storjshare-daemon) 8 | [![NPM](https://img.shields.io/npm/v/storjshare-daemon.svg?style=flat-square)](https://www.npmjs.com/package/storjshare-daemon) 9 | [![License](https://img.shields.io/badge/license-AGPL3.0-blue.svg?style=flat-square)](https://raw.githubusercontent.com/Storj/storjshare-daemon/master/LICENSE) 10 | [![Docker](https://img.shields.io/badge/docker-ready-blue.svg?style=flat-square)](https://store.docker.com/community/images/computeronix/storjshare-daemon) 11 | 12 | Daemon + CLI for farming data on the Storj network, suitable for standalone 13 | use or inclusion in other packages. 14 | 15 | ## Installation via Arch User Repositories 16 | 17 | storjshare daemon is also available for Arch Linux as a package on the AUR as [storjshare-daemon](https://aur.archlinux.org/packages/storjshare-daemon/). Install it via your favourite AUR helper. 18 | 19 | ## Manual Installation 20 | 21 | Make sure you have the following prerequisites installed: 22 | 23 | * Git 24 | * Node.js LTS (8.x.x) 25 | * NPM 26 | * Python 2.7 27 | * GCC/G++/Make 28 | 29 | ### Node.js + NPM 30 | 31 | #### GNU+Linux & Mac OSX 32 | 33 | ``` 34 | wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.0/install.sh | bash 35 | ``` 36 | 37 | Close your shell and open an new one. Now that you can call the `nvm` program, 38 | install Node.js (which comes with NPM): 39 | 40 | ``` 41 | nvm install --lts 42 | ``` 43 | 44 | #### Windows 45 | 46 | Download [Node.js LTS](https://nodejs.org/en/download/) for Windows, launch the 47 | installer and follow the setup instructions. Restart your PC, then test it from 48 | the command prompt: 49 | 50 | ``` 51 | node --version 52 | npm --version 53 | ``` 54 | 55 | ### Build Dependencies 56 | 57 | #### GNU+Linux 58 | 59 | Debian based (like Ubuntu) 60 | ``` 61 | apt install git python build-essential 62 | ``` 63 | 64 | Red Hat / Centos 65 | ``` 66 | yum groupinstall 'Development Tools' 67 | ``` 68 | You might also find yourself lacking a C++11 compiler - [see this](https://hiltmon.com/blog/2015/08/09/c-plus-plus-11-on-centos-6-dot-6/) 69 | 70 | #### Mac OSX 71 | 72 | ``` 73 | xcode-select --install 74 | ``` 75 | 76 | #### Windows 77 | 78 | ``` 79 | npm install --global windows-build-tools 80 | ``` 81 | 82 | --- 83 | 84 | ### Install ### 85 | 86 | Once build dependencies have been installed for your platform, install the 87 | package globally using Node Package Manager: 88 | 89 | ``` 90 | npm install --global storjshare-daemon 91 | ``` 92 | 93 | ## Usage (CLI) 94 | 95 | Once installed, you will have access to the `storjshare` program, so start by 96 | asking it for some help. 97 | 98 | ``` 99 | storjshare --help 100 | 101 | Usage: storjshare [options] [command] 102 | 103 | 104 | Commands: 105 | 106 | start start a farming node 107 | stop stop a farming node 108 | restart restart a farming node 109 | status check status of node(s) 110 | logs tail the logs for a node 111 | create create a new configuration 112 | destroy kills the farming node 113 | killall kills all shares and stops the daemon 114 | daemon starts the daemon 115 | help [cmd] display help for [cmd] 116 | 117 | Options: 118 | 119 | -h, --help output usage information 120 | -V, --version output the version number 121 | ``` 122 | 123 | You can also get more detailed help for a specific command. 124 | 125 | ``` 126 | storjshare help create 127 | 128 | Usage: storjshare-create [options] 129 | 130 | generates a new share configuration 131 | 132 | Options: 133 | 134 | -h, --help output usage information 135 | --storj specify the STORJ address (required) 136 | --key specify the private key 137 | --storage specify the storage path 138 | --size specify share size (ex: 10GB, 1TB) 139 | --rpcport specify the rpc port number 140 | --rpcaddress specify the rpc address 141 | --maxtunnels specify the max tunnels 142 | --tunnelportmin specify min gateway port 143 | --tunnelportmax specify max gateway port 144 | --manualforwarding do not use nat traversal strategies 145 | --logdir specify the log directory 146 | --noedit do not open generated config in editor 147 | -o, --outfile write config to path 148 | ``` 149 | 150 | ## Usage (Programmatic) 151 | 152 | The Storj Share daemon uses a local [dnode](https://github.com/substack/dnode) 153 | server to handle RPC message from the CLI and other applications. Assuming the 154 | daemon is running, your program can communicate with it using this interface. 155 | The example that follows is using Node.js, but dnode is implemented in many 156 | [other languages](https://github.com/substack/dnode#dnode-in-other-languages). 157 | 158 | ```js 159 | const dnode = require('dnode'); 160 | const daemon = dnode.connect(45015); 161 | 162 | daemon.on('remote', (rpc) => { 163 | // rpc.start(configPath, callback); 164 | // rpc.stop(nodeId, callback); 165 | // rpc.restart(nodeId, callback); 166 | // rpc.status(callback); 167 | // rpc.destroy(nodeId, callback); 168 | // rpc.save(snapshotPath, callback); 169 | // rpc.load(snapshotPath, callback); 170 | // rpc.killall(callback); 171 | }); 172 | ``` 173 | 174 | You can also easily start the daemon from your program by creating a dnode 175 | server and passing it an instance of the `RPC` class exposed from this package. 176 | 177 | ```js 178 | const storjshare = require('storjshare-daemon'); 179 | const dnode = require('dnode'); 180 | const api = new storjshare.RPC(); 181 | 182 | dnode(api.methods).listen(45015, '127.0.0.1'); 183 | ``` 184 | 185 | ## Configuring the Daemon 186 | 187 | The Storj Share daemon loads configuration from anywhere the 188 | [rc](https://www.npmjs.com/package/rc) package can read it. The first time you 189 | run the daemon, it will create a directory in `$HOME/.config/storjshare`, so 190 | the simplest way to change the daemon's behavior is to create a file at 191 | `$HOME/.config/storjshare/config` containing the following: 192 | 193 | ```json 194 | { 195 | "daemonRpcPort": 45015, 196 | "daemonRpcAddress": "127.0.0.1", 197 | "daemonLogFilePath": "", 198 | "daemonLogVerbosity": 3 199 | } 200 | ``` 201 | 202 | Modify these parameters to your liking, see `example/daemon.config.json` for 203 | detailed explanation of these properties. 204 | 205 | ## Debugging the Daemon 206 | 207 | The daemon logs activity to the configured log file, which by default is 208 | `$HOME/.config/storjshare/logs/daemon.log`. However if you find yourself 209 | needing to frequently restart the daemon and check the logs during 210 | development, you can run the daemon as a foreground process for a tighter 211 | feedback loop. 212 | 213 | ``` 214 | storjshare killall 215 | storjshare daemon --foreground 216 | ``` 217 | 218 | ## Connecting to a remote Daemon 219 | 220 | **Note: Exposing your storjshare-daemon to the Internet is a bad idea 221 | as everybody could read your Private Key!** 222 | 223 | To connect to a remote running daemon instance you will first need to 224 | ensure this daemon is running on a different address than the default 225 | `127.0.0.1`. This can be achieved by [configuring the Daemon](#configuring-the-daemon). 226 | 227 | After your storjshare-daemon is reachable (eg. within your home network) 228 | you can use `-r` or `--remote` option (on supported commands) to use the 229 | specified IP/hostname and port to connect to, instead of `127.0.0.1`. 230 | 231 | **Note that this option does not support to start the storjshare-daemon 232 | on a different system, only connect to an already running one!** 233 | 234 | Example to connect to remote daemon running on `192.168.0.10` on the default port (`45015`) and show the status: 235 | 236 | ``` 237 | storjshare status --remote 192.168.0.10 238 | ``` 239 | 240 | If the port is changed, just append it like so: 241 | 242 | ``` 243 | storjshare status --remote 192.168.0.10:51000 244 | ``` 245 | 246 | ## Migrating from [`storjshare-gui`](https://github.com/storj/storjshare-gui) or [`storjshare-cli`](https://github.com/storj/storjshare-cli) 247 | #### storjshare-gui 248 | If you are using the `storjshare-gui` package you can go on with the latest 249 | GUI release. You don't need to migrate but if you like you can do it. If you 250 | choose to migrate from the old storjshare-gui to the CLI version of 251 | storjshare-daemon, please follow the instructions below. 252 | 253 | #### storjshare-cli 254 | Storj Share provides a simple method for creating new shares, but if you were 255 | previously using the `storjshare-cli` package superceded by this one, you'll 256 | want to migrate your configuration to the new format. To do this, first you'll 257 | need to dump your private key **before** installing this package. 258 | 259 | > If you accidentally overwrote your old `storjshare-cli` installation with 260 | > this package, don't worry - just reinstall the old package to dump the key, 261 | > then reinstall this package. 262 | 263 | ### Step 0: Dump Your Private Key 264 | 265 | #### storjshare-gui 266 | Open `%AppData%\Storj Share\settings.json` in any texteditor. 267 | For each GUI drive you will find the private key and the dataDir. Use these 268 | information and go on with Step 1 and 2. 269 | ``` 270 | { 271 | "tabs": [ 272 | { 273 | "key": "4154e85e87b323611cba45ab1cd51203f2508b1da8455cdff8b641cce827f3d6", 274 | "address": "0xfB691...", 275 | "storage": { 276 | "dataDir": "D:\\Storj\\storjshare-5f4722" 277 | } 278 | }, 279 | { 280 | "key": "0b0341a9913bb84b51485152a1b0a8a6ed68fa4f9a4fedb26c61ff778ce61ec8", 281 | "address": "0xfB691...", 282 | "storage": { 283 | "dataDir": "D:\\Storj\\storjshare-48a1c4" 284 | } 285 | ], 286 | "appSettings": {...} 287 | } 288 | ``` 289 | 290 | #### storjshare-cli 291 | You can print your cleartext private key from storjshare-cli, using the 292 | `dump-key` command: 293 | 294 | ``` 295 | storjshare dump-key 296 | [...] > Unlock your private key to start storj > ******** 297 | 298 | [info] Cleartext Private Key: 299 | [info] ====================== 300 | [info] 4154e85e87b323611cba45ab1cd51203f2508b1da8455cdff8b641cce827f3d6 301 | [info] 302 | [info] (This key is suitable for importing into Storj Share GUI) 303 | ``` 304 | 305 | If you are using a custom data directory, be sure to add the `--datadir ` 306 | option to be sure you get the correct key. Also be sure to note your defined 307 | payout address and data directory. 308 | 309 | ### Step 1: Install Storj Share and Create Config 310 | 311 | Now that you have your private key, you can generate a new configuration file. 312 | To do this, first install the `storjshare-daemon` package globally and use the 313 | `create` command. You'll need to remove the `storjshare-cli` package first, so 314 | make sure you perform the previous step for all shared drives before 315 | proceeding forward. 316 | 317 | ``` 318 | npm remove -g storjshare-cli 319 | npm install -g storjshare-daemon 320 | ``` 321 | 322 | Now that you have Storj Share installed, use the `create` command to generate 323 | your configuration. 324 | 325 | ``` 326 | storjshare create --key 4154e8... --storj 0xfB691... --storage -o 327 | ``` 328 | 329 | This will generate your configuration file given the parameters you passed in, 330 | write the file to the path following the `-o` option, and open it in your text 331 | editor. Here, you can make other changes to the configuration following the 332 | detailed comments in the generated file. 333 | 334 | ### Step 2: Use The New Configuration 335 | 336 | Now that you have successfully migrated your configuration file, you can use 337 | it to start the share. 338 | 339 | ``` 340 | storjshare start --config path/to/config.json 341 | 342 | * daemon is not running, starting... 343 | 344 | * starting share with config at path/to/config.json 345 | ``` 346 | 347 | #### Updating storjshare and restoring sessions 348 | 349 | If you want to upgrade storjshare you can save your current session and 350 | reload it after updating 351 | 352 | ``` 353 | storjshare save 354 | storjshare killall 355 | npm install -g storjshare-daemon 356 | storjshare daemon & 357 | storjshare load 358 | ``` 359 | 360 | ## License 361 | 362 | Storj Share - Daemon + CLI for farming data on the Storj network. 363 | Copyright (C) 2017 Storj Labs, Inc 364 | 365 | This program is free software: you can redistribute it and/or modify 366 | it under the terms of the GNU Affero General Public License as published by 367 | the Free Software Foundation, either version 3 of the License, or 368 | (at your option) any later version. 369 | 370 | This program is distributed in the hope that it will be useful, 371 | but WITHOUT ANY WARRANTY; without even the implied warranty of 372 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 373 | GNU Affero General Public License for more details. 374 | 375 | You should have received a copy of the GNU Affero General Public License 376 | along with this program. If not, see http://www.gnu.org/licenses/. 377 | -------------------------------------------------------------------------------- /test/api.unit.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const RPC = require('../lib/api'); 4 | const proxyquire = require('proxyquire'); 5 | const sinon = require('sinon'); 6 | const {expect} = require('chai'); 7 | const {Readable, Writable} = require('stream'); 8 | const {EventEmitter} = require('events'); 9 | 10 | describe('class:RPC', function() { 11 | 12 | describe('#_log', function() { 13 | 14 | it('should call the log method', function() { 15 | let rpc = new RPC({ loggerVerbosity: 0 }); 16 | let info = sinon.stub(rpc.jsonlogger, 'info'); 17 | rpc._log('test'); 18 | expect(info.called).to.equal(true); 19 | }); 20 | 21 | }); 22 | 23 | describe('#_processShareIpc', function() { 24 | 25 | it('should add the message to the meta.farmerState', function() { 26 | let rpc = new RPC(); 27 | let share = { meta: {} }; 28 | rpc._processShareIpc(share, { foo: 'bar' }); 29 | expect(share.meta.farmerState.foo).to.equal('bar'); 30 | }); 31 | 32 | }); 33 | 34 | describe('#start', function() { 35 | 36 | it('should callback error if too many shares', function(done) { 37 | let _RPC = proxyquire('../lib/api', { 38 | os: { 39 | cpus: sinon.stub().returns([]) 40 | } 41 | }); 42 | let rpc = new _RPC({ loggerVerbosity: 0 }); 43 | rpc.start('path/to/config', function(err) { 44 | expect(err.message).to.equal( 45 | 'insufficient system resources available' 46 | ); 47 | done(); 48 | }); 49 | }); 50 | 51 | it('should fall through is unsafe flag', function(done) { 52 | let _RPC = proxyquire('../lib/api', { 53 | os: { 54 | cpus: sinon.stub().returns([]) 55 | } 56 | }); 57 | let rpc = new _RPC({ loggerVerbosity: 0 }); 58 | rpc.start('path/to/config', function(err) { 59 | expect(err.message).to.equal( 60 | 'failed to read config at path/to/config' 61 | ); 62 | done(); 63 | }, true); 64 | }); 65 | 66 | it('should callback error if no config given', function(done) { 67 | let _RPC = proxyquire('../lib/api', { 68 | fs: { 69 | statSync: sinon.stub().throws(new Error()) 70 | } 71 | }); 72 | let rpc = new _RPC({ loggerVerbosity: 0 }); 73 | rpc.start('path/to/config', function(err) { 74 | expect(err.message).to.equal( 75 | 'failed to read config at path/to/config' 76 | ); 77 | done(); 78 | }); 79 | }); 80 | 81 | it('should callback error if cannot parse config', function(done) { 82 | let _RPC = proxyquire('../lib/api', { 83 | fs: { 84 | statSync: sinon.stub(), 85 | readFileSync: sinon.stub().returns(Buffer.from('not json')) 86 | } 87 | }); 88 | let rpc = new _RPC({ loggerVerbosity: 0 }); 89 | rpc.start('path/to/config', function(err) { 90 | expect(err.message).to.equal( 91 | 'failed to parse config at path/to/config' 92 | ); 93 | done(); 94 | }); 95 | }); 96 | 97 | it('should callback error if config invalid', function(done) { 98 | let _RPC = proxyquire('../lib/api', { 99 | fs: { 100 | statSync: sinon.stub(), 101 | readFileSync: sinon.stub().returns(Buffer.from('{}')) 102 | } 103 | }); 104 | let rpc = new _RPC({ loggerVerbosity: 0 }); 105 | rpc.start('path/to/config', function(err) { 106 | expect(err.message).to.equal('invalid payout address'); 107 | done(); 108 | }); 109 | }); 110 | 111 | it('should callback error if share running', function(done) { 112 | let _RPC = proxyquire('../lib/api', { 113 | fs: { 114 | statSync: sinon.stub(), 115 | readFileSync: sinon.stub().returns(Buffer.from( 116 | '{"networkPrivateKey":"02d2e5fb5a1fe74804bc1ae3b63bb130441' + 117 | 'cc9b5c877e225ea723c24bcea4f3b"}' 118 | )) 119 | }, 120 | './utils': { 121 | validate: sinon.stub() 122 | } 123 | }); 124 | let rpc = new _RPC({ loggerVerbosity: 0 }); 125 | rpc.shares.set('2c9e76f298cb3a023785be8985205d371580ba27', { 126 | readyState: 1 127 | }); 128 | rpc.start('path/to/config', function(err) { 129 | expect(err.message).to.equal( 130 | 'node 2c9e76f298cb3a023785be8985205d371580ba27 is already running' 131 | ); 132 | done(); 133 | }); 134 | }); 135 | 136 | it('should callback error if invalid space allocation', function(done) { 137 | let _RPC = proxyquire('../lib/api', { 138 | fs: { 139 | statSync: sinon.stub(), 140 | readFileSync: sinon.stub().returns( 141 | Buffer.from('{"storageAllocation":"23GB"}') 142 | ) 143 | }, 144 | './utils': { 145 | validate: sinon.stub(), 146 | validateAllocation: sinon.stub().callsArgWith( 147 | 1, 148 | new Error('Bad space') 149 | ) 150 | } 151 | }); 152 | let rpc = new _RPC({ loggerVerbosity: 0 }); 153 | rpc.start('path/to/config', function(err) { 154 | expect(err.message).to.equal('bad space'); 155 | done(); 156 | }); 157 | }); 158 | 159 | it('should callback error if invalid space specified', function(done) { 160 | let _RPC = proxyquire('../lib/api', { 161 | fs: { 162 | statSync: sinon.stub(), 163 | readFileSync: sinon.stub().returns( 164 | Buffer.from('{"storageAllocation":"23G"}') 165 | ) 166 | }, 167 | './utils': { 168 | validate: sinon.stub() 169 | } 170 | }); 171 | let rpc = new _RPC({ loggerVerbosity: 0 }); 172 | rpc.start('path/to/config', function(err) { 173 | expect(err.message).to.eql('invalid storage size specified: 23g'); 174 | done(); 175 | }); 176 | }); 177 | 178 | it('should callback error if invalid network Private key', function(done) { 179 | let _RPC = proxyquire('../lib/api', { 180 | fs: { 181 | statSync: sinon.stub(), 182 | readFileSync: sinon.stub().returns( 183 | Buffer.from('{"storageAllocation":"23GB","networkPrivateKey":' + 184 | '"02d2e5fb5a1fe74804bc1ae3b63bb130441cc9b5c877e22' + 185 | '5ea723c24bcea4f3babc123"}') 186 | ) 187 | }, 188 | './utils': { 189 | validate: sinon.stub(), 190 | validateAllocation: sinon.stub() 191 | } 192 | }); 193 | let rpc = new _RPC({ loggerVerbosity: 0 }); 194 | rpc.start('path/to/config', function(err) { 195 | expect(err.message).to.equal('Invalid Private Key'); 196 | done(); 197 | }); 198 | }); 199 | 200 | it('should fork the share and setup listeners', function(done) { 201 | let _proc = new EventEmitter(); 202 | _proc.stdout = new Readable({ read: () => null }); 203 | _proc.stderr = new Readable({ read: () => null }); 204 | var MockFsLogger = function(){}; 205 | MockFsLogger.prototype.setLogLevel = sinon.stub(); 206 | MockFsLogger.prototype.write = sinon.stub(); 207 | let _RPC = proxyquire('../lib/api', { 208 | fs: { 209 | createWriteStream: sinon.stub().returns(new Writable({ 210 | write: (d, e, cb) => cb() 211 | })), 212 | statSync: sinon.stub().returns({ 213 | isDirectory: () => true 214 | }), 215 | readFileSync: sinon.stub().returns( 216 | Buffer.from('{"storageAllocation":"23GB"}') 217 | ) 218 | }, 219 | './utils': { 220 | validate: sinon.stub(), 221 | validateAllocation: sinon.stub().callsArg(1) 222 | }, 223 | child_process: { 224 | fork: sinon.stub().returns(_proc) 225 | }, 226 | fslogger: MockFsLogger 227 | }); 228 | let rpc = new _RPC({ loggerVerbosity: 0 }); 229 | let _ipc = sinon.stub(rpc, '_processShareIpc'); 230 | rpc.start('/tmp/', function() { 231 | let id = rpc.shares.keys().next().value; 232 | let share = rpc.shares.get(id); 233 | share.meta.uptimeMs = 6000; 234 | _proc.emit('message', {}); 235 | setImmediate(() => { 236 | expect(_ipc.called).to.equal(true); 237 | _proc.emit('exit'); 238 | setImmediate(() => { 239 | expect(rpc.shares.get(id).readyState).to.equal(RPC.SHARE_STOPPED); 240 | _proc.emit('error', new Error()); 241 | setImmediate(() => { 242 | expect(rpc.shares.get(id).readyState).to.equal(RPC.SHARE_ERRORED); 243 | done(); 244 | }); 245 | }); 246 | }); 247 | }); 248 | }); 249 | 250 | it('should call fslogger.write on data', function(done) { 251 | let _proc = new EventEmitter(); 252 | _proc.stdout = new Readable({ read: () => null }); 253 | _proc.stderr = new Readable({ read: () => null }); 254 | var MockFsLogger = function(){}; 255 | MockFsLogger.prototype.setLogLevel = sinon.stub(); 256 | MockFsLogger.prototype.write = sinon.stub(); 257 | let _RPC = proxyquire('../lib/api', { 258 | fs: { 259 | createWriteStream: sinon.stub().returns(new Writable({ 260 | write: (d, e, cb) => cb() 261 | })), 262 | statSync: sinon.stub().returns({ 263 | isDirectory: () => false 264 | }), 265 | readFileSync: sinon.stub().returns( 266 | Buffer.from('{"storageAllocation":"23GB"}') 267 | ) 268 | }, 269 | './utils': { 270 | validate: sinon.stub(), 271 | validateAllocation: sinon.stub().callsArg(1) 272 | }, 273 | child_process: { 274 | fork: sinon.stub().returns(_proc) 275 | }, 276 | fslogger: MockFsLogger 277 | }); 278 | let rpc = new _RPC({ loggerVerbosity: 0 }); 279 | rpc.start('/tmp/', function() { 280 | let id = rpc.shares.keys().next().value; 281 | let share = rpc.shares.get(id); 282 | share.meta.uptimeMs = 6000; 283 | _proc.stdout.emit('data', {}); 284 | setImmediate(() => { 285 | expect(MockFsLogger.prototype.write.called).to.equal(true); 286 | MockFsLogger.prototype.write.called = false; 287 | _proc.stderr.emit('data', {}); 288 | setImmediate(() => { 289 | expect(MockFsLogger.prototype.write.called).to.equal(true); 290 | _proc.emit('error', new Error()); 291 | done(); 292 | }); 293 | }); 294 | }); 295 | }); 296 | 297 | }); 298 | 299 | describe('#stop', function() { 300 | 301 | it('should callback error if no share', function(done) { 302 | let rpc = new RPC({ loggerVerbosity: 0 }); 303 | rpc.stop('test', function(err) { 304 | expect(err.message).to.equal('node test is not running'); 305 | done(); 306 | }); 307 | }); 308 | 309 | it('should send sigint to process', function(done) { 310 | let rpc = new RPC({ loggerVerbosity: 0 }); 311 | let _proc = { 312 | kill: sinon.stub() 313 | }; 314 | rpc.shares.set('test', { 315 | process: _proc, 316 | readyState: 1 317 | }); 318 | rpc.stop('test', function() { 319 | expect(_proc.kill.calledWithMatch('SIGINT')).to.equal(true); 320 | done(); 321 | }); 322 | }); 323 | 324 | 325 | it('should reset stoped share status', function (done) { 326 | let rpc = new RPC({loggerVerbosity: 0}); 327 | 328 | let _proc = { 329 | kill: sinon.stub() 330 | }; 331 | 332 | let meta = { 333 | uptimeMs: -1, 334 | numRestarts: -1, 335 | peers: -1, 336 | farmerState: { 337 | bridgesConnectionStatus: -1, 338 | totalPeers: -1, 339 | ntpStatus: { 340 | delta: -1 341 | } 342 | } 343 | }; 344 | 345 | rpc.shares.set('test', { 346 | process: _proc, 347 | readyState: 1, 348 | meta: meta 349 | }); 350 | 351 | rpc.stop('test', function () { 352 | expect(rpc.shares.get('test').meta.uptimeMs).to.equal(0); 353 | expect(rpc.shares.get('test').meta.numRestarts).to.equal(0); 354 | expect(rpc.shares.get('test').meta.peers).to.equal(0); 355 | expect(rpc.shares.get('test') 356 | .meta.farmerState.bridgesConnectionStatus).to.equal(0); 357 | expect(rpc.shares.get('test') 358 | .meta.farmerState.totalPeers).to.equal(0); 359 | expect(rpc.shares.get('test') 360 | .meta.farmerState.ntpStatus.delta).to.equal(0); 361 | done(); 362 | }); 363 | }); 364 | 365 | }); 366 | 367 | describe('#restart', function() { 368 | 369 | it('should call stop and start', function(done) { 370 | let rpc = new RPC({ loggerVerbosity: 0 }); 371 | rpc.shares.set('test', {}); 372 | let stop = sinon.stub(rpc, 'stop').callsArg(1); 373 | let start = sinon.stub(rpc, 'start').callsArg(1); 374 | rpc.restart('test', function() { 375 | expect(stop.called).to.equal(true); 376 | expect(start.called).to.equal(true); 377 | done(); 378 | }); 379 | }); 380 | 381 | it('should call restart for every share if wildcard', function(done) { 382 | let rpc = new RPC({ loggerVerbosity: 0 }); 383 | rpc.shares.set('test1', {}); 384 | rpc.shares.set('test2', {}); 385 | rpc.shares.set('test3', {}); 386 | let stop = sinon.stub(rpc, 'stop').callsArg(1); 387 | let start = sinon.stub(rpc, 'start').callsArg(1); 388 | rpc.restart('*', function() { 389 | expect(stop.callCount).to.equal(3); 390 | expect(start.callCount).to.equal(3); 391 | done(); 392 | }); 393 | }); 394 | 395 | }); 396 | 397 | describe('#status', function() { 398 | 399 | it('should return the share statuses', function(done) { 400 | let rpc = new RPC({ loggerVerbosity: 0 }); 401 | let meta = {}; 402 | rpc.shares.set('test', { 403 | config: 'CONFIG', 404 | readyState: 'READYSTATE', 405 | meta: meta 406 | }); 407 | rpc.status(function(err, status) { 408 | expect(status[0].id).to.equal('test'); 409 | expect(status[0].config).to.equal('CONFIG'); 410 | expect(status[0].state).to.equal('READYSTATE'); 411 | expect(status[0].meta).to.equal(meta); 412 | done(); 413 | }); 414 | }); 415 | 416 | }); 417 | 418 | describe('#killall', function() { 419 | 420 | it('should destroy shares and exit process', function() { 421 | let rpc = new RPC({ loggerVerbosity: 0 }); 422 | let destroy = sinon.stub(rpc, 'destroy').callsArg(1); 423 | let exit = sinon.stub(process, 'exit'); 424 | rpc.shares.set('test1', {}); 425 | rpc.shares.set('test2', {}); 426 | rpc.shares.set('test3', {}); 427 | rpc.killall(() => { 428 | expect(destroy.callCount).to.equal(3); 429 | setTimeout(() => { 430 | expect(exit.called).to.equal(true); 431 | exit.restore(); 432 | }, 1200); 433 | }); 434 | }); 435 | 436 | }); 437 | 438 | describe('#destroy', function() { 439 | 440 | it('should callback error if share not running', function(done) { 441 | let rpc = new RPC({ loggerVerbosity: 0 }); 442 | rpc.shares.set('test', { process: null }); 443 | rpc.destroy('test', function(err) { 444 | expect(err.message).to.equal('node test is not running'); 445 | done(); 446 | }); 447 | }); 448 | 449 | it('should send sigint and delete reference', function(done) { 450 | let rpc = new RPC({ loggerVerbosity: 0 }); 451 | let kill = sinon.stub(); 452 | rpc.shares.set('test', { 453 | process: { 454 | kill: kill 455 | } 456 | }); 457 | rpc.destroy('test', function() { 458 | expect(kill.calledWithMatch('SIGINT')).to.equal(true); 459 | expect(rpc.shares.has('test')).to.equal(false); 460 | done(); 461 | }); 462 | 463 | }); 464 | }); 465 | 466 | describe('#save', function() { 467 | 468 | it('should error if cannot write file', function(done) { 469 | let _RPC = proxyquire('../lib/api', { 470 | fs: { 471 | writeFile: sinon.stub().callsArgWith(2, new Error('Failed')) 472 | } 473 | }); 474 | let rpc = new _RPC({ loggerVerbosity: 0 }); 475 | rpc.save('save/path', (err) => { 476 | expect(err.message).to.equal( 477 | 'failed to write snapshot, reason: Failed' 478 | ); 479 | done(); 480 | }); 481 | }); 482 | 483 | it('should write the snapshot file', function(done) { 484 | let writeFile = sinon.stub().callsArgWith(2, null); 485 | let _RPC = proxyquire('../lib/api', { 486 | fs: { 487 | writeFile: writeFile 488 | } 489 | }); 490 | let rpc = new _RPC({ loggerVerbosity: 0 }); 491 | rpc.shares.set('test1', { path: 'path/1' }); 492 | rpc.shares.set('test2', { path: 'path/2' }); 493 | rpc.shares.set('test3', { path: 'path/3' }); 494 | rpc.save('save/path', (err) => { 495 | expect(err).to.equal(null); 496 | expect(writeFile.calledWithMatch('save/path', JSON.stringify([ 497 | { path: 'path/1', id: 'test1' }, 498 | { path: 'path/2', id: 'test2' }, 499 | { path: 'path/3', id: 'test3' } 500 | ], null, 2))).to.equal(true); 501 | done(); 502 | }); 503 | }); 504 | 505 | }); 506 | 507 | describe('#load', function() { 508 | 509 | it('should error if cannot read snapshot', function(done) { 510 | let _RPC = proxyquire('../lib/api', { 511 | fs: { 512 | readFile: sinon.stub().callsArgWith(1, new Error('Failed')) 513 | } 514 | }); 515 | let rpc = new _RPC({ loggerVerbosity: 0 }); 516 | rpc.load('load/path', (err) => { 517 | expect(err.message).to.equal( 518 | 'failed to read snapshot, reason: Failed' 519 | ); 520 | done(); 521 | }); 522 | }); 523 | 524 | it('should error if cannot parse snapshot', function(done) { 525 | let _RPC = proxyquire('../lib/api', { 526 | fs: { 527 | readFile: sinon.stub().callsArgWith(1, null, Buffer.from('notjson')) 528 | } 529 | }); 530 | let rpc = new _RPC({ loggerVerbosity: 0 }); 531 | rpc.load('load/path', (err) => { 532 | expect(err.message).to.equal( 533 | 'failed to parse snapshot' 534 | ); 535 | done(); 536 | }); 537 | }); 538 | 539 | it('should start all of the shares in the snapshot', function(done) { 540 | let _RPC = proxyquire('../lib/api', { 541 | fs: { 542 | readFile: sinon.stub().callsArgWith( 543 | 1, 544 | null, 545 | Buffer.from( 546 | `[ 547 | { "path": "test/1" }, 548 | { "path": "test/2" }, 549 | { "path": "test/3" }, 550 | { "path": "test/4" }, 551 | { "path": "test/5" } 552 | ]` 553 | ) 554 | ) 555 | } 556 | }); 557 | let rpc = new _RPC({ loggerVerbosity: 0 }); 558 | let start = sinon.stub(rpc, 'start').callsArg(1); 559 | rpc.load('load/path', () => { 560 | expect(start.callCount).to.equal(5); 561 | expect(start.getCall(0).calledWithMatch('test/1')); 562 | expect(start.getCall(1).calledWithMatch('test/2')); 563 | expect(start.getCall(2).calledWithMatch('test/3')); 564 | expect(start.getCall(3).calledWithMatch('test/4')); 565 | expect(start.getCall(4).calledWithMatch('test/5')); 566 | done(); 567 | }); 568 | }); 569 | 570 | }); 571 | 572 | describe('get#methods', function() { 573 | 574 | it('should return the public methods', function() { 575 | let rpc = new RPC({ loggerVerbosity: 0 }); 576 | let methods = Object.keys(rpc.methods); 577 | expect(methods.includes('start')).to.equal(true); 578 | expect(methods.includes('restart')).to.equal(true); 579 | expect(methods.includes('stop')).to.equal(true); 580 | expect(methods.includes('destroy')).to.equal(true); 581 | expect(methods.includes('status')).to.equal(true); 582 | expect(methods.includes('killall')).to.equal(true); 583 | }); 584 | 585 | }); 586 | 587 | }); 588 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------