Майнинг на сайте с помощью JavaScript — JavaScript Miner

JavaScript майнер на сайте
JavaScript майнер на сайте

Coinhive JavaScript Miner позволяет встраивать код майнера Monero прямо на ваш сайт. Сам майнер не оснащен пользовательским интерфейсом — вы несете полную ответственность за то, чтобы сообщить своим пользователям, что происходит процесс майнинга.

Код JavaScript майнера можно запустить, не сообщив своим пользователям. Мы настоятельно рекомендуем вам, обязательно сообщать о процессе майнинга свойм пользователям. Вы знаете, что это долгосрочная перспектива и она должна основываться на лояльности ваших пользователей, это гораздо важнее любой краткосрочной прибыли.

Вы можете ограничивать процесс JavaScript майнинга путем ограничения количества найденных хэшей от имени пользователя. JavaScript майнер работает до тех пор, пока вы не остановите его принудительно или пользователь не уйдет. Вы также можете использовать хэш случайного токена, и майнер автоматически остановится, когда достигнет указанного количества хэшей.

© 2017 Coinhive

Оригинал – Original

Synopsis

Load the Coinhive Miner and start Mining with the recommended settings — 70% CPU usage, disabled on mobile:

<script src=»https://authedmine.com/lib/authedmine.min.js»></script>

<script>

var miner = new CoinHive.Anonymous(‘YOUR_SITE_KEY’, {throttle: 0.3});

 

// Only start on non-mobile devices and if not opted-out

// in the last 14400 seconds (4 hours):

if (!miner.isMobile() && !miner.didOptOut(14400)) {

miner.start();

}

</script>

Note that the Miner is loaded from a different domain (authedmine.com) that enforces an opt-in as soon as miner.start() is called.

You may load the miner from https://coinhive.com/lib/coinhive.min.js instead if you don’t want to show the opt-in screen. See our AuthedMine documentation for the details.

Optionally you can listen on events, update stats on your website, etc.:

<script>

// Listen on events

miner.on(‘found’, function() { /* Hash found */ })

miner.on(‘accepted’, function() { /* Hash accepted by the pool */ })

 

// Update stats once per second

setInterval(function() {

var hashesPerSecond = miner.getHashesPerSecond();

var totalHashes = miner.getTotalHashes();

var acceptedHashes = miner.getAcceptedHashes();

 

// Output to HTML elements…

}, 1000);

</script>

API Reference

Constructors

  • CoinHive.Anonymous(siteKey [, options])
  • CoinHive.User(siteKey, userName [, options])
  • CoinHive.Token(siteKey, targetHashes [, options])

Instance Methods

  • .start([mode])
  • .stop()
  • .isRunning()
  • .isMobile()
  • .didOptOut(seconds)
  • .on(event, callback)
  • .hasWASMSupport()
  • .getNumThreads()
  • .setNumThreads(numThreads)
  • .getThrottle()
  • .setThrottle(throttle)
  • .getToken()
  • .getHashesPerSecond()
  • .getTotalHashes([interpolate])
  • .getAcceptedHashes()

new CoinHive.Anonymous(siteKey [, options])

Create a new miner that is not attached to a token or user name.

Common use-cases include donations to your website, where users just run the miner without any direct incentives for solved hashes.

Parameters

siteKey Your public Site-Key. See Settings » Sites.
options An optional object which defines further settings. See Constructor Options.

new CoinHive.User(siteKey, userName [, options])

Create a new miner and credit all hashes to the specified user name. You can check a user’s balance and withdraw hashes for a user with our HTTP API.

Common use-cases include granting in-game currency or other incentives to a user account on your website in turn for running the miner.

Please only use the CoinHive.User miner if you later intend to retreive the number of hashes using the HTTP API. Don’t use it to store random session names that you never read back.

Parameters

