Debian9.8でEthereumのプライベートネットワークを作成する

1,はじめに

Debian9.8でEthereumのプライベートネットワークを作成し、自前のブロックチェーンを構築します。

下記の記事を参考に実施しました。

2,イーサリアムの導入

(1)Gethのインストール(失敗

注意:apt-getでのGethインストールは失敗に終わりました。下記(2)Gethのインストール(成功)まで読み飛ばして頂いて問題ありません。

上記の記事及び、EthereumのGitHubの下記ドキュメントの記述を基に、Gethインストールを行います。

(A) リポジトリの追加(エラー1)

apt-getコマンドで、Ethereumをインストールできるように、下記のコマンドを実行します。

ドキュメントを読むと「add-apt-repository」コマンドでリポジトリを追加する、とあるのですが、私の環境で試したところ「コマンドが見つかりません」とのエラーが出ました。

そこで、add-apt-repositoryコマンドのインストールをまず行います。

ちなみに、リポジトリの追加をしないで、installを試みると下記のエラーがでました。

root@VAIO-S-SB-Debian:~# apt-get install ethereum
パッケージリストを読み込んでいます... 完了
依存関係ツリーを作成しています                
状態情報を読み取っています... 完了
E: パッケージ ethereum が見つかりません
(i) install add-apt-repository command

上記のサイトの記述を参考に下記のコマンドを実行しました。

apt-get install software-properties-common
(ii) result
root@VAIO-S-SB-Debian:~# apt-get install software-properties-common
パッケージリストを読み込んでいます... 完了
依存関係ツリーを作成しています                
状態情報を読み取っています... 完了
以下の追加パッケージがインストールされます:
  python3-software-properties unattended-upgrades
提案パッケージ:
  bsd-mailx mail-transport-agent needrestart
以下のパッケージが新たにインストールされます:
  python3-software-properties software-properties-common unattended-upgrades
アップグレード: 0 個、新規インストール: 3 個、削除: 0 個、保留: 0 個。
195 kB のアーカイブを取得する必要があります。
この操作後に追加で 845 kB のディスク容量が消費されます。
続行しますか? [Y/n] y
0% [処理中]
取得:1 ftp://ftp.riken.jp/Linux/debian/debian stretch/main amd64 python3-software-properties all 0.96.20.2-1 [49.5 kB]
取得:2 ftp://ftp.riken.jp/Linux/debian/debian stretch/main amd64 software-properties-common all 0.96.20.2-1 [83.6 kB]
取得:3 ftp://ftp.riken.jp/Linux/debian/debian stretch/main amd64 unattended-upgrades all 0.93.1+nmu1 [61.7 kB]
195 kB を 2秒 で取得しました (68.5 kB/s)       
パッケージを事前設定しています ...
以前に未選択のパッケージ python3-software-properties を選択しています。
(データベースを読み込んでいます ... 現在 143469 個のファイルとディレクトリがインストールされています。)
.../python3-software-properties_0.96.20.2-1_all.deb を展開する準備をしています ...
python3-software-properties (0.96.20.2-1) を展開しています...
以前に未選択のパッケージ software-properties-common を選択しています。
.../software-properties-common_0.96.20.2-1_all.deb を展開する準備をしています ...
software-properties-common (0.96.20.2-1) を展開しています...
以前に未選択のパッケージ unattended-upgrades を選択しています。
.../unattended-upgrades_0.93.1+nmu1_all.deb を展開する準備をしています ...
unattended-upgrades (0.93.1+nmu1) を展開しています...
systemd (232-25+deb9u11) のトリガを処理しています ...
unattended-upgrades (0.93.1+nmu1) を設定しています ...

Creating config file /etc/apt/apt.conf.d/20auto-upgrades with new version

Creating config file /etc/apt/apt.conf.d/50unattended-upgrades with new version
Created symlink /etc/systemd/system/multi-user.target.wants/unattended-upgrades.service → /lib/systemd/system/unattended-upgrades.service.
Synchronizing state of unattended-upgrades.service with SysV service script with /lib/systemd/systemd-sysv-install.
Executing: /lib/systemd/systemd-sysv-install enable unattended-upgrades
man-db (2.7.6.1-2) のトリガを処理しています ...
python3-software-properties (0.96.20.2-1) を設定しています ...
dbus (1.10.26-0+deb9u1) のトリガを処理しています ...
software-properties-common (0.96.20.2-1) を設定しています ...
systemd (232-25+deb9u11) のトリガを処理しています ...
dbus (1.10.26-0+deb9u1) のトリガを処理しています ...
root@VAIO-S-SB-Debian:~# 

(B) リポジトリの追加(エラー2)

では、リポジトリの追加を試みます。

下記コマンドを実行します。

add-apt-repository -y ppa:ethereum/ethereum

エラーが出ました。

root@VAIO-S-SB-Debian:~# add-apt-repository -y ppa:ethereum/ethereum
gpg: keybox '/tmp/tmpni_1z73k/pubring.gpg' created
gpg: failed to start the dirmngr '/usr/bin/dirmngr': そのようなファイルやディレクトリはありません
gpg: connecting dirmngr at '/tmp/tmpni_1z73k/S.dirmngr' failed: そのようなファイルやディレクトリはありません
gpg: keyserver receive failed: dirmngrがありません
root@VAIO-S-SB-Debian:~# 
(i) install dirmngr

ネットで検索をしたところ、下記の記事が出てきました。

dirmngrがインストールされていないことが原因なので、下記のコマンドを実行しました。

apt-get install dirmngr
(ii) result
root@VAIO-S-SB-Debian:~# apt-get install dirmngr
パッケージリストを読み込んでいます... 完了
依存関係ツリーを作成しています                
状態情報を読み取っています... 完了
提案パッケージ:
  tor
以下のパッケージが新たにインストールされます:
  dirmngr
アップグレード: 0 個、新規インストール: 1 個、削除: 0 個、保留: 0 個。
597 kB のアーカイブを取得する必要があります。
この操作後に追加で 1,114 kB のディスク容量が消費されます。
取得:1 ftp://ftp.riken.jp/Linux/debian/debian stretch/main amd64 dirmngr amd64 2.1.18-8~deb9u4 [597 kB]
597 kB を 1秒 で取得しました (299 kB/s)                  
以前に未選択のパッケージ dirmngr を選択しています。
(データベースを読み込んでいます ... 現在 143609 個のファイルとディレクトリがインストールされています。)
.../dirmngr_2.1.18-8~deb9u4_amd64.deb を展開する準備をしています ...
dirmngr (2.1.18-8~deb9u4) を展開しています...
man-db (2.7.6.1-2) のトリガを処理しています ...
dirmngr (2.1.18-8~deb9u4) を設定しています ...
root@VAIO-S-SB-Debian:~# 

(C) リポジトリの追加(三度目の失敗)

三度目の正直ということわざが日本にはあります。

トラディショナルなジャパニーズのことわざは、物事に3回挑戦すれば、成功すること述べています。

そのことわざを心にともして、リポジトリの追加を試みます。

(i) command
add-apt-repository -y ppa:ethereum/ethereum
(ii) result

エラーが出ました。

root@VAIO-S-SB-Debian:~# add-apt-repository -y ppa:ethereum/ethereum
gpg: keybox '/tmp/tmpjve59rz6/pubring.gpg' created
gpg: /tmp/tmpjve59rz6/trustdb.gpg: trustdb created
gpg: key 1C52189C923F6CA9: public key "Launchpad PPA for Ethereum" imported
gpg: Total number processed: 1
gpg:               imported: 1
gpg: no valid OpenPGP data found.
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "/usr/lib/python3/dist-packages/softwareproperties/SoftwareProperties.py", line 688, in addkey_func
    func(**kwargs)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 386, in add_key
    return apsk.add_ppa_signing_key()
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 273, in add_ppa_signing_key
    cleanup(tmp_keyring_dir)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 234, in cleanup
    shutil.rmtree(tmp_keyring_dir)
  File "/usr/lib/python3.5/shutil.py", line 480, in rmtree
    _rmtree_safe_fd(fd, path, onerror)
  File "/usr/lib/python3.5/shutil.py", line 438, in _rmtree_safe_fd
    onerror(os.unlink, fullname, sys.exc_info())
  File "/usr/lib/python3.5/shutil.py", line 436, in _rmtree_safe_fd
    os.unlink(name, dir_fd=topfd)
FileNotFoundError: [Errno 2] そのようなファイルやディレクトリはありません: 'S.gpg-agent.browser'

root@VAIO-S-SB-Debian:~# 

(D) apt-getでEthereumをインストールするのを諦めます

リポジトリ設定をもとに戻すため下記のコマンドを実行しました。

add-apt-repository --remove ppa:ethereum/ethereum

今後の方針として、イーサリアムの公式サイトで配布しているLinux用のバイナリをインストールします。

(2)Gethのインストール(成功)

(A) バイナリのダウンロード

下記のサイトからLinux用のバイナリをダウンロードします。

本稿執筆時にダウンロードできたのは「geth-linux-amd64-1.8.27-4bcc0a37.tar.gz」でした。

(B) ファイルを展開

jskny@VAIO-S-SB-Debian:~/ダウンロード$ tar -zxvf geth-linux-amd64-1.8.27-4bcc0a37.tar.gz 
geth-linux-amd64-1.8.27-4bcc0a37/
geth-linux-amd64-1.8.27-4bcc0a37/COPYING
geth-linux-amd64-1.8.27-4bcc0a37/geth
jskny@VAIO-S-SB-Debian:~/ダウンロード$

上記でダウンロードしたファイルを展開すると、2つのファイルが作成されました。

(C) 動作確認

展開したファイル「geth」がイーサリアムのプログラムなので、動作確認を行います。

(i) command
geth -h
(ii) result
jskny@VAIO-S-SB-Debian:~/ダウンロード/geth-linux-amd64-1.8.27-4bcc0a37$ ./geth -h
NAME:
   geth - the go-ethereum command line interface

   Copyright 2013-2018 The go-ethereum Authors

USAGE:
   geth [options] command [command options] [arguments...]
   
VERSION:
   1.8.27-stable-4bcc0a37
   
COMMANDS:
   account           Manage accounts
   attach            Start an interactive JavaScript environment (connect to node)
   bug               opens a window to report a bug on the geth repo
   console           Start an interactive JavaScript environment
   copydb            Create a local chain from a target chaindata folder
   dump              Dump a specific block from storage
   dumpconfig        Show configuration values
   export            Export blockchain into file
   export-preimages  Export the preimage database into an RLP stream
   import            Import a blockchain file
   import-preimages  Import the preimage database from an RLP stream
   init              Bootstrap and initialize a new genesis block
   js                Execute the specified JavaScript files
   license           Display license information
   makecache         Generate ethash verification cache (for testing)
   makedag           Generate ethash mining DAG (for testing)
   monitor           Monitor and visualize node metrics
   removedb          Remove blockchain and state databases
   version           Print version numbers
   wallet            Manage Ethereum presale wallets
   help, h           Shows a list of commands or help for one command
   
ETHEREUM OPTIONS:
  --config value                     TOML configuration file
  --datadir "/home/jskny/.ethereum"  Data directory for the databases and keystore
  --keystore                         Directory for the keystore (default = inside the datadir)
  --nousb                            Disables monitoring for and managing USB hardware wallets
  --networkid value                  Network identifier (integer, 1=Frontier, 2=Morden (disused), 3=Ropsten, 4=Rinkeby) (default: 1)
  --testnet                          Ropsten network: pre-configured proof-of-work test network
  --rinkeby                          Rinkeby network: pre-configured proof-of-authority test network
  --goerli                           Görli network: pre-configured proof-of-authority test network
  --syncmode "fast"                  Blockchain sync mode ("fast", "full", or "light")
  --gcmode value                     Blockchain garbage collection mode ("full", "archive") (default: "full")
  --ethstats value                   Reporting URL of a ethstats service (nodename:secret@host:port)
  --identity value                   Custom node name
  --lightserv value                  Maximum percentage of time allowed for serving LES requests (0-90) (default: 0)
  --lightpeers value                 Maximum number of LES client peers (default: 100)
  --lightkdf                         Reduce key-derivation RAM & CPU usage at some expense of KDF strength
  --whitelist value                  Comma separated block number-to-hash mappings to enforce (<number>=<hash>)
  
DEVELOPER CHAIN OPTIONS:
  --dev               Ephemeral proof-of-authority network with a pre-funded developer account, mining enabled
  --dev.period value  Block period to use in developer mode (0 = mine only if transaction pending) (default: 0)
  
ETHASH OPTIONS:
  --ethash.cachedir                      Directory to store the ethash verification caches (default = inside the datadir)
  --ethash.cachesinmem value             Number of recent ethash caches to keep in memory (16MB each) (default: 2)
  --ethash.cachesondisk value            Number of recent ethash caches to keep on disk (16MB each) (default: 3)
  --ethash.dagdir "/home/jskny/.ethash"  Directory to store the ethash mining DAGs (default = inside home folder)
  --ethash.dagsinmem value               Number of recent ethash mining DAGs to keep in memory (1+GB each) (default: 1)
  --ethash.dagsondisk value              Number of recent ethash mining DAGs to keep on disk (1+GB each) (default: 2)
  
TRANSACTION POOL OPTIONS:
  --txpool.locals value        Comma separated accounts to treat as locals (no flush, priority inclusion)
  --txpool.nolocals            Disables price exemptions for locally submitted transactions
  --txpool.journal value       Disk journal for local transaction to survive node restarts (default: "transactions.rlp")
  --txpool.rejournal value     Time interval to regenerate the local transaction journal (default: 1h0m0s)
  --txpool.pricelimit value    Minimum gas price limit to enforce for acceptance into the pool (default: 1)
  --txpool.pricebump value     Price bump percentage to replace an already existing transaction (default: 10)
  --txpool.accountslots value  Minimum number of executable transaction slots guaranteed per account (default: 16)
  --txpool.globalslots value   Maximum number of executable transaction slots for all accounts (default: 4096)
  --txpool.accountqueue value  Maximum number of non-executable transaction slots permitted per account (default: 64)
  --txpool.globalqueue value   Maximum number of non-executable transaction slots for all accounts (default: 1024)
  --txpool.lifetime value      Maximum amount of time non-executable transaction are queued (default: 3h0m0s)
  
PERFORMANCE TUNING OPTIONS:
  --cache value            Megabytes of memory allocated to internal caching (default: 1024)
  --cache.database value   Percentage of cache memory allowance to use for database io (default: 50)
  --cache.trie value       Percentage of cache memory allowance to use for trie caching (default: 25)
  --cache.gc value         Percentage of cache memory allowance to use for trie pruning (default: 25)
  --trie-cache-gens value  Number of trie node generations to keep in memory (default: 120)
  
ACCOUNT OPTIONS:
  --unlock value    Comma separated list of accounts to unlock
  --password value  Password file to use for non-interactive password input
  
API AND CONSOLE OPTIONS:
  --rpc                  Enable the HTTP-RPC server
  --rpcaddr value        HTTP-RPC server listening interface (default: "localhost")
  --rpcport value        HTTP-RPC server listening port (default: 8545)
  --rpcapi value         API's offered over the HTTP-RPC interface
  --rpc.gascap value     Sets a cap on gas that can be used in eth_call/estimateGas (default: 0)
  --ws                   Enable the WS-RPC server
  --wsaddr value         WS-RPC server listening interface (default: "localhost")
  --wsport value         WS-RPC server listening port (default: 8546)
  --wsapi value          API's offered over the WS-RPC interface
  --wsorigins value      Origins from which to accept websockets requests
  --ipcdisable           Disable the IPC-RPC server
  --ipcpath              Filename for IPC socket/pipe within the datadir (explicit paths escape it)
  --rpccorsdomain value  Comma separated list of domains from which to accept cross origin requests (browser enforced)
  --rpcvhosts value      Comma separated list of virtual hostnames from which to accept requests (server enforced). Accepts '*' wildcard. (default: "localhost")
  --jspath loadScript    JavaScript root path for loadScript (default: ".")
  --exec value           Execute JavaScript statement
  --preload value        Comma separated list of JavaScript files to preload into the console
  
NETWORKING OPTIONS:
  --bootnodes value     Comma separated enode URLs for P2P discovery bootstrap (set v4+v5 instead for light servers)
  --bootnodesv4 value   Comma separated enode URLs for P2P v4 discovery bootstrap (light server, full nodes)
  --bootnodesv5 value   Comma separated enode URLs for P2P v5 discovery bootstrap (light server, light nodes)
  --port value          Network listening port (default: 30303)
  --maxpeers value      Maximum number of network peers (network disabled if set to 0) (default: 25)
  --maxpendpeers value  Maximum number of pending connection attempts (defaults used if set to 0) (default: 0)
  --nat value           NAT port mapping mechanism (any|none|upnp|pmp|extip:<IP>) (default: "any")
  --nodiscover          Disables the peer discovery mechanism (manual peer addition)
  --v5disc              Enables the experimental RLPx V5 (Topic Discovery) mechanism
  --netrestrict value   Restricts network communication to the given IP networks (CIDR masks)
  --nodekey value       P2P node key file
  --nodekeyhex value    P2P node key as hex (for testing)
  
MINER OPTIONS:
  --mine                         Enable mining
  --miner.threads value          Number of CPU threads to use for mining (default: 0)
  --miner.notify value           Comma separated HTTP URL list to notify of new work packages
  --miner.gasprice "1000000000"  Minimum gas price for mining a transaction
  --miner.gastarget value        Target gas floor for mined blocks (default: 8000000)
  --miner.gaslimit value         Target gas ceiling for mined blocks (default: 8000000)
  --miner.etherbase value        Public address for block mining rewards (default = first account) (default: "0")
  --miner.extradata value        Block extra data set by the miner (default = client version)
  --miner.recommit value         Time interval to recreate the block being mined (default: 3s)
  --miner.noverify               Disable remote sealing verification
  
GAS PRICE ORACLE OPTIONS:
  --gpoblocks value      Number of recent blocks to check for gas prices (default: 20)
  --gpopercentile value  Suggested gas price is the given percentile of a set of recent transaction gas prices (default: 60)
  
VIRTUAL MACHINE OPTIONS:
  --vmdebug         Record information useful for VM and contract debugging
  --vm.evm value    External EVM configuration (default = built-in interpreter)
  --vm.ewasm value  External ewasm configuration (default = built-in interpreter)
  
LOGGING AND DEBUGGING OPTIONS:
  --fakepow                 Disables proof-of-work verification
  --nocompaction            Disables db compaction after import
  --verbosity value         Logging verbosity: 0=silent, 1=error, 2=warn, 3=info, 4=debug, 5=detail (default: 3)
  --vmodule value           Per-module verbosity: comma-separated list of <pattern>=<level> (e.g. eth/*=5,p2p=4)
  --backtrace value         Request a stack trace at a specific logging statement (e.g. "block.go:271")
  --debug                   Prepends log messages with call-site location (file and line number)
  --pprof                   Enable the pprof HTTP server
  --pprofaddr value         pprof HTTP server listening interface (default: "127.0.0.1")
  --pprofport value         pprof HTTP server listening port (default: 6060)
  --memprofilerate value    Turn on memory profiling with the given rate (default: 524288)
  --blockprofilerate value  Turn on block profiling with the given rate (default: 0)
  --cpuprofile value        Write CPU profile to the given file
  --trace value             Write execution trace to the given file
  
METRICS AND STATS OPTIONS:
  --metrics                          Enable metrics collection and reporting
  --metrics.influxdb                 Enable metrics export/push to an external InfluxDB database
  --metrics.influxdb.endpoint value  InfluxDB API endpoint to report metrics to (default: "http://localhost:8086")
  --metrics.influxdb.database value  InfluxDB database name to push reported metrics to (default: "geth")
  --metrics.influxdb.username value  Username to authorize access to the database (default: "test")
  --metrics.influxdb.password value  Password to authorize access to the database (default: "test")
  --metrics.influxdb.tags value      Comma-separated InfluxDB tags (key/values) attached to all measurements (default: "host=localhost")
  
WHISPER (EXPERIMENTAL) OPTIONS:
  --shh                       Enable Whisper
  --shh.maxmessagesize value  Max message size accepted (default: 1048576)
  --shh.pow value             Minimum POW accepted (default: 0.2)
  --shh.restrict-light        Restrict connection between two whisper light clients
  
DEPRECATED OPTIONS:
  --minerthreads value     Number of CPU threads to use for mining (deprecated, use --miner.threads) (default: 0)
  --targetgaslimit value   Target gas floor for mined blocks (deprecated, use --miner.gastarget) (default: 8000000)
  --gasprice "1000000000"  Minimum gas price for mining a transaction (deprecated, use --miner.gasprice)
  --etherbase value        Public address for block mining rewards (default = first account, deprecated, use --miner.etherbase) (default: "0")
  --extradata value        Block extra data set by the miner (default = client version, deprecated, use --miner.extradata)
  
MISC OPTIONS:
  --override.constantinople value  Manually specify constantinople fork-block, overriding the bundled setting (default: 0)
  --help, -h                       show help
  

COPYRIGHT:
   Copyright 2013-2018 The go-ethereum Authors
   
jskny@VAIO-S-SB-Debian:~/ダウンロード/geth-linux-amd64-1.8.27-4bcc0a37$ 

無事に動作確認ができました。

3,プライベートネットワークの作成

(1) ブロックチェーンを作成

作業用のフォルダに「test-eth」ディレクトリを作成します。

jskny@VAIO-S-SB-Debian:~/Workspace$ pwd
/home/jskny/Workspace
jskny@VAIO-S-SB-Debian:~/Workspace$ mkdir test-eth
jskny@VAIO-S-SB-Debian:~/Workspace$ ls
Share_it_with_the_QR_code.html  Sysrigar  flowers-ink  hello_world_by_flutter  test-eth  test_textbox
jskny@VAIO-S-SB-Debian:~/Workspace$ 

次に、そこにブロックチェーンの基本情報を記入するJSONファイルを作成します。

名前は何でも良いとのことなので、「test.json」とします。

jskny@VAIO-S-SB-Debian:~/Workspace$ cd test-eth/
jskny@VAIO-S-SB-Debian:~/Workspace/test-eth$ echo > test.json
jskny@VAIO-S-SB-Debian:~/Workspace/test-eth$ ls
test.json
jskny@VAIO-S-SB-Debian:~/Workspace/test-eth$ 

作成した「test.json」に対して、下記の内容を記入する。

この記述が、ブロックチェーンの一番最初の設定ファイルになるそうです。

設定情報等は、上述のサイトの記事を参考にしています。

test.json

{
  "config": {
    "chainId": 15
  },
  "nonce": "0x0000000000000042",
  "timestamp": "0x0",
  "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "extraData": "",
  "gasLimit": "0x8000000",
  "difficulty": "0x4000",
  "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "coinbase": "0x3333333333333333333333333333333333333333",
  "alloc": {}
}

次に、この設定情報に基づきブロックチェーンの初期化を行います。

下記のコマンドを実行します。

(A) command

/home/jskny/ダウンロード/geth-linux-amd64-1.8.27-4bcc0a37/geth --datadir ./ init test.json

環境構築をバイナリのダウンロードで行ったため、パス長くてすみません。

(B) result

jskny@VAIO-S-SB-Debian:~/Workspace/test-eth$ pwd
/home/jskny/Workspace/test-eth
jskny@VAIO-S-SB-Debian:~/Workspace/test-eth$ /home/jskny/ダウンロード/geth-linux-amd64-1.8.27-4bcc0a37/geth --datadir ./ init test.json
INFO [05-19|13:36:17.960] Maximum peer count                       ETH=25 LES=0 total=25
INFO [05-19|13:36:17.962] Allocated cache and file handles         database=/home/jskny/Workspace/test-eth/geth/chaindata cache=16 handles=16
INFO [05-19|13:36:17.971] Writing custom genesis block 
INFO [05-19|13:36:17.971] Persisted trie from memory database      nodes=0 size=0.00B time=3.455µs gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [05-19|13:36:17.971] Successfully wrote genesis state         database=chaindata                                     hash=7b2e8b…7e0432
INFO [05-19|13:36:17.971] Allocated cache and file handles         database=/home/jskny/Workspace/test-eth/geth/lightchaindata cache=16 handles=16
INFO [05-19|13:36:17.979] Writing custom genesis block 
INFO [05-19|13:36:17.979] Persisted trie from memory database      nodes=0 size=0.00B time=4.042µs gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [05-19|13:36:17.979] Successfully wrote genesis state         database=lightchaindata                                     hash=7b2e8b…7e0432
jskny@VAIO-S-SB-Debian:~/Workspace/test-eth$ 

初期ブロックの初期化できました。

初期化が成功すると、ブロックチェーンの情報を記録するディレクトリが、参考文献の通り作成されました。

jskny@VAIO-S-SB-Debian:~/Workspace/test-eth$ pwd
/home/jskny/Workspace/test-eth
jskny@VAIO-S-SB-Debian:~/Workspace/test-eth$ ls
geth  keystore  test.json
jskny@VAIO-S-SB-Debian:~/Workspace/test-eth$

(2)プライベートネットワークの起動

イーサリアムはいくつかの形態でブロックチェーンのP2Pネットワークを運用できます。

パブリック・ネットワーク:不特定多数のノードのノードが参加し、かつその参加に制限が全くないネットワークです。参加ノードはそのネットワーク上で共有管理されたブロックチェーンに対して自由に、読み取り、トランザクションの発行、マイニングが可能です。仮想通貨としてのEthereumや、多くのパブリックなdAppはこのパブリックネットワーク上で運用されています。
コンソーシアム・ネットワーク:あらかじめ参加を許されたノードのみが参加することが可能なネットワークです。参加を許されるノードは一つの組織のみに管理されたものとは限らず、複数の利害関係が一致しない組織がそれぞれのノードを管理することが通常です。例えば国際送金の管理を行うブロックチェーンを構築したい場合、予め参加を許された複数の金融企業がそれぞれ管理するノードをこのP2Pのネットワークに参加することで、一つの企業にのみ管理されたシステムではない半非中央集権なシステムが構築可能になります。
プライベート・ネットワーク:一つの組織のみに管理されたノードのみが参加することが可能なネットワークです。ネットワークは自身の管理下に置くことが可能になり、中央集権的なP2Pシステムが可能になります。

プライベート・ネットに接続する · Ethereum入門

今回は、私を含むごく少数が使用するネットワークなので、プライベート・ネットワークでブロックチェーンを運用します。

下記のコマンドでプライベートネットワークを起動します。

(A) 対話コンソールの起動

(i) command
/home/jskny/ダウンロード/geth-linux-amd64-1.8.27-4bcc0a37/geth --networkid "15" --nodiscover --datadir "./" console 2>> ./geth_err.log

コマンドのパラメーターについて、

--datadir :本オプションはgethの動作時のブロックチェーンデータや各種ログの出力先を指定します。genesisブロックの初期化で指定したディレクトリと同一のものを指定してください。
--networkid "15" :本オプションで任意の正の整数のIDを指定することで、ライブ・ネットとは異なるネットワークを立ち上げることが可能です(ここでは15を指定)。genesisブロックの初期化で指定したchainidと同一の値を指定する必要があります。
--nodiscover :Gethはデフォルトで自動的に(同じネットワークID)のEthereumネットワークのノード(Peer)を探し接続を試みます。プライベート・ネットでは未知のノードとの接続を避けるため、このオプションで自動Peer探索機能を無効にします。
console:Gethには採掘やトランザクションの生成などを対話的に進めることができるコンソールが用意されています。consoleサブ・コマンドを指定することで、Gethの起動時に同時にコンソール立ち上げることが可能です。なお、consoleサブ・コマンドを付加せずに、Gethのプロセスをバックグラウンドで起動させておき、後からそのプロセスのコンソールを起動する事も可能です(下記TIP参照)。

プライベート・ネットに接続する · Ethereum入門
(ii) result
jskny@VAIO-S-SB-Debian:~/Workspace/test-eth$ pwd
/home/jskny/Workspace/test-eth
jskny@VAIO-S-SB-Debian:~/Workspace/test-eth$ /home/jskny/ダウンロード/geth-linux-amd64-1.8.27-4bcc0a37/geth --networkid "15" --nodiscover --datadir "./" console 2>> ./geth_err.log
Welcome to the Geth JavaScript console!

instance: Geth/v1.8.27-stable-4bcc0a37/linux-amd64/go1.11.9
 modules: admin:1.0 debug:1.0 eth:1.0 ethash:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0

> 

イーサリアムの対話式コンソールが起動しました。

(B) 一番最初のブロック情報を表示する

下記のイーサリアムの対話コンソール上で下記のコマンドを実行すると、一番最初のブロックの情報を表示できます。

(i) command
eth.getBlock(0)
(ii) result
jskny@VAIO-S-SB-Debian:~/Workspace/test-eth$ /home/jskny/ダウンロード/geth-linux-amd64-1.8.27-4bcc0a37/geth --networkid "15" --nodiscover --datadir "./" console 2>> ./geth_err.log
Welcome to the Geth JavaScript console!

instance: Geth/v1.8.27-stable-4bcc0a37/linux-amd64/go1.11.9
 modules: admin:1.0 debug:1.0 eth:1.0 ethash:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0

> eth.getBlock(0)
{
  difficulty: 16384,
  extraData: "0x",
  gasLimit: 134217728,
  gasUsed: 0,
  hash: "0x7b2e8be699df0d329cc74a99271ff7720e2875cd2c4dd0b419ec60d1fe7e0432",
  logsBloom: "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
  miner: "0x3333333333333333333333333333333333333333",
  mixHash: "0x0000000000000000000000000000000000000000000000000000000000000000",
  nonce: "0x0000000000000042",
  number: 0,
  parentHash: "0x0000000000000000000000000000000000000000000000000000000000000000",
  receiptsRoot: "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
  sha3Uncles: "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
  size: 507,
  stateRoot: "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
  timestamp: 0,
  totalDifficulty: 16384,
  transactions: [],
  transactionsRoot: "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
  uncles: []
}
> 

無事に一番最初のブロックの情報が表示されました。

(C) アカウントの種類について

ドキュメントを読むとイーサリアムのアカウントは2種類あると記述があります。

Ethereumには2種類のアカウントが存在します。一つはEOA(Externally Owned Account)、もう一つはContractです。
EOAは私たちユーザーによりコントロールされるアカウントであり、我々ユーザーによる任意のタイミングで、EOAがトランザクションを発生させ、他のアカウントへのetherの送金、コントラクト・コードの実行などを行います。また、etherの採掘もこのEOAアカウントにより行われます。
一方Contractは一種の自動エージェントであり、EOAにより発生したトランザクションをトリガにContractアカウントが内部に持つコントラクト・コードが実行されます。それによりContractのフィールドのデータも更新されます。オブジェクト指向言語に馴染みのある人には、「Contractは一種のクラスのようなもので、EOAによりContractのメソッドが呼ばれ、そのメソッドが実行されるとContractの持つクラス変数が書き換えられる」というアナロジーでの説明が分かりやすいかもしれません。

etherを採掘する · Ethereum入門

今回は、EOAアカウントを作成します。

まず、このノードに現在登録されているEOAアカウントを確認します。

コマンドは下記の通りです。

(i) command
eth.accounts
(ii) result
> eth.accounts
[]
>

このノードにはまだアカウントを登録していないため、空だという応答が表示されました。

(D) アカウントの作成

EOAの作成はpersonal.newAccount("passwd")コマンドで行います。ここでpasswdの部分は作成するEOAのパスワードです。実行時には適宜書き換えて実行してください。実行すると、作成されたEOAの20バイトのアドレスが表示されます。また、personal.listAccountsコマンドの実行結果にも作成したアカウントのアドレスが表示されるようになります。

etherを採掘する · Ethereum入門

上記サイトの記述に従い、アカウントを作成する。

(i) command
personal.newAccount("hogehoge01")
(ii) result
> personal.newAccount("hogehoge01")
"0xa3bb6689056948924a467c71c7a36a0ad728a8ef"
> 
(iii) check
(x) command
eth.accounts
(y) result
> eth.accounts
["0xa3bb6689056948924a467c71c7a36a0ad728a8ef"]
>

(E) 採掘報酬を紐付けるアカウント

採掘を行った際に、その報酬を紐付けるアカウントを確認します。

(i) command
eth.coinbase
(ii) result
> eth.coinbase
"0xa3bb6689056948924a467c71c7a36a0ad728a8ef"
>

先程作成したアカウントのアドレスが表示されました。

(3)採掘の開始

プライベートネットの作成ができたので、採掘を開始します。

その前に、まず採掘関連のコマンドを整理します。

(A) 基本的なコマンド

採掘の開始は、下記のコマンドで行います。

miner.start()

また、採掘の停止をしたい場合は、下記のコマンドを実行します。

miner.stop()

そして、採掘しているかを判断したい場合は、下記のコマンドを実行します。

eth.mining

miningの戻り値がtrueなら採掘中で、そうでなければ停止中です。

(B) 採掘の開始

では、採掘を始めましょう。

(i) command
miner.start()
(ii) result
> miner.start()
null
>

採掘が始まりました。

ノートパソコンの動作がめちゃくちゃ重いです。

(C) 採掘結果の確認

採掘開始からある程度時間を起き、eth.blockNumberを確認します。

(i) command
eth.blockNumber
(ii) result
> eth.blockNumber
204
>

採掘されたブロック数が0から進んでいることが確認できたので、採掘を停止させます。

(i) command
miner.stop()
(ii) result
> miner.stop()
null
>

(D) 報酬の確認

報酬を確認します。

報酬の確認は下記のコマンドで行います。

(i) command
eth.getBalance(eth.accounts[0])
(ii) result
> eth.getBalance(eth.accounts[0])
1.02e+21
>

イーサリアムは、etherとweiで報酬を管理しています。

1 ether = 1,000,000,000,000,000,000 wei

ここでの表示はweiの表示なので、すごい額になっています。

表示する単位を、etherにするには、下記のコマンドを使用します。

(i) command
web3.fromWei(eth.getBalance(eth.accounts[0]),"ether")
(ii) result
> web3.fromWei(eth.getBalance(eth.accounts[0]),"ether")
1020
>

これがパブリックネットワークでだったらすごい。

わぁおかねもちー(26,792円 * 1020 2019/05/19現在)。

4,おわりに

プライベートネットワークの作成と、採掘を行いました。

暗号通貨系は難しいイメージでしたが、先人の方々が、とてもわかりやすいドキュメントを残してくださっているので、進めることができました。

感謝です。

まだ、送金やスマートコントラクトは試していませんが、やっていきたいと思います。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA