├── .gitignore
├── LICENSE
├── README.md
├── config_example.json
├── init.js
├── lib
├── api.js
├── apiInterfaces.js
├── blockUnlocker.js
├── cli.js
├── configReader.js
├── exceptionWriter.js
├── logger.js
├── paymentProcessor.js
├── pool.js
└── utils.js
├── package.json
├── redisBlocksUpgrade.js
└── website_example
├── admin.html
├── config.js
├── custom.css
├── custom.js
├── index.html
└── pages
├── getting_started.html
├── home.html
├── payments.html
├── pool_blocks.html
└── support.html
/.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 | ## This repo is not maintained. Pull requests that are critical or of high quality and well tested are accepted - but not much more.
2 | ### Looking for maintainers. Please open an issue if interested.
3 |
4 | --------
5 |
6 |
7 | node-cryptonote-pool
8 | ====================
9 |
10 | High performance Node.js (with native C addons) mining pool for CryptoNote based coins such as Bytecoin, Monero, QuazarCoin, HoneyPenny, etc..
11 | Comes with lightweight example front-end script which uses the pool's AJAX API.
12 |
13 |
14 |
15 | #### Table of Contents
16 | * [Features](#features)
17 | * [Community Support](#community--support)
18 | * [Pools Using This Software](#pools-using-this-software)
19 | * [Usage](#usage)
20 | * [Requirements](#requirements)
21 | * [Downloading & Installing](#1-downloading--installing)
22 | * [Configuration](#2-configuration)
23 | * [Configure Easyminer](#3-optional-configure-cryptonote-easy-miner-for-your-pool)
24 | * [Starting the Pool](#4-start-the-pool)
25 | * [Host the front-end](#5-host-the-front-end)
26 | * [Customizing your website](#6-customize-your-website)
27 | * [Upgrading](#upgrading)
28 | * [Setting up Testnet](#setting-up-testnet)
29 | * [JSON-RPC Commands from CLI](#json-rpc-commands-from-cli)
30 | * [Monitoring Your Pool](#monitoring-your-pool)
31 | * [Donations](#donations)
32 | * [Credits](#credits)
33 | * [License](#license)
34 |
35 |
36 | #### Features
37 |
38 | * TCP (stratum-like) protocol for server-push based jobs
39 | * Compared to old HTTP protocol, this has a higher hash rate, lower network/CPU server load, lower orphan
40 | block percent, and less error prone
41 | * IP banning to prevent low-diff share attacks
42 | * Socket flooding detection
43 | * Payment processing
44 | * Splintered transactions to deal with max transaction size
45 | * Minimum payment threshold before balance will be paid out
46 | * Minimum denomination for truncating payment amount precision to reduce size/complexity of block transactions
47 | * Detailed logging
48 | * Ability to configure multiple ports - each with their own difficulty
49 | * Variable difficulty / share limiter
50 | * Share trust algorithm to reduce share validation hashing CPU load
51 | * Clustering for vertical scaling
52 | * Modular components for horizontal scaling (pool server, database, stats/API, payment processing, front-end)
53 | * Live stats API (using AJAX long polling with CORS)
54 | * Currency network/block difficulty
55 | * Current block height
56 | * Network hashrate
57 | * Pool hashrate
58 | * Each miners' individual stats (hashrate, shares submitted, pending balance, total paid, etc)
59 | * Blocks found (pending, confirmed, and orphaned)
60 | * An easily extendable, responsive, light-weight front-end using API to display data
61 | * Worker login validation (make sure miners are using proper wallet addresses for mining)
62 |
63 |
64 | ### Community / Support
65 |
66 | * [CryptoNote Forum](https://forum.cryptonote.org/)
67 | * [Bytecoin Github](https://github.com/amjuarez/bytecoin)
68 | * [Monero Github](https://github.com/monero-project/bitmonero)
69 | * [Monero Announcement Thread](https://bitcointalk.org/index.php?topic=583449.0)
70 | * IRC (freenode)
71 | * Support / general discussion join #monero: https://webchat.freenode.net/?channels=#monero
72 | * Development discussion join #monero-dev: https://webchat.freenode.net/?channels=#monero-dev
73 |
74 |
75 | #### Pools Using This Software
76 |
77 | * http://xminingpool.com
78 | * http://xmr.poolto.be
79 | * https://moneropool.com
80 | * http://monero.crypto-pool.fr
81 | * https://minexmr.com
82 |
83 | A pool must be operational for 6 months or more before it can be added to this list.
84 |
85 |
86 | Usage
87 | ===
88 |
89 | #### Requirements
90 | * Coin daemon(s) (find the coin's repo and build latest version from source)
91 | * [Node.js](http://nodejs.org/) v0.10+ ([follow these installation instructions](https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager))
92 | * [Redis](http://redis.io/) key-value store v2.6+ ([follow these instructions](http://redis.io/topics/quickstart))
93 | * libssl required for the node-multi-hashing module
94 | * For Ubuntu: `sudo apt-get install libssl-dev`
95 | * Boost is required for the cryptonote-util module
96 | * For Ubuntu: `sudo apt-get install libboost-all-dev`
97 |
98 |
99 | ##### Seriously
100 | 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.
101 |
102 |
103 | [**Redis security warning**](http://redis.io/topics/security): be sure firewall access to redis - an easy way is to
104 | include `bind 127.0.0.1` in your `redis.conf` file. Also it's a good idea to learn about and understand software that
105 | you are using - a good place to start with redis is [data persistence](http://redis.io/topics/persistence).
106 |
107 |
108 | #### 1) Downloading & Installing
109 |
110 |
111 | Clone the repository and run `npm update` for all the dependencies to be installed:
112 |
113 | ```bash
114 | git clone https://github.com/zone117x/node-cryptonote-pool.git pool
115 | cd pool
116 |
117 | nvm install 0.10.48
118 | nvm use 0.10.48
119 | nvm alias default 0.10.48
120 | nvm use default
121 |
122 | npm update
123 | ```
124 |
125 | #### 2) Configuration
126 |
127 |
128 | *Warning for Cyrptonote coins other than Monero:* this software may or may not work with any given cryptonote coin.
129 | Be wary of altcoins that change the number of minimum coin units because you will have to reconfigure several config
130 | values to account for those changes. Unless you're offering a bounty reward - do not open an issue asking for help
131 | getting a coin other than Monero working with this software.
132 |
133 |
134 | Copy the `config_example.json` file to `config.json` then overview each options and change any to match your preferred setup.
135 |
136 |
137 | Explanation for each field:
138 | ```javascript
139 | /* Used for storage in redis so multiple coins can share the same redis instance. */
140 | "coin": "monero",
141 |
142 | /* Used for front-end display */
143 | "symbol": "MRO",
144 |
145 | "logging": {
146 |
147 | "files": {
148 |
149 | /* Specifies the level of log output verbosity. This level and anything
150 | more severe will be logged. Options are: info, warn, or error. */
151 | "level": "info",
152 |
153 | /* Directory where to write log files. */
154 | "directory": "logs",
155 |
156 | /* How often (in seconds) to append/flush data to the log files. */
157 | "flushInterval": 5
158 | },
159 |
160 | "console": {
161 | "level": "info",
162 | /* Gives console output useful colors. If you direct that output to a log file
163 | then disable this feature to avoid nasty characters in the file. */
164 | "colors": true
165 | }
166 | },
167 |
168 | /* Modular Pool Server */
169 | "poolServer": {
170 | "enabled": true,
171 |
172 | /* Set to "auto" by default which will spawn one process/fork/worker for each CPU
173 | core in your system. Each of these workers will run a separate instance of your
174 | pool(s), and the kernel will load balance miners using these forks. Optionally,
175 | the 'forks' field can be a number for how many forks will be spawned. */
176 | "clusterForks": "auto",
177 |
178 | /* Address where block rewards go, and miner payments come from. */
179 | "poolAddress": "4AsBy39rpUMTmgTUARGq2bFQWhDhdQNekK5v4uaLU699NPAnx9CubEJ82AkvD5ScoAZNYRwBxybayainhyThHAZWCdKmPYn"
180 |
181 | /* Poll RPC daemons for new blocks every this many milliseconds. */
182 | "blockRefreshInterval": 1000,
183 |
184 | /* How many seconds until we consider a miner disconnected. */
185 | "minerTimeout": 900,
186 |
187 | "ports": [
188 | {
189 | "port": 3333, //Port for mining apps to connect to
190 | "difficulty": 100, //Initial difficulty miners are set to
191 | "desc": "Low end hardware" //Description of port
192 | },
193 | {
194 | "port": 5555,
195 | "difficulty": 2000,
196 | "desc": "Mid range hardware"
197 | },
198 | {
199 | "port": 7777,
200 | "difficulty": 10000,
201 | "desc": "High end hardware"
202 | }
203 | ],
204 |
205 | /* Variable difficulty is a feature that will automatically adjust difficulty for
206 | individual miners based on their hashrate in order to lower networking and CPU
207 | overhead. */
208 | "varDiff": {
209 | "minDiff": 2, //Minimum difficulty
210 | "maxDiff": 100000,
211 | "targetTime": 100, //Try to get 1 share per this many seconds
212 | "retargetTime": 30, //Check to see if we should retarget every this many seconds
213 | "variancePercent": 30, //Allow time to vary this % from target without retargeting
214 | "maxJump": 100 //Limit diff percent increase/decrease in a single retargetting
215 | },
216 |
217 | /* Feature to trust share difficulties from miners which can
218 | significantly reduce CPU load. */
219 | "shareTrust": {
220 | "enabled": true,
221 | "min": 10, //Minimum percent probability for share hashing
222 | "stepDown": 3, //Increase trust probability % this much with each valid share
223 | "threshold": 10, //Amount of valid shares required before trusting begins
224 | "penalty": 30 //Upon breaking trust require this many valid share before trusting
225 | },
226 |
227 | /* If under low-diff share attack we can ban their IP to reduce system/network load. */
228 | "banning": {
229 | "enabled": true,
230 | "time": 600, //How many seconds to ban worker for
231 | "invalidPercent": 25, //What percent of invalid shares triggers ban
232 | "checkThreshold": 30 //Perform check when this many shares have been submitted
233 | },
234 | /* [Warning: several reports of this feature being broken. Proposed fix needs to be tested.]
235 | Slush Mining is a reward calculation technique which disincentivizes pool hopping and rewards
236 | 'loyal' miners by valuing younger shares higher than older shares. Remember adjusting the weight!
237 | More about it here: https://mining.bitcoin.cz/help/#!/manual/rewards */
238 | "slushMining": {
239 | "enabled": false, //Enables slush mining. Recommended for pools catering to professional miners
240 | "weight": 300, //Defines how fast the score assigned to a share declines in time. The value should roughly be equivalent to the average round duration in seconds divided by 8. When deviating by too much numbers may get too high for JS.
241 | "lastBlockCheckRate": 1 //How often the pool checks the timestamp of the last block. Lower numbers increase load but raise precision of the share value
242 | }
243 | },
244 |
245 | /* Module that sends payments to miners according to their submitted shares. */
246 | "payments": {
247 | "enabled": true,
248 | "interval": 600, //how often to run in seconds
249 | "maxAddresses": 50, //split up payments if sending to more than this many addresses
250 | "mixin": 3, //number of transactions yours is indistinguishable from
251 | "transferFee": 5000000000, //fee to pay for each transaction
252 | "minPayment": 100000000000, //miner balance required before sending payment
253 | "denomination": 100000000000 //truncate to this precision and store remainder
254 | },
255 |
256 | /* Module that monitors the submitted block maturities and manages rounds. Confirmed
257 | blocks mark the end of a round where workers' balances are increased in proportion
258 | to their shares. */
259 | "blockUnlocker": {
260 | "enabled": true,
261 | "interval": 30, //how often to check block statuses in seconds
262 |
263 | /* Block depth required for a block to unlocked/mature. Found in daemon source as
264 | the variable CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW */
265 | "depth": 60,
266 | "poolFee": 1.8, //1.8% pool fee (2% total fee total including donations)
267 | "devDonation": 0.1, //0.1% donation to send to pool dev - only works with Monero
268 | "coreDevDonation": 0.1 //0.1% donation to send to core devs - only works with Monero
269 | },
270 |
271 | /* AJAX API used for front-end website. */
272 | "api": {
273 | "enabled": true,
274 | "hashrateWindow": 600, //how many second worth of shares used to estimate hash rate
275 | "updateInterval": 3, //gather stats and broadcast every this many seconds
276 | "port": 8117,
277 | "blocks": 30, //amount of blocks to send at a time
278 | "payments": 30, //amount of payments to send at a time
279 | "password": "test" //password required for admin stats
280 | },
281 |
282 | /* Coin daemon connection details. */
283 | "daemon": {
284 | "host": "127.0.0.1",
285 | "port": 18081
286 | },
287 |
288 | /* Wallet daemon connection details. */
289 | "wallet": {
290 | "host": "127.0.0.1",
291 | "port": 8082
292 | },
293 |
294 | /* Redis connection into. */
295 | "redis": {
296 | "host": "127.0.0.1",
297 | "port": 6379,
298 | "auth": null //If set, client will run redis auth command on connect. Use for remote db
299 | }
300 | ```
301 |
302 | #### 3) [Optional] Configure cryptonote-easy-miner for your pool
303 | Your miners that are Windows users can use [cryptonote-easy-miner](https://github.com/zone117x/cryptonote-easy-miner)
304 | which will automatically generate their wallet address and stratup multiple threads of simpleminer. You can download
305 | it and edit the `config.ini` file to point to your own pool.
306 | Inside the `easyminer` folder, edit `config.init` to point to your pool details
307 | ```ini
308 | pool_host=example.com
309 | pool_port=5555
310 | ```
311 |
312 | Rezip and upload to your server or a file host. Then change the `easyminerDownload` link in your `config.json` file to
313 | point to your zip file.
314 |
315 | #### 4) Start the pool
316 |
317 | ```bash
318 | node init.js
319 | ```
320 |
321 | The file `config.json` is used by default but a file can be specified using the `-config=file` command argument, for example:
322 |
323 | ```bash
324 | node init.js -config=config_backup.json
325 | ```
326 |
327 | This software contains four distinct modules:
328 | * `pool` - Which opens ports for miners to connect and processes shares
329 | * `api` - Used by the website to display network, pool and miners' data
330 | * `unlocker` - Processes block candidates and increases miners' balances when blocks are unlocked
331 | * `payments` - Sends out payments to miners according to their balances stored in redis
332 |
333 |
334 | By default, running the `init.js` script will start up all four modules. You can optionally have the script start
335 | only start a specific module by using the `-module=name` command argument, for example:
336 |
337 | ```bash
338 | node init.js -module=api
339 | ```
340 |
341 | [Example screenshot](http://i.imgur.com/SEgrI3b.png) of running the pool in single module mode with tmux.
342 |
343 |
344 | #### 5) Host the front-end
345 |
346 | Simply host the contents of the `website_example` directory on file server capable of serving simple static files.
347 |
348 |
349 | Edit the variables in the `website_example/config.js` file to use your pool's specific configuration.
350 | Variable explanations:
351 |
352 | ```javascript
353 |
354 | /* Must point to the API setup in your config.json file. */
355 | var api = "http://poolhost:8117";
356 |
357 | /* Minimum units in a single coin, for Bytecoin its 100000000. */
358 | var coinUnits = 1000000000000;
359 |
360 | /* Pool server host to instruct your miners to point to. */
361 | var poolHost = "cryppit.com";
362 |
363 | /* IRC Server and room used for embedded KiwiIRC chat. */
364 | var irc = "irc.freenode.net/#monero";
365 |
366 | /* Contact email address. */
367 | var email = "support@cryppit.com";
368 |
369 | /* Market stat display params from https://www.cryptonator.com/widget */
370 | var cryptonatorWidget = ["XMR-BTC", "XMR-USD", "XMR-EUR", "XMR-GBP"];
371 |
372 | /* Download link to cryptonote-easy-miner for Windows users. */
373 | var easyminerDownload = "https://github.com/zone117x/cryptonote-easy-miner/releases/";
374 |
375 | /* Used for front-end block links. For other coins it can be changed, for example with
376 | Bytecoin you can use "https://minergate.com/blockchain/bcn/block/". */
377 | var blockchainExplorer = "http://monerochain.info/block/";
378 |
379 | /* Used by front-end transaction links. Change for other coins. */
380 | var transactionExplorer = "http://monerochain.info/tx/";
381 |
382 | ```
383 |
384 | #### 6) Customize your website
385 |
386 | The following files are included so that you can customize your pool website without having to make significant changes
387 | to `index.html` or other front-end files thus reducing the difficulty of merging updates with your own changes:
388 | * `custom.css` for creating your own pool style
389 | * `custom.js` for changing the functionality of your pool website
390 |
391 |
392 | Then simply serve the files via nginx, Apache, Google Drive, or anything that can host static content.
393 |
394 |
395 | #### Upgrading
396 | When updating to the latest code its important to not only `git pull` the latest from this repo, but to also update
397 | the Node.js modules, and any config files that may have been changed.
398 | * Inside your pool directory (where the init.js script is) do `git pull` to get the latest code.
399 | * Remove the dependencies by deleting the `node_modules` directory with `rm -r node_modules`.
400 | * Run `npm update` to force updating/reinstalling of the dependencies.
401 | * 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.
402 |
403 | ### Setting up Testnet
404 |
405 | No cryptonote based coins have a testnet mode (yet) but you can effectively create a testnet with the following steps:
406 |
407 | * 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)
408 | * Build the coin from source
409 | * 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)
410 | * Run first instance with `./coind --p2p-bind-port 28080 --allow-local-ip`
411 | * Run second instance with `./coind --p2p-bind-port 5011 --rpc-bind-port 5010 --add-peer 0.0.0.0:28080 --allow-local-ip`
412 | * 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
413 |
414 | *Credit to surfer43 for these instructions*
415 |
416 |
417 | ### JSON-RPC Commands from CLI
418 |
419 | Documentation for JSON-RPC commands can be found here:
420 | * Daemon https://wiki.bytecoin.org/wiki/Daemon_JSON_RPC_API
421 | * Wallet https://wiki.bytecoin.org/wiki/Wallet_JSON_RPC_API
422 |
423 |
424 | Curl can be used to use the JSON-RPC commands from command-line. Here is an example of calling `getblockheaderbyheight` for block 100:
425 |
426 | ```bash
427 | curl 127.0.0.1:18081/json_rpc -d '{"method":"getblockheaderbyheight","params":{"height":100}}'
428 | ```
429 |
430 |
431 | ### Monitoring Your Pool
432 |
433 | * To inspect and make changes to redis I suggest using [redis-commander](https://github.com/joeferner/redis-commander)
434 | * To monitor server load for CPU, Network, IO, etc - I suggest using [New Relic](http://newrelic.com/)
435 | * 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)
436 |
437 |
438 | Donations
439 | ---------
440 | * BTC: `1667jMt7NTZDaC8WXAxtMYBR8DPWCVoU4d`
441 | * MRO: `48Y4SoUJM5L3YXBEfNQ8bFNsvTNsqcH5Rgq8RF7BwpgvTBj2xr7CmWVanaw7L4U9MnZ4AG7U6Pn1pBhfQhFyFZ1rL1efL8z`
442 |
443 | Credits
444 | ===
445 |
446 | * [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.
447 | * [surfer43](//github.com/iamasupernova) - Did lots of testing during development to help figure out bugs and get them fixed
448 | * [wallet42](http://moneropool.com) - Funded development of payment denominating and min threshold feature
449 | * [Wolf0](https://bitcointalk.org/index.php?action=profile;u=80740) - Helped try to deobfuscate some of the daemon code for getting a bug fixed
450 | * [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
451 |
452 | License
453 | -------
454 | Released under the GNU General Public License v2
455 |
456 | http://www.gnu.org/licenses/gpl-2.0.html
457 |
--------------------------------------------------------------------------------
/config_example.json:
--------------------------------------------------------------------------------
1 | {
2 | "coin": "monero",
3 | "symbol": "XMR",
4 |
5 | "logging": {
6 | "files": {
7 | "level": "info",
8 | "directory": "logs",
9 | "flushInterval": 5
10 | },
11 | "console": {
12 | "level": "info",
13 | "colors": true
14 | }
15 | },
16 |
17 | "poolServer": {
18 | "enabled": true,
19 | "clusterForks": "auto",
20 | "poolAddress": "48Y4SoUJM5L3YXBEfNQ8bFNsvTNsqcH5Rgq8RF7BwpgvTBj2xr7CmWVanaw7L4U9MnZ4AG7U6Pn1pBhfQhFyFZ1rL1efL8z",
21 | "blockRefreshInterval": 1000,
22 | "minerTimeout": 900,
23 | "ports": [
24 | {
25 | "port": 3333,
26 | "difficulty": 100,
27 | "desc": "Low end hardware"
28 | },
29 | {
30 | "port": 5555,
31 | "difficulty": 2000,
32 | "desc": "Mid range hardware"
33 | },
34 | {
35 | "port": 7777,
36 | "difficulty": 10000,
37 | "desc": "High end hardware"
38 | },
39 | {
40 | "port": 8888,
41 | "difficulty": 10000,
42 | "desc": "Hidden port",
43 | "hidden": true
44 | }
45 | ],
46 | "varDiff": {
47 | "minDiff": 2,
48 | "maxDiff": 100000,
49 | "targetTime": 100,
50 | "retargetTime": 30,
51 | "variancePercent": 30,
52 | "maxJump": 100
53 | },
54 | "shareTrust": {
55 | "enabled": true,
56 | "min": 10,
57 | "stepDown": 3,
58 | "threshold": 10,
59 | "penalty": 30
60 | },
61 | "banning": {
62 | "enabled": true,
63 | "time": 600,
64 | "invalidPercent": 25,
65 | "checkThreshold": 30
66 | },
67 | "slushMining": {
68 | "enabled": false,
69 | "weight": 300,
70 | "blockTime": 60,
71 | "lastBlockCheckRate": 1
72 | }
73 | },
74 |
75 | "payments": {
76 | "enabled": true,
77 | "interval": 600,
78 | "maxAddresses": 50,
79 | "mixin": 3,
80 | "transferFee": 5000000000,
81 | "minPayment": 100000000000,
82 | "denomination": 100000000000
83 | },
84 |
85 | "blockUnlocker": {
86 | "enabled": true,
87 | "interval": 30,
88 | "depth": 60,
89 | "poolFee": 2,
90 | "devDonation": 0.1,
91 | "coreDevDonation": 0.1
92 | },
93 |
94 | "api": {
95 | "enabled": true,
96 | "hashrateWindow": 600,
97 | "updateInterval": 5,
98 | "port": 8117,
99 | "blocks": 30,
100 | "payments": 30,
101 | "password": "your_password"
102 | },
103 |
104 | "daemon": {
105 | "host": "127.0.0.1",
106 | "port": 18081
107 | },
108 |
109 | "wallet": {
110 | "host": "127.0.0.1",
111 | "port": 8082
112 | },
113 |
114 | "redis": {
115 | "host": "127.0.0.1",
116 | "port": 6379,
117 | "auth": null
118 | }
119 | }
120 |
--------------------------------------------------------------------------------
/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, {auth_pass: config.redis.auth});
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 | }
34 | return;
35 | }
36 |
37 | var logSystem = 'master';
38 | require('./lib/exceptionWriter.js')(logSystem);
39 |
40 |
41 | var singleModule = (function(){
42 |
43 | var validModules = ['pool', 'api', 'unlocker', 'payments'];
44 |
45 | for (var i = 0; i < process.argv.length; i++){
46 | if (process.argv[i].indexOf('-module=') === 0){
47 | var moduleName = process.argv[i].split('=')[1];
48 | if (validModules.indexOf(moduleName) > -1)
49 | return moduleName;
50 |
51 | log('error', logSystem, 'Invalid module "%s", valid modules: %s', [moduleName, validModules.join(', ')]);
52 | process.exit();
53 | }
54 | }
55 | })();
56 |
57 |
58 | (function init(){
59 |
60 | checkRedisVersion(function(){
61 |
62 | if (singleModule){
63 | log('info', logSystem, 'Running in single module mode: %s', [singleModule]);
64 |
65 | switch(singleModule){
66 | case 'pool':
67 | spawnPoolWorkers();
68 | break;
69 | case 'unlocker':
70 | spawnBlockUnlocker();
71 | break;
72 | case 'payments':
73 | spawnPaymentProcessor();
74 | break;
75 | case 'api':
76 | spawnApi();
77 | break;
78 | }
79 | }
80 | else{
81 | spawnPoolWorkers();
82 | spawnBlockUnlocker();
83 | spawnPaymentProcessor();
84 | spawnApi();
85 | }
86 |
87 | spawnCli();
88 |
89 | });
90 | })();
91 |
92 |
93 | function checkRedisVersion(callback){
94 |
95 | redisClient.info(function(error, response){
96 | if (error){
97 | log('error', logSystem, 'Redis version check failed');
98 | return;
99 | }
100 | var parts = response.split('\r\n');
101 | var version;
102 | var versionString;
103 | for (var i = 0; i < parts.length; i++){
104 | if (parts[i].indexOf(':') !== -1){
105 | var valParts = parts[i].split(':');
106 | if (valParts[0] === 'redis_version'){
107 | versionString = valParts[1];
108 | version = parseFloat(versionString);
109 | break;
110 | }
111 | }
112 | }
113 | if (!version){
114 | log('error', logSystem, 'Could not detect redis version - must be super old or broken');
115 | return;
116 | }
117 | else if (version < 2.6){
118 | log('error', logSystem, "You're using redis version %s the minimum required version is 2.6. Follow the damn usage instructions...", [versionString]);
119 | return;
120 | }
121 | callback();
122 | });
123 | }
124 |
125 | function spawnPoolWorkers(){
126 |
127 | if (!config.poolServer || !config.poolServer.enabled || !config.poolServer.ports || config.poolServer.ports.length === 0) return;
128 |
129 | if (config.poolServer.ports.length === 0){
130 | log('error', logSystem, 'Pool server enabled but no ports specified');
131 | return;
132 | }
133 |
134 |
135 | var numForks = (function(){
136 | if (!config.poolServer.clusterForks)
137 | return 1;
138 | if (config.poolServer.clusterForks === 'auto')
139 | return os.cpus().length;
140 | if (isNaN(config.poolServer.clusterForks))
141 | return 1;
142 | return config.poolServer.clusterForks;
143 | })();
144 |
145 | var poolWorkers = {};
146 |
147 | var createPoolWorker = function(forkId){
148 | var worker = cluster.fork({
149 | workerType: 'pool',
150 | forkId: forkId
151 | });
152 | worker.forkId = forkId;
153 | worker.type = 'pool';
154 | poolWorkers[forkId] = worker;
155 | worker.on('exit', function(code, signal){
156 | log('error', logSystem, 'Pool fork %s died, spawning replacement worker...', [forkId]);
157 | setTimeout(function(){
158 | createPoolWorker(forkId);
159 | }, 2000);
160 | }).on('message', function(msg){
161 | switch(msg.type){
162 | case 'banIP':
163 | Object.keys(cluster.workers).forEach(function(id) {
164 | if (cluster.workers[id].type === 'pool'){
165 | cluster.workers[id].send({type: 'banIP', ip: msg.ip});
166 | }
167 | });
168 | break;
169 | }
170 | });
171 | };
172 |
173 | var i = 1;
174 | var spawnInterval = setInterval(function(){
175 | createPoolWorker(i.toString());
176 | i++;
177 | if (i - 1 === numForks){
178 | clearInterval(spawnInterval);
179 | log('info', logSystem, 'Pool spawned on %d thread(s)', [numForks]);
180 | }
181 | }, 10);
182 | }
183 |
184 | function spawnBlockUnlocker(){
185 |
186 | if (!config.blockUnlocker || !config.blockUnlocker.enabled) return;
187 |
188 | var worker = cluster.fork({
189 | workerType: 'blockUnlocker'
190 | });
191 | worker.on('exit', function(code, signal){
192 | log('error', logSystem, 'Block unlocker died, spawning replacement...');
193 | setTimeout(function(){
194 | spawnBlockUnlocker();
195 | }, 2000);
196 | });
197 |
198 | }
199 |
200 | function spawnPaymentProcessor(){
201 |
202 | if (!config.payments || !config.payments.enabled) return;
203 |
204 | var worker = cluster.fork({
205 | workerType: 'paymentProcessor'
206 | });
207 | worker.on('exit', function(code, signal){
208 | log('error', logSystem, 'Payment processor died, spawning replacement...');
209 | setTimeout(function(){
210 | spawnPaymentProcessor();
211 | }, 2000);
212 | });
213 | }
214 |
215 | function spawnApi(){
216 | if (!config.api || !config.api.enabled) return;
217 |
218 | var worker = cluster.fork({
219 | workerType: 'api'
220 | });
221 | worker.on('exit', function(code, signal){
222 | log('error', logSystem, 'API died, spawning replacement...');
223 | setTimeout(function(){
224 | spawnApi();
225 | }, 2000);
226 | });
227 | }
228 |
229 | function spawnCli(){
230 |
231 | }
--------------------------------------------------------------------------------
/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 |
10 | var logSystem = 'api';
11 | require('./exceptionWriter.js')(logSystem);
12 |
13 | var redisCommands = [
14 | ['zremrangebyscore', config.coin + ':hashrate', '-inf', ''],
15 | ['zrange', config.coin + ':hashrate', 0, -1],
16 | ['hgetall', config.coin + ':stats'],
17 | ['zrange', config.coin + ':blocks:candidates', 0, -1, 'WITHSCORES'],
18 | ['zrevrange', config.coin + ':blocks:matured', 0, config.api.blocks - 1, 'WITHSCORES'],
19 | ['hgetall', config.coin + ':shares:roundCurrent'],
20 | ['hgetall', config.coin + ':stats'],
21 | ['zcard', config.coin + ':blocks:matured'],
22 | ['zrevrange', config.coin + ':payments:all', 0, config.api.payments - 1, 'WITHSCORES'],
23 | ['zcard', config.coin + ':payments:all'],
24 | ['keys', config.coin + ':payments:*']
25 | ];
26 |
27 | var currentStats = "";
28 | var currentStatsCompressed = "";
29 |
30 | var minerStats = {};
31 |
32 | var liveConnections = {};
33 | var addressConnections = {};
34 |
35 |
36 |
37 | function collectStats(){
38 |
39 | var startTime = Date.now();
40 | var redisFinished;
41 | var daemonFinished;
42 |
43 | var windowTime = (((Date.now() / 1000) - config.api.hashrateWindow) | 0).toString();
44 | redisCommands[0][3] = '(' + windowTime;
45 |
46 | async.parallel({
47 | pool: function(callback){
48 | redisClient.multi(redisCommands).exec(function(error, replies){
49 |
50 | redisFinished = Date.now();
51 | var dateNowSeconds = Date.now() / 1000 | 0;
52 |
53 | if (error){
54 | log('error', logSystem, 'Error getting redis data %j', [error]);
55 | callback(true);
56 | return;
57 | }
58 |
59 | var data = {
60 | stats: replies[2],
61 | blocks: replies[3].concat(replies[4]),
62 | totalBlocks: parseInt(replies[7]) + (replies[3].length / 2),
63 | payments: replies[8],
64 | totalPayments: parseInt(replies[9]),
65 | totalMinersPaid: replies[10].length - 1
66 | };
67 |
68 | var hashrates = replies[1];
69 |
70 | minerStats = {};
71 |
72 | for (var i = 0; i < hashrates.length; i++){
73 | var hashParts = hashrates[i].split(':');
74 | minerStats[hashParts[1]] = (minerStats[hashParts[1]] || 0) + parseInt(hashParts[0]);
75 | }
76 |
77 | var totalShares = 0;
78 |
79 | for (var miner in minerStats){
80 | var shares = minerStats[miner];
81 | totalShares += shares;
82 | minerStats[miner] = getReadableHashRateString(shares / config.api.hashrateWindow);
83 | }
84 |
85 | data.miners = Object.keys(minerStats).length;
86 |
87 | data.hashrate = totalShares / config.api.hashrateWindow;
88 |
89 | data.roundHashes = 0;
90 |
91 | if (replies[5]){
92 | for (var miner in replies[5]){
93 | if (config.poolServer.slushMining.enabled) {
94 | data.roundHashes += parseInt(replies[5][miner]) / Math.pow(Math.E, ((data.lastBlockFound - dateNowSeconds) / config.poolServer.slushMining.weight)); //TODO: Abstract: If something different than lastBlockfound is used for scoreTime, this needs change.
95 | }
96 | else {
97 | data.roundHashes += parseInt(replies[5][miner]);
98 | }
99 | }
100 | }
101 |
102 | if (replies[6]) {
103 | data.lastBlockFound = replies[6].lastBlockFound;
104 | }
105 |
106 | callback(null, data);
107 | });
108 | },
109 | network: function(callback){
110 | apiInterfaces.rpcDaemon('getlastblockheader', {}, function(error, reply){
111 | daemonFinished = Date.now();
112 | if (error){
113 | log('error', logSystem, 'Error getting daemon data %j', [error]);
114 | callback(true);
115 | return;
116 | }
117 | var blockHeader = reply.block_header;
118 | callback(null, {
119 | difficulty: blockHeader.difficulty,
120 | height: blockHeader.height,
121 | timestamp: blockHeader.timestamp,
122 | reward: blockHeader.reward,
123 | hash: blockHeader.hash
124 | });
125 | });
126 | },
127 | config: function(callback){
128 | callback(null, {
129 | ports: getPublicPorts(config.poolServer.ports),
130 | hashrateWindow: config.api.hashrateWindow,
131 | fee: config.blockUnlocker.poolFee,
132 | coin: config.coin,
133 | symbol: config.symbol,
134 | depth: config.blockUnlocker.depth,
135 | donation: config.blockUnlocker.devDonation,
136 | coreDonation: config.blockUnlocker.coreDevDonation,
137 | doDonations: doDonations,
138 | version: version,
139 | minPaymentThreshold: config.payments.minPayment,
140 | denominationUnit: config.payments.denomination,
141 | blockTime: config.poolServer.slushMining.blockTime,
142 | slushMiningEnabled: config.poolServer.slushMining.enabled,
143 | weight: config.poolServer.slushMining.weight
144 | });
145 | }
146 | }, function(error, results){
147 |
148 | log('info', logSystem, 'Stat collection finished: %d ms redis, %d ms daemon', [redisFinished - startTime, daemonFinished - startTime]);
149 |
150 | if (error){
151 | log('error', logSystem, 'Error collecting all stats');
152 | }
153 | else{
154 | currentStats = JSON.stringify(results);
155 | zlib.deflateRaw(currentStats, function(error, result){
156 | currentStatsCompressed = result;
157 | broadcastLiveStats();
158 | });
159 |
160 | }
161 |
162 | setTimeout(collectStats, config.api.updateInterval * 1000);
163 | });
164 |
165 | }
166 |
167 | function getPublicPorts(ports){
168 | return ports.filter(function(port) {
169 | return !port.hidden;
170 | });
171 | }
172 |
173 | function getReadableHashRateString(hashrate){
174 | var i = 0;
175 | var byteUnits = [' H', ' KH', ' MH', ' GH', ' TH', ' PH' ];
176 | while (hashrate > 1000){
177 | hashrate = hashrate / 1000;
178 | i++;
179 | }
180 | return hashrate.toFixed(2) + byteUnits[i];
181 | }
182 |
183 | function broadcastLiveStats(){
184 |
185 | log('info', logSystem, 'Broadcasting to %d visitors and %d address lookups', [Object.keys(liveConnections).length, Object.keys(addressConnections).length]);
186 |
187 | for (var uid in liveConnections){
188 | var res = liveConnections[uid];
189 | res.end(currentStatsCompressed);
190 | }
191 |
192 | var redisCommands = [];
193 | for (var address in addressConnections){
194 | redisCommands.push(['hgetall', config.coin + ':workers:' + address]);
195 | redisCommands.push(['zrevrange', config.coin + ':payments:' + address, 0, config.api.payments - 1, 'WITHSCORES']);
196 | }
197 | redisClient.multi(redisCommands).exec(function(error, replies){
198 |
199 | var addresses = Object.keys(addressConnections);
200 |
201 | for (var i = 0; i < addresses.length; i++){
202 | var offset = i * 2;
203 | var address = addresses[i];
204 | var stats = replies[offset];
205 | var res = addressConnections[address];
206 | if (!stats){
207 | res.end(JSON.stringify({error: "not found"}));
208 | return;
209 | }
210 | stats.hashrate = minerStats[address];
211 | res.end(JSON.stringify({stats: stats, payments: replies[offset + 1]}));
212 | }
213 | });
214 | }
215 |
216 | function handleMinerStats(urlParts, response){
217 | response.writeHead(200, {
218 | 'Access-Control-Allow-Origin': '*',
219 | 'Cache-Control': 'no-cache',
220 | 'Content-Type': 'application/json',
221 | 'Connection': 'keep-alive'
222 | });
223 | response.write('\n');
224 | var address = urlParts.query.address;
225 |
226 | if (urlParts.query.longpoll === 'true'){
227 | redisClient.exists(config.coin + ':workers:' + address, function(error, result){
228 | if (!result){
229 | response.end(JSON.stringify({error: 'not found'}));
230 | return;
231 | }
232 | addressConnections[address] = response;
233 | response.on('finish', function(){
234 | delete addressConnections[address];
235 | })
236 | });
237 | }
238 | else{
239 | redisClient.multi([
240 | ['hgetall', config.coin + ':workers:' + address],
241 | ['zrevrange', config.coin + ':payments:' + address, 0, config.api.payments - 1, 'WITHSCORES']
242 | ]).exec(function(error, replies){
243 | if (error || !replies[0]){
244 | response.end(JSON.stringify({error: 'not found'}));
245 | return;
246 | }
247 | var stats = replies[0];
248 | stats.hashrate = minerStats[address];
249 | response.end(JSON.stringify({stats: stats, payments: replies[1]}));
250 | });
251 | }
252 | }
253 |
254 |
255 | function handleGetPayments(urlParts, response){
256 | var paymentKey = ':payments:all';
257 |
258 | if (urlParts.query.address)
259 | paymentKey = ':payments:' + urlParts.query.address;
260 |
261 | redisClient.zrevrangebyscore(
262 | config.coin + paymentKey,
263 | '(' + urlParts.query.time,
264 | '-inf',
265 | 'WITHSCORES',
266 | 'LIMIT',
267 | 0,
268 | config.api.payments,
269 | function(err, result){
270 |
271 | var reply;
272 |
273 | if (err)
274 | reply = JSON.stringify({error: 'query failed'});
275 | else
276 | reply = JSON.stringify(result);
277 |
278 | response.writeHead("200", {
279 | 'Access-Control-Allow-Origin': '*',
280 | 'Cache-Control': 'no-cache',
281 | 'Content-Type': 'application/json',
282 | 'Content-Length': reply.length
283 | });
284 | response.end(reply);
285 |
286 | }
287 | )
288 | }
289 |
290 | function handleGetBlocks(urlParts, response){
291 | redisClient.zrevrangebyscore(
292 | config.coin + ':blocks:matured',
293 | '(' + urlParts.query.height,
294 | '-inf',
295 | 'WITHSCORES',
296 | 'LIMIT',
297 | 0,
298 | config.api.blocks,
299 | function(err, result){
300 |
301 | var reply;
302 |
303 | if (err)
304 | reply = JSON.stringify({error: 'query failed'});
305 | else
306 | reply = JSON.stringify(result);
307 |
308 | response.writeHead("200", {
309 | 'Access-Control-Allow-Origin': '*',
310 | 'Cache-Control': 'no-cache',
311 | 'Content-Type': 'application/json',
312 | 'Content-Length': reply.length
313 | });
314 | response.end(reply);
315 |
316 | });
317 | }
318 |
319 |
320 | collectStats();
321 |
322 | function authorize(request, response){
323 |
324 | response.setHeader('Access-Control-Allow-Origin', '*');
325 |
326 | var sentPass = url.parse(request.url, true).query.password;
327 |
328 | if (sentPass !== config.api.password){
329 | response.statusCode = 401;
330 | response.end('invalid password');
331 | return;
332 | }
333 |
334 | response.statusCode = 200;
335 | response.setHeader('Cache-Control', 'no-cache');
336 | response.setHeader('Content-Type', 'application/json');
337 |
338 | return true;
339 | }
340 |
341 | function handleAdminStats(response){
342 |
343 | async.waterfall([
344 |
345 | //Get worker keys & unlocked blocks
346 | function(callback){
347 | redisClient.multi([
348 | ['keys', config.coin + ':workers:*'],
349 | ['zrange', config.coin + ':blocks:matured', 0, -1]
350 | ]).exec(function(error, replies) {
351 | if (error) {
352 | log('error', logSystem, 'Error trying to get admin data from redis %j', [error]);
353 | callback(true);
354 | return;
355 | }
356 | callback(null, replies[0], replies[1]);
357 | });
358 | },
359 |
360 | //Get worker balances
361 | function(workerKeys, blocks, callback){
362 | var redisCommands = workerKeys.map(function(k){
363 | return ['hmget', k, 'balance', 'paid'];
364 | });
365 | redisClient.multi(redisCommands).exec(function(error, replies){
366 | if (error){
367 | log('error', logSystem, 'Error with getting balances from redis %j', [error]);
368 | callback(true);
369 | return;
370 | }
371 |
372 | callback(null, replies, blocks);
373 | });
374 | },
375 | function(workerData, blocks, callback){
376 | var stats = {
377 | totalOwed: 0,
378 | totalPaid: 0,
379 | totalRevenue: 0,
380 | totalDiff: 0,
381 | totalShares: 0,
382 | blocksOrphaned: 0,
383 | blocksUnlocked: 0,
384 | totalWorkers: 0
385 | };
386 |
387 | for (var i = 0; i < workerData.length; i++){
388 | stats.totalOwed += parseInt(workerData[i][0]) || 0;
389 | stats.totalPaid += parseInt(workerData[i][1]) || 0;
390 | stats.totalWorkers++;
391 | }
392 |
393 | for (var i = 0; i < blocks.length; i++){
394 | var block = blocks[i].split(':');
395 | if (block[5]) {
396 | stats.blocksUnlocked++;
397 | stats.totalDiff += parseInt(block[2]);
398 | stats.totalShares += parseInt(block[3]);
399 | stats.totalRevenue += parseInt(block[5]);
400 | }
401 | else{
402 | stats.blocksOrphaned++;
403 | }
404 | }
405 | callback(null, stats);
406 | }
407 | ], function(error, stats){
408 | if (error){
409 | response.end(JSON.stringify({error: 'error collecting stats'}));
410 | return;
411 | }
412 | response.end(JSON.stringify(stats));
413 | }
414 | );
415 |
416 | }
417 |
418 | var server = http.createServer(function(request, response){
419 |
420 | if (request.method.toUpperCase() === "OPTIONS"){
421 |
422 | response.writeHead("204", "No Content", {
423 | "access-control-allow-origin": '*',
424 | "access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
425 | "access-control-allow-headers": "content-type, accept",
426 | "access-control-max-age": 10, // Seconds.
427 | "content-length": 0
428 | });
429 |
430 | return(response.end());
431 | }
432 |
433 |
434 | var urlParts = url.parse(request.url, true);
435 |
436 | switch(urlParts.pathname){
437 | case '/stats':
438 | var reply = currentStatsCompressed;
439 | response.writeHead("200", {
440 | 'Access-Control-Allow-Origin': '*',
441 | 'Cache-Control': 'no-cache',
442 | 'Content-Type': 'application/json',
443 | 'Content-Encoding': 'deflate',
444 | 'Content-Length': reply.length
445 | });
446 | response.end(reply);
447 | break;
448 | case '/live_stats':
449 | response.writeHead(200, {
450 | 'Access-Control-Allow-Origin': '*',
451 | 'Cache-Control': 'no-cache',
452 | 'Content-Type': 'application/json',
453 | 'Content-Encoding': 'deflate',
454 | 'Connection': 'keep-alive'
455 | });
456 | var uid = Math.random().toString();
457 | liveConnections[uid] = response;
458 | response.on("finish", function() {
459 | delete liveConnections[uid];
460 | });
461 | break;
462 | case '/stats_address':
463 | handleMinerStats(urlParts, response);
464 | break;
465 | case '/get_payments':
466 | handleGetPayments(urlParts, response);
467 | break;
468 | case '/get_blocks':
469 | handleGetBlocks(urlParts, response);
470 | break;
471 | case '/admin_stats':
472 | if (!authorize(request, response))
473 | return;
474 | log('warn', logSystem, 'Admin authorized');
475 | handleAdminStats(response);
476 | break;
477 | default:
478 | response.writeHead(404, {
479 | 'Access-Control-Allow-Origin': '*'
480 | });
481 | response.end('Invalid API call');
482 | break;
483 | }
484 |
485 |
486 | });
487 |
488 |
489 | server.listen(config.api.port, function(){
490 | log('info', logSystem, 'API started & listening on port %d', [config.api.port]);
491 | });
--------------------------------------------------------------------------------
/lib/apiInterfaces.js:
--------------------------------------------------------------------------------
1 | var http = require('http');
2 |
3 | function jsonHttpRequest(host, port, data, callback){
4 |
5 | var options = {
6 | hostname: host,
7 | port: port,
8 | path: '/json_rpc',
9 | method: 'POST',
10 | headers: {
11 | 'Content-Length': data.length,
12 | 'Content-Type': 'application/json',
13 | 'Accept': 'application/json'
14 | }
15 | };
16 |
17 | var req = http.request(options, function(res){
18 | var replyData = '';
19 | res.setEncoding('utf8');
20 | res.on('data', function(chunk){
21 | replyData += chunk;
22 | });
23 | res.on('end', function(){
24 | var replyJson;
25 | try{
26 | replyJson = JSON.parse(replyData);
27 | }
28 | catch(e){
29 | callback(e);
30 | return;
31 | }
32 | callback(null, replyJson);
33 | });
34 | });
35 |
36 | req.on('error', function(e){
37 | callback(e);
38 | });
39 |
40 | req.end(data);
41 | }
42 |
43 | function rpc(host, port, method, params, callback){
44 |
45 | var data = JSON.stringify({
46 | id: "0",
47 | jsonrpc: "2.0",
48 | method: method,
49 | params: params
50 | });
51 | jsonHttpRequest(host, port, data, function(error, replyJson){
52 | if (error){
53 | callback(error);
54 | return;
55 | }
56 | callback(replyJson.error, replyJson.result)
57 | });
58 | }
59 |
60 | function batchRpc(host, port, array, callback){
61 | var rpcArray = [];
62 | for (var i = 0; i < array.length; i++){
63 | rpcArray.push({
64 | id: i.toString(),
65 | jsonrpc: "2.0",
66 | method: array[i][0],
67 | params: array[i][1]
68 | });
69 | }
70 | var data = JSON.stringify(rpcArray);
71 | jsonHttpRequest(host, port, data, callback);
72 | }
73 |
74 |
75 | module.exports = function(daemonConfig, walletConfig){
76 | return {
77 | batchRpcDaemon: function(batchArray, callback){
78 | batchRpc(daemonConfig.host, daemonConfig.port, batchArray, callback);
79 | },
80 | rpcDaemon: function(method, params, callback){
81 | rpc(daemonConfig.host, daemonConfig.port, method, params, callback);
82 | },
83 | rpcWallet: function(method, params, callback){
84 | rpc(walletConfig.host, walletConfig.port, method, params, callback);
85 | }
86 | }
87 | };
--------------------------------------------------------------------------------
/lib/blockUnlocker.js:
--------------------------------------------------------------------------------
1 | var async = require('async');
2 |
3 | var apiInterfaces = require('./apiInterfaces.js')(config.daemon, config.wallet);
4 |
5 | var logSystem = 'unlocker';
6 | require('./exceptionWriter.js')(logSystem);
7 |
8 |
9 | log('info', logSystem, 'Started');
10 |
11 |
12 | //Use this in payment processing to get block info once batch RPC is supported
13 | /*
14 | var batchArray = [
15 | ['getblockheaderbyheight', {height: 21}],
16 | ['getblockheaderbyheight', {height: 22}],
17 | ['getblockheaderbyheight', {height: 23
18 | }]
19 | ];
20 |
21 | apiInterfaces.batchRpcDaemon(batchArray, function(error, response){
22 |
23 | });
24 | */
25 |
26 |
27 | function runInterval(){
28 | async.waterfall([
29 |
30 | //Get all block candidates in redis
31 | function(callback){
32 | redisClient.zrange(config.coin + ':blocks:candidates', 0, -1, 'WITHSCORES', function(error, results){
33 | if (error){
34 | log('error', logSystem, 'Error trying to get pending blocks from redis %j', [error]);
35 | callback(true);
36 | return;
37 | }
38 | if (results.length === 0){
39 | log('info', logSystem, 'No blocks candidates in redis');
40 | callback(true);
41 | return;
42 | }
43 |
44 | var blocks = [];
45 |
46 | for (var i = 0; i < results.length; i += 2){
47 | var parts = results[i].split(':');
48 | blocks.push({
49 | serialized: results[i],
50 | height: parseInt(results[i + 1]),
51 | hash: parts[0],
52 | time: parts[1],
53 | difficulty: parts[2],
54 | shares: parts[3]
55 | });
56 | }
57 |
58 | callback(null, blocks);
59 | });
60 | },
61 |
62 | //Check if blocks are orphaned
63 | function(blocks, callback){
64 | async.filter(blocks, function(block, mapCback){
65 | apiInterfaces.rpcDaemon('getblockheaderbyheight', {height: block.height}, function(error, result){
66 | if (error){
67 | log('error', logSystem, 'Error with getblockheaderbyheight RPC request for block %s - %j', [block.serialized, error]);
68 | block.unlocked = false;
69 | mapCback();
70 | return;
71 | }
72 | if (!result.block_header){
73 | log('error', logSystem, 'Error with getblockheaderbyheight, no details returned for %s - %j', [block.serialized, result]);
74 | block.unlocked = false;
75 | mapCback();
76 | return;
77 | }
78 | var blockHeader = result.block_header;
79 | block.orphaned = blockHeader.hash === block.hash ? 0 : 1;
80 | block.unlocked = blockHeader.depth >= config.blockUnlocker.depth;
81 | block.reward = blockHeader.reward;
82 | mapCback(block.unlocked);
83 | });
84 | }, function(unlockedBlocks){
85 |
86 | if (unlockedBlocks.length === 0){
87 | log('info', logSystem, 'No pending blocks are unlocked yet (%d pending)', [blocks.length]);
88 | callback(true);
89 | return;
90 | }
91 |
92 | callback(null, unlockedBlocks)
93 | })
94 | },
95 |
96 | //Get worker shares for each unlocked block
97 | function(blocks, callback){
98 |
99 |
100 | var redisCommands = blocks.map(function(block){
101 | return ['hgetall', config.coin + ':shares:round' + block.height];
102 | });
103 |
104 |
105 | redisClient.multi(redisCommands).exec(function(error, replies){
106 | if (error){
107 | log('error', logSystem, 'Error with getting round shares from redis %j', [error]);
108 | callback(true);
109 | return;
110 | }
111 | for (var i = 0; i < replies.length; i++){
112 | var workerShares = replies[i];
113 | blocks[i].workerShares = workerShares;
114 | }
115 | callback(null, blocks);
116 | });
117 | },
118 |
119 | //Handle orphaned blocks
120 | function(blocks, callback){
121 | var orphanCommands = [];
122 |
123 | blocks.forEach(function(block){
124 | if (!block.orphaned) return;
125 |
126 | orphanCommands.push(['del', config.coin + ':shares:round' + block.height]);
127 |
128 | orphanCommands.push(['zrem', config.coin + ':blocks:candidates', block.serialized]);
129 | orphanCommands.push(['zadd', config.coin + ':blocks:matured', block.height, [
130 | block.hash,
131 | block.time,
132 | block.difficulty,
133 | block.shares,
134 | block.orphaned
135 | ].join(':')]);
136 |
137 | if (block.workerShares) {
138 | var workerShares = block.workerShares;
139 | Object.keys(workerShares).forEach(function (worker) {
140 | orphanCommands.push(['hincrby', config.coin + ':shares:roundCurrent', worker, workerShares[worker]]);
141 | });
142 | }
143 | });
144 |
145 | if (orphanCommands.length > 0){
146 | redisClient.multi(orphanCommands).exec(function(error, replies){
147 | if (error){
148 | log('error', logSystem, 'Error with cleaning up data in redis for orphan block(s) %j', [error]);
149 | callback(true);
150 | return;
151 | }
152 | callback(null, blocks);
153 | });
154 | }
155 | else{
156 | callback(null, blocks);
157 | }
158 | },
159 |
160 | //Handle unlocked blocks
161 | function(blocks, callback){
162 | var unlockedBlocksCommands = [];
163 | var payments = {};
164 | var totalBlocksUnlocked = 0;
165 | blocks.forEach(function(block){
166 | if (block.orphaned) return;
167 | totalBlocksUnlocked++;
168 |
169 | unlockedBlocksCommands.push(['del', config.coin + ':shares:round' + block.height]);
170 | unlockedBlocksCommands.push(['zrem', config.coin + ':blocks:candidates', block.serialized]);
171 | unlockedBlocksCommands.push(['zadd', config.coin + ':blocks:matured', block.height, [
172 | block.hash,
173 | block.time,
174 | block.difficulty,
175 | block.shares,
176 | block.orphaned,
177 | block.reward
178 | ].join(':')]);
179 |
180 | var feePercent = config.blockUnlocker.poolFee / 100;
181 |
182 | if (doDonations) {
183 | feePercent += config.blockUnlocker.devDonation / 100;
184 | feePercent += config.blockUnlocker.coreDevDonation / 100;
185 |
186 | var devDonation = block.reward * (config.blockUnlocker.devDonation / 100);
187 | payments[devDonationAddress] = devDonation;
188 |
189 | var coreDevDonation = block.reward * (config.blockUnlocker.coreDevDonation / 100);
190 | payments[coreDevDonationAddress] = coreDevDonation;
191 | }
192 |
193 | var reward = block.reward - (block.reward * feePercent);
194 |
195 | if (block.workerShares) {
196 | var totalShares = parseInt(block.shares);
197 | Object.keys(block.workerShares).forEach(function (worker) {
198 | var percent = block.workerShares[worker] / totalShares;
199 | var workerReward = reward * percent;
200 | payments[worker] = (payments[worker] || 0) + workerReward;
201 | });
202 | }
203 | });
204 |
205 | for (var worker in payments) {
206 | var amount = parseInt(payments[worker]);
207 | if (amount <= 0){
208 | delete payments[worker];
209 | continue;
210 | }
211 | unlockedBlocksCommands.push(['hincrby', config.coin + ':workers:' + worker, 'balance', amount]);
212 | }
213 |
214 | if (unlockedBlocksCommands.length === 0){
215 | log('info', logSystem, 'No unlocked blocks yet (%d pending)', [blocks.length]);
216 | callback(true);
217 | return;
218 | }
219 |
220 | redisClient.multi(unlockedBlocksCommands).exec(function(error, replies){
221 | if (error){
222 | log('error', logSystem, 'Error with unlocking blocks %j', [error]);
223 | callback(true);
224 | return;
225 | }
226 | log('info', logSystem, 'Unlocked %d blocks and update balances for %d workers', [totalBlocksUnlocked, Object.keys(payments).length]);
227 | callback(null);
228 | });
229 | }
230 | ], function(error, result){
231 | setTimeout(runInterval, config.blockUnlocker.interval * 1000);
232 | })
233 | }
234 |
235 | runInterval();
--------------------------------------------------------------------------------
/lib/cli.js:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zone117x/node-cryptonote-pool/dd3147c1753acccbdddf0e2185cf7ddf98fc91d8/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 | global.version = "v0.99.3.3";
21 | global.devDonationAddress = '45Jmf8PnJKziGyrLouJMeBFw2yVyX1QB52sKEQ4S1VSU2NVsaVGPNu4bWKkaHaeZ6tWCepP6iceZk8XhTLzDaEVa72QrtVh';
22 | global.coreDevDonationAddress = '46BeWrHpwXmHDpDEUmZBWZfoQpdc6HaERCNmx1pEYL2rAcuwufPN9rXHHtyUA4QVy66qeFQkn6sfK8aHYjA3jk3o1Bv16em';
23 | global.doDonations = devDonationAddress[0] === config.poolServer.poolAddress[0] && (
24 | config.blockUnlocker.devDonation > 0 || config.blockUnlocker.coreDevDonation > 0
25 | );
--------------------------------------------------------------------------------
/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);
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 |
75 | var transferCommandsLength = Math.ceil(Object.keys(payments).length / config.payments.maxAddresses);
76 |
77 | for (var i = 0; i < transferCommandsLength; i++){
78 | transferCommands.push({
79 | redis: [],
80 | amount : 0,
81 | rpc: {
82 | destinations: [],
83 | fee: config.payments.transferFee,
84 | mixin: config.payments.mixin,
85 | unlock_time: 0
86 | }
87 | });
88 | }
89 |
90 | var addresses = 0;
91 | var commandIndex = 0;
92 |
93 | for (var worker in payments){
94 | var amount = parseInt(payments[worker]);
95 | transferCommands[commandIndex].rpc.destinations.push({amount: amount, address: worker});
96 | transferCommands[commandIndex].redis.push(['hincrby', config.coin + ':workers:' + worker, 'balance', -amount]);
97 | transferCommands[commandIndex].redis.push(['hincrby', config.coin + ':workers:' + worker, 'paid', amount]);
98 | transferCommands[commandIndex].amount += amount;
99 |
100 | addresses++;
101 | if (addresses >= config.payments.maxAddresses){
102 | commandIndex++;
103 | addresses = 0;
104 | }
105 | }
106 |
107 | var timeOffset = 0;
108 |
109 | async.filter(transferCommands, function(transferCmd, cback){
110 | apiInterfaces.rpcWallet('transfer', transferCmd.rpc, function(error, result){
111 | if (error){
112 | log('error', logSystem, 'Error with transfer RPC request to wallet daemon %j', [error]);
113 | log('error', logSystem, 'Payments failed to send to %j', transferCmd.rpc.destinations);
114 | cback(false);
115 | return;
116 | }
117 |
118 | var now = (timeOffset++) + Date.now() / 1000 | 0;
119 | var txHash = result.tx_hash.replace('<', '').replace('>', '');
120 |
121 |
122 | transferCmd.redis.push(['zadd', config.coin + ':payments:all', now, [
123 | txHash,
124 | transferCmd.amount,
125 | transferCmd.rpc.fee,
126 | transferCmd.rpc.mixin,
127 | Object.keys(transferCmd.rpc.destinations).length
128 | ].join(':')]);
129 |
130 |
131 | for (var i = 0; i < transferCmd.rpc.destinations.length; i++){
132 | var destination = transferCmd.rpc.destinations[i];
133 | transferCmd.redis.push(['zadd', config.coin + ':payments:' + destination.address, now, [
134 | txHash,
135 | destination.amount,
136 | transferCmd.rpc.fee,
137 | transferCmd.rpc.mixin
138 | ].join(':')]);
139 | }
140 |
141 |
142 | log('info', logSystem, 'Payments sent via wallet daemon %j', [result]);
143 | redisClient.multi(transferCmd.redis).exec(function(error, replies){
144 | if (error){
145 | log('error', logSystem, 'Super critical error! Payments sent yet failing to update balance in redis, double payouts likely to happen %j', [error]);
146 | log('error', logSystem, 'Double payments likely to be sent to %j', transferCmd.rpc.destinations);
147 | cback(false);
148 | return;
149 | }
150 | cback(true);
151 | });
152 | });
153 | }, function(succeeded){
154 | var failedAmount = transferCommands.length - succeeded.length;
155 | log('info', logSystem, 'Payments splintered and %d successfully sent, %d failed', [succeeded.length, failedAmount]);
156 | callback(null);
157 | });
158 |
159 | }
160 |
161 | ], function(error, result){
162 | setTimeout(runInterval, config.payments.interval * 1000);
163 | });
164 | }
165 |
166 | runInterval();
--------------------------------------------------------------------------------
/lib/pool.js:
--------------------------------------------------------------------------------
1 | var fs = require('fs');
2 | var net = require('net');
3 | var crypto = require('crypto');
4 |
5 | var async = require('async');
6 | var bignum = require('bignum');
7 | var multiHashing = require('multi-hashing');
8 | var cnUtil = require('cryptonote-util');
9 |
10 | // Must exactly be 8 hex chars
11 | var noncePattern = new RegExp("^[0-9A-Fa-f]{8}$");
12 |
13 | var threadId = '(Thread ' + process.env.forkId + ') ';
14 |
15 | var logSystem = 'pool';
16 | require('./exceptionWriter.js')(logSystem);
17 |
18 | var apiInterfaces = require('./apiInterfaces.js')(config.daemon, config.wallet);
19 | var utils = require('./utils.js');
20 |
21 | var log = function(severity, system, text, data){
22 | global.log(severity, system, threadId + text, data);
23 | };
24 |
25 | var cryptoNight = multiHashing['cryptonight'];
26 |
27 | function cryptoNightFast(buf) {
28 | return cryptoNight(Buffer.concat([new Buffer([buf.length]), buf]), true);
29 | }
30 |
31 | var diff1 = bignum('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF', 16);
32 |
33 | var instanceId = crypto.randomBytes(4);
34 |
35 | var validBlockTemplates = [];
36 | var currentBlockTemplate;
37 |
38 | //Vars for slush mining
39 | var scoreTime;
40 | var lastChecked = 0;
41 |
42 | var connectedMiners = {};
43 |
44 | var bannedIPs = {};
45 | var perIPStats = {};
46 |
47 | var shareTrustEnabled = config.poolServer.shareTrust && config.poolServer.shareTrust.enabled;
48 | var shareTrustStepFloat = shareTrustEnabled ? config.poolServer.shareTrust.stepDown / 100 : 0;
49 | var shareTrustMinFloat = shareTrustEnabled ? config.poolServer.shareTrust.min / 100 : 0;
50 |
51 |
52 | var banningEnabled = config.poolServer.banning && config.poolServer.banning.enabled;
53 |
54 | var isMonero = config.coin === "monero";
55 |
56 |
57 | setInterval(function(){
58 | var now = Date.now() / 1000 | 0;
59 | for (var minerId in connectedMiners){
60 | var miner = connectedMiners[minerId];
61 | miner.retarget(now);
62 | }
63 | }, config.poolServer.varDiff.retargetTime * 1000);
64 |
65 |
66 | /* Every 30 seconds clear out timed-out miners and old bans */
67 | setInterval(function(){
68 | var now = Date.now();
69 | var timeout = config.poolServer.minerTimeout * 1000;
70 | for (var minerId in connectedMiners){
71 | var miner = connectedMiners[minerId];
72 | if (now - miner.lastBeat > timeout){
73 | log('warn', logSystem, 'Miner timed out and disconnected %s@%s', [miner.login, miner.ip]);
74 | delete connectedMiners[minerId];
75 | }
76 | }
77 |
78 | if (banningEnabled){
79 | for (ip in bannedIPs){
80 | var banTime = bannedIPs[ip];
81 | if (now - banTime > config.poolServer.banning.time * 1000) {
82 | delete bannedIPs[ip];
83 | delete perIPStats[ip];
84 | log('info', logSystem, 'Ban dropped for %s', [ip]);
85 | }
86 | }
87 | }
88 |
89 | }, 30000);
90 |
91 |
92 | process.on('message', function(message) {
93 | switch (message.type) {
94 | case 'banIP':
95 | bannedIPs[message.ip] = Date.now();
96 | break;
97 | }
98 | });
99 |
100 |
101 | function IsBannedIp(ip){
102 | if (!banningEnabled || !bannedIPs[ip]) return false;
103 |
104 | var bannedTime = bannedIPs[ip];
105 | var bannedTimeAgo = Date.now() - bannedTime;
106 | var timeLeft = config.poolServer.banning.time * 1000 - bannedTimeAgo;
107 | if (timeLeft > 0){
108 | return true;
109 | }
110 | else {
111 | delete bannedIPs[ip];
112 | log('info', logSystem, 'Ban dropped for %s', [ip]);
113 | return false;
114 | }
115 | }
116 |
117 |
118 | function BlockTemplate(template){
119 | this.blob = template.blocktemplate_blob;
120 | this.difficulty = template.difficulty;
121 | this.height = template.height;
122 | this.reserveOffset = template.reserved_offset;
123 | this.buffer = new Buffer(this.blob, 'hex');
124 | instanceId.copy(this.buffer, this.reserveOffset + 4, 0, 3);
125 | this.extraNonce = 0;
126 | }
127 | BlockTemplate.prototype = {
128 | nextBlob: function(){
129 | this.buffer.writeUInt32BE(++this.extraNonce, this.reserveOffset);
130 | return cnUtil.convert_blob(this.buffer).toString('hex');
131 | }
132 | };
133 |
134 |
135 |
136 | function getBlockTemplate(callback){
137 | apiInterfaces.rpcDaemon('getblocktemplate', {reserve_size: 8, wallet_address: config.poolServer.poolAddress}, callback);
138 | }
139 |
140 |
141 |
142 | function jobRefresh(loop, callback){
143 | callback = callback || function(){};
144 | getBlockTemplate(function(error, result){
145 | if (loop)
146 | setTimeout(function(){
147 | jobRefresh(true);
148 | }, config.poolServer.blockRefreshInterval);
149 | if (error){
150 | log('error', logSystem, 'Error polling getblocktemplate %j', [error]);
151 | callback(false);
152 | return;
153 | }
154 | if (!currentBlockTemplate || result.height > currentBlockTemplate.height){
155 | log('info', logSystem, 'New block to mine at height %d w/ difficulty of %d', [result.height, result.difficulty]);
156 | processBlockTemplate(result);
157 | }
158 | callback(true);
159 | })
160 | }
161 |
162 |
163 |
164 | function processBlockTemplate(template){
165 |
166 | if (currentBlockTemplate)
167 | validBlockTemplates.push(currentBlockTemplate);
168 |
169 | if (validBlockTemplates.length > 3)
170 | validBlockTemplates.shift();
171 |
172 | currentBlockTemplate = new BlockTemplate(template);
173 |
174 | for (var minerId in connectedMiners){
175 | var miner = connectedMiners[minerId];
176 | miner.pushMessage('job', miner.getJob());
177 | }
178 | }
179 |
180 |
181 |
182 | (function init(){
183 | jobRefresh(true, function(sucessful){
184 | if (!sucessful){
185 | log('error', logSystem, 'Could not start pool');
186 | return;
187 | }
188 | startPoolServerTcp(function(successful){
189 |
190 | });
191 | });
192 | })();
193 |
194 | var VarDiff = (function(){
195 | var variance = config.poolServer.varDiff.variancePercent / 100 * config.poolServer.varDiff.targetTime;
196 | return {
197 | variance: variance,
198 | bufferSize: config.poolServer.varDiff.retargetTime / config.poolServer.varDiff.targetTime * 4,
199 | tMin: config.poolServer.varDiff.targetTime - variance,
200 | tMax: config.poolServer.varDiff.targetTime + variance,
201 | maxJump: config.poolServer.varDiff.maxJump
202 | };
203 | })();
204 |
205 | function Miner(id, login, pass, ip, startingDiff, pushMessage){
206 | this.id = id;
207 | this.login = login;
208 | this.pass = pass;
209 | this.ip = ip;
210 | this.pushMessage = pushMessage;
211 | this.heartbeat();
212 | this.difficulty = startingDiff;
213 | this.validJobs = [];
214 |
215 | // Vardiff related variables
216 | this.shareTimeRing = utils.ringBuffer(16);
217 | this.lastShareTime = Date.now() / 1000 | 0;
218 |
219 | if (shareTrustEnabled) {
220 | this.trust = {
221 | threshold: config.poolServer.shareTrust.threshold,
222 | probability: 1,
223 | penalty: 0
224 | };
225 | }
226 | }
227 | Miner.prototype = {
228 | retarget: function(now){
229 |
230 | var options = config.poolServer.varDiff;
231 |
232 | var sinceLast = now - this.lastShareTime;
233 | var decreaser = sinceLast > VarDiff.tMax;
234 |
235 | var avg = this.shareTimeRing.avg(decreaser ? sinceLast : null);
236 | var newDiff;
237 |
238 | var direction;
239 |
240 | if (avg > VarDiff.tMax && this.difficulty > options.minDiff){
241 | newDiff = options.targetTime / avg * this.difficulty;
242 | newDiff = newDiff > options.minDiff ? newDiff : options.minDiff;
243 | direction = -1;
244 | }
245 | else if (avg < VarDiff.tMin && this.difficulty < options.maxDiff){
246 | newDiff = options.targetTime / avg * this.difficulty;
247 | newDiff = newDiff < options.maxDiff ? newDiff : options.maxDiff;
248 | direction = 1;
249 | }
250 | else{
251 | return;
252 | }
253 |
254 | if (Math.abs(newDiff - this.difficulty) / this.difficulty * 100 > options.maxJump){
255 | var change = options.maxJump / 100 * this.difficulty * direction;
256 | newDiff = this.difficulty + change;
257 | }
258 |
259 | this.setNewDiff(newDiff);
260 | this.shareTimeRing.clear();
261 | if (decreaser) this.lastShareTime = now;
262 | },
263 | setNewDiff: function(newDiff){
264 | newDiff = Math.round(newDiff);
265 | if (this.difficulty === newDiff) return;
266 | log('info', logSystem, 'Retargetting difficulty %d to %d for %s', [this.difficulty, newDiff, this.login]);
267 | this.pendingDifficulty = newDiff;
268 | this.pushMessage('job', this.getJob());
269 | },
270 | heartbeat: function(){
271 | this.lastBeat = Date.now();
272 | },
273 | getTargetHex: function(){
274 | if (this.pendingDifficulty){
275 | this.lastDifficulty = this.difficulty;
276 | this.difficulty = this.pendingDifficulty;
277 | this.pendingDifficulty = null;
278 | }
279 |
280 | var padded = new Buffer(32);
281 | padded.fill(0);
282 |
283 | var diffBuff = diff1.div(this.difficulty).toBuffer();
284 | diffBuff.copy(padded, 32 - diffBuff.length);
285 |
286 | var buff = padded.slice(0, 4);
287 | var buffArray = buff.toJSON();
288 | buffArray.reverse();
289 | var buffReversed = new Buffer(buffArray);
290 | this.target = buffReversed.readUInt32BE(0);
291 | var hex = buffReversed.toString('hex');
292 | return hex;
293 | },
294 | getJob: function(){
295 | if (this.lastBlockHeight === currentBlockTemplate.height && !this.pendingDifficulty) {
296 | return {
297 | blob: '',
298 | job_id: '',
299 | target: ''
300 | };
301 | }
302 |
303 | var blob = currentBlockTemplate.nextBlob();
304 | this.lastBlockHeight = currentBlockTemplate.height;
305 | var target = this.getTargetHex();
306 |
307 | var newJob = {
308 | id: utils.uid(),
309 | extraNonce: currentBlockTemplate.extraNonce,
310 | height: currentBlockTemplate.height,
311 | difficulty: this.difficulty,
312 | score: this.score,
313 | diffHex: this.diffHex,
314 | submissions: []
315 | };
316 |
317 | this.validJobs.push(newJob);
318 |
319 | if (this.validJobs.length > 4)
320 | this.validJobs.shift();
321 |
322 | return {
323 | blob: blob,
324 | job_id: newJob.id,
325 | target: target,
326 | id: this.id
327 | };
328 | },
329 | checkBan: function(validShare){
330 | if (!banningEnabled) return;
331 |
332 | // Init global per-IP shares stats
333 | if (!perIPStats[this.ip]){
334 | perIPStats[this.ip] = { validShares: 0, invalidShares: 0 };
335 | }
336 |
337 | var stats = perIPStats[this.ip];
338 | validShare ? stats.validShares++ : stats.invalidShares++;
339 |
340 | if (stats.validShares + stats.invalidShares >= config.poolServer.banning.checkThreshold){
341 | if (stats.invalidShares / stats.validShares >= config.poolServer.banning.invalidPercent / 100){
342 | log('warn', logSystem, 'Banned %s@%s', [this.login, this.ip]);
343 | bannedIPs[this.ip] = Date.now();
344 | delete connectedMiners[this.id];
345 | process.send({type: 'banIP', ip: this.ip});
346 | }
347 | else{
348 | stats.invalidShares = 0;
349 | stats.validShares = 0;
350 | }
351 | }
352 | }
353 | };
354 |
355 |
356 |
357 | function recordShareData(miner, job, shareDiff, blockCandidate, hashHex, shareType, blockTemplate){
358 |
359 | var dateNow = Date.now();
360 | var dateNowSeconds = dateNow / 1000 | 0;
361 |
362 | //Weighting older shares lower than newer ones to prevent pool hopping
363 | if (config.poolServer.slushMining.enabled) {
364 | if (lastChecked + config.poolServer.slushMining.lastBlockCheckRate <= dateNowSeconds || lastChecked == 0) {
365 | redisClient.hget(config.coin + ':stats', 'lastBlockFound', function(error, result) {
366 | if (error) {
367 | log('error', logSystem, 'Unable to determine the timestamp of the last block found');
368 | return;
369 | }
370 | scoreTime = result / 1000 | 0; //scoreTime could potentially be something else than the beginning of the current round, though this would warrant changes in api.js (and potentially the redis db)
371 | lastChecked = dateNowSeconds;
372 | });
373 | }
374 |
375 | job.score = job.difficulty * Math.pow(Math.E, ((dateNowSeconds - scoreTime) / config.poolServer.slushMining.weight)); //Score Calculation
376 | log('info', logSystem, 'Submitted score ' + job.score + ' with difficulty ' + job.difficulty + ' and the time ' + scoreTime);
377 | }
378 | else {
379 | job.score = job.difficulty;
380 | }
381 |
382 | var redisCommands = [
383 | ['hincrby', config.coin + ':shares:roundCurrent', miner.login, job.score],
384 | ['zadd', config.coin + ':hashrate', dateNowSeconds, [job.difficulty, miner.login, dateNow].join(':')],
385 | ['hincrby', config.coin + ':workers:' + miner.login, 'hashes', job.difficulty],
386 | ['hset', config.coin + ':workers:' + miner.login, 'lastShare', dateNowSeconds]
387 | ];
388 |
389 | if (blockCandidate){
390 | redisCommands.push(['hset', config.coin + ':stats', 'lastBlockFound', Date.now()]);
391 | redisCommands.push(['rename', config.coin + ':shares:roundCurrent', config.coin + ':shares:round' + job.height]);
392 | redisCommands.push(['hgetall', config.coin + ':shares:round' + job.height]);
393 | }
394 |
395 | redisClient.multi(redisCommands).exec(function(err, replies){
396 | if (err){
397 | log('error', logSystem, 'Failed to insert share data into redis %j \n %j', [err, redisCommands]);
398 | return;
399 | }
400 | if (blockCandidate){
401 | var workerShares = replies[replies.length - 1];
402 | var totalShares = Object.keys(workerShares).reduce(function(p, c){
403 | return p + parseInt(workerShares[c])
404 | }, 0);
405 | redisClient.zadd(config.coin + ':blocks:candidates', job.height, [
406 | hashHex,
407 | Date.now() / 1000 | 0,
408 | blockTemplate.difficulty,
409 | totalShares
410 | ].join(':'), function(err, result){
411 | if (err){
412 | log('error', logSystem, 'Failed inserting block candidate %s \n %j', [hashHex, err]);
413 | }
414 | });
415 | }
416 |
417 | });
418 |
419 | log('info', logSystem, 'Accepted %s share at difficulty %d/%d from %s@%s', [shareType, job.difficulty, shareDiff, miner.login, miner.ip]);
420 |
421 | }
422 |
423 | function processShare(miner, job, blockTemplate, nonce, resultHash){
424 | var shareBuffer = new Buffer(blockTemplate.buffer.length);
425 | blockTemplate.buffer.copy(shareBuffer);
426 | shareBuffer.writeUInt32BE(job.extraNonce, blockTemplate.reserveOffset);
427 | new Buffer(nonce, 'hex').copy(shareBuffer, 39);
428 |
429 | var convertedBlob;
430 | var hash;
431 | var shareType;
432 |
433 | if (shareTrustEnabled && miner.trust.threshold <= 0 && miner.trust.penalty <= 0 && Math.random() > miner.trust.probability){
434 | hash = new Buffer(resultHash, 'hex');
435 | shareType = 'trusted';
436 | }
437 | else {
438 | convertedBlob = cnUtil.convert_blob(shareBuffer);
439 | var cn_variant = isMonero && convertedBlob[0] >= 7 ? convertedBlob[0] - 6 : 0;
440 | hash = cryptoNight(convertedBlob, cn_variant);
441 | shareType = 'valid';
442 | }
443 |
444 |
445 | if (hash.toString('hex') !== resultHash) {
446 | log('warn', logSystem, 'Bad hash from miner %s@%s', [miner.login, miner.ip]);
447 | return false;
448 | }
449 |
450 | var hashArray = hash.toJSON();
451 | hashArray.reverse();
452 | var hashNum = bignum.fromBuffer(new Buffer(hashArray));
453 | var hashDiff = diff1.div(hashNum);
454 |
455 |
456 |
457 | if (hashDiff.ge(blockTemplate.difficulty)){
458 |
459 | apiInterfaces.rpcDaemon('submitblock', [shareBuffer.toString('hex')], function(error, result){
460 | if (error){
461 | log('error', logSystem, 'Error submitting block at height %d from %s@%s, share type: "%s" - %j', [job.height, miner.login, miner.ip, shareType, error]);
462 | recordShareData(miner, job, hashDiff.toString(), false, null, shareType);
463 | }
464 | else{
465 | var blockFastHash = cryptoNightFast(convertedBlob || cnUtil.convert_blob(shareBuffer)).toString('hex');
466 | log('info', logSystem,
467 | 'Block %s found at height %d by miner %s@%s - submit result: %j',
468 | [blockFastHash.substr(0, 6), job.height, miner.login, miner.ip, result]
469 | );
470 | recordShareData(miner, job, hashDiff.toString(), true, blockFastHash, shareType, blockTemplate);
471 | jobRefresh();
472 | }
473 | });
474 | }
475 |
476 | else if (hashDiff.lt(job.difficulty)){
477 | log('warn', logSystem, 'Rejected low difficulty share of %s from %s@%s', [hashDiff.toString(), miner.login, miner.ip]);
478 | return false;
479 | }
480 | else{
481 | recordShareData(miner, job, hashDiff.toString(), false, null, shareType);
482 | }
483 |
484 | return true;
485 | }
486 |
487 |
488 | function handleMinerMethod(method, params, ip, portData, sendReply, pushMessage){
489 |
490 |
491 | var miner = connectedMiners[params.id];
492 |
493 | // Check for ban here, so preconnected attackers can't continue to screw you
494 | if (IsBannedIp(ip)){
495 | sendReply('your IP is banned');
496 | return;
497 | }
498 |
499 | switch(method){
500 | case 'login':
501 | if (!params.login){
502 | sendReply('missing login');
503 | return;
504 | }
505 | if (!utils.isValidAddress(params.login, config.poolServer.poolAddress[0])){
506 | sendReply('invalid address used for login');
507 | return;
508 | }
509 | var minerId = utils.uid();
510 | miner = new Miner(minerId, params.login, params.pass, ip, portData.difficulty, pushMessage);
511 | connectedMiners[minerId] = miner;
512 | sendReply(null, {
513 | id: minerId,
514 | job: miner.getJob(),
515 | status: 'OK'
516 | });
517 | log('info', logSystem, 'Miner connected %s@%s', [params.login, miner.ip]);
518 | break;
519 | case 'getjob':
520 | if (!miner){
521 | sendReply('Unauthenticated');
522 | return;
523 | }
524 | miner.heartbeat();
525 | sendReply(null, miner.getJob());
526 | break;
527 | case 'submit':
528 | if (!miner){
529 | sendReply('Unauthenticated');
530 | return;
531 | }
532 | miner.heartbeat();
533 |
534 | var job = miner.validJobs.filter(function(job){
535 | return job.id === params.job_id;
536 | })[0];
537 |
538 | if (!job){
539 | sendReply('Invalid job id');
540 | return;
541 | }
542 |
543 | if (!noncePattern.test(params.nonce)) {
544 | var minerText = miner ? (' ' + miner.login + '@' + miner.ip) : '';
545 | log('warn', logSystem, 'Malformed nonce: ' + JSON.stringify(params) + ' from ' + minerText);
546 | perIPStats[miner.ip] = { validShares: 0, invalidShares: 999999 };
547 | miner.checkBan(false);
548 | sendReply('Duplicate share');
549 | return;
550 | }
551 |
552 | // Force lowercase for further comparison
553 | params.nonce = params.nonce.toLowerCase();
554 |
555 | if (job.submissions.indexOf(params.nonce) !== -1){
556 | var minerText = miner ? (' ' + miner.login + '@' + miner.ip) : '';
557 | log('warn', logSystem, 'Duplicate share: ' + JSON.stringify(params) + ' from ' + minerText);
558 | perIPStats[miner.ip] = { validShares: 0, invalidShares: 999999 };
559 | miner.checkBan(false);
560 | sendReply('Duplicate share');
561 | return;
562 | }
563 |
564 | job.submissions.push(params.nonce);
565 |
566 | var blockTemplate = currentBlockTemplate.height === job.height ? currentBlockTemplate : validBlockTemplates.filter(function(t){
567 | return t.height === job.height;
568 | })[0];
569 |
570 | if (!blockTemplate){
571 | sendReply('Block expired');
572 | return;
573 | }
574 |
575 | var shareAccepted = processShare(miner, job, blockTemplate, params.nonce, params.result);
576 | miner.checkBan(shareAccepted);
577 | if (shareTrustEnabled){
578 | if (shareAccepted){
579 | miner.trust.probability -= shareTrustStepFloat;
580 | if (miner.trust.probability < shareTrustMinFloat)
581 | miner.trust.probability = shareTrustMinFloat;
582 | miner.trust.penalty--;
583 | miner.trust.threshold--;
584 | }
585 | else{
586 | log('warn', logSystem, 'Share trust broken by %s@%s', [miner.login, miner.ip]);
587 | miner.trust.probability = 1;
588 | miner.trust.penalty = config.poolServer.shareTrust.penalty;
589 | }
590 | }
591 |
592 | if (!shareAccepted){
593 | sendReply('Low difficulty share');
594 | return;
595 | }
596 |
597 | var now = Date.now() / 1000 | 0;
598 | miner.shareTimeRing.append(now - miner.lastShareTime);
599 | miner.lastShareTime = now;
600 | //miner.retarget(now);
601 |
602 | sendReply(null, {status: 'OK'});
603 | break;
604 | case 'keepalived' :
605 | miner.heartbeat()
606 | sendReply(null, { status:'KEEPALIVED'
607 | });
608 | break;
609 | default:
610 | sendReply("invalid method");
611 | var minerText = miner ? (' ' + miner.login + '@' + miner.ip) : '';
612 | log('warn', logSystem, 'Invalid method: %s (%j) from %s', [method, params, minerText]);
613 | break;
614 | }
615 | }
616 |
617 |
618 | var httpResponse = ' 200 OK\nContent-Type: text/plain\nContent-Length: 20\n\nmining server online';
619 |
620 |
621 | function startPoolServerTcp(callback){
622 | async.each(config.poolServer.ports, function(portData, cback){
623 | var handleMessage = function(socket, jsonData, pushMessage){
624 | if (!jsonData.id) {
625 | log('warn', logSystem, 'Miner RPC request missing RPC id');
626 | return;
627 | }
628 | else if (!jsonData.method) {
629 | log('warn', logSystem, 'Miner RPC request missing RPC method');
630 | return;
631 | }
632 | else if (!jsonData.params) {
633 | log('warn', logSystem, 'Miner RPC request missing RPC params');
634 | return;
635 | }
636 |
637 | var sendReply = function(error, result){
638 | if(!socket.writable) return;
639 | var sendData = JSON.stringify({
640 | id: jsonData.id,
641 | jsonrpc: "2.0",
642 | error: error ? {code: -1, message: error} : null,
643 | result: result
644 | }) + "\n";
645 | socket.write(sendData);
646 | };
647 |
648 | handleMinerMethod(jsonData.method, jsonData.params, socket.remoteAddress, portData, sendReply, pushMessage);
649 | };
650 |
651 | net.createServer(function(socket){
652 | socket.setKeepAlive(true);
653 | socket.setEncoding('utf8');
654 |
655 | var dataBuffer = '';
656 |
657 | var pushMessage = function(method, params){
658 | if(!socket.writable) return;
659 | var sendData = JSON.stringify({
660 | jsonrpc: "2.0",
661 | method: method,
662 | params: params
663 | }) + "\n";
664 | socket.write(sendData);
665 | };
666 |
667 | socket.on('data', function(d){
668 | dataBuffer += d;
669 | if (Buffer.byteLength(dataBuffer, 'utf8') > 10240){ //10KB
670 | dataBuffer = null;
671 | log('warn', logSystem, 'Socket flooding detected and prevented from %s', [socket.remoteAddress]);
672 | socket.destroy();
673 | return;
674 | }
675 | if (dataBuffer.indexOf('\n') !== -1){
676 | var messages = dataBuffer.split('\n');
677 | var incomplete = dataBuffer.slice(-1) === '\n' ? '' : messages.pop();
678 | for (var i = 0; i < messages.length; i++){
679 | var message = messages[i];
680 | if (message.trim() === '') continue;
681 | var jsonData;
682 | try{
683 | jsonData = JSON.parse(message);
684 | }
685 | catch(e){
686 | if (message.indexOf('GET /') === 0) {
687 | if (message.indexOf('HTTP/1.1') !== -1) {
688 | socket.end('HTTP/1.1' + httpResponse);
689 | break;
690 | }
691 | else if (message.indexOf('HTTP/1.0') !== -1) {
692 | socket.end('HTTP/1.0' + httpResponse);
693 | break;
694 | }
695 | }
696 |
697 | log('warn', logSystem, 'Malformed message from %s: %s', [socket.remoteAddress, message]);
698 | socket.destroy();
699 |
700 | break;
701 | }
702 | handleMessage(socket, jsonData, pushMessage);
703 | }
704 | dataBuffer = incomplete;
705 | }
706 | }).on('error', function(err){
707 | if (err.code !== 'ECONNRESET')
708 | log('warn', logSystem, 'Socket error from %s %j', [socket.remoteAddress, err]);
709 | }).on('close', function(){
710 | pushMessage = function(){};
711 | });
712 |
713 | }).listen(portData.port, function (error, result) {
714 | if (error) {
715 | log('error', logSystem, 'Could not start server listening on port %d, error: $j', [portData.port, error]);
716 | cback(true);
717 | return;
718 | }
719 | log('info', logSystem, 'Started server listening on port %d', [portData.port]);
720 | cback();
721 | });
722 |
723 | }, function(err){
724 | if (err)
725 | callback(false);
726 | else
727 | callback(true);
728 | });
729 | }
730 |
731 |
732 |
733 |
734 |
--------------------------------------------------------------------------------
/lib/utils.js:
--------------------------------------------------------------------------------
1 | var base58 = require('base58-native');
2 | var cnUtil = require('cryptonote-util');
3 |
4 | var addressBase58Prefix = cnUtil.address_decode(new Buffer(config.poolServer.poolAddress));
5 |
6 | exports.uid = function(){
7 | var min = 100000000000000;
8 | var max = 999999999999999;
9 | var id = Math.floor(Math.random() * (max - min + 1)) + min;
10 | return id.toString();
11 | };
12 |
13 | exports.ringBuffer = function(maxSize){
14 | var data = [];
15 | var cursor = 0;
16 | var isFull = false;
17 |
18 | return {
19 | append: function(x){
20 | if (isFull){
21 | data[cursor] = x;
22 | cursor = (cursor + 1) % maxSize;
23 | }
24 | else{
25 | data.push(x);
26 | cursor++;
27 | if (data.length === maxSize){
28 | cursor = 0;
29 | isFull = true;
30 | }
31 | }
32 | },
33 | avg: function(plusOne){
34 | var sum = data.reduce(function(a, b){ return a + b }, plusOne || 0);
35 | return sum / ((isFull ? maxSize : cursor) + (plusOne ? 1 : 0));
36 | },
37 | size: function(){
38 | return isFull ? maxSize : cursor;
39 | },
40 | clear: function(){
41 | data = [];
42 | cursor = 0;
43 | isFull = false;
44 | }
45 | };
46 | };
47 |
48 | exports.varIntEncode = function(n){
49 |
50 | };
51 |
52 | exports.isValidAddress = function(addr){
53 |
54 | // config.poolServer.poolAddress
55 | //
56 |
57 | return addressBase58Prefix === cnUtil.address_decode(new Buffer(addr));
58 |
59 | };
60 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "cryptonote-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/zone117x/node-cryptonote-pool.git"
9 | },
10 | "dependencies": {
11 | "bignum": "0.12.5",
12 | "async": "1.5.2",
13 | "redis": "0.12.1",
14 | "cli-color": "1.1.0",
15 | "dateformat": "1.0.12",
16 | "base58-native": "0.1.4",
17 | "multi-hashing": "git://github.com/zone117x/node-multi-hashing.git",
18 | "cryptonote-util": "git://github.com/Snipa22/node-cryptonote-util#xmr-Nan-2.0"
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_example/admin.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
27 |
28 |
29 |
30 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
Admin Center
132 |
133 |
134 |
135 |
Stats
136 |
137 | Total Owed ...
138 | Total Paid ...
139 | Total Mined ...
140 | Profit (before tx fees) ...
141 | Average Luck ...
142 | Orphan Percent ...
143 | Registered Addresses ...
144 |
145 |
146 |
147 |
148 |
149 |
Miner Lookup
150 |
151 |
152 |
153 |
154 |
155 |
--------------------------------------------------------------------------------
/website_example/config.js:
--------------------------------------------------------------------------------
1 | var api = "http://cryppit.com:8117";
2 |
3 | var coinUnits = 1000000000000;
4 |
5 | var poolHost = "cryppit.com";
6 |
7 | var irc = "irc.freenode.net/#monero-pools";
8 |
9 | var email = "support@cryppit.com";
10 |
11 | var cryptonatorWidget = ["XMR-BTC", "XMR-USD", "XMR-EUR", "XMR-GBP"];
12 |
13 | var easyminerDownload = "https://github.com/zone117x/cryptonote-easy-miner/releases/";
14 |
15 | var blockchainExplorer = "http://chainradar.com/xmr/block/";
16 |
17 | var transactionExplorer = "http://chainradar.com/xmr/transaction/";
18 |
--------------------------------------------------------------------------------
/website_example/custom.css:
--------------------------------------------------------------------------------
1 | /* Insert your pool's unique css here */
--------------------------------------------------------------------------------
/website_example/custom.js:
--------------------------------------------------------------------------------
1 | /* Insert your pool's unique Javascript here */
--------------------------------------------------------------------------------
/website_example/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | Cryptonote Mining Pool
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
83 |
84 |
85 |
86 |
299 |
300 |
301 |
302 |
311 |
312 |
335 |
Stats Updated
336 |
337 |
338 |
339 |
340 |
341 |
342 |
343 |
344 |
345 |
346 |
347 |
348 |
349 |
356 |
357 |
358 |
359 |
--------------------------------------------------------------------------------
/website_example/pages/getting_started.html:
--------------------------------------------------------------------------------
1 |
49 |
50 |
51 | Connection Details
52 |
53 |
Mining Pool Address:
54 |
55 |
56 | Mining Ports
57 |
58 |
59 |
Port:
60 |
Starting Difficulty:
61 |
Description:
62 |
63 |
64 |
65 |
66 |
67 | For Windows users new to mining
68 |
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 |
73 |
74 |
75 |
76 | Wallet & Daemon Software
77 |
78 |
82 |
83 |
84 |
85 |
86 | Mining Apps
87 |
88 |
89 |
90 |
91 | App Name
92 | Architecture
93 | Downloads
94 | Discussion
95 | Source Code
96 |
97 |
98 |
99 |
100 | CPUMiner (forked by LucasJones & Wolf)
101 | CPU
102 | BitcoinTalk
103 | BitcoinTalk
104 | Github
105 |
106 |
107 |
108 | Example:
109 | minerd -a cryptonight -o stratum+tcp:// : -u YOUR_WALLET_ADDRESS -p x
110 |
111 |
112 |
113 | YAM Miner (by yvg1900)
114 | CPU
115 | MEGA
116 | Twitter
117 | Proprietary
118 |
119 |
120 |
121 | Example:
122 | yam -c x -M stratum+tcp://YOUR_WALLET_ADDRESS :x@ : /xmr
123 |
124 |
125 |
126 | Claymore CPU Miner
127 | CPU
128 | BitcoinTalk
129 | BitcoinTalk
130 | Proprietary
131 |
132 |
133 |
134 | Example:
135 | NsCpuCNMiner64 -o stratum+tcp:// : -u YOUR_WALLET_ADDRESS -p x
136 |
137 |
138 |
139 | Claymore GPU Miner
140 | OpenCL (AMD)
141 | BitcoinTalk
142 | Discussion
143 | Proprietary
144 |
145 |
146 |
147 | Example:
148 | NsGpuCNMiner -o stratum+tcp:// : -u YOUR_WALLET_ADDRESS -p x
149 |
150 |
151 |
152 | ccminer (forked by tsiv)
153 | CUDA (Nvidia)
154 | Github
155 | BitcoinTalk
156 | Github
157 |
158 |
159 |
160 | Example:
161 | ccminer -o stratum+tcp:// : -u YOUR_WALLET_ADDRESS -p x
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
--------------------------------------------------------------------------------
/website_example/pages/home.html:
--------------------------------------------------------------------------------
1 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
Network
89 |
Hash Rate:
90 |
Block Found:
91 |
Difficulty:
92 |
Blockchain Height:
93 |
Last Reward:
94 |
95 |
96 |
97 |
98 |
Our Pool
99 |
Hash Rate:
100 |
Block Found:
101 |
Connected Miners:
102 |
Donations:
103 |
Total Pool Fee:
104 |
Block Found Every: (est.)
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
Estimate Mining Profits
118 |
135 |
136 |
137 |
138 |
139 |
140 |
Your Stats & Payment History
141 |
142 |
143 |
144 |
145 | Lookup
146 | Searching...
147 |
148 |
149 |
150 |
151 |
Address:
152 |
Pending Balance:
153 |
Total Paid:
154 |
Last Share Submitted:
155 |
Hash Rate:
156 |
Total Hashes Submitted:
157 |
158 |
159 |
160 |
Payments
161 |
162 |
163 |
164 |
165 | Time Sent
166 | Transaction Hash
167 | Amount
168 | Mixin
169 |
170 |
171 |
172 |
173 |
174 |
175 |
176 |
177 | Load More
178 |
179 |
180 |
181 |
182 |
468 |
--------------------------------------------------------------------------------
/website_example/pages/payments.html:
--------------------------------------------------------------------------------
1 |
19 |
20 |
21 | Total Payments:
22 | Total Miners Paid:
23 | Minimum Payment Threshold:
24 | Denomination Unit:
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 | Time Sent
34 | Transaction Hash
35 | Amount
36 | Fee
37 | Mixin
38 | Payees
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 | Load More
49 |
50 |
51 |
52 |
--------------------------------------------------------------------------------
/website_example/pages/pool_blocks.html:
--------------------------------------------------------------------------------
1 |
25 |
26 |
27 | Total Blocks Mined:
28 | Maturity Depth Requirement:
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 | Height
38 | Maturity
39 | Difficulty
40 | Block Hash
41 | Time Found
42 | Luck
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 | Load More
53 |
54 |
55 |
217 |
--------------------------------------------------------------------------------
/website_example/pages/support.html:
--------------------------------------------------------------------------------
1 | Contact
2 | Email pool support at
3 |
4 | Chat Room
5 |
6 |
7 |
--------------------------------------------------------------------------------