5
2

More than 5 years have passed since last update.

JSでBitcoin開発: Bitcoinネットワークの種類と起動スクリプト

Last updated at Posted at 2018-04-24

BitcoinはP2Pプロトコルです。実際にお金をやりとりするmainnettestnetの二種類があります。

bitcoindではtestnetの派生系にregtestというモードがあり、名前の通りregression testに最適です。

  • 明示的に指定しないとtestnetに接続しにいかない
  • regtest用のディレクトリにデータを保存する
  • regtest用のディレクトリを消せば簡単にブロックチェーンデータを初期化できる

JavaScriptでbitcoindをregtestで簡単起動

bitcoindを起動するときにオプション指定をしたり、いちいちregtestディレクトリを削除するのも面倒です。JavaScriptで簡単にregtestを起動できるようにしましょう。

// exec-regtest.js
/*
Copyright 2018, SASAKI Shunsuke  https://rabbit-house.tokyo/books/bitcoin-complete/

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

const fs = require('fs')
const path = require('path')
const os = require('os')
const childPorcess = require('child_process')
const net = require('net')

/**
 * regtestモードでbitcoindを起動する
 * @param {object} opt オプションオブジェクト
 * @param {string} opt.datadir データディレクトリ。未指定ならテンポラリを作成して新規のブロックチェーンを作る
 * @param {number} opt.port P2P用通信ポート番号
 * @param {number} opt.rpcport JSON/RPC用通信ポート番号 
 * @param {string} opt.user JSON/RPC ユーザー名
 * @param {string} opt.pass JSON/RPC パスワード 
 * @returns {Promise<string>} 起動が完了したらデータディレクトリが渡ってくる
 * @example
 * const app = async () => {
 *   const datadir = await execRegtest()
 *   console.log('datadir', datadir)
 * }
 */
const execRegtest = (opt) => {
  return new Promise((resolve, reject) => {
    const datadir = fs.mkdtempSync(path.join(os.tmpdir(), 'regtest-'))

    const params = [
      'bitcoind',
      '-regtest',
      `-datadir=${datadir}`,
      '-txindex',
      '-server',
      '-rest',
      `-port=${opt.port}`,
      `-rpcuser=${opt.user}`,
      `-rpcpassword=${opt.pass}`,
      `-rpcport=${opt.rpcport}`
    ]

    const child = childPorcess.exec(params.join(' '))
    child.stdout.on('data', data => {
      console.log('bitcoind stdout:', data.toString())
    })

    child.stderr.on('data', data => {
      console.log('bitcoind stderr:', data.toString())
    })

    child.on('close', code => {
      console.log(`bitcoind closed: ${code}`)
      process.exit(1)
    })

    const interval = setInterval(() => {
      const socket = net.connect(opt.port, '127.0.0.1')
      socket.on('connect', () => {
        clearInterval(interval)
        resolve(datadir)
      })
      socket.on('error', err => {
        if (err.code !== 'ECONNREFUSED') {
          console.log(err)
        }
      })
    }, 100)
  })
}

module.exports = {
  execRegtest
}

次に、execRegtest関数を叩いて起動するスクリプトを作成します。

#! /usr/bin/env node
# regtest

const {execRegtest} = require('./exec-regtest')

const runRegtest = async () => {
  await execRegtest()
  console.log('bitcoind start.')
}

runRegtest().catch(err => console.error(err))
$ chmod +x regtest
$ ./regtest
bitcoind start.

Bitcoin関連のソフトウェアに組み込みたい場合は const {execRegtest} = require('./exec-regtest')で読み込んでいい感じにPromiseなりasync/awaitなりで叩いてみてください。

JavaScriptで覚える暗号通貨入門シリーズ

本記事は、JavaScriptで覚える暗号通貨入門#1 Bitcoin完全に理解したの技術調査によるものです。また、JavaScriptで覚える暗号通貨入門#1 Bitcoin完全に理解した (サンプルコード)のリポジトリを公開しています。

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2