├── .gitignore
├── LICENSE
├── README.md
├── config.json
├── init.js
├── lib
├── api.js
├── apiInterfaces.js
├── blockUnlocker.js
├── charts.js
├── chartsDataCollector.js
├── cli.js
├── configReader.js
├── exceptionWriter.js
├── logger.js
├── paymentProcessor.js
├── pool.js
└── utils.js
├── package.json
├── redisBlocksUpgrade.js
└── website
├── admin.html
├── config.js
├── custom.css
├── custom.js
├── index.html
├── pages
├── admin
│ ├── monitoring.html
│ ├── statistics.html
│ └── userslist.html
├── getting_started.html
├── home.html
├── payments.html
├── pool_blocks.html
└── support.html
└── themes
├── deep-gray-dark-theme.css
├── default-theme.css
├── ease-way-light-theme.css
├── img
├── bg.jpg
└── bg2.jpg
├── motherboard-dark-theme.css
└── nightly-mining-dark-theme.css
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
2 | .idea/
3 | config.json
4 | logs/
5 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | cryptonote-universal-pool
2 | ====================
3 |
4 | High performance Node.js (with native C addons) mining pool for CryptoNote based coins such as Bytecoin, DuckNote, Monero, QuazarCoin, Boolberry, Dashcoin, etc..
5 | Comes with lightweight example front-end script which uses the pool's AJAX API.
6 |
7 |
8 |
9 | #### Table of Contents
10 | * [Features](#features)
11 | * [Community Support](#community--support)
12 | * [Pools Using This Software](#pools-using-this-software)
13 | * [Usage](#usage)
14 | * [Requirements](#requirements)
15 | * [Downloading & Installing](#1-downloading--installing)
16 | * [Configuration](#2-configuration)
17 | * [Configure Easyminer](#3-optional-configure-cryptonote-easy-miner-for-your-pool)
18 | * [Starting the Pool](#4-start-the-pool)
19 | * [Host the front-end](#5-host-the-front-end)
20 | * [Customizing your website](#6-customize-your-website)
21 | * [Upgrading](#upgrading)
22 | * [Setting up Testnet](#setting-up-testnet)
23 | * [JSON-RPC Commands from CLI](#json-rpc-commands-from-cli)
24 | * [Monitoring Your Pool](#monitoring-your-pool)
25 | * [Donations](#donations)
26 | * [Credits](#credits)
27 | * [License](#license)
28 |
29 |
30 | #### Basic features
31 |
32 | * TCP (stratum-like) protocol for server-push based jobs
33 | * Compared to old HTTP protocol, this has a higher hash rate, lower network/CPU server load, lower orphan
34 | block percent, and less error prone
35 | * IP banning to prevent low-diff share attacks
36 | * Socket flooding detection
37 | * Payment processing
38 | * Splintered transactions to deal with max transaction size
39 | * Minimum payment threshold before balance will be paid out
40 | * Minimum denomination for truncating payment amount precision to reduce size/complexity of block transactions
41 | * Detailed logging
42 | * Ability to configure multiple ports - each with their own difficulty
43 | * Variable difficulty / share limiter
44 | * Share trust algorithm to reduce share validation hashing CPU load
45 | * Clustering for vertical scaling
46 | * Modular components for horizontal scaling (pool server, database, stats/API, payment processing, front-end)
47 | * Live stats API (using AJAX long polling with CORS)
48 | * Currency network/block difficulty
49 | * Current block height
50 | * Network hashrate
51 | * Pool hashrate
52 | * Each miners' individual stats (hashrate, shares submitted, pending balance, total paid, etc)
53 | * Blocks found (pending, confirmed, and orphaned)
54 | * An easily extendable, responsive, light-weight front-end using API to display data
55 |
56 | #### Extra features
57 |
58 | * Admin panel
59 | * Aggregated pool statistics
60 | * Coin daemon & wallet RPC services stability monitoring
61 | * Log files data access
62 | * Users list with detailed statistics
63 | * Historic charts of pool's hashrate and miners count, coin difficulty, rates and coin profitability
64 | * Historic charts of users's hashrate and payments
65 | * Miner login(wallet address) validation
66 | * Five configurable CSS themes
67 | * Universal blocks and transactions explorer based on [chainradar.com](http://chainradar.com)
68 | * FantomCoin & MonetaVerde support
69 | * Set fixed difficulty on miner client by passing "address" param with ".[difficulty]" postfix
70 | * Prevent "transaction is too big" error with "payments.maxTransactionAmount" option
71 |
72 |
73 | ### Community / Support
74 |
75 | * [CryptoNote Technology](https://cryptonote.org)
76 | * [CryptoNote Forum](https://forum.cryptonote.org/)
77 | * [CryptoNote Universal Pool Forum](https://bitcointalk.org/index.php?topic=705509)
78 |
79 | #### Pools Using This Software
80 |
81 | * http://xminingpool.com
82 | * http://extremepool.org
83 | * http://noclaymorefee.com
84 | * http://nicepool.org
85 | * https://yaymining.com
86 | * http://bbr.unipool.pro
87 | * http://multihash.de
88 | * http://monero.rs
89 | * http://backup-pool.com/monero
90 |
91 | Usage
92 | ===
93 |
94 | #### Requirements
95 | * Coin daemon(s) (find the coin's repo and build latest version from source)
96 | * [Node.js](http://nodejs.org/) v0.10+ ([follow these installation instructions](https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager))
97 | * [Redis](http://redis.io/) key-value store v2.6+ ([follow these instructions](http://redis.io/topics/quickstart))
98 | * libssl required for the node-multi-hashing module
99 | * For Ubuntu: `sudo apt-get install libssl-dev`
100 |
101 |
102 | ##### Seriously
103 | Those are legitimate requirements. If you use old versions of Node.js or Redis that may come with your system package manager then you will have problems. Follow the linked instructions to get the last stable versions.
104 |
105 |
106 | [**Redis security warning**](http://redis.io/topics/security): be sure firewall access to redis - an easy way is to
107 | include `bind 127.0.0.1` in your `redis.conf` file. Also it's a good idea to learn about and understand software that
108 | you are using - a good place to start with redis is [data persistence](http://redis.io/topics/persistence).
109 |
110 | ##### Easy install on Ubuntu 14 LTS
111 | Installing pool on different Linux distributives is different because it depends on system default components and versions. For now the easiest way to install pool is to use Ubuntu 14 LTS. Thus, all you had to do in order to prepare Ubunty 14 for pool installation is to run:
112 |
113 | ```bash
114 | sudo apt-get install git redis-server libboost1.55-all-dev nodejs-dev nodejs-legacy npm cmake libssl-dev
115 | ```
116 |
117 |
118 | #### 1) Downloading & Installing
119 |
120 |
121 | Clone the repository and run `npm update` for all the dependencies to be installed:
122 |
123 | ```bash
124 | git clone https://github.com/fancoder/cryptonote-universal-pool.git pool
125 | cd pool
126 | npm update
127 | ```
128 |
129 | #### 2) Configuration
130 |
131 |
132 | Explanation for each field:
133 | ```javascript
134 | /* Used for storage in redis so multiple coins can share the same redis instance. */
135 | "coin": "ducknote",
136 |
137 | /* Used for front-end display */
138 | "symbol": "XDN",
139 |
140 | /* Minimum units in a single coin, see COIN constant in DAEMON_CODE/src/cryptonote_config.h */
141 | "coinUnits": 100000000,
142 |
143 | /* Coin network time to mine one block, see DIFFICULTY_TARGET constant in DAEMON_CODE/src/cryptonote_config.h */
144 | "coinDifficultyTarget": 240,
145 |
146 | "logging": {
147 |
148 | "files": {
149 |
150 | /* Specifies the level of log output verbosity. This level and anything
151 | more severe will be logged. Options are: info, warn, or error. */
152 | "level": "info",
153 |
154 | /* Directory where to write log files. */
155 | "directory": "logs",
156 |
157 | /* How often (in seconds) to append/flush data to the log files. */
158 | "flushInterval": 5
159 | },
160 |
161 | "console": {
162 | "level": "info",
163 | /* Gives console output useful colors. If you direct that output to a log file
164 | then disable this feature to avoid nasty characters in the file. */
165 | "colors": true
166 | }
167 | },
168 |
169 | /* Modular Pool Server */
170 | "poolServer": {
171 | "enabled": true,
172 |
173 | /* Set to "auto" by default which will spawn one process/fork/worker for each CPU
174 | core in your system. Each of these workers will run a separate instance of your
175 | pool(s), and the kernel will load balance miners using these forks. Optionally,
176 | the 'forks' field can be a number for how many forks will be spawned. */
177 | "clusterForks": "auto",
178 |
179 | /* Address where block rewards go, and miner payments come from. */
180 | "poolAddress": "ddehi53dwGSBEXdhTYtga2R3fS4y9hRz4YHAsLABJpH75yUd5EDQmuL3yDBj1mG6MMeDfydY9vp4zFVVNQ99FTYq2PpsFJP2y"
181 |
182 | /* Poll RPC daemons for new blocks every this many milliseconds. */
183 | "blockRefreshInterval": 1000,
184 |
185 | /* Enable merged mining feature starting from this version. */
186 | "mergedMiningMinVersion": "99",
187 |
188 | /* How many seconds until we consider a miner disconnected. */
189 | "minerTimeout": 900,
190 |
191 | "ports": [
192 | {
193 | "port": 3333, //Port for mining apps to connect to
194 | "difficulty": 100, //Initial difficulty miners are set to
195 | "desc": "Low end hardware" //Description of port
196 | },
197 | {
198 | "port": 5555,
199 | "difficulty": 2000,
200 | "desc": "Mid range hardware"
201 | },
202 | {
203 | "port": 7777,
204 | "difficulty": 10000,
205 | "desc": "High end hardware"
206 | }
207 | ],
208 |
209 | /* Variable difficulty is a feature that will automatically adjust difficulty for
210 | individual miners based on their hashrate in order to lower networking and CPU
211 | overhead. */
212 | "varDiff": {
213 | "minDiff": 2, //Minimum difficulty
214 | "maxDiff": 100000,
215 | "targetTime": 100, //Try to get 1 share per this many seconds
216 | "retargetTime": 30, //Check to see if we should retarget every this many seconds
217 | "variancePercent": 30, //Allow time to very this % from target without retargeting
218 | "maxJump": 100 //Limit diff percent increase/decrease in a single retargetting
219 | },
220 |
221 | /* Set difficulty on miner client side by passing
param with . postfix
222 | minerd -u 4AsBy39rpUMTmgTUARGq2bFQWhDhdQNekK5v4uaLU699NPAnx9CubEJ82AkvD5ScoAZNYRwBxybayainhyThHAZWCdKmPYn.5000 */
223 | "fixedDiff": {
224 | "enabled": true,
225 | "separator": ".", // character separator between and
226 | },
227 |
228 | /* Feature to trust share difficulties from miners which can
229 | significantly reduce CPU load. */
230 | "shareTrust": {
231 | "enabled": true,
232 | "min": 10, //Minimum percent probability for share hashing
233 | "stepDown": 3, //Increase trust probability % this much with each valid share
234 | "threshold": 10, //Amount of valid shares required before trusting begins
235 | "penalty": 30 //Upon breaking trust require this many valid share before trusting
236 | },
237 |
238 | /* If under low-diff share attack we can ban their IP to reduce system/network load. */
239 | "banning": {
240 | "enabled": true,
241 | "time": 600, //How many seconds to ban worker for
242 | "invalidPercent": 25, //What percent of invalid shares triggers ban
243 | "checkThreshold": 30 //Perform check when this many shares have been submitted
244 | }
245 | },
246 |
247 | /* Module that sends payments to miners according to their submitted shares. */
248 | "payments": {
249 | "enabled": true,
250 | "interval": 600, //how often to run in seconds
251 | "maxAddresses": 50, //split up payments if sending to more than this many addresses
252 | "mixin": 3, //number of transactions yours is indistinguishable from
253 | "transferFee": 5000000000, //fee to pay for each transaction
254 | "minPayment": 100000000000, //miner balance required before sending payment
255 | "maxTransactionAmount": 0, //split transactions by this amount(to prevent "too big transaction" error)
256 | "denomination": 100000000000 //truncate to this precision and store remainder
257 | },
258 |
259 | /* Module that monitors the submitted block maturities and manages rounds. Confirmed
260 | blocks mark the end of a round where workers' balances are increased in proportion
261 | to their shares. */
262 | "blockUnlocker": {
263 | "enabled": true,
264 | "interval": 30, //how often to check block statuses in seconds
265 |
266 | /* Block depth required for a block to unlocked/mature. Found in daemon source as
267 | the variable CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW */
268 | "depth": 60,
269 | "poolFee": 1.8, //1.8% pool fee (2% total fee total including donations)
270 | "devDonation": 0.1, //0.1% donation to send to pool dev - only works with Monero
271 | "coreDevDonation": 0.1 //0.1% donation to send to core devs - works with Bytecoin, Monero, Dashcoin, QuarazCoin, Fantoncoin, AEON and OneEvilCoin
272 | },
273 |
274 | /* AJAX API used for front-end website. */
275 | "api": {
276 | "enabled": true,
277 | "hashrateWindow": 600, //how many second worth of shares used to estimate hash rate
278 | "updateInterval": 3, //gather stats and broadcast every this many seconds
279 | "port": 8117,
280 | "blocks": 30, //amount of blocks to send at a time
281 | "payments": 30, //amount of payments to send at a time
282 | "password": "test" //password required for admin stats
283 | },
284 |
285 | /* Coin daemon connection details. */
286 | "daemon": {
287 | "host": "127.0.0.1",
288 | "port": 18081
289 | },
290 |
291 | /* Wallet daemon connection details. */
292 | "wallet": {
293 | "host": "127.0.0.1",
294 | "port": 8082
295 | },
296 |
297 | /* Redis connection into. */
298 | "redis": {
299 | "host": "127.0.0.1",
300 | "port": 6379
301 | }
302 |
303 | /* Monitoring RPC services. Statistics will be displayed in Admin panel */
304 | "monitoring": {
305 | "daemon": {
306 | "checkInterval": 60, //interval of sending rpcMethod request
307 | "rpcMethod": "getblockcount" //RPC method name
308 | },
309 | "wallet": {
310 | "checkInterval": 60,
311 | "rpcMethod": "getbalance"
312 | }
313 |
314 | /* Collect pool statistics to display in frontend charts */
315 | "charts": {
316 | "pool": {
317 | "hashrate": {
318 | "enabled": true, //enable data collection and chart displaying in frontend
319 | "updateInterval": 60, //how often to get current value
320 | "stepInterval": 1800, //chart step interval calculated as average of all updated values
321 | "maximumPeriod": 86400 //chart maximum periods (chart points number = maximumPeriod / stepInterval = 48)
322 | },
323 | "workers": {
324 | "enabled": true,
325 | "updateInterval": 60,
326 | "stepInterval": 1800, //chart step interval calculated as maximum of all updated values
327 | "maximumPeriod": 86400
328 | },
329 | "difficulty": {
330 | "enabled": true,
331 | "updateInterval": 1800,
332 | "stepInterval": 10800,
333 | "maximumPeriod": 604800
334 | },
335 | "price": { //USD price of one currency coin received from cryptonator.com/api
336 | "enabled": true,
337 | "updateInterval": 1800,
338 | "stepInterval": 10800,
339 | "maximumPeriod": 604800
340 | },
341 | "profit": { //Reward * Rate / Difficulty
342 | "enabled": true,
343 | "updateInterval": 1800,
344 | "stepInterval": 10800,
345 | "maximumPeriod": 604800
346 | }
347 | },
348 | "user": { //chart data displayed in user stats block
349 | "hashrate": {
350 | "enabled": true,
351 | "updateInterval": 180,
352 | "stepInterval": 1800,
353 | "maximumPeriod": 86400
354 | },
355 | "payments": { //payment chart uses all user payments data stored in DB
356 | "enabled": true
357 | }
358 | }
359 | ```
360 |
361 | #### 3) [Optional] Configure cryptonote-easy-miner for your pool
362 | Your miners that are Windows users can use [cryptonote-easy-miner](https://github.com/zone117x/cryptonote-easy-miner)
363 | which will automatically generate their wallet address and stratup multiple threads of simpleminer. You can download
364 | it and edit the `config.ini` file to point to your own pool.
365 | Inside the `easyminer` folder, edit `config.init` to point to your pool details
366 | ```ini
367 | pool_host=example.com
368 | pool_port=5555
369 | ```
370 |
371 | Rezip and upload to your server or a file host. Then change the `easyminerDownload` link in your `config.json` file to
372 | point to your zip file.
373 |
374 | #### 4) Start the pool
375 |
376 | ```bash
377 | node init.js
378 | ```
379 |
380 | The file `config.json` is used by default but a file can be specified using the `-config=file` command argument, for example:
381 |
382 | ```bash
383 | node init.js -config=config_backup.json
384 | ```
385 |
386 | This software contains four distinct modules:
387 | * `pool` - Which opens ports for miners to connect and processes shares
388 | * `api` - Used by the website to display network, pool and miners' data
389 | * `unlocker` - Processes block candidates and increases miners' balances when blocks are unlocked
390 | * `payments` - Sends out payments to miners according to their balances stored in redis
391 |
392 |
393 | By default, running the `init.js` script will start up all four modules. You can optionally have the script start
394 | only start a specific module by using the `-module=name` command argument, for example:
395 |
396 | ```bash
397 | node init.js -module=api
398 | ```
399 |
400 | [Example screenshot](http://i.imgur.com/SEgrI3b.png) of running the pool in single module mode with tmux.
401 |
402 |
403 | #### 5) Host the front-end
404 |
405 | Simply host the contents of the `website_example` directory on file server capable of serving simple static files.
406 |
407 |
408 | Edit the variables in the `website_example/config.js` file to use your pool's specific configuration.
409 | Variable explanations:
410 |
411 | ```javascript
412 |
413 | /* Must point to the API setup in your config.json file. */
414 | var api = "http://poolhost:8117";
415 |
416 | /* Pool server host to instruct your miners to point to. */
417 | var poolHost = "poolhost.com";
418 |
419 | /* IRC Server and room used for embedded KiwiIRC chat. */
420 | var irc = "irc.freenode.net/#ducknote";
421 |
422 | /* Contact email address. */
423 | var email = "support@poolhost.com";
424 |
425 | /* Market stat display params from https://www.cryptonator.com/widget */
426 | var cryptonatorWidget = ["XDN-BTC", "XDN-USD", "XDN-EUR"];
427 |
428 | /* Download link to cryptonote-easy-miner for Windows users. */
429 | var easyminerDownload = "https://github.com/zone117x/cryptonote-easy-miner/releases/";
430 |
431 | /* Used for front-end block links. */
432 | var blockchainExplorer = "http://chainradar.com/{symbol}/block/{id}";
433 |
434 | /* Used by front-end transaction links. */
435 | var transactionExplorer = "http://chainradar.com/{symbol}/transaction/{id}";
436 |
437 | /* Any custom CSS theme for pool frontend */
438 | var themeCss = "themes/default-theme.css";
439 |
440 | ```
441 |
442 | #### 6) Customize your website
443 |
444 | The following files are included so that you can customize your pool website without having to make significant changes
445 | to `index.html` or other front-end files thus reducing the difficulty of merging updates with your own changes:
446 | * `custom.css` for creating your own pool style
447 | * `custom.js` for changing the functionality of your pool website
448 |
449 |
450 | Then simply serve the files via nginx, Apache, Google Drive, or anything that can host static content.
451 |
452 |
453 | #### Upgrading
454 | When updating to the latest code its important to not only `git pull` the latest from this repo, but to also update
455 | the Node.js modules, and any config files that may have been changed.
456 | * Inside your pool directory (where the init.js script is) do `git pull` to get the latest code.
457 | * Remove the dependencies by deleting the `node_modules` directory with `rm -r node_modules`.
458 | * Run `npm update` to force updating/reinstalling of the dependencies.
459 | * Compare your `config.json` to the latest example ones in this repo or the ones in the setup instructions where each config field is explained. You may need to modify or add any new changes.
460 |
461 | ### Setting up Testnet
462 |
463 | No cryptonote based coins have a testnet mode (yet) but you can effectively create a testnet with the following steps:
464 |
465 | * Open `/src/p2p/net_node.inl` and remove lines with `ADD_HARDCODED_SEED_NODE` to prevent it from connecting to mainnet (Monero example: http://git.io/0a12_Q)
466 | * Build the coin from source
467 | * You now need to run two instance of the daemon and connect them to each other (without a connection to another instance the daemon will not accept RPC requests)
468 | * Run first instance with `./coind --p2p-bind-port 28080 --allow-local-ip`
469 | * Run second instance with `./coind --p2p-bind-port 5011 --rpc-bind-port 5010 --add-peer 0.0.0.0:28080 --allow-local-ip`
470 | * You should now have a local testnet setup. The ports can be changes as long as the second instance is pointed to the first instance, obviously
471 |
472 | *Credit to surfer43 for these instructions*
473 |
474 |
475 | ### JSON-RPC Commands from CLI
476 |
477 | Documentation for JSON-RPC commands can be found here:
478 | * Daemon https://wiki.bytecoin.org/wiki/Daemon_JSON_RPC_API
479 | * Wallet https://wiki.bytecoin.org/wiki/Wallet_JSON_RPC_API
480 |
481 |
482 | Curl can be used to use the JSON-RPC commands from command-line. Here is an example of calling `getblockheaderbyheight` for block 100:
483 |
484 | ```bash
485 | curl 127.0.0.1:18081/json_rpc -d '{"method":"getblockheaderbyheight","params":{"height":100}}'
486 | ```
487 |
488 |
489 | ### Monitoring Your Pool
490 |
491 | * To inspect and make changes to redis I suggest using [redis-commander](https://github.com/joeferner/redis-commander)
492 | * To monitor server load for CPU, Network, IO, etc - I suggest using [New Relic](http://newrelic.com/)
493 | * To keep your pool node script running in background, logging to file, and automatically restarting if it crashes - I suggest using [forever](https://github.com/nodejitsu/forever)
494 |
495 |
496 | Donations
497 | ---------
498 | * BTC: `1667jMt7NTZDaC8WXAxtMYBR8DPWCVoU4d`
499 | * MRO: `48Y4SoUJM5L3YXBEfNQ8bFNsvTNsqcH5Rgq8RF7BwpgvTBj2xr7CmWVanaw7L4U9MnZ4AG7U6Pn1pBhfQhFyFZ1rL1efL8z`
500 |
501 | Credits
502 | ===
503 |
504 | * [LucasJones](//github.com/LucasJones) - Co-dev on this project; did tons of debugging for binary structures and fixing them. Pool couldn't have been made without him.
505 | * [surfer43](//github.com/iamasupernova) - Did lots of testing during development to help figure out bugs and get them fixed
506 | * [wallet42](http://moneropool.com) - Funded development of payment denominating and min threshold feature
507 | * [Wolf0](https://bitcointalk.org/index.php?action=profile;u=80740) - Helped try to deobfuscate some of the daemon code for getting a bug fixed
508 | * [Tacotime](https://bitcointalk.org/index.php?action=profile;u=19270) - helping with figuring out certain problems and lead the bounty for this project's creation
509 |
510 | License
511 | -------
512 | Released under the GNU General Public License v2
513 |
514 | http://www.gnu.org/licenses/gpl-2.0.html
515 |
--------------------------------------------------------------------------------
/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "coin": "ducknote",
3 | "symbol": "XDN",
4 | "coinUnits": 100000000,
5 | "coinDifficultyTarget": 240,
6 |
7 | "logging": {
8 | "files": {
9 | "level": "info",
10 | "directory": "logs",
11 | "flushInterval": 5
12 | },
13 | "console": {
14 | "level": "info",
15 | "colors": true
16 | }
17 | },
18 |
19 | "poolServer": {
20 | "enabled": true,
21 | "clusterForks": "auto",
22 | "poolAddress": "ddehi53dwGSBEXdhTYtga2R3fS4y9hRz4YHAsLABJpH75yUd5EDQmuL3yDBj1mG6MMeDfydY9vp4zFVVNQ99FTYq2PpsFJP2y",
23 | "mergedMiningMinVersion": "99",
24 | "blockRefreshInterval": 1000,
25 | "minerTimeout": 900,
26 | "ports": [
27 | {
28 | "port": 3333,
29 | "difficulty": 100,
30 | "desc": "Low end hardware"
31 | },
32 | {
33 | "port": 5555,
34 | "difficulty": 2000,
35 | "desc": "Mid range hardware"
36 | },
37 | {
38 | "port": 7777,
39 | "difficulty": 10000,
40 | "desc": "High end hardware"
41 | },
42 | {
43 | "port": 8888,
44 | "difficulty": 10000,
45 | "desc": "Hidden port",
46 | "hidden": true
47 | }
48 | ],
49 | "varDiff": {
50 | "minDiff": 100,
51 | "maxDiff": 200000,
52 | "targetTime": 100,
53 | "retargetTime": 30,
54 | "variancePercent": 30,
55 | "maxJump": 100
56 | },
57 | "fixedDiff": {
58 | "enabled": true,
59 | "addressSeparator": "."
60 | },
61 | "shareTrust": {
62 | "enabled": true,
63 | "min": 10,
64 | "stepDown": 3,
65 | "threshold": 10,
66 | "penalty": 30
67 | },
68 | "banning": {
69 | "enabled": true,
70 | "time": 600,
71 | "invalidPercent": 25,
72 | "checkThreshold": 30
73 | }
74 | },
75 |
76 | "payments": {
77 | "enabled": true,
78 | "interval": 600,
79 | "maxAddresses": 50,
80 | "mixin": 3,
81 | "transferFee": 50000000,
82 | "minPayment": 1000000000,
83 | "maxTransactionAmount": 0,
84 | "denomination": 1000000000
85 | },
86 |
87 | "blockUnlocker": {
88 | "enabled": true,
89 | "interval": 30,
90 | "depth": 10,
91 | "poolFee": 2,
92 | "devDonation": 0.1,
93 | "coreDevDonation": 0.1,
94 | "extraFeaturesDevDonation":0.1
95 | },
96 |
97 | "api": {
98 | "enabled": true,
99 | "hashrateWindow": 600,
100 | "updateInterval": 5,
101 | "port": 8117,
102 | "blocks": 30,
103 | "payments": 30,
104 | "password": "your_password"
105 | },
106 |
107 | "daemon": {
108 | "host": "127.0.0.1",
109 | "port": 42081
110 | },
111 |
112 | "wallet": {
113 | "host": "127.0.0.1",
114 | "port": 8082
115 | },
116 |
117 | "redis": {
118 | "host": "127.0.0.1",
119 | "port": 6379
120 | },
121 |
122 | "monitoring": {
123 | "daemon": {
124 | "checkInterval": 60,
125 | "rpcMethod": "getblockcount"
126 | },
127 | "wallet": {
128 | "checkInterval": 60,
129 | "rpcMethod": "getbalance"
130 | }
131 | },
132 |
133 | "charts": {
134 | "pool": {
135 | "hashrate": {
136 | "enabled": true,
137 | "updateInterval": 60,
138 | "stepInterval": 1800,
139 | "maximumPeriod": 86400
140 | },
141 | "workers": {
142 | "enabled": true,
143 | "updateInterval": 60,
144 | "stepInterval": 1800,
145 | "maximumPeriod": 86400
146 | },
147 | "difficulty": {
148 | "enabled": true,
149 | "updateInterval": 1800,
150 | "stepInterval": 10800,
151 | "maximumPeriod": 604800
152 | },
153 | "price": {
154 | "enabled": true,
155 | "updateInterval": 1800,
156 | "stepInterval": 10800,
157 | "maximumPeriod": 604800
158 | },
159 | "profit": {
160 | "enabled": true,
161 | "updateInterval": 1800,
162 | "stepInterval": 10800,
163 | "maximumPeriod": 604800
164 | }
165 | },
166 | "user": {
167 | "hashrate": {
168 | "enabled": true,
169 | "updateInterval": 180,
170 | "stepInterval": 1800,
171 | "maximumPeriod": 86400
172 | },
173 | "payments": {
174 | "enabled": true
175 | }
176 | }
177 | }
178 | }
179 |
--------------------------------------------------------------------------------
/init.js:
--------------------------------------------------------------------------------
1 | var fs = require('fs');
2 | var cluster = require('cluster');
3 | var os = require('os');
4 |
5 | var redis = require('redis');
6 |
7 |
8 | require('./lib/configReader.js');
9 |
10 | require('./lib/logger.js');
11 |
12 |
13 | global.redisClient = redis.createClient(config.redis.port, config.redis.host);
14 |
15 |
16 | if (cluster.isWorker){
17 | switch(process.env.workerType){
18 | case 'pool':
19 | require('./lib/pool.js');
20 | break;
21 | case 'blockUnlocker':
22 | require('./lib/blockUnlocker.js');
23 | break;
24 | case 'paymentProcessor':
25 | require('./lib/paymentProcessor.js');
26 | break;
27 | case 'api':
28 | require('./lib/api.js');
29 | break;
30 | case 'cli':
31 | require('./lib/cli.js');
32 | break
33 | case 'chartsDataCollector':
34 | require('./lib/chartsDataCollector.js');
35 | break
36 |
37 | }
38 | return;
39 | }
40 |
41 | var logSystem = 'master';
42 | require('./lib/exceptionWriter.js')(logSystem);
43 |
44 |
45 | var singleModule = (function(){
46 |
47 | var validModules = ['pool', 'api', 'unlocker', 'payments', 'chartsDataCollector'];
48 |
49 | for (var i = 0; i < process.argv.length; i++){
50 | if (process.argv[i].indexOf('-module=') === 0){
51 | var moduleName = process.argv[i].split('=')[1];
52 | if (validModules.indexOf(moduleName) > -1)
53 | return moduleName;
54 |
55 | log('error', logSystem, 'Invalid module "%s", valid modules: %s', [moduleName, validModules.join(', ')]);
56 | process.exit();
57 | }
58 | }
59 | })();
60 |
61 |
62 | (function init(){
63 |
64 | checkRedisVersion(function(){
65 |
66 | if (singleModule){
67 | log('info', logSystem, 'Running in single module mode: %s', [singleModule]);
68 |
69 | switch(singleModule){
70 | case 'pool':
71 | spawnPoolWorkers();
72 | break;
73 | case 'unlocker':
74 | spawnBlockUnlocker();
75 | break;
76 | case 'payments':
77 | spawnPaymentProcessor();
78 | break;
79 | case 'api':
80 | spawnApi();
81 | break;
82 | case 'chartsDataCollector':
83 | spawnChartsDataCollector();
84 | break;
85 | }
86 | }
87 | else{
88 | spawnPoolWorkers();
89 | spawnBlockUnlocker();
90 | spawnPaymentProcessor();
91 | spawnApi();
92 | spawnChartsDataCollector();
93 | }
94 |
95 | spawnCli();
96 |
97 | });
98 | })();
99 |
100 |
101 | function checkRedisVersion(callback){
102 |
103 | redisClient.info(function(error, response){
104 | if (error){
105 | log('error', logSystem, 'Redis version check failed');
106 | return;
107 | }
108 | var parts = response.split('\r\n');
109 | var version;
110 | var versionString;
111 | for (var i = 0; i < parts.length; i++){
112 | if (parts[i].indexOf(':') !== -1){
113 | var valParts = parts[i].split(':');
114 | if (valParts[0] === 'redis_version'){
115 | versionString = valParts[1];
116 | version = parseFloat(versionString);
117 | break;
118 | }
119 | }
120 | }
121 | if (!version){
122 | log('error', logSystem, 'Could not detect redis version - must be super old or broken');
123 | return;
124 | }
125 | else if (version < 2.6){
126 | log('error', logSystem, "You're using redis version %s the minimum required version is 2.6. Follow the damn usage instructions...", [versionString]);
127 | return;
128 | }
129 | callback();
130 | });
131 | }
132 |
133 | function spawnPoolWorkers(){
134 |
135 | if (!config.poolServer || !config.poolServer.enabled || !config.poolServer.ports || config.poolServer.ports.length === 0) return;
136 |
137 | if (config.poolServer.ports.length === 0){
138 | log('error', logSystem, 'Pool server enabled but no ports specified');
139 | return;
140 | }
141 |
142 | if (!config.poolServer.hasOwnProperty("mergedMiningMinVersion")) {
143 | config.poolServer.mergedMiningMinVersion = 2;
144 | }
145 |
146 | var numForks = (function(){
147 | if (!config.poolServer.clusterForks)
148 | return 1;
149 | if (config.poolServer.clusterForks === 'auto')
150 | return os.cpus().length;
151 | if (isNaN(config.poolServer.clusterForks))
152 | return 1;
153 | return config.poolServer.clusterForks;
154 | })();
155 |
156 | var poolWorkers = {};
157 |
158 | var createPoolWorker = function(forkId){
159 | var worker = cluster.fork({
160 | workerType: 'pool',
161 | forkId: forkId
162 | });
163 | worker.forkId = forkId;
164 | worker.type = 'pool';
165 | poolWorkers[forkId] = worker;
166 | worker.on('exit', function(code, signal){
167 | log('error', logSystem, 'Pool fork %s died, spawning replacement worker...', [forkId]);
168 | setTimeout(function(){
169 | createPoolWorker(forkId);
170 | }, 2000);
171 | }).on('message', function(msg){
172 | switch(msg.type){
173 | case 'banIP':
174 | Object.keys(cluster.workers).forEach(function(id) {
175 | if (cluster.workers[id].type === 'pool'){
176 | cluster.workers[id].send({type: 'banIP', ip: msg.ip});
177 | }
178 | });
179 | break;
180 | }
181 | });
182 | };
183 |
184 | var i = 1;
185 | var spawnInterval = setInterval(function(){
186 | createPoolWorker(i.toString());
187 | i++;
188 | if (i - 1 === numForks){
189 | clearInterval(spawnInterval);
190 | log('info', logSystem, 'Pool spawned on %d thread(s)', [numForks]);
191 | }
192 | }, 10);
193 | }
194 |
195 | function spawnBlockUnlocker(){
196 |
197 | if (!config.blockUnlocker || !config.blockUnlocker.enabled) return;
198 |
199 | var worker = cluster.fork({
200 | workerType: 'blockUnlocker'
201 | });
202 | worker.on('exit', function(code, signal){
203 | log('error', logSystem, 'Block unlocker died, spawning replacement...');
204 | setTimeout(function(){
205 | spawnBlockUnlocker();
206 | }, 2000);
207 | });
208 |
209 | }
210 |
211 | function spawnPaymentProcessor(){
212 |
213 | if (!config.payments || !config.payments.enabled) return;
214 |
215 | var worker = cluster.fork({
216 | workerType: 'paymentProcessor'
217 | });
218 | worker.on('exit', function(code, signal){
219 | log('error', logSystem, 'Payment processor died, spawning replacement...');
220 | setTimeout(function(){
221 | spawnPaymentProcessor();
222 | }, 2000);
223 | });
224 | }
225 |
226 | function spawnApi(){
227 | if (!config.api || !config.api.enabled) return;
228 |
229 | var worker = cluster.fork({
230 | workerType: 'api'
231 | });
232 | worker.on('exit', function(code, signal){
233 | log('error', logSystem, 'API died, spawning replacement...');
234 | setTimeout(function(){
235 | spawnApi();
236 | }, 2000);
237 | });
238 | }
239 |
240 | function spawnCli(){
241 |
242 | }
243 |
244 | function spawnChartsDataCollector(){
245 | if (!config.charts) return;
246 |
247 | var worker = cluster.fork({
248 | workerType: 'chartsDataCollector'
249 | });
250 | worker.on('exit', function(code, signal){
251 | log('error', logSystem, 'chartsDataCollector died, spawning replacement...');
252 | setTimeout(function(){
253 | spawnChartsDataCollector();
254 | }, 2000);
255 | });
256 | }
257 |
--------------------------------------------------------------------------------
/lib/api.js:
--------------------------------------------------------------------------------
1 | var fs = require('fs');
2 | var http = require('http');
3 | var url = require("url");
4 | var zlib = require('zlib');
5 |
6 | var async = require('async');
7 |
8 | var apiInterfaces = require('./apiInterfaces.js')(config.daemon, config.wallet);
9 | var charts = require('./charts.js');
10 | var authSid = Math.round(Math.random() * 10000000000) + '' + Math.round(Math.random() * 10000000000);
11 |
12 | var logSystem = 'api';
13 | require('./exceptionWriter.js')(logSystem);
14 |
15 | var redisCommands = [
16 | ['zremrangebyscore', config.coin + ':hashrate', '-inf', ''],
17 | ['zrange', config.coin + ':hashrate', 0, -1],
18 | ['hgetall', config.coin + ':stats'],
19 | ['zrange', config.coin + ':blocks:candidates', 0, -1, 'WITHSCORES'],
20 | ['zrevrange', config.coin + ':blocks:matured', 0, config.api.blocks - 1, 'WITHSCORES'],
21 | ['hgetall', config.coin + ':shares:roundCurrent'],
22 | ['hgetall', config.coin + ':stats'],
23 | ['zcard', config.coin + ':blocks:matured'],
24 | ['zrevrange', config.coin + ':payments:all', 0, config.api.payments - 1, 'WITHSCORES'],
25 | ['zcard', config.coin + ':payments:all'],
26 | ['keys', config.coin + ':payments:*']
27 | ];
28 |
29 | var currentStats = "";
30 | var currentStatsCompressed = "";
31 |
32 | var minerStats = {};
33 | var minersHashrate = {};
34 |
35 | var liveConnections = {};
36 | var addressConnections = {};
37 |
38 |
39 |
40 | function collectStats(){
41 |
42 | var startTime = Date.now();
43 | var redisFinished;
44 | var daemonFinished;
45 |
46 | var windowTime = (((Date.now() / 1000) - config.api.hashrateWindow) | 0).toString();
47 | redisCommands[0][3] = '(' + windowTime;
48 |
49 | async.parallel({
50 | pool: function(callback){
51 | redisClient.multi(redisCommands).exec(function(error, replies){
52 |
53 | redisFinished = Date.now();
54 |
55 | if (error){
56 | log('error', logSystem, 'Error getting redis data %j', [error]);
57 | callback(true);
58 | return;
59 | }
60 |
61 | var data = {
62 | stats: replies[2],
63 | blocks: replies[3].concat(replies[4]),
64 | totalBlocks: parseInt(replies[7]) + (replies[3].length / 2),
65 | payments: replies[8],
66 | totalPayments: parseInt(replies[9]),
67 | totalMinersPaid: replies[10].length - 1
68 | };
69 |
70 | var hashrates = replies[1];
71 |
72 | minerStats = {};
73 | minersHashrate = {};
74 |
75 | for (var i = 0; i < hashrates.length; i++){
76 | var hashParts = hashrates[i].split(':');
77 | minersHashrate[hashParts[1]] = (minersHashrate[hashParts[1]] || 0) + parseInt(hashParts[0]);
78 | }
79 |
80 | var totalShares = 0;
81 |
82 | for (var miner in minersHashrate){
83 | var shares = minersHashrate[miner];
84 | totalShares += shares;
85 | minersHashrate[miner] = Math.round(shares / config.api.hashrateWindow);
86 | minerStats[miner] = getReadableHashRateString(minersHashrate[miner]);
87 | }
88 |
89 | data.miners = Object.keys(minerStats).length;
90 |
91 | data.hashrate = Math.round(totalShares / config.api.hashrateWindow);
92 |
93 | data.roundHashes = 0;
94 |
95 | if (replies[5]){
96 | for (var miner in replies[5]){
97 | data.roundHashes += parseInt(replies[5][miner]);
98 | }
99 | }
100 |
101 | if (replies[6]) {
102 | data.lastBlockFound = replies[6].lastBlockFound;
103 | }
104 |
105 | callback(null, data);
106 | });
107 | },
108 | network: function(callback){
109 | apiInterfaces.rpcDaemon('getlastblockheader', {}, function(error, reply){
110 | daemonFinished = Date.now();
111 | if (error){
112 | log('error', logSystem, 'Error getting daemon data %j', [error]);
113 | callback(true);
114 | return;
115 | }
116 | var blockHeader = reply.block_header;
117 | callback(null, {
118 | difficulty: blockHeader.difficulty,
119 | height: blockHeader.height,
120 | timestamp: blockHeader.timestamp,
121 | reward: blockHeader.reward,
122 | hash: blockHeader.hash
123 | });
124 | });
125 | },
126 | config: function(callback){
127 | callback(null, {
128 | ports: getPublicPorts(config.poolServer.ports),
129 | hashrateWindow: config.api.hashrateWindow,
130 | fee: config.blockUnlocker.poolFee,
131 | coin: config.coin,
132 | coinUnits: config.coinUnits,
133 | coinDifficultyTarget: config.coinDifficultyTarget,
134 | symbol: config.symbol,
135 | depth: config.blockUnlocker.depth,
136 | donation: donations,
137 | version: version,
138 | minPaymentThreshold: config.payments.minPayment,
139 | denominationUnit: config.payments.denomination
140 | });
141 | },
142 | charts: charts.getPoolChartsData
143 | }, function(error, results){
144 |
145 | log('info', logSystem, 'Stat collection finished: %d ms redis, %d ms daemon', [redisFinished - startTime, daemonFinished - startTime]);
146 |
147 | if (error){
148 | log('error', logSystem, 'Error collecting all stats');
149 | }
150 | else{
151 | currentStats = JSON.stringify(results);
152 | zlib.deflateRaw(currentStats, function(error, result){
153 | currentStatsCompressed = result;
154 | broadcastLiveStats();
155 | });
156 |
157 | }
158 |
159 | setTimeout(collectStats, config.api.updateInterval * 1000);
160 | });
161 |
162 | }
163 |
164 | function getPublicPorts(ports){
165 | return ports.filter(function(port) {
166 | return !port.hidden;
167 | });
168 | }
169 |
170 | function getReadableHashRateString(hashrate){
171 | var i = 0;
172 | var byteUnits = [' H', ' KH', ' MH', ' GH', ' TH', ' PH' ];
173 | while (hashrate > 1024){
174 | hashrate = hashrate / 1024;
175 | i++;
176 | }
177 | return hashrate.toFixed(2) + byteUnits[i];
178 | }
179 |
180 | function broadcastLiveStats(){
181 |
182 | log('info', logSystem, 'Broadcasting to %d visitors and %d address lookups', [Object.keys(liveConnections).length, Object.keys(addressConnections).length]);
183 |
184 | for (var uid in liveConnections){
185 | var res = liveConnections[uid];
186 | res.end(currentStatsCompressed);
187 | }
188 |
189 | var redisCommands = [];
190 | for (var address in addressConnections){
191 | redisCommands.push(['hgetall', config.coin + ':workers:' + address]);
192 | redisCommands.push(['zrevrange', config.coin + ':payments:' + address, 0, config.api.payments - 1, 'WITHSCORES']);
193 | }
194 | redisClient.multi(redisCommands).exec(function(error, replies){
195 |
196 | var addresses = Object.keys(addressConnections);
197 |
198 | for (var i = 0; i < addresses.length; i++){
199 | var offset = i * 2;
200 | var address = addresses[i];
201 | var stats = replies[offset];
202 | var res = addressConnections[address];
203 | if (!stats){
204 | res.end(JSON.stringify({error: "not found"}));
205 | return;
206 | }
207 | stats.hashrate = minerStats[address];
208 | res.end(JSON.stringify({stats: stats, payments: replies[offset + 1]}));
209 | }
210 | });
211 | }
212 |
213 | function handleMinerStats(urlParts, response){
214 | response.writeHead(200, {
215 | 'Access-Control-Allow-Origin': '*',
216 | 'Cache-Control': 'no-cache',
217 | 'Content-Type': 'application/json',
218 | 'Connection': 'keep-alive'
219 | });
220 | response.write('\n');
221 | var address = urlParts.query.address;
222 |
223 | if (urlParts.query.longpoll === 'true'){
224 | redisClient.exists(config.coin + ':workers:' + address, function(error, result){
225 | if (!result){
226 | response.end(JSON.stringify({error: 'not found'}));
227 | return;
228 | }
229 | addressConnections[address] = response;
230 | response.on('finish', function(){
231 | delete addressConnections[address];
232 | })
233 | });
234 | }
235 | else{
236 | redisClient.multi([
237 | ['hgetall', config.coin + ':workers:' + address],
238 | ['zrevrange', config.coin + ':payments:' + address, 0, config.api.payments - 1, 'WITHSCORES']
239 | ]).exec(function(error, replies){
240 | if (error || !replies[0]){
241 | response.end(JSON.stringify({error: 'not found'}));
242 | return;
243 | }
244 | var stats = replies[0];
245 | stats.hashrate = minerStats[address];
246 | charts.getUserChartsData(address, replies[1], function(error, chartsData) {
247 | response.end(JSON.stringify({
248 | stats: stats,
249 | payments: replies[1],
250 | charts: chartsData
251 | }));
252 | });
253 | });
254 | }
255 | }
256 |
257 |
258 | function handleGetPayments(urlParts, response){
259 | var paymentKey = ':payments:all';
260 |
261 | if (urlParts.query.address)
262 | paymentKey = ':payments:' + urlParts.query.address;
263 |
264 | redisClient.zrevrangebyscore(
265 | config.coin + paymentKey,
266 | '(' + urlParts.query.time,
267 | '-inf',
268 | 'WITHSCORES',
269 | 'LIMIT',
270 | 0,
271 | config.api.payments,
272 | function(err, result){
273 |
274 | var reply;
275 |
276 | if (err)
277 | reply = JSON.stringify({error: 'query failed'});
278 | else
279 | reply = JSON.stringify(result);
280 |
281 | response.writeHead("200", {
282 | 'Access-Control-Allow-Origin': '*',
283 | 'Cache-Control': 'no-cache',
284 | 'Content-Type': 'application/json',
285 | 'Content-Length': reply.length
286 | });
287 | response.end(reply);
288 |
289 | }
290 | )
291 | }
292 |
293 | function handleGetBlocks(urlParts, response){
294 | redisClient.zrevrangebyscore(
295 | config.coin + ':blocks:matured',
296 | '(' + urlParts.query.height,
297 | '-inf',
298 | 'WITHSCORES',
299 | 'LIMIT',
300 | 0,
301 | config.api.blocks,
302 | function(err, result){
303 |
304 | var reply;
305 |
306 | if (err)
307 | reply = JSON.stringify({error: 'query failed'});
308 | else
309 | reply = JSON.stringify(result);
310 |
311 | response.writeHead("200", {
312 | 'Access-Control-Allow-Origin': '*',
313 | 'Cache-Control': 'no-cache',
314 | 'Content-Type': 'application/json',
315 | 'Content-Length': reply.length
316 | });
317 | response.end(reply);
318 |
319 | });
320 | }
321 |
322 | function handleGetMinersHashrate(response) {
323 | var reply = JSON.stringify({
324 | minersHashrate: minersHashrate
325 | });
326 | response.writeHead("200", {
327 | 'Access-Control-Allow-Origin': '*',
328 | 'Cache-Control': 'no-cache',
329 | 'Content-Type': 'application/json',
330 | 'Content-Length': reply.length
331 | });
332 | response.end(reply);
333 | }
334 |
335 | function parseCookies(request) {
336 | var list = {},
337 | rc = request.headers.cookie;
338 | rc && rc.split(';').forEach(function(cookie) {
339 | var parts = cookie.split('=');
340 | list[parts.shift().trim()] = unescape(parts.join('='));
341 | });
342 | return list;
343 | }
344 |
345 | function authorize(request, response){
346 | if(request.connection.remoteAddress == '127.0.0.1') {
347 | return true;
348 | }
349 |
350 | response.setHeader('Access-Control-Allow-Origin', '*');
351 |
352 | var cookies = parseCookies(request);
353 | if(cookies.sid && cookies.sid == authSid) {
354 | return true;
355 | }
356 |
357 | var sentPass = url.parse(request.url, true).query.password;
358 |
359 |
360 | if (sentPass !== config.api.password){
361 | response.statusCode = 401;
362 | response.end('invalid password');
363 | return;
364 | }
365 |
366 | log('warn', logSystem, 'Admin authorized');
367 | response.statusCode = 200;
368 |
369 | var cookieExpire = new Date( new Date().getTime() + 60*60*24*1000);
370 | response.setHeader('Set-Cookie', 'sid=' + authSid + '; path=/; expires=' + cookieExpire.toUTCString());
371 | response.setHeader('Cache-Control', 'no-cache');
372 | response.setHeader('Content-Type', 'application/json');
373 |
374 |
375 | return true;
376 | }
377 |
378 | function handleAdminStats(response){
379 |
380 | async.waterfall([
381 |
382 | //Get worker keys & unlocked blocks
383 | function(callback){
384 | redisClient.multi([
385 | ['keys', config.coin + ':workers:*'],
386 | ['zrange', config.coin + ':blocks:matured', 0, -1]
387 | ]).exec(function(error, replies) {
388 | if (error) {
389 | log('error', logSystem, 'Error trying to get admin data from redis %j', [error]);
390 | callback(true);
391 | return;
392 | }
393 | callback(null, replies[0], replies[1]);
394 | });
395 | },
396 |
397 | //Get worker balances
398 | function(workerKeys, blocks, callback){
399 | var redisCommands = workerKeys.map(function(k){
400 | return ['hmget', k, 'balance', 'paid'];
401 | });
402 | redisClient.multi(redisCommands).exec(function(error, replies){
403 | if (error){
404 | log('error', logSystem, 'Error with getting balances from redis %j', [error]);
405 | callback(true);
406 | return;
407 | }
408 |
409 | callback(null, replies, blocks);
410 | });
411 | },
412 | function(workerData, blocks, callback){
413 | var stats = {
414 | totalOwed: 0,
415 | totalPaid: 0,
416 | totalRevenue: 0,
417 | totalDiff: 0,
418 | totalShares: 0,
419 | blocksOrphaned: 0,
420 | blocksUnlocked: 0,
421 | totalWorkers: 0
422 | };
423 |
424 | for (var i = 0; i < workerData.length; i++){
425 | stats.totalOwed += parseInt(workerData[i][0]) || 0;
426 | stats.totalPaid += parseInt(workerData[i][1]) || 0;
427 | stats.totalWorkers++;
428 | }
429 |
430 | for (var i = 0; i < blocks.length; i++){
431 | var block = blocks[i].split(':');
432 | if (block[5]) {
433 | stats.blocksUnlocked++;
434 | stats.totalDiff += parseInt(block[2]);
435 | stats.totalShares += parseInt(block[3]);
436 | stats.totalRevenue += parseInt(block[5]);
437 | }
438 | else{
439 | stats.blocksOrphaned++;
440 | }
441 | }
442 | callback(null, stats);
443 | }
444 | ], function(error, stats){
445 | if (error){
446 | response.end(JSON.stringify({error: 'error collecting stats'}));
447 | return;
448 | }
449 | response.end(JSON.stringify(stats));
450 | }
451 | );
452 |
453 | }
454 |
455 |
456 | function handleAdminUsers(response){
457 | async.waterfall([
458 | // get workers Redis keys
459 | function(callback) {
460 | redisClient.keys(config.coin + ':workers:*', callback);
461 | },
462 | // get workers data
463 | function(workerKeys, callback) {
464 | var redisCommands = workerKeys.map(function(k) {
465 | return ['hmget', k, 'balance', 'paid', 'lastShare', 'hashes'];
466 | });
467 | redisClient.multi(redisCommands).exec(function(error, redisData) {
468 | var workersData = {};
469 | var addressLength = config.poolServer.poolAddress.length;
470 | for(var i in redisData) {
471 | var address = workerKeys[i].substr(-addressLength);
472 | var data = redisData[i];
473 | workersData[address] = {
474 | pending: data[0],
475 | paid: data[1],
476 | lastShare: data[2],
477 | hashes: data[3],
478 | hashrate: minersHashrate[address] ? minersHashrate[address] : 0
479 | };
480 | }
481 | callback(null, workersData);
482 | });
483 | }
484 | ], function(error, workersData) {
485 | if(error) {
486 | response.end(JSON.stringify({error: 'error collecting users stats'}));
487 | return;
488 | }
489 | response.end(JSON.stringify(workersData));
490 | }
491 | );
492 | }
493 |
494 |
495 | function handleAdminMonitoring(response) {
496 | response.writeHead("200", {
497 | 'Access-Control-Allow-Origin': '*',
498 | 'Cache-Control': 'no-cache',
499 | 'Content-Type': 'application/json'
500 | });
501 | async.parallel({
502 | monitoring: getMonitoringData,
503 | logs: getLogFiles
504 | }, function(error, result) {
505 | response.end(JSON.stringify(result));
506 | });
507 | }
508 |
509 | function handleAdminLog(urlParts, response){
510 | var file = urlParts.query.file;
511 | var filePath = config.logging.files.directory + '/' + file;
512 | if(!file.match(/^\w+\.log$/)) {
513 | response.end('wrong log file');
514 | }
515 | response.writeHead(200, {
516 | 'Content-Type': 'text/plain',
517 | 'Cache-Control': 'no-cache',
518 | 'Content-Length': fs.statSync(filePath).size
519 | });
520 | fs.createReadStream(filePath).pipe(response)
521 | }
522 |
523 |
524 | function startRpcMonitoring(rpc, module, method, interval) {
525 | setInterval(function() {
526 | rpc(method, {}, function(error, response) {
527 | var stat = {
528 | lastCheck: new Date() / 1000 | 0,
529 | lastStatus: error ? 'fail' : 'ok',
530 | lastResponse: JSON.stringify(error ? error : response)
531 | };
532 | if(error) {
533 | stat.lastFail = stat.lastCheck;
534 | stat.lastFailResponse = stat.lastResponse;
535 | }
536 | var key = getMonitoringDataKey(module);
537 | var redisCommands = [];
538 | for(var property in stat) {
539 | redisCommands.push(['hset', key, property, stat[property]]);
540 | }
541 | redisClient.multi(redisCommands).exec();
542 | });
543 | }, interval * 1000);
544 | }
545 |
546 | function getMonitoringDataKey(module) {
547 | return config.coin + ':status:' + module;
548 | }
549 |
550 | function initMonitoring() {
551 | var modulesRpc = {
552 | daemon: apiInterfaces.rpcDaemon,
553 | wallet: apiInterfaces.rpcWallet
554 | };
555 | for(var module in config.monitoring) {
556 | var settings = config.monitoring[module];
557 | if(settings.checkInterval) {
558 | startRpcMonitoring(modulesRpc[module], module, settings.rpcMethod, settings.checkInterval);
559 | }
560 | }
561 | }
562 |
563 |
564 |
565 | function getMonitoringData(callback) {
566 | var modules = Object.keys(config.monitoring);
567 | var redisCommands = [];
568 | for(var i in modules) {
569 | redisCommands.push(['hgetall', getMonitoringDataKey(modules[i])])
570 | }
571 | redisClient.multi(redisCommands).exec(function(error, results) {
572 | var stats = {};
573 | for(var i in modules) {
574 | if(results[i]) {
575 | stats[modules[i]] = results[i];
576 | }
577 | }
578 | callback(error, stats);
579 | });
580 | }
581 |
582 | function getLogFiles(callback) {
583 | var dir = config.logging.files.directory;
584 | fs.readdir(dir, function(error, files) {
585 | var logs = {};
586 | for(var i in files) {
587 | var file = files[i];
588 | var stats = fs.statSync(dir + '/' + file);
589 | logs[file] = {
590 | size: stats.size,
591 | changed: Date.parse(stats.mtime) / 1000 | 0
592 | }
593 | }
594 | callback(error, logs);
595 | });
596 | }
597 |
598 | var server = http.createServer(function(request, response){
599 |
600 | if (request.method.toUpperCase() === "OPTIONS"){
601 |
602 | response.writeHead("204", "No Content", {
603 | "access-control-allow-origin": '*',
604 | "access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
605 | "access-control-allow-headers": "content-type, accept",
606 | "access-control-max-age": 10, // Seconds.
607 | "content-length": 0
608 | });
609 |
610 | return(response.end());
611 | }
612 |
613 |
614 | var urlParts = url.parse(request.url, true);
615 |
616 | switch(urlParts.pathname){
617 | case '/stats':
618 | var deflate = request.headers['accept-encoding'] && request.headers['accept-encoding'].indexOf('deflate') != -1;
619 | var reply = deflate ? currentStatsCompressed : currentStats;
620 | response.writeHead("200", {
621 | 'Access-Control-Allow-Origin': '*',
622 | 'Cache-Control': 'no-cache',
623 | 'Content-Type': 'application/json',
624 | 'Content-Encoding': deflate ? 'deflate' : '',
625 | 'Content-Length': reply.length
626 | });
627 | response.end(reply);
628 | break;
629 | case '/live_stats':
630 | response.writeHead(200, {
631 | 'Access-Control-Allow-Origin': '*',
632 | 'Cache-Control': 'no-cache',
633 | 'Content-Type': 'application/json',
634 | 'Content-Encoding': 'deflate',
635 | 'Connection': 'keep-alive'
636 | });
637 | var uid = Math.random().toString();
638 | liveConnections[uid] = response;
639 | response.on("finish", function() {
640 | delete liveConnections[uid];
641 | });
642 | break;
643 | case '/stats_address':
644 | handleMinerStats(urlParts, response);
645 | break;
646 | case '/get_payments':
647 | handleGetPayments(urlParts, response);
648 | break;
649 | case '/get_blocks':
650 | handleGetBlocks(urlParts, response);
651 | break;
652 | case '/admin_stats':
653 | if (!authorize(request, response))
654 | return;
655 | handleAdminStats(response);
656 | break;
657 | case '/admin_monitoring':
658 | if(!authorize(request, response)) {
659 | return;
660 | }
661 | handleAdminMonitoring(response);
662 | break;
663 | case '/admin_log':
664 | if(!authorize(request, response)) {
665 | return;
666 | }
667 | handleAdminLog(urlParts, response);
668 | break;
669 | case '/admin_users':
670 | if(!authorize(request, response)) {
671 | return;
672 | }
673 | handleAdminUsers(response);
674 | break;
675 |
676 | case '/miners_hashrate':
677 | if (!authorize(request, response))
678 | return;
679 | handleGetMinersHashrate(response);
680 | break;
681 |
682 | default:
683 | response.writeHead(404, {
684 | 'Access-Control-Allow-Origin': '*'
685 | });
686 | response.end('Invalid API call');
687 | break;
688 | }
689 | });
690 |
691 | collectStats();
692 | initMonitoring();
693 |
694 | server.listen(config.api.port, function(){
695 | log('info', logSystem, 'API started & listening on port %d', [config.api.port]);
696 | });
697 |
--------------------------------------------------------------------------------
/lib/apiInterfaces.js:
--------------------------------------------------------------------------------
1 | var http = require('http');
2 | var https = require('https');
3 |
4 | function jsonHttpRequest(host, port, data, callback, path){
5 | path = path || '/json_rpc';
6 |
7 | var options = {
8 | hostname: host,
9 | port: port,
10 | path: path,
11 | method: data ? 'POST' : 'GET',
12 | headers: {
13 | 'Content-Length': data.length,
14 | 'Content-Type': 'application/json',
15 | 'Accept': 'application/json'
16 | }
17 | };
18 |
19 | var req = (port == 443 ? https : http).request(options, function(res){
20 | var replyData = '';
21 | res.setEncoding('utf8');
22 | res.on('data', function(chunk){
23 | replyData += chunk;
24 | });
25 | res.on('end', function(){
26 | var replyJson;
27 | try{
28 | replyJson = JSON.parse(replyData);
29 | }
30 | catch(e){
31 | callback(e);
32 | return;
33 | }
34 | callback(null, replyJson);
35 | });
36 | });
37 |
38 | req.on('error', function(e){
39 | callback(e);
40 | });
41 |
42 | req.end(data);
43 | }
44 |
45 | function rpc(host, port, method, params, callback){
46 |
47 | var data = JSON.stringify({
48 | id: "0",
49 | jsonrpc: "2.0",
50 | method: method,
51 | params: params
52 | });
53 | jsonHttpRequest(host, port, data, function(error, replyJson){
54 | if (error){
55 | callback(error);
56 | return;
57 | }
58 | callback(replyJson.error, replyJson.result)
59 | });
60 | }
61 |
62 | function batchRpc(host, port, array, callback){
63 | var rpcArray = [];
64 | for (var i = 0; i < array.length; i++){
65 | rpcArray.push({
66 | id: i.toString(),
67 | jsonrpc: "2.0",
68 | method: array[i][0],
69 | params: array[i][1]
70 | });
71 | }
72 | var data = JSON.stringify(rpcArray);
73 | jsonHttpRequest(host, port, data, callback);
74 | }
75 |
76 |
77 | module.exports = function(daemonConfig, walletConfig, poolApiConfig){
78 | return {
79 | batchRpcDaemon: function(batchArray, callback){
80 | batchRpc(daemonConfig.host, daemonConfig.port, batchArray, callback);
81 | },
82 | rpcDaemon: function(method, params, callback){
83 | rpc(daemonConfig.host, daemonConfig.port, method, params, callback);
84 | },
85 | rpcWallet: function(method, params, callback){
86 | rpc(walletConfig.host, walletConfig.port, method, params, callback);
87 | },
88 | pool: function(method, callback){
89 | jsonHttpRequest('127.0.0.1', poolApiConfig.port, '', callback, method);
90 | },
91 | jsonHttpRequest: jsonHttpRequest
92 | }
93 | };
94 |
--------------------------------------------------------------------------------
/lib/blockUnlocker.js:
--------------------------------------------------------------------------------
1 | var async = require('async');
2 |
3 | var apiInterfaces = require('./apiInterfaces.js')(config.daemon, config.wallet, config.api);
4 |
5 | var logSystem = 'unlocker';
6 | require('./exceptionWriter.js')(logSystem);
7 |
8 | log('info', logSystem, 'Started');
9 |
10 | function runInterval(){
11 | async.waterfall([
12 |
13 | //Get all block candidates in redis
14 | function(callback){
15 | redisClient.zrange(config.coin + ':blocks:candidates', 0, -1, 'WITHSCORES', function(error, results){
16 | if (error){
17 | log('error', logSystem, 'Error trying to get pending blocks from redis %j', [error]);
18 | callback(true);
19 | return;
20 | }
21 | if (results.length === 0){
22 | log('info', logSystem, 'No blocks candidates in redis');
23 | callback(true);
24 | return;
25 | }
26 |
27 | var blocks = [];
28 |
29 | for (var i = 0; i < results.length; i += 2){
30 | var parts = results[i].split(':');
31 | blocks.push({
32 | serialized: results[i],
33 | height: parseInt(results[i + 1]),
34 | hash: parts[0],
35 | time: parts[1],
36 | difficulty: parts[2],
37 | shares: parts[3]
38 | });
39 | }
40 |
41 | callback(null, blocks);
42 | });
43 | },
44 |
45 | //Check if blocks are orphaned
46 | function(blocks, callback){
47 | async.filter(blocks, function(block, mapCback){
48 | apiInterfaces.rpcDaemon('getblockheaderbyheight', {height: block.height}, function(error, result){
49 | if (error){
50 | log('error', logSystem, 'Error with getblockheaderbyheight RPC request for block %s - %j', [block.serialized, error]);
51 | block.unlocked = false;
52 | mapCback();
53 | return;
54 | }
55 | if (!result.block_header){
56 | log('error', logSystem, 'Error with getblockheaderbyheight, no details returned for %s - %j', [block.serialized, result]);
57 | block.unlocked = false;
58 | mapCback();
59 | return;
60 | }
61 | var blockHeader = result.block_header;
62 | block.orphaned = blockHeader.hash === block.hash ? 0 : 1;
63 | block.unlocked = blockHeader.depth >= config.blockUnlocker.depth;
64 | block.reward = blockHeader.reward;
65 | mapCback(block.unlocked);
66 | });
67 | }, function(unlockedBlocks){
68 |
69 | if (unlockedBlocks.length === 0){
70 | log('info', logSystem, 'No pending blocks are unlocked yet (%d pending)', [blocks.length]);
71 | callback(true);
72 | return;
73 | }
74 |
75 | callback(null, unlockedBlocks)
76 | })
77 | },
78 |
79 | //Get worker shares for each unlocked block
80 | function(blocks, callback){
81 |
82 | var redisCommands = blocks.map(function(block){
83 | return ['hgetall', config.coin + ':shares:round' + block.height];
84 | });
85 |
86 |
87 | redisClient.multi(redisCommands).exec(function(error, replies){
88 | if (error){
89 | log('error', logSystem, 'Error with getting round shares from redis %j', [error]);
90 | callback(true);
91 | return;
92 | }
93 | for (var i = 0; i < replies.length; i++){
94 | var workerShares = replies[i];
95 | blocks[i].workerShares = workerShares;
96 | }
97 | callback(null, blocks);
98 | });
99 | },
100 |
101 | //Handle orphaned blocks
102 | function(blocks, callback){
103 | var orphanCommands = [];
104 |
105 | blocks.forEach(function(block){
106 | if (!block.orphaned) return;
107 |
108 | orphanCommands.push(['del', config.coin + ':shares:round' + block.height]);
109 |
110 | orphanCommands.push(['zrem', config.coin + ':blocks:candidates', block.serialized]);
111 | orphanCommands.push(['zadd', config.coin + ':blocks:matured', block.height, [
112 | block.hash,
113 | block.time,
114 | block.difficulty,
115 | block.shares,
116 | block.orphaned
117 | ].join(':')]);
118 |
119 | if (block.workerShares) {
120 | var workerShares = block.workerShares;
121 | Object.keys(workerShares).forEach(function (worker) {
122 | orphanCommands.push(['hincrby', config.coin + ':shares:roundCurrent', worker, workerShares[worker]]);
123 | });
124 | }
125 | });
126 |
127 | if (orphanCommands.length > 0){
128 | redisClient.multi(orphanCommands).exec(function(error, replies){
129 | if (error){
130 | log('error', logSystem, 'Error with cleaning up data in redis for orphan block(s) %j', [error]);
131 | callback(true);
132 | return;
133 | }
134 | callback(null, blocks);
135 | });
136 | }
137 | else{
138 | callback(null, blocks);
139 | }
140 | },
141 |
142 | //Handle unlocked blocks
143 | function(blocks, callback){
144 | var unlockedBlocksCommands = [];
145 | var payments = {};
146 | var totalBlocksUnlocked = 0;
147 | blocks.forEach(function(block){
148 | if (block.orphaned) return;
149 | totalBlocksUnlocked++;
150 |
151 | unlockedBlocksCommands.push(['del', config.coin + ':shares:round' + block.height]);
152 | unlockedBlocksCommands.push(['zrem', config.coin + ':blocks:candidates', block.serialized]);
153 | unlockedBlocksCommands.push(['zadd', config.coin + ':blocks:matured', block.height, [
154 | block.hash,
155 | block.time,
156 | block.difficulty,
157 | block.shares,
158 | block.orphaned,
159 | block.reward
160 | ].join(':')]);
161 |
162 | var feePercent = config.blockUnlocker.poolFee / 100;
163 |
164 | if (Object.keys(donations).length) {
165 | for(var wallet in donations) {
166 | var percent = donations[wallet] / 100;
167 | feePercent += percent;
168 | payments[wallet] = Math.round(block.reward * percent);
169 | log('info', logSystem, 'Block %d donation to %s as %d percent of reward: %d', [block.height, wallet, percent, payments[wallet]]);
170 | }
171 | }
172 |
173 | var reward = Math.round(block.reward - (block.reward * feePercent));
174 |
175 | log('info', logSystem, 'Unlocked %d block with reward %d and donation fee %d. Miners reward: %d', [block.height, block.reward, feePercent, reward]);
176 |
177 | if (block.workerShares) {
178 | var totalShares = parseInt(block.shares);
179 | Object.keys(block.workerShares).forEach(function (worker) {
180 | var percent = block.workerShares[worker] / totalShares;
181 | var workerReward = Math.round(reward * percent);
182 | payments[worker] = (payments[worker] || 0) + workerReward;
183 | log('info', logSystem, 'Block %d payment to %s for %d shares: %d', [block.height, worker, totalShares, payments[worker]]);
184 | });
185 | }
186 | });
187 |
188 | for (var worker in payments) {
189 | var amount = parseInt(payments[worker]);
190 | if (amount <= 0){
191 | delete payments[worker];
192 | continue;
193 | }
194 | unlockedBlocksCommands.push(['hincrby', config.coin + ':workers:' + worker, 'balance', amount]);
195 | }
196 |
197 | if (unlockedBlocksCommands.length === 0){
198 | log('info', logSystem, 'No unlocked blocks yet (%d pending)', [blocks.length]);
199 | callback(true);
200 | return;
201 | }
202 |
203 | redisClient.multi(unlockedBlocksCommands).exec(function(error, replies){
204 | if (error){
205 | log('error', logSystem, 'Error with unlocking blocks %j', [error]);
206 | callback(true);
207 | return;
208 | }
209 | log('info', logSystem, 'Unlocked %d blocks and update balances for %d workers', [totalBlocksUnlocked, Object.keys(payments).length]);
210 | callback(null);
211 | });
212 | }
213 | ], function(error, result){
214 | setTimeout(runInterval, config.blockUnlocker.interval * 1000);
215 | })
216 | }
217 |
218 | runInterval();
219 |
--------------------------------------------------------------------------------
/lib/charts.js:
--------------------------------------------------------------------------------
1 | var fs = require('fs');
2 | var async = require('async');
3 | var http = require('http');
4 | var apiInterfaces = require('./apiInterfaces.js')(config.daemon, config.wallet, config.api);
5 |
6 | var logSystem = 'charts';
7 | require('./exceptionWriter.js')(logSystem);
8 |
9 | log('info', logSystem, 'Started');
10 |
11 | function startDataCollectors() {
12 | async.each(Object.keys(config.charts.pool), function(chartName) {
13 | var settings = config.charts.pool[chartName];
14 | if(settings.enabled) {
15 | setInterval(function() {
16 | collectPoolStatWithInterval(chartName, settings);
17 | }, settings.updateInterval * 1000);
18 | }
19 | });
20 |
21 | var settings = config.charts.user.hashrate;
22 | if(settings.enabled) {
23 | setInterval(function() {
24 | collectUsersHashrate('hashrate', settings);
25 | }, settings.updateInterval * 1000)
26 | }
27 | }
28 |
29 | function getChartDataFromRedis(chartName, callback) {
30 | redisClient.get(getStatsRedisKey(chartName), function(error, data) {
31 | callback(data ? JSON.parse(data) : []);
32 | });
33 | }
34 |
35 | function getUserHashrateChartData(address, callback) {
36 | getChartDataFromRedis('hashrate:' + address, callback);
37 | }
38 |
39 | function convertPaymentsDataToChart(paymentsData) {
40 | var data = [];
41 | if(paymentsData && paymentsData.length) {
42 | for(var i = 0; paymentsData[i]; i += 2) {
43 | data.unshift([+paymentsData[i + 1], paymentsData[i].split(':')[1]]);
44 | }
45 | }
46 | return data;
47 | }
48 |
49 | function getUserChartsData(address, paymentsData, callback) {
50 | var stats = {};
51 | var chartsFuncs = {
52 | hashrate: function(callback) {
53 | getUserHashrateChartData(address, function(data) {
54 | callback(null, data);
55 | });
56 | },
57 |
58 | payments: function(callback) {
59 | callback(null, convertPaymentsDataToChart(paymentsData));
60 | }
61 | };
62 | for(var chartName in chartsFuncs) {
63 | if(!config.charts.user[chartName].enabled) {
64 | delete chartsFuncs[chartName];
65 | }
66 | }
67 | async.parallel(chartsFuncs, callback);
68 | }
69 |
70 | function getStatsRedisKey(chartName) {
71 | return config.coin + ':charts:' + chartName;
72 | }
73 |
74 | var chartStatFuncs = {
75 | hashrate: getPoolHashrate,
76 | workers: getPoolWorkers,
77 | difficulty: getNetworkDifficulty,
78 | price: getCoinPrice,
79 | profit: getCoinProfit
80 | };
81 |
82 | var statValueHandler = {
83 | avg: function(set, value) {
84 | set[1] = (set[1] * set[2] + value) / (set[2] + 1);
85 | },
86 | avgRound: function(set, value) {
87 | statValueHandler.avg(set, value);
88 | set[1] = Math.round(set[1]);
89 | },
90 | max: function(set, value) {
91 | if(value > set[1]) {
92 | set[1] = value;
93 | }
94 | }
95 | };
96 |
97 | var preSaveFunctions = {
98 | hashrate: statValueHandler.avgRound,
99 | workers: statValueHandler.max,
100 | difficulty: statValueHandler.avgRound,
101 | price: statValueHandler.avg,
102 | profit: statValueHandler.avg
103 | };
104 |
105 | function storeCollectedValues(chartName, values, settings) {
106 | for(var i in values) {
107 | storeCollectedValue(chartName + ':' + i, values[i], settings);
108 | }
109 | }
110 |
111 | function storeCollectedValue(chartName, value, settings) {
112 | var now = new Date() / 1000 | 0;
113 | getChartDataFromRedis(chartName, function(sets) {
114 | var lastSet = sets[sets.length - 1]; // [time, avgValue, updatesCount]
115 | if(!lastSet || now - lastSet[0] > settings.stepInterval) {
116 | lastSet = [now, value, 1];
117 | sets.push(lastSet);
118 | while(now - sets[0][0] > settings.maximumPeriod) { // clear old sets
119 | sets.shift();
120 | }
121 | }
122 | else {
123 | preSaveFunctions[chartName]
124 | ? preSaveFunctions[chartName](lastSet, value)
125 | : statValueHandler.avgRound(lastSet, value);
126 | lastSet[2]++;
127 | }
128 | redisClient.set(getStatsRedisKey(chartName), JSON.stringify(sets));
129 | log('info', logSystem, chartName + ' chart collected value ' + value + '. Total sets count ' + sets.length);
130 | });
131 | }
132 |
133 | function collectPoolStatWithInterval(chartName, settings) {
134 | async.waterfall([
135 | chartStatFuncs[chartName],
136 | function(value, callback) {
137 | storeCollectedValue(chartName, value, settings, callback);
138 | }
139 | ]);
140 | }
141 |
142 | function getPoolStats(callback) {
143 | apiInterfaces.pool('/stats', callback);
144 | }
145 |
146 | function getPoolHashrate(callback) {
147 | getPoolStats(function(error, stats) {
148 | callback(error, stats.pool ? Math.round(stats.pool.hashrate) : null);
149 | });
150 | }
151 |
152 | function getPoolWorkers(callback) {
153 | getPoolStats(function(error, stats) {
154 | callback(error, stats.pool ? stats.pool.miners : null);
155 | });
156 | }
157 |
158 | function getNetworkDifficulty(callback) {
159 | getPoolStats(function(error, stats) {
160 | callback(error, stats.pool ? stats.network.difficulty : null);
161 | });
162 | }
163 |
164 | function getUsersHashrates(callback) {
165 | apiInterfaces.pool('/miners_hashrate', function(error, data) {
166 | callback(data.minersHashrate);
167 | });
168 | }
169 |
170 | function collectUsersHashrate(chartName, settings) {
171 | var redisBaseKey = getStatsRedisKey(chartName) + ':';
172 | redisClient.keys(redisBaseKey + '*', function(keys) {
173 | var hashrates = {};
174 | for(var i in keys) {
175 | hashrates[keys[i].substr(keys[i].length)] = 0;
176 | }
177 | getUsersHashrates(function(newHashrates) {
178 | for(var address in newHashrates) {
179 | hashrates[address] = newHashrates[address];
180 | }
181 | storeCollectedValues(chartName, hashrates, settings);
182 | });
183 | });
184 | }
185 |
186 | function getCoinPrice(callback) {
187 | apiInterfaces.jsonHttpRequest('www.cryptonator.com', 443, '', function(error, response) {
188 | callback(response.error ? response.error : error, response.success ? +response.ticker.price : null);
189 | }, '/api/ticker/' + config.symbol.toLowerCase() + '-usd');
190 | }
191 |
192 | function getCoinProfit(callback) {
193 | getCoinPrice(function(error, price) {
194 | if(error) {
195 | callback(error);
196 | return;
197 | }
198 | getPoolStats(function(error, stats) {
199 | if(error) {
200 | callback(error);
201 | return;
202 | }
203 | callback(null, stats.network.reward * price / stats.network.difficulty / config.coinUnits);
204 | });
205 | });
206 | }
207 |
208 | function getPoolChartsData(callback) {
209 | var chartsNames = [];
210 | var redisKeys = [];
211 | for(var chartName in config.charts.pool) {
212 | if(config.charts.pool[chartName].enabled) {
213 | chartsNames.push(chartName);
214 | redisKeys.push(getStatsRedisKey(chartName));
215 | }
216 | }
217 | if(redisKeys.length) {
218 | redisClient.mget(redisKeys, function(error, data) {
219 | var stats = {};
220 | if(data) {
221 | for(var i in data) {
222 | if(data[i]) {
223 | stats[chartsNames[i]] = JSON.parse(data[i]);
224 | }
225 | }
226 | }
227 | callback(error, stats);
228 | });
229 | }
230 | else {
231 | callback(null, {});
232 | }
233 | }
234 |
235 | module.exports = {
236 | startDataCollectors: startDataCollectors,
237 | getUserChartsData: getUserChartsData,
238 | getPoolChartsData: getPoolChartsData
239 | };
240 |
--------------------------------------------------------------------------------
/lib/chartsDataCollector.js:
--------------------------------------------------------------------------------
1 | var fs = require('fs');
2 | var async = require('async');
3 | var http = require('http');
4 | var charts = require('./charts.js');
5 |
6 | var logSystem = 'chartsDataCollector';
7 | require('./exceptionWriter.js')(logSystem);
8 |
9 | log('info', logSystem, 'Started');
10 |
11 | charts.startDataCollectors();
12 |
--------------------------------------------------------------------------------
/lib/cli.js:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xdn-project/cryptonote-universal-pool/ff103c5859879825028d51fa6e8a280968d5fc51/lib/cli.js
--------------------------------------------------------------------------------
/lib/configReader.js:
--------------------------------------------------------------------------------
1 | var fs = require('fs');
2 |
3 | var configFile = (function(){
4 | for (var i = 0; i < process.argv.length; i++){
5 | if (process.argv[i].indexOf('-config=') === 0)
6 | return process.argv[i].split('=')[1];
7 | }
8 | return 'config.json';
9 | })();
10 |
11 |
12 | try {
13 | global.config = JSON.parse(fs.readFileSync(configFile));
14 | }
15 | catch(e){
16 | console.error('Failed to read config file ' + configFile + '\n\n' + e);
17 | return;
18 | }
19 |
20 | var donationAddresses = {
21 | devDonation: {
22 | XMR: '45Jmf8PnJKziGyrLouJMeBFw2yVyX1QB52sKEQ4S1VSU2NVsaVGPNu4bWKkaHaeZ6tWCepP6iceZk8XhTLzDaEVa72QrtVh'
23 | },
24 | coreDevDonation: {
25 | BCN: '252m7ru3wT5McAUztrZDExJ9PgnmyJVgk2ayucQLt13dFrf5DE4SrSBVkbtVhvZbRj1Ty4cVWaE6MGDVArZLpuMhCkrvToA',
26 | BBR: '@zoidberg',
27 | XMR: '46BeWrHpwXmHDpDEUmZBWZfoQpdc6HaERCNmx1pEYL2rAcuwufPN9rXHHtyUA4QVy66qeFQkn6sfK8aHYjA3jk3o1Bv16em',
28 | QCN: '1R9wwAH68XNGHZBsSCbyPL5EBepCoqnPPYpUuYx7jyZtc1SqekoM5p4iiB4EnkHBMXUrkwg7vR35vcoC6h48t7AjKXqXWqX',
29 | FCN: '6ntYwFY2syKVha7K1KZrhD8Uyzc2VsCpAjGi8YptCVHmfeqkAyRWQSX8gV23uvnHZY2LssBMoidGfCrVAc9k1RSsN7WKSf2',
30 | AEON: 'WmsG9mv8iSeJ8w2U9J1jRXNbLT7bCUj9VShzGuBctrhEBMHWxLZ2noSYhs8WgM4RDR68mrMW7hm33NRiDV8bNVu52azJb6XoN',
31 | OEC: 'C9ouydpeiyT2gVr5MqPUjHVJ26nJ9b8ZmMtVYRRTpGqHXA973MvzUWiFFhFCapkLmdVivd1c8Fj5wKDNw3oao7K44bUeAqx',
32 | DSH: 'D3z2DDWygoZU4NniCNa4oMjjKi45dC2KHUWUyD1RZ1pfgnRgcHdfLVQgh5gmRv4jwEjCX5LoLERAf5PbjLS43Rkd8vFUM1m'
33 | },
34 | extraFeaturesDevDonation: {
35 | XDN: 'dddcPW8VjhJA9U2QDPunnkL8Yky83TdEBGThXsETtmAx8q7jvni7Kt4hn8pqS3ks7GhM2z9BeD22jgKewZ2kQhWK27ZaGfLHQ',
36 | BCN: '23emzdEQqoWAifE1ZQLTrGAmVkdzjami82xgX4zWoX2VbiuGuunMJ1oF14PPa1cVRgGFz8tUWevsSNzMcPqHiQmF7iSzS1g',
37 | BBR: '1Gy4NimzTgyhcZ22432N4ojP9HC6mHpML2g8SsmmjPZS4o8SYNFND99LAihRPHA2ddarf3okkJ3umTC2gLpysKBfLi4hfTF',
38 | XMR: '43JNtJkxnhX789pJnCV6W4DQt8BqAWVoV4pqjGiWZ9845ee3aTBRBibMBzSziQi9BD5aEEpegQjLwguUgsXecB5bCY5wrMe',
39 | QCN: '1MafhBsdrkW3ssQexQzHf8Q2VBEWE3DmrbySKJzXXNJFeHHTWahDkJ3iLkiKnAMMtzHPeLrsYVmkQJJ9DJx3ToodKUapV8p',
40 | FCN: '6iAu6xDGnSFekMxJj7S61aepNVXbyCrV7PgWWKSfsEPyXbUjHAxjgq3KwED3dWrgddCRRtwBrrYgmVLZR7vdBr3KLe9Cowd',
41 | MCN: 'Vdufe8Pjkp2apvJC2N3Q7KdqiDDnLR3cH8hPhB2hjBtdXRxnHmHdgESbCjAD5dv1oiFrA1jKJQqszHWELdNygCGW2Ri6qRH1B',
42 | AEON: 'Wmsfi4rDdUC4xQyMo7f4BkfuPtSooPZ3wfx8e7JFXaKyfFY5buDJF4UakwhLp3FXxKVwB3ZFLQ3bTUBksCoG3tVQ2tzkrCZDm',
43 | OEC: 'C53KdM3sWk2P27yvqihNDEVsCtDQH9koJTdmEX96ftqgTvSsuvg5HMJ2dLnynwcWr5d3oMvwzsQVKdVeYchG5iU6L5rNJjd',
44 | DSH: 'D9t1KjB9w2haRp29ueJ9jHfTyq1FSzpMqavKpfFuwa8yEdHKuryfmh4W6ZzbHC71JFLoRD4ny7HWm15jb52JYcye7bBjD62',
45 | INF8: 'inf8FtwGgmaATeXKvycUT7BfxiawxqhfRXaahPog7s4c7L8qreSvnebNDvwfDBXrip8ptgKgbToV73mS5M1cNviY5sbKhKitCd'
46 | }
47 | };
48 |
49 | global.donations = {};
50 |
51 | for(var configOption in donationAddresses) {
52 | var percent = config.blockUnlocker[configOption];
53 | var wallet = donationAddresses[configOption][config.symbol];
54 | if(percent && wallet) {
55 | global.donations[wallet] = percent;
56 | }
57 | }
58 |
59 | global.version = "v1.1.4";
60 |
--------------------------------------------------------------------------------
/lib/exceptionWriter.js:
--------------------------------------------------------------------------------
1 | var fs = require('fs');
2 | var cluster = require('cluster');
3 |
4 | var dateFormat = require('dateformat');
5 |
6 |
7 | module.exports = function(logSystem){
8 |
9 | process.on('uncaughtException', function(err) {
10 | console.log('\n' + err.stack + '\n');
11 | var time = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss');
12 | fs.appendFile(config.logging.files.directory + '/' + logSystem + '_crash.log', time + '\n' + err.stack + '\n\n', function(err){
13 | if (cluster.isWorker)
14 | process.exit();
15 | });
16 | });
17 | };
--------------------------------------------------------------------------------
/lib/logger.js:
--------------------------------------------------------------------------------
1 | var fs = require('fs');
2 | var util = require('util');
3 |
4 | var dateFormat = require('dateformat');
5 | var clc = require('cli-color');
6 |
7 | var severityMap = {
8 | 'info': clc.blue,
9 | 'warn': clc.yellow,
10 | 'error': clc.red
11 | };
12 |
13 | var severityLevels = ['info', 'warn', 'error'];
14 |
15 |
16 | var logDir = config.logging.files.directory;
17 |
18 | if (!fs.existsSync(logDir)){
19 | try {
20 | fs.mkdirSync(logDir);
21 | }
22 | catch(e){
23 | throw e;
24 | }
25 | }
26 |
27 | var pendingWrites = {};
28 |
29 | setInterval(function(){
30 | for (var fileName in pendingWrites){
31 | var data = pendingWrites[fileName];
32 | fs.appendFile(fileName, data);
33 | delete pendingWrites[fileName];
34 | }
35 | }, config.logging.files.flushInterval * 1000);
36 |
37 | global.log = function(severity, system, text, data){
38 |
39 | var logConsole = severityLevels.indexOf(severity) >= severityLevels.indexOf(config.logging.console.level);
40 | var logFiles = severityLevels.indexOf(severity) >= severityLevels.indexOf(config.logging.files.level);
41 |
42 | if (!logConsole && !logFiles) return;
43 |
44 | var time = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss');
45 | var formattedMessage = text;
46 |
47 | if (data) {
48 | data.unshift(text);
49 | formattedMessage = util.format.apply(null, data);
50 | }
51 |
52 | if (logConsole){
53 | if (config.logging.console.colors)
54 | console.log(severityMap[severity](time) + clc.white.bold(' [' + system + '] ') + formattedMessage);
55 | else
56 | console.log(time + ' [' + system + '] ' + formattedMessage);
57 | }
58 |
59 |
60 | if (logFiles) {
61 | var fileName = logDir + '/' + system + '_' + severity + '.log';
62 | var fileLine = time + ' ' + formattedMessage + '\n';
63 | pendingWrites[fileName] = (pendingWrites[fileName] || '') + fileLine;
64 | }
65 | };
--------------------------------------------------------------------------------
/lib/paymentProcessor.js:
--------------------------------------------------------------------------------
1 | var fs = require('fs');
2 |
3 | var async = require('async');
4 |
5 | var apiInterfaces = require('./apiInterfaces.js')(config.daemon, config.wallet, config.api);
6 |
7 |
8 | var logSystem = 'payments';
9 | require('./exceptionWriter.js')(logSystem);
10 |
11 |
12 | log('info', logSystem, 'Started');
13 |
14 |
15 | function runInterval(){
16 | async.waterfall([
17 |
18 | //Get worker keys
19 | function(callback){
20 | redisClient.keys(config.coin + ':workers:*', function(error, result) {
21 | if (error) {
22 | log('error', logSystem, 'Error trying to get worker balances from redis %j', [error]);
23 | callback(true);
24 | return;
25 | }
26 | callback(null, result);
27 | });
28 | },
29 |
30 | //Get worker balances
31 | function(keys, callback){
32 | var redisCommands = keys.map(function(k){
33 | return ['hget', k, 'balance'];
34 | });
35 | redisClient.multi(redisCommands).exec(function(error, replies){
36 | if (error){
37 | log('error', logSystem, 'Error with getting balances from redis %j', [error]);
38 | callback(true);
39 | return;
40 | }
41 | var balances = {};
42 | for (var i = 0; i < replies.length; i++){
43 | var parts = keys[i].split(':');
44 | var workerId = parts[parts.length - 1];
45 | balances[workerId] = parseInt(replies[i]) || 0
46 |
47 | }
48 | callback(null, balances);
49 | });
50 | },
51 |
52 | //Filter workers under balance threshold for payment
53 | function(balances, callback){
54 |
55 | var payments = {};
56 |
57 | for (var worker in balances){
58 | var balance = balances[worker];
59 | if (balance >= config.payments.minPayment){
60 | var remainder = balance % config.payments.denomination;
61 | var payout = balance - remainder;
62 | if (payout < 0) continue;
63 | payments[worker] = payout;
64 | }
65 | }
66 |
67 | if (Object.keys(payments).length === 0){
68 | log('info', logSystem, 'No workers\' balances reached the minimum payment threshold');
69 | callback(true);
70 | return;
71 | }
72 |
73 | var transferCommands = [];
74 | var addresses = 0;
75 | var commandAmount = 0;
76 | var commandIndex = 0;
77 |
78 | for (var worker in payments){
79 | var amount = parseInt(payments[worker]);
80 | if(config.payments.maxTransactionAmount && amount + commandAmount > config.payments.maxTransactionAmount) {
81 | amount = config.payments.maxTransactionAmount - commandAmount;
82 | }
83 |
84 | if(!transferCommands[commandIndex]) {
85 | transferCommands[commandIndex] = {
86 | redis: [],
87 | amount : 0,
88 | rpc: {
89 | destinations: [],
90 | fee: config.payments.transferFee,
91 | mixin: config.payments.mixin,
92 | unlock_time: 0
93 | }
94 | };
95 | }
96 |
97 | transferCommands[commandIndex].rpc.destinations.push({amount: amount, address: worker});
98 | transferCommands[commandIndex].redis.push(['hincrby', config.coin + ':workers:' + worker, 'balance', -amount]);
99 | transferCommands[commandIndex].redis.push(['hincrby', config.coin + ':workers:' + worker, 'paid', amount]);
100 | transferCommands[commandIndex].amount += amount;
101 |
102 | addresses++;
103 | commandAmount += amount;
104 | if (addresses >= config.payments.maxAddresses || ( config.payments.maxTransactionAmount && commandAmount >= config.payments.maxTransactionAmount)) {
105 | commandIndex++;
106 | addresses = 0;
107 | commandAmount = 0;
108 | }
109 | }
110 |
111 | var timeOffset = 0;
112 |
113 | async.filter(transferCommands, function(transferCmd, cback){
114 | apiInterfaces.rpcWallet('transfer', transferCmd.rpc, function(error, result){
115 | if (error){
116 | log('error', logSystem, 'Error with transfer RPC request to wallet daemon %j', [error]);
117 | log('error', logSystem, 'Payments failed to send to %j', transferCmd.rpc.destinations);
118 | cback(false);
119 | return;
120 | }
121 |
122 | var now = (timeOffset++) + Date.now() / 1000 | 0;
123 | var txHash = result.tx_hash.replace('<', '').replace('>', '');
124 |
125 |
126 | transferCmd.redis.push(['zadd', config.coin + ':payments:all', now, [
127 | txHash,
128 | transferCmd.amount,
129 | transferCmd.rpc.fee,
130 | transferCmd.rpc.mixin,
131 | Object.keys(transferCmd.rpc.destinations).length
132 | ].join(':')]);
133 |
134 |
135 | for (var i = 0; i < transferCmd.rpc.destinations.length; i++){
136 | var destination = transferCmd.rpc.destinations[i];
137 | transferCmd.redis.push(['zadd', config.coin + ':payments:' + destination.address, now, [
138 | txHash,
139 | destination.amount,
140 | transferCmd.rpc.fee,
141 | transferCmd.rpc.mixin
142 | ].join(':')]);
143 | }
144 |
145 |
146 | log('info', logSystem, 'Payments sent via wallet daemon %j', [result]);
147 | redisClient.multi(transferCmd.redis).exec(function(error, replies){
148 | if (error){
149 | log('error', logSystem, 'Super critical error! Payments sent yet failing to update balance in redis, double payouts likely to happen %j', [error]);
150 | log('error', logSystem, 'Double payments likely to be sent to %j', transferCmd.rpc.destinations);
151 | cback(false);
152 | return;
153 | }
154 | cback(true);
155 | });
156 | });
157 | }, function(succeeded){
158 | var failedAmount = transferCommands.length - succeeded.length;
159 | log('info', logSystem, 'Payments splintered and %d successfully sent, %d failed', [succeeded.length, failedAmount]);
160 | callback(null);
161 | });
162 |
163 | }
164 |
165 | ], function(error, result){
166 | setTimeout(runInterval, config.payments.interval * 1000);
167 | });
168 | }
169 |
170 | runInterval();
171 |
--------------------------------------------------------------------------------
/lib/utils.js:
--------------------------------------------------------------------------------
1 | var base58 = require('base58-native');
2 | var cnUtil = require('cryptonote-util');
3 |
4 | exports.uid = function(){
5 | var min = 100000000000000;
6 | var max = 999999999999999;
7 | var id = Math.floor(Math.random() * (max - min + 1)) + min;
8 | return id.toString();
9 | };
10 |
11 | exports.ringBuffer = function(maxSize){
12 | var data = [];
13 | var cursor = 0;
14 | var isFull = false;
15 |
16 | return {
17 | append: function(x){
18 | if (isFull){
19 | data[cursor] = x;
20 | cursor = (cursor + 1) % maxSize;
21 | }
22 | else{
23 | data.push(x);
24 | cursor++;
25 | if (data.length === maxSize){
26 | cursor = 0;
27 | isFull = true;
28 | }
29 | }
30 | },
31 | avg: function(plusOne){
32 | var sum = data.reduce(function(a, b){ return a + b }, plusOne || 0);
33 | return sum / ((isFull ? maxSize : cursor) + (plusOne ? 1 : 0));
34 | },
35 | size: function(){
36 | return isFull ? maxSize : cursor;
37 | },
38 | clear: function(){
39 | data = [];
40 | cursor = 0;
41 | isFull = false;
42 | }
43 | };
44 | };
45 |
46 | exports.varIntEncode = function(n){
47 |
48 | };
49 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "cryptonote-universal-pool",
3 | "version": "0.0.1",
4 | "license": "GPL-2.0",
5 | "author": "Matthew Little",
6 | "repository": {
7 | "type": "git",
8 | "url": "https://github.com/fancoder/cryptonote-universal-pool.git"
9 | },
10 | "dependencies": {
11 | "bignum": "*",
12 | "async": "*",
13 | "redis": "*",
14 | "cli-color": "*",
15 | "dateformat": "*",
16 | "base58-native": "*",
17 | "multi-hashing": "git://github.com/fancoder/node-multi-hashing.git",
18 | "cryptonote-util": "https://github.com/xdn-project/node-cryptonote-util"
19 | },
20 | "engines": {
21 | "node": ">=0.10"
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/redisBlocksUpgrade.js:
--------------------------------------------------------------------------------
1 |
2 |
3 | /*
4 |
5 | This script converts the block data in redis from the old format (v0.99.0.6 and earlier) to the new format
6 | used in v0.99.1+
7 |
8 | */
9 |
10 | var util = require('util');
11 |
12 | var async = require('async');
13 |
14 | var redis = require('redis');
15 |
16 | require('./lib/configReader.js');
17 |
18 | var apiInterfaces = require('./lib/apiInterfaces.js')(config.daemon, config.wallet);
19 |
20 |
21 | function log(severity, system, text, data){
22 |
23 | var formattedMessage = text;
24 |
25 | if (data) {
26 | data.unshift(text);
27 | formattedMessage = util.format.apply(null, data);
28 | }
29 |
30 | console.log(severity + ': ' + formattedMessage);
31 | }
32 |
33 |
34 | var logSystem = 'reward script';
35 |
36 | var redisClient = redis.createClient(config.redis.port, config.redis.host);
37 |
38 | function getTotalShares(height, callback){
39 |
40 | redisClient.hgetall(config.coin + ':shares:round' + height, function(err, workerShares){
41 |
42 | if (err) {
43 | callback(err);
44 | return;
45 | }
46 |
47 | var totalShares = Object.keys(workerShares).reduce(function(p, c){
48 | return p + parseInt(workerShares[c])
49 | }, 0);
50 |
51 | callback(null, totalShares);
52 |
53 | });
54 | }
55 |
56 |
57 | async.series([
58 | function(callback){
59 | redisClient.smembers(config.coin + ':blocksUnlocked', function(error, result){
60 | if (error){
61 | log('error', logSystem, 'Error trying to get unlocke blocks from redis %j', [error]);
62 | callback();
63 | return;
64 | }
65 | if (result.length === 0){
66 | log('info', logSystem, 'No unlocked blocks in redis');
67 | callback();
68 | return;
69 | }
70 |
71 | var blocks = result.map(function(item){
72 | var parts = item.split(':');
73 | return {
74 | height: parseInt(parts[0]),
75 | difficulty: parts[1],
76 | hash: parts[2],
77 | time: parts[3],
78 | shares: parts[4],
79 | orphaned: 0
80 | };
81 | });
82 |
83 | async.map(blocks, function(block, mapCback){
84 | apiInterfaces.rpcDaemon('getblockheaderbyheight', {height: block.height}, function(error, result){
85 | if (error){
86 | log('error', logSystem, 'Error with getblockheaderbyheight RPC request for block %s - %j', [block.serialized, error]);
87 | mapCback(null, block);
88 | return;
89 | }
90 | if (!result.block_header){
91 | log('error', logSystem, 'Error with getblockheaderbyheight, no details returned for %s - %j', [block.serialized, result]);
92 | mapCback(null, block);
93 | return;
94 | }
95 | var blockHeader = result.block_header;
96 | block.reward = blockHeader.reward;
97 | mapCback(null, block);
98 | });
99 | }, function(err, blocks){
100 |
101 | if (blocks.length === 0){
102 | log('info', logSystem, 'No unlocked blocks');
103 | callback();
104 | return;
105 | }
106 |
107 | var zaddCommands = [config.coin + ':blocks:matured'];
108 |
109 | for (var i = 0; i < blocks.length; i++){
110 | var block = blocks[i];
111 | zaddCommands.push(block.height);
112 | zaddCommands.push([
113 | block.hash,
114 | block.time,
115 | block.difficulty,
116 | block.shares,
117 | block.orphaned,
118 | block.reward
119 | ].join(':'));
120 | }
121 |
122 | redisClient.zadd(zaddCommands, function(err, result){
123 | if (err){
124 | console.log('failed zadd ' + JSON.stringify(err));
125 | callback();
126 | return;
127 | }
128 | console.log('successfully converted unlocked blocks to matured blocks');
129 | callback();
130 | });
131 |
132 |
133 | });
134 | });
135 | },
136 | function(callback){
137 | redisClient.smembers(config.coin + ':blocksPending', function(error, result) {
138 | if (error) {
139 | log('error', logSystem, 'Error trying to get pending blocks from redis %j', [error]);
140 | callback();
141 | return;
142 | }
143 | if (result.length === 0) {
144 | log('info', logSystem, 'No pending blocks in redis');
145 | callback();
146 | return;
147 | }
148 |
149 | async.map(result, function(item, mapCback){
150 | var parts = item.split(':');
151 | var block = {
152 | height: parseInt(parts[0]),
153 | difficulty: parts[1],
154 | hash: parts[2],
155 | time: parts[3],
156 | serialized: item
157 | };
158 | getTotalShares(block.height, function(err, shares){
159 | block.shares = shares;
160 | mapCback(null, block);
161 | });
162 | }, function(err, blocks){
163 |
164 | var zaddCommands = [config.coin + ':blocks:candidates'];
165 |
166 | for (var i = 0; i < blocks.length; i++){
167 | var block = blocks[i];
168 | zaddCommands.push(block.height);
169 | zaddCommands.push([
170 | block.hash,
171 | block.time,
172 | block.difficulty,
173 | block.shares
174 | ].join(':'));
175 | }
176 |
177 | redisClient.zadd(zaddCommands, function(err, result){
178 | if (err){
179 | console.log('failed zadd ' + JSON.stringify(err));
180 | return;
181 | }
182 | console.log('successfully converted pending blocks to block candidates');
183 | });
184 |
185 | });
186 |
187 | });
188 | }
189 | ], function(){
190 | process.exit();
191 | });
--------------------------------------------------------------------------------
/website/admin.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
68 |
69 |
70 |
71 |
222 |
223 |
224 |
225 |
226 |
69 | You can Download
70 | and run cryptonote-easy-miner
71 | which will automatically generate your wallet address and run CPUMiner with the proper parameters.
72 |