forEach内でpromiseによる逐次処理

すべてブロッキングしながら逐次処理を行う。(コマンドスクリプト用)

参考:http://www.html5rocks.com/en/tutorials/es6/promises/#toc-parallelism-sequencing

var vals = ['hello', 'nice', 'bye']
var sequence = Promise.resolve()

vals.forEach(function (currVal) {
  sequence = sequence
  .then(function () {
    return currVal
  })
  .then(init)
  .then(m1)
  .then(m2)
})

function init (val) {
  return new Promise((resolve, reject) => {
    console.log('init:', val)
    resolve(val)
  })
}


function m1 (val) {
  return new Promise((resolve, reject) => {
    setTimeout(function () {
      console.log('m1:', val)
      resolve(val)
    }, 300)
  })
}

function m2 (val) {
  return new Promise((resolve, reject) => {
    setTimeout(function () {
      console.log('m2:', val)
      resolve(val)
    }, 100)
  })
}

結果

init: hello
m1: hello
m2: hello
init: nice
m1: nice
m2: nice
init: bye
m1: bye
m2: bye

Ethereum マイニングと送金

マイニング(採掘)する

gethを起動しアカウントの作成と確認。

geth --networkid "10" --datadir "D:\Ethereum\etherdata10" --olympic console 2>D:\Ethereum\log\eth.log

accountを作成(既に2つ作成済みの状態)

> eth.accounts[0]
"0xe76dac08981340ff9343ca791bc4b8267603889f"
# meの変数に格納しておく
> me = eth.accounts[0]
"0xe76dac08981340ff9343ca791bc4b8267603889f"

# 3つ目のアカウントを作成
> personal.newAccount("password")
"0x29d2fc7cdcb294d0cb78a722b8fb5d30aa641393"

マイニングしてetherを稼いでおく

> miner.start(4)
# しばらく待って
> miner.stop()
# 手持ちのetherを確認する
> web3.fromWei(eth.getBalance(eth.accounts[0]), "ether")
> 251.87

送金する

参考:https://ethereum.gitbooks.io/frontier-guide/content/ether_transfer.htmlhttp://book.ethereum-jp.net/content/first_use/sending_ether.html

アカウントを確認する

# 参考までにmeはcoinBaseと同値
> me
"0xe76dac08981340ff9343ca791bc4b8267603889f"
> eth.coinbase
"0xe76dac08981340ff9343ca791bc4b8267603889f"

> eth.accounts
["0xe76dac08981340ff9343ca791bc4b8267603889f", "0x0c987d5001bebaabe0602cbea2304c4ab7b67874", "0x29d2fc7cdcb294d0cb78a722b8fb5d30aa641393"]

3つ目のアカウントに送金する

# 3つ目のアカウントの残高
> web3.fromWei(eth.getBalance(eth.accounts[2]), "ether")
0

# 送金先の変数を設定
> receiver = eth.accounts[2];
"0x29d2fc7cdcb294d0cb78a722b8fb5d30aa641393"

# 金額の変数を設定/金額は0.3ether
> amount = web3.toWei(0.30, "ether")
"300000000000000000"

# 送金
> eth.sendTransaction({from:me, to:receiver, value: amount})
Please unlock account e76dac08981340ff9343ca791bc4b8267603889f.
Passphrase:
Account is now unlocked for this session.
"0x822981399c79fc0eb8900efe5c976546f722e89b00294df1781e0c223a6736de"

# 3つ目のアカウント残高を見る。まだblockに書き込まれていない状況
> web3.fromWei(eth.getBalance(eth.accounts[2]), "ether")
0

# マイニングする
> miner.start(3)
true
> miner.stop()
true

# 3つ目のアカウント残高を見る/0.3ether送金された
> web3.fromWei(eth.getBalance(eth.accounts[2]), "ether")
0.3