siteKey Your public Site-Key. See Settings » Sites.
userName A unique identifier for the user account on your website. This can be a userId, an email address, the user’s nick name or (if you don’t want to share your user names with our service) the md5 hash or otherwise obfuscated name of the user. Max length: 128 chars, case insensitive.
options An optional object which defines further settings. See Constructor Options.

new CoinHive.Token(siteKey, targetHashes [, options])

Create a new miner and stop once the specified number of hashes (targetHashes) was found. Tokens can be verified with our HTTP API. Tokens remain valid for 1 hour after they have reached the target.

The random token name is created by our mining pool. You can read it client side with miner.getToken() after the miner successfully authed on the pool.

Common use-cases include one off proof of work verifications to limit actions on your site or grant access to a resource. For example, this is used by the Coinhive captcha and shortlinks.

Parameters

siteKey Your public Site-Key. See Settings » Sites.
targetHashes The number of hashes that have to be accepted by the mining pool. Our pool uses a difficulty of 256, so your hashes goal should be a multiple of 256. Min: 256.
options An optional object which defines further settings. See Constructor Options.

Constructor Options

The options parameter for the CoinHive.User, CoinHive.Token and CoinHive.Anonymous constructors is optional. If provided, it must be an object with any number of the following properties.

threads The number of threads the miner should start with. The default is navigator.hardwareConcurrency, i.e. the number of CPU cores available on the user’s computer.
throttle The fraction of time that threads should be idle. See miner.setThrottle() for a detailed explanation. The default is 0.
forceASMJS If true, the miner will always use the asm.js implementation of the hashing algorithm. If false, the miner will use the faster WebAssembly version if supported and otherwise fall back to asm.js. The default is false.
theme The color theme for the opt-in screen — AuthedMine only. «light» or «dark». The default is «light».
language The language (ISO 639-1 code) to use for the opt-in screen — AuthedMine only. The default is «auto» which selects the language based on the user’s «accept-language» browser setting. Currently supported: ab, af, ar, be, bg, bs, ca, cs, da, de, el, en, eo, es, et, eu, fa, fi, fr, he, hi, hr, hu, id, it, ja, ka, ko, lt, lv, mr, ms, nb, nl, nn, no, os, pl, pt, pt-BR, ro, ru, si, sl, sq, sr, sv, ta, th, tr, uk, vi, yo, zh.

Full example, using the CoinHive.User miner:

var miner = new CoinHive.User(‘YOUR_SITE_KEY’, ‘john-doe’, {

threads: 4,

throttle: 0.8,

forceASMJS: false,

theme: ‘dark’,

language: ‘auto’

});

.start( [mode] )

Connect to the pool and start mining. The optional mode parameter specifies how the miner should behave if a miner in another tab is already running. The default is CoinHive.IF_EXCLUSIVE_TAB.

Note that the mode only affects other miners on the same origin/domain. Miners on other websites can’t kill yours, nor can you kill miners on other websites.

When loaded through authedmine.com our JavaScript API will ask the user for consent as soon as .start() is called. See our AuthedMine documentation for the details.

Mode

CoinHive.IF_EXCLUSIVE_TAB The miner will only start if no other tabs are already mining. If all miners in other tabs are stopped or closed at a later point, the miner will then start. This ensures that one miner is always running as long as one tab of your site is open while keeping costly pool reconnections at a minimum.
CoinHive.FORCE_EXCLUSIVE_TAB The miner will always start and immediately kill all miners in other tabs that have not specified CoinHive.FORCE_MULTI_TAB.
CoinHive.FORCE_MULTI_TAB The miner will always start. It will not announce its presence to other tabs, will not kill any other miners and can’t be killed by other miners. This mode is used by the captcha and shortlinks.

Example

miner.start(CoinHive.IF_EXCLUSIVE_TAB);

.stop( )

Stop mining and disconnect from the pool.

.isRunning( )

Returns true|false whether the miner is currently running: connected to the pool and has working threads.

