一度コイン採掘とやらをやってみたかったので、モナーコインでやってみた

マイニングは計算なので、CPUでやる場合、GPUでやる場合、FPGAでやる場合などがあるようだ。
この順で効率が違う。今回はシンプルにCPUだけでやってみる。
単独でやるソロマイニングと、チームでやって利益を分配したりそのシステム利用コストを引かれたりするプールマイニングがある。
今回はソロを選択。
Monacoin-QtのMac用(英語版だけ)をダウンロードして財布は作っておく。
起動して、同期するまで長く待って、財布を暗号化しておくだけ。
バックアップも忘れずに。


環境はMBPなので、MacMinerをダウンロードして起動してみた。
http://fabulouspanda.co.uk/macminer/
入れたバイナリはこれ。
MacMiner.app-1.5.18b.zip。
起動すると、プールはプリセットがいくつかあるんだけど、UIにはソロマイニング用のはない感じ。
これはソロマイニングできない系?


"/Users/[username]/Library/Application Support/MacMiner/"あたりに、設定ファイルができてるってことだったんだけど、できてねー。
cpuminerとしては、MacMiner.appの中にminerdが入っていて、コマンドラインから動作させることはできるようだ。
minerdって、これか。
https://github.com/pooler/cpuminer
使い方は...
https://github.com/pooler/cpuminer/blob/master/README
minerd --help見ろって... orz
しょうがないな。

$ cd MacMiner.app/Contents/Resources/
$ ls
AppFonts		en.lproj		maxcoincpu
MacMiner.momd		fabric.png		maxminer
apiaccess		icon.icns		menu2.png
apiaccess.1		imine.icns		minerbackground.jpg
asicDock.png		jansson			minerd
bfgDockLabel.png	libblkmaker		mobileminer.png
bfgminer		libevent		nobackup.conf
bfgminer.conf		libidn			openssl
bfgurls.conf		libmicrohttpd		pool.png
bin			libusb			pooler-minerd
cgDockLabel.png		litebackup.conf		setupbackground.jpg
cgminer			litecoin.conf		vertcgminer
cpuDockLabel.png	ltcurls.conf		welcomeback.jpg
curl			macminer.icns		whiter.png
driverfiles		maxcgminer

minerdが入っているのを確認。
ヘルプ起動してみる。