# トランザクションを確認する
> eth.getTransaction("0x822981399c79fc0eb8900efe5c976546f722e89b00294df1781e0c223a6736de")
{
  blockHash: "0x5aceeeb030bde71fa0e4dac0f72545d123fcf54b2ed8bee6f26a9e9ec000020b",
  blockNumber: 169,
  from: "0xe76dac08981340ff9343ca791bc4b8267603889f",
  gas: 90000,
  gasPrice: 50000000000,
  hash: "0x822981399c79fc0eb8900efe5c976546f722e89b00294df1781e0c223a6736de",
  input: "0x",
  nonce: 3,
  to: "0x29d2fc7cdcb294d0cb78a722b8fb5d30aa641393",
  transactionIndex: 0,
  value: 300000000000000000
}

Ethereum コマンド抜粋

基本的なコマンド

geth コマンドライン 補足
geth account new personal.newAccount("password") account作成
geth account list eth.accounts
geth account update [id / address]
geth account import
personal.unlockAccount(eth.coinbase) アンロック In order to spend your earnings
miner.start(n) n...thread数を指定
miner.hashrate minerの動作状況確認
miner.stop()
eth.blockNumber blockNumber表示
eth.getBalance(eth.coinbase).toNumber()
web3.fromWei(eth.getBalance(eth.coinbase), "ether") Checking account balances
eth.sendTransaction({from:sender, to:receiver, value: amount})
eth.getTransaction("xxx") トランザクションを確認
eth.getBlock(nn)
eth.getTransactionReceipt(nn)
eth.getTransactionFromBlock(nn)
eth.getCompilers()
admin.setSolc("solc.exe") windowsでは無理?

Ethereum gethの起動

geth起動

起動サンプル。ethについては記載していない。

ubuntu

geth --networkid "10" --datadir "/home/ether/eth10" --logfile "/home/ether/eth10/geth_01.log" --olympic console 2>> /home/ether/eth10/geth_e01.log

windows

geth --networkid "10" --datadir "D:\Ethereum\etherdata10" --olympic console 2>D:\Ethereum\log\eth.log

rpcで起動

geth --rpc --rpccorsdomain "*" --networkid "10" --datadir "D:\Ethereum\etherdata10" --olympic console 2>D:\Ethereum\log\eth.log

gethのhelp

NAME:
   geth - the go-ethereum command line interface

USAGE:
   geth [options] command [command options] [arguments...]
   
VERSION:
   1.3.3
   
COMMANDS:
   recover  Attempts to recover a corrupted database by setting a new block by number or hash
   blocktest    loads a block test file
   import   import a blockchain file
   export   export blockchain into file
   upgradedb    upgrade chainblock database
   removedb Remove blockchain and state databases
   dump     dump a specific block from storage
   monitor  Geth Monitor: node metrics monitoring and visualization
   makedag  generate ethash dag (for testing)
   gpuinfo  gpuinfo
   gpubench benchmark GPU
   version  print ethereum version numbers
   wallet   ethereum presale wallet
   account  manage accounts
   console  Geth Console: interactive JavaScript environment
   attach   Geth Console: interactive JavaScript environment (connect to node)
   js       executes the given JavaScript files in the Geth JavaScript VM
   help, h  Shows a list of commands or help for one command
   
ETHEREUM OPTIONS:
  --datadir "C:\Users\owner\AppData\Roaming\Ethereum"   Data directory for the databases and keystore
  --networkid "1"   Network identifier (integer, 0=Olympic, 1=Frontier, 2=Morden)
  --olympic         Olympic network: pre-configured pre-release test network
  --testnet         Morden network: pre-configured test network with modified starting nonces (replay protection)
  --dev         Developer mode: pre-configured private network with several debugging flags
  --genesis         Insert/overwrite the genesis block (JSON format)
  --identity        Custom node name
  --fast            Enable fast syncing through state downloads
  --lightkdf            Reduce key-derivation RAM & CPU usage at some expense of KDF strength
  --cache "0"       Megabytes of memory allocated to internal caching (min 16MB / database forced)
  --blockchainversion "3"       Blockchain version (integer)
  
ACCOUNT OPTIONS:
  --unlock  Unlock an account (may be creation index) until this program exits (prompts for password)
  --password    Password file to use with options/subcommands needing a pass phrase
  