.isMobile( )

Returns true|false whether the user is using a phone or tablet device. You can use this to only start the miner on laptops and PCs.

Example

// Only start on non-mobile devices

if (!miner.isMobile()) {

miner.start();

}

.didOptOut( [seconds] )

Returns true|false whether the user has clicked the «Cancel» button in the opt-in screen in the last seconds seconds. The seconds parameter is optional and defaults to 14400 (4 hours).

You can use this function to only show the opt-in screen again after a certain time, if the user has canceled the previous opt-in.

Example

// Only attempt to start and show the opt-in screen every 4 hours:

if (!miner.didOptOut(60 * 60 * 4)) {

miner.start();

}

.on(event, callback(params) { })

Specify a callback for an event.

Parameters

event The name of the event you want to listen to.
callback(params){} The function that should be called when the event is triggered.

Event Types

optin The user took action on the opt-in screen (AuthedMine only). The params.status is either «accepted» or «canceled». See below for an example.
open The connection to our mining pool was opened. Usually happens shortly after miner.start() was called.
authed The miner successfully authed with the mining pool and the siteKey was verified. Usually happens right after open. In case the miner was constructed with CoinHive.Token, a token name was received from the pool.
close The connection to the pool was closed. Usually happens when miner.stop() was called or the CoinHive.Token miner reached its goal.
error An error occured. In case of a connection error, the miner will automatically try to reconnect to the pool.
job A new mining job was received from the pool.
found A hash meeting the pool’s difficulty (currently 256) was found and will be send to the pool.
accepted A hash that was sent to the pool was accepted.

Example

miner.on(‘authed’, function(params) {

console.log(‘Token name is: ‘, miner.getToken());

});

 

miner.on(‘error’, function(params) {

if (params.error !== ‘connection_error’) {

console.log(‘The pool reported an error’, params.error);

}

});

 

miner.on(‘optin’, function(params) {

if (params.status === ‘accepted’) {

console.log(‘User accepted opt-in’);

}

else {

console.log(‘User canceled opt-in’);

}

});

.hasWASMSupport( )

Returns true|false whether the Browser supports WebAssembly. If WASM is not supported, the miner will automatically use the slower asm.js version. Consider displaying a warning message to the user to update their browser.

Current browser support for WASM.

.getNumThreads( )

Returns the current number of threads. Note that this will report the configured number of threads, even if the miner is not yet started.

.setNumThreads(numThreads)

Set the desired number of threads. Min: 1. Typically you shouldn’t go any higher than maybe 8 or 16 threads even if your users have all new AMD Threadripper CPUs.

Also see the threads property in the Constructor Options.

.getThrottle( )

Returns the current throttle value.

.setThrottle(throttle)

Set the fraction of time that threads should be idle. A value of 0 means no throttling (i.e. full speed), a value of 0.5 means that threads will stay idle 50% of the time, with 0.8 they will stay idle 80% of the time.

Also see the throttle property in the Constructor Options.

.getToken( )

If the miner was constructed with CoinHive.Token, this returns the token name (string) that was received from the pool. This token name will be empty until the miner has authed with the pool. You should listen for the authed event.

Example

miner.on(‘authed’, function(params) {

console.log(‘Token name is: ‘, miner.getToken());

});

.getHashesPerSecond( )

Returns the total number of hashes per second for all threads combined. Note that each thread typically updates this only once per second.

.getTotalHashes([interpolate])

Returns the total number of hashes this miner has solved. Note that this number is typically updated only once per second.

If interpolate is true, the miner will estimate the current number of hashes down to the millisecond. This can be useful if you want to display a fast increasing number to the user, such as in the miner on Coinhive’s start page.

.getAcceptedHashes( )

Returns the number of hashes that have been accepted by the pool. Also see the accepted event.

For the CoinHive.User miner, this includes all hashes ever accepted for the current user name.

© 2017 Coinhive