$ ./minerd --help
Usage: minerd [OPTIONS]
Options:
  -a, --algo=ALGO       specify the algorithm to use
                          scrypt    scrypt(1024, 1, 1) (default)
                          sha256d   SHA-256d
                          quark     Quarkcoin
  -o, --url=URL         URL of mining server (default: http://127.0.0.1:9332/)
  -O, --userpass=U:P    username:password pair for mining server
  -u, --user=USERNAME   username for mining server
  -p, --pass=PASSWORD   password for mining server
      --cert=FILE       certificate for mining server using SSL
  -x, --proxy=[PROTOCOL://]HOST[:PORT]  connect through a proxy
  -t, --threads=N       number of miner threads (default: number of processors)
  -r, --retries=N       number of times to retry if a network call fails
                          (default: retry indefinitely)
  -R, --retry-pause=N   time to pause between retries, in seconds (default: 30)
  -T, --timeout=N       network timeout, in seconds (default: 270)
  -s, --scantime=N      upper bound on time spent scanning current work when
                          long polling is unavailable, in seconds (default: 5)
      --no-longpoll     disable X-Long-Polling support
      --no-stratum      disable X-Stratum support
  -q, --quiet           disable per-thread hashmeter output
  -D, --debug           enable debug output
  -H, --hashdebug       enable hash debug output
  -P, --protocol-dump   verbose dump of protocol-level activities
  -S, --syslog          use system log for output messages
  -B, --background      run the miner in the background
      --benchmark       run in offline benchmark mode
  -c, --config=FILE     load a JSON-format configuration file
  -V, --version         display version information and exit
  -h, --help            display this help text and exit

どうやら、設定はJSON形式で書いて渡すらしい。
他には、使いそうなオプションはこのくらいか。

--threads=N --algo=ALGO --url=URL --user=USERNAME --pass=PASSWORD

algoはアルゴリズムの指定。scrypt, sha256d, quarkの3種類が指定可能。デフォルトはscrypt。モナーコインもscryptでいいようだ。
threadsは、走らせるスレッド数。何も指定しなければ、CPU数と同じになる。
urlは、マイニングサーバーのURLとポート番号を指定する。モナーコインでは、118.157.9.160:9301のようだけど、これはいつでも使えるとは限らないそう。
ユーザー名とパスワードは何を入れればいいんだろう?poolを使うのであれば、poolに登録したものを使うのだが。
採掘の報酬としてのコインは、どうやって財布に入れるのだろう?
財布のIDを渡すところはないし...


プールマイニングでは、ユーザー名と財布の登録があるから理解できるんだけど、ソロでは、
鯖との通信はどうするのかと、採掘されたコインはどのように財布に入るのかがわからない。
調べてみると、どうも財布のほうに、そのような中継機能が埋め込まれているようだ。
考えてみれば、取引履歴の情報は財布が持っているので、これを使ってまだ未解決の部分の演算したらよくて、当たり前な実装だな。
しかし、Monacoin-Qtには、そんな設定画面はない。


Monacoin-Qt.appの中を見てみると、どうやら、基本的にはMonacoin-Qtというコマンドがあって、それ以外はMac用のラッパのようだ。
Monacoin-Qtのヘルプを見てみる。

$ Monacoin-Qt.app/Contents/MacOS/Monacoin-Qt --help
Monacoin-Qt version v0.8.6.1-g88e2a2e-beta

Usage:
  monacoin-qt [command-line options]

Options:
  -?                     This help message
  -conf=<file>           Specify configuration file (default: monacoin.conf)
  -pid=<file>            Specify pid file (default: monacoind.pid)
  -gen                   Generate coins (default: 0)
  -datadir=<dir>         Specify data directory
  -dbcache=<n>           Set database cache size in megabytes (default: 25)
  -timeout=<n>           Specify connection timeout in milliseconds (default: 5000)
  -proxy=<ip:port>       Connect through socks proxy
  -socks=<n>             Select the version of socks proxy to use (4-5, default: 5)
  -tor=<ip:port>         Use proxy to reach tor hidden services (default: same as -proxy)
  -dns                   Allow DNS lookups for -addnode, -seednode and -connect
  -port=<port>           Listen for connections on <port> (default: 9401 or testnet: 19401)
  -maxconnections=<n>    Maintain at most <n> connections to peers (default: 125)
  -addnode=<ip>          Add a node to connect to and attempt to keep the connection open
  -connect=<ip>          Connect only to the specified node(s)
  -seednode=<ip>         Connect to a node to retrieve peer addresses, and disconnect
  -externalip=<ip>       Specify your own public address
  -onlynet=<net>         Only connect to nodes in network <net> (IPv4, IPv6 or Tor)
  -discover              Discover own IP address (default: 1 when listening and no -externalip)
  -checkpoints           Only accept block chain matching built-in checkpoints (default: 1)
  -listen                Accept connections from outside (default: 1 if no -proxy or -connect)
  -bind=<addr>           Bind to given address and always listen on it. Use [host]:port notation for IPv6
  -dnsseed               Find peers using DNS lookup (default: 1 unless -connect)
  -banscore=<n>          Threshold for disconnecting misbehaving peers (default: 100)
  -bantime=<n>           Number of seconds to keep misbehaving peers from reconnecting (default: 86400)
  -maxreceivebuffer=<n>  Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)
  -maxsendbuffer=<n>     Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)
  -bloomfilters          Allow peers to set bloom filters (default: 1)
  -paytxfee=<amt>        Fee per KB to add to transactions you send
  -mininput=<amt>        When creating transactions, ignore inputs with value less than this (default: 0.0001)
  -server                Accept command line and JSON-RPC commands
  -testnet               Use the test network
  -debug                 Output extra debugging information. Implies all other -debug* options
  -debugnet              Output extra network debugging information
  -logtimestamps         Prepend debug output with timestamp (default: 1)
  -shrinkdebugfile       Shrink debug.log file on client startup (default: 1 when no -debug)
  -printtoconsole        Send trace/debug info to console instead of debug.log file
  -rpcuser=<user>        Username for JSON-RPC connections
  -rpcpassword=<pw>      Password for JSON-RPC connections
  -rpcport=<port>        Listen for JSON-RPC connections on <port> (default: 9402 or testnet: 19402)
  -rpcallowip=<ip>       Allow JSON-RPC connections from specified IP address
  -rpcthreads=<n>        Set the number of threads to service RPC calls (default: 4)
  -blocknotify=<cmd>     Execute command when the best block changes (%s in cmd is replaced by block hash)
  -walletnotify=<cmd>    Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)
  -alertnotify=<cmd>     Execute command when a relevant alert is received (%s in cmd is replaced by message)
  -upgradewallet         Upgrade wallet to latest format
  -keypool=<n>           Set key pool size to <n> (default: 100)
  -rescan                Rescan the block chain for missing wallet transactions
  -salvagewallet         Attempt to recover private keys from a corrupt wallet.dat
  -checkblocks=<n>       How many blocks to check at startup (default: 288, 0 = all)
  -checklevel=<n>        How thorough the block verification is (0-4, default: 3)
  -txindex               Maintain a full transaction index (default: 0)
  -loadblock=<file>      Imports blocks from external blk000??.dat file
  -reindex               Rebuild block chain index from current blk000??.dat files
  -par=<n>               Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)