API AND CONSOLE OPTIONS:
  --rpc             Enable the HTTP-RPC server
  --rpcaddr "127.0.0.1" HTTP-RPC server listening interface
  --rpcport "8545"      HTTP-RPC server listening port
  --rpcapi "db,eth,net,web3"    API's offered over the HTTP-RPC interface
  --ipcdisable          Disable the IPC-RPC server
  --ipcapi "admin,db,eth,debug,miner,net,shh,txpool,personal,web3"  API's offered over the IPC-RPC interface
  --ipcpath "\\.\pipe\geth.ipc" Filename for IPC socket/pipe
  --rpccorsdomain       Domains from which to accept cross origin requests (browser enforced)
  --jspath "."          JavaSript root path for `loadScript` and document root for `admin.httpGet`
  --exec                Execute JavaScript statement (only in combination with console/attach)
  
NETWORKING OPTIONS:
  --bootnodes       Space-separated enode URLs for P2P discovery bootstrap
  --port "30303"    Network listening port
  --maxpeers "25"   Maximum number of network peers (network disabled if set to 0)
  --maxpendpeers "0"    Maximum number of pending connection attempts (defaults used if set to 0)
  --nat "any"       NAT port mapping mechanism (any|none|upnp|pmp|extip:<IP>)
  --nodiscover      Disables the peer discovery mechanism (manual peer addition)
  --nodekey         P2P node key file
  --nodekeyhex      P2P node key as hex (for testing)
  
MINER OPTIONS:
  --mine            Enable mining
  --minerthreads "8"        Number of CPU threads to use for mining
  --minergpus           List of GPUs to use for mining (e.g. '0,1' will use the first two GPUs found)
  --autodag         Enable automatic DAG pregeneration
  --etherbase "0"       Public address for block mining rewards (default = first account created)
  --gasprice "50000000000"  Minimal gas price to accept for mining a transactions
  --extradata           Block extra data set by the miner (default = client version)
  
GAS PRICE ORACLE OPTIONS:
  --gpomin "50000000000"    Minimum suggested gas price
  --gpomax "500000000000"   Maximum suggested gas price
  --gpofull "80"        Full block threshold for gas price calculation (%)
  --gpobasedown "10"        Suggested gas price base step down ratio (1/1000)
  --gpobaseup "100"     Suggested gas price base step up ratio (1/1000)
  --gpobasecf "110"     Suggested gas price base correction factor (%)
  
VIRTUAL MACHINE OPTIONS:
  --vmdebug     Virtual Machine debug output
  --jitvm       Enable the JIT VM
  --forcejit        Force the JIT VM to take precedence
  --jitcache "64"   Amount of cached JIT VM programs
  
LOGGING AND DEBUGGING OPTIONS:
  --verbosity "3"   Logging verbosity: 0-6 (0=silent, 1=error, 2=warn, 3=info, 4=core, 5=debug, 6=debug detail)
  --vmodule ""      Per-module verbosity: comma-separated list of <module>=<level>, where <module> is file literal or a glog pattern
  --backtrace ":0"  Request a stack trace at a specific logging statement (e.g. "block.go:271")
  --logfile         Log output file within the data dir (default = no log file generated)
  --pprof       Enable the profiling server on localhost
  --pprofport "6060"    Profile server listening port
  --metrics     Enable metrics collection and reporting
  
EXPERIMENTAL OPTIONS:
  --shh     Enable Whisper
  --natspec Enable NatSpec confirmation notice
  
MISCELLANEOUS OPTIONS:
  --solc "solc" Solidity compiler command to be used
  --help, -h    show help

Ethereum command line toolインストール

参考にした情報

Ethereumのホームページ

ubuntu14.04へインストール

プロキシ環境の場合は以下を行う。(PPA登録時にproxy設定が引き継がれず、後述のインストールでエラーとなるため)

sudo apt-get install software-properties-common
sudo -E add-apt-repository -y ppa:ethereum/ethereum
sudo apt-get update

Toolのインストール

# ethインストール
bash <(curl https://install-eth.ethereum.org -L)
# gethインストール
bash <(curl https://install-geth.ethereum.org -L)
# solidityコンパイラーのインストール
sudo add-apt-repository ppa:ethereum/ethereum
sudo apt-get update
sudo apt-get install solc
which solc

Winfowsの場合

webthree-umbrellaより最新がダウンロードできる模様。