Block creation options:
  -blockminsize=<n>      Set minimum block size in bytes (default: 0)
  -blockmaxsize=<n>      Set maximum block size in bytes (default: 250000)
  -blockprioritysize=<n> Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)

SSL options: (see the Monacoin Wiki for SSL setup instructions)
  -rpcssl                                  Use OpenSSL (https) for JSON-RPC connections
  -rpcsslcertificatechainfile=<file.cert>  Server certificate file (default: server.cert)
  -rpcsslprivatekeyfile=<file.pem>         Server private key (default: server.pem)
  -rpcsslciphers=<ciphers>                 Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)

UI options:
  -lang=<lang>           Set language, for example "de_DE" (default: system locale)
  -min                   Start minimized
  -splash                Show splash screen on startup (default: 1)

-serverって起動オプションあるんじゃん!
monacoin.conf書いて、-confで指定したらいいのかな。


というわけで、基本構成は、財布をサーバーで起動して、マイナーでは財布を指定して採掘できそう。
やってみる。


monacoin.confはこんな感じ。

rpcuser=[てきとーに文字列]
rpcpassword=[てきとーに文字列(rpcuserと同じはダメ)]
rpcallowip=127.0.0.1
rpcport=9302 
daemon=1 
server=1 
gen=0

財布を鯖起動してみる。

$ Monacoin-Qt.app/Contents/MacOS/Monacoin-Qt -conf=monacoin.conf -server
libpng warning: iCCP: known incorrect sRGB profile

何もおきないなと思っていたら、GUIのほうで、エラー出てた。

To use the "-server" option, you must set a rpcpassword in the configuration file:
/Users/kinneko/Library/Application Support/Monacoin/monacoin.conf
It is recommended you use the following random password:
rpcuser=monacoinrpc
rpcpassword=3crVGV61ywmKq61fzwr9UvB8W7C15rpH8oGQ6psCuv93
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %s | mail -s "Monacoin Alert" admin@foo.com

丁寧なことで。
-conf=monacoin.confは受け付けないようだ。
指定の場所に、すでにmonacoin.confがあるかどうか調べる。

$ ls /Users/kinneko/Library/Application\ Support/Monacoin/
blocks		database	debug.log	peers.dat.8151
chainstate	db.log		peers.dat	wallet.dat

ねーよ。
作ればいいのか。

$ mv monacoin.conf /Users/kinneko/Library/Application\ Support/Monacoin/
$ Monacoin-Qt.app/Contents/MacOS/Monacoin-Qt -conf=monacoin.conf -server
libpng warning: iCCP: known incorrect sRGB profile

起動してこないな。
ビーチボール。
サーバーとして、カギの同期しているのかな?
それともマイナーの起動を待っている?
マイナーを起動してみる。

MacBook:Monacoin kinneko$ MacMiner.app/Contents/Resources/minerd -o http://localhost:9302/ --userpass [rpcuser]:[rpcpassword]
[2014-02-22 23:44:45] Binding thread 0 to cpu 0
[2014-02-22 23:44:45] 4 miner threads started, using 'scrypt' algorithm.
[2014-02-22 23:44:45] Binding thread 1 to cpu 1
[2014-02-22 23:44:45] Binding thread 2 to cpu 2
[2014-02-22 23:44:45] Binding thread 3 to cpu 3
[2014-02-22 23:44:45] HTTP request failed: Failed connect to localhost:9302; Connection refused
[2014-02-22 23:44:45] json_rpc_call failed, retry after 30 seconds

うむ。ダメだな。

MacBook:Monacoin kinneko$ kill -KILL 25026
[1]+  Killed: 9               Monacoin-Qt.app/Contents/MacOS/Monacoin-Qt -conf=monacoin.conf -server

$ Monacoin-Qt.app/Contents/MacOS/Monacoin-Qt -server

こんどは起動してきた。
マイナーを起動する。

$ MacMiner.app/Contents/Resources/minerd -o localhost:9302 --userpass [rpcuser]:[rpcpassword]
[2014-02-22 23:49:26] Binding thread 1 to cpu 1
[2014-02-22 23:49:26] Binding thread 0 to cpu 0
[2014-02-22 23:49:26] 4 miner threads started, using 'scrypt' algorithm.
[2014-02-22 23:49:26] Binding thread 2 to cpu 2
[2014-02-22 23:49:26] Binding thread 3 to cpu 3
[2014-02-22 23:49:28] thread 1: 4104 hashes, 7.14 khash/s
[2014-02-22 23:49:28] thread 0: 4104 hashes, 7.22 khash/s
[2014-02-22 23:49:29] thread 2: 4104 hashes, 5.32 khash/s
[2014-02-22 23:49:29] thread 3: 4104 hashes, 5.20 khash/s

おお、きたきた。
わりと、すぐにCPUファンが回り始めた。
minerdは、メモリは3.1MBくらいと少ないものの、残りのCPUパワーである300%以上をバリバリ使っている。
データの送受信そのものは、ほとんどない。
スレッドあたりで、5秒前後で1処理をやっているようだ。
khash/sと処理時間はかわらないようなので、1khashずつの処理になっているのか。
この状態だと、20khash/sという感じか。


というわけで、非力なCPUマイニングだが、少しやってみる。
いろんなサイトでは、一週間で1回掘れるかどうかって感じということが書いてあったので、あんまり期待してない。
でも、掘れるってのは、どういうことなのか見てみたいという気持ちだけね。
掘れないと、ちゃんと動いているかもわかんないし。


というわけで、コイン掘れた!

[2014-02-23 18:09:54] accepted: 1/1 (100.00%), 21.44 khash/s (yay!!!)

財布のほうの画面にも、50.009 MONAが追加されたことが書かれている。
この半端な数はなんだろう?
イメージとしては、管理鯖から送金という形で採掘結果が来るような感じがしていたのだけど、分散環境で構築されているので、特にそういうこともないのか。アナウンスが伝播するだけ。つまんないな。
掘ったとこのIDをクリックすると、以下の様な画面のダイアログが出る。

Status: 203 confirmations, broadcast through 8 node(s)
Date: 2014/02/23 18:09
Source: Generated
Credit: 50.009 MONA
Net amount: +50.009 MONA
Transaction ID: 8c66c5d19dc9660ac3c8e353999531b2cdfca069ecd2320f47a81e3a5dcbfddc

Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.

同じブロックを数秒差で掘れちゃった人が他にいたりすると、無効になったりするそうな。


というわけで、1日未満であっさり採掘できちゃったので、つまんなかったな。
cgminerとか、bfgminerとかあったりするので、使えるのなら使ってみるかな?
まぁ、気が向いたら。


でも、まだモナーコインのやり取りはしたことないんだよね。
50コインほど掘れたので、誰かやりとりしてみない?
ちなみに、わたしの財布はこれ:
Monacoin: MEFfn469EWqYNAHwn3rhuFWiT53EFKnBpb


一人でやりとりできたので、それは後述。