# 拡張手動セットアップ

このドキュメントでは、BTCPay Server を手動でデプロイする手順と、関連する追加コンポーネントを説明します。これらの手順には長時間かかる可能性があります。より短く実践的な方法として、Docker ベースのデプロイ (opens new window)を利用できます。

この手順では、アプリケーションの全コンポーネントをソースからビルドします。これは、特定の監査やセキュリティ要件の場面で利点になることがあります。

DANGER

# 本番利用には非推奨

手動インストールは、OS 運用と Bitcoin セキュリティに関する十分な知識と経験がない限り、本番利用には推奨されません。不安がある場合は、Docker デプロイ、または他のデプロイオプションを利用してください。

# 技術的な素養があり、問題を自力で解決できることが必要です。このデプロイ方法に対してコミュニティから手厚いサポートは提供されません。

# インストール手順の概要

このページの手順は Ubuntu 20.04 で検証されています。他の Linux ディストリビューションにも適用できるはずです。また、すべてのコンポーネントを同一ホストまたは仮想マシン上に配置する前提になっています。コンポーネントを複数ホストに分離することも可能ですが、この手順では扱いません。

ここではホスト名の例として mainnet.demo.btcpayserver.org を使用しています。実際には、あなたの BTCPay Server で使用するホスト名に置き換えてください。

# セキュリティ

この手順で Bitcoin メインネットに接続する BTCPay Server を構築する場合、最低限ウォレットの仕組みを理解しておく必要があります。以下の 2 つの記事を読み、不明点があれば質問することを強く推奨します。

補足として、開放が必要なすべてのポートを含む想定の iptables ルールと手順を以下に示します。無保証です。自身を締め出してしまうリスクを含め、自己責任で利用してください。

~$ vi iptables.txt
# Generated by iptables-save v1.6.1 on Mon May 27 18:48:11 2019
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT     # SSH
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT     # BTCPay HTTP
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT    # BTCPay HTTPS
-A INPUT -p tcp -m tcp --dport 8333 -j ACCEPT   # Bitcoind P2P
-A INPUT -p tcp -m tcp --dport 9735 -j ACCEPT   # Lightning P2P
-A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
COMMIT
# Completed on Mon May 27 18:48:11 2019
~$ sudo iptables-restore < iptables.txt

この時点で SSH セッションが維持されていれば良い兆候です。もし切断されても、ルールは一時的なため、利用可能な手段でサーバーをリモート再起動して再試行できます。

ルールはここまでで一時適用されています。サーバー起動時に毎回自動適用するには iptables-persistent パッケージを使用します。

~$ sudo apt install iptables-persistent

後で iptables ルールを変更し、再起動後も保持したい場合は次のコマンドを使います。

~$ sudo netfilter-persistent save

# 非特権ユーザー

この手順では、すべてを admin という非特権ユーザーで実行するように構成します。先にこのユーザーを作成してください。

~$ sudo useradd -M admin && sudo usermod -L admin

# 前提条件

  • Postgresql
  • Tor
  • NGINX と Let's Encrypt

# アプリケーションコンポーネント

  • Bitcoin Core1,2
  • NBXplorer1,2
  • BTCPay Server1,2
  • Lightning Network Daemon (LND)(Lightning デーモン)2
  • Ride The Lightning (RTL)(Lightning 管理UI)2

1 BTCPay Server の最小構成インストールでは、これらだけが必要です。最小構成では機能が制限されます: Lightning 支払い不可、TLS 証明書の自動更新なし、データストアの信頼性低下、NAT 対応力の低下など。

2 ソースコードからビルド。

# Postgresql

BTCPay Server では、既定の SQLite ファイルベースストレージの代わりに Postgresql を使用できます。MySQL を使用することも可能です。

# インストール
~$ sudo apt install postgresql postgresql-contrib
# 設定

BTCPay Server の設定セクションで扱います。

# 確認
~$ psql --version
psql (PostgreSQL) 12.2 (Ubuntu 12.2-4)
~$ sudo systemctl status postgresql
~$ sudo -u postgres psql
psql (12.2 (Ubuntu 12.2-4))
Type "help" for help.

postgres=# \q

# Tor

Tor は、プライバシー強化や NAT 越えの補助のために、以下のコンポーネントで利用できます。

  • Bitcoin Core デーモン
  • Lightning Network Daemon (LND)(Lightning デーモン)

Bitcoin Core を Tor サポート付きで実行するための追加情報はこちら (opens new window)です。

# インストール
~$ sudo apt install tor
# 設定
~$ sudo vi /etc/tor/torrc  # (and uncomment two lines below)
ControlPort 9051
CookieAuthentication 1
~$ sudo systemctl restart tor

詳細は Bitcoin セクションおよび Lightning Network Daemon セクションで説明します。

# 確認
~$ tor --version
Tor version 0.4.2.7
~$ sudo netstat -tlnp | grep tor # (lines below correspond to the tor control port and SOCKS proxy)
tcp        0      0 127.0.0.1:9050          0.0.0.0:*               LISTEN      1376/tor
tcp        0      0 127.0.0.1:9051          0.0.0.0:*               LISTEN      1376/tor

# NGINX と Let's Encrypt

NGINX は、BTCPay Server と Ride The Lightning への HTTP リクエストを処理する Web サーバーとして使用します。Let's Encrypt と組み合わせることで、BTCPay Server インスタンス向け TLS 証明書の取得と更新をシームレスに行えます。

Let's Encrypt は TLS 証明書の取得と更新を行う無料サービスです。処理全体を自動管理するためのスクリプトも提供されています。

# インストール
# 1. NGINX をインストール
~$ sudo apt install nginx
# 2. Let's Encrypt をインストール
~$ sudo apt install certbot python3-certbot-nginx
# 設定
# 1. Let's Encrypt TLS 証明書

<your domain name> について、サーバーインスタンスの IP アドレスを指す A または AAAA レコードを作成する必要があります。 サーバーが NAT 配下にある場合は、ポート 80 をインスタンスへフォワードする必要があります。

certbot スクリプトは、要求したドメインをホストしている Web サーバー上に特定のファイルが存在するかを確認して動作します。ファイルを取得できない場合、TLS 証明書は発行されません。初回の試行に失敗した場合は定期的に再試行されるか、手動でコマンドを再実行できます。

sudo certbot --nginx -d <your domain name> # (e.g: sudo certbot --nginx -d mainnet.demo.btcpayserver.org)
# 2. NGINX 設定ファイルを追加

以下の設定ファイルは、BTCPay Server の Docker インストールからコピーしたものです。

mainnet.demo.btcpayserver.org を検索し、あなた自身のドメイン名に置き換えてください。

~$ vi /etc/nginx/conf.d/default.conf
# If we receive X-Forwarded-Proto, pass it through; otherwise, pass along the
# scheme used to connect to this server
map $http_x_forwarded_proto $proxy_x_forwarded_proto {
  default $http_x_forwarded_proto;
  ''      $scheme;
}
# If we receive X-Forwarded-Port, pass it through; otherwise, pass along the
# server port the client connected to
map $http_x_forwarded_port $proxy_x_forwarded_port {
  default $http_x_forwarded_port;
  ''      $server_port;
}
# If we receive Upgrade, set Connection to "upgrade"; otherwise, delete any
# Connection header that may have been passed to this server
map $http_upgrade $proxy_connection {
  default upgrade;
  '' close;
}
# Apply fix for very long server names
server_names_hash_bucket_size 128;
# Prevent Nginx Information Disclosure
server_tokens off;
# Default dhparam
# Set appropriate X-Forwarded-Ssl header
map $scheme $proxy_x_forwarded_ssl {
  default off;
  https on;
}

gzip_types text/plain text/css application/javascript application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
log_format vhost '$host $remote_addr - $remote_user [$time_local] '
                 '"$request" $status $body_bytes_sent '
                 '"$http_referer" "$http_user_agent"';
access_log off;
# HTTP 1.1 support
proxy_http_version 1.1;
proxy_buffering off;
proxy_set_header Host $http_host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $proxy_connection;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $proxy_x_forwarded_proto;
proxy_set_header X-Forwarded-Ssl $proxy_x_forwarded_ssl;
proxy_set_header X-Forwarded-Port $proxy_x_forwarded_port;
proxy_buffer_size          128k;
proxy_buffers              4 256k;
proxy_busy_buffers_size    256k;
client_header_buffer_size 500k;
large_client_header_buffers 4 500k;
# Mitigate httpoxy attack (see README for details)
proxy_set_header Proxy "";

server {
        server_name mainnet.demo.btcpayserver.org;
        listen 80;
        access_log /var/log/nginx/access.log vhost;
        return 301 https://$host$request_uri;
}
server {
        client_max_body_size 100M;
        server_name mainnet.demo.btcpayserver.org;
        listen 443 ssl http2 ;
        access_log /var/log/nginx/access.log vhost;
        ssl_protocols TLSv1.2;
        ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256';
        ssl_prefer_server_ciphers on;
        ssl_session_timeout 5m;
        ssl_session_cache shared:SSL:50m;
        ssl_session_tickets off;
        ssl_certificate /etc/letsencrypt/live/mainnet.demo.btcpayserver.org/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/mainnet.demo.btcpayserver.org/privkey.pem;
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
        ssl_stapling on;
        ssl_stapling_verify on;
                ssl_trusted_certificate /etc/letsencrypt/live/mainnet.demo.btcpayserver.org/fullchain.pem;
        add_header Strict-Transport-Security "max-age=31536000" always;
        #include /etc/nginx/vhost.d/default;

        # Here is the main BTCPay Server application
        location / {
                proxy_pass http://127.0.0.1:23000;
        }

        # Include the next two stanzas if and only if you want to expose your lightning gRPC & RPC interfaces to the internet
        location /lnrpc.Lightning {
                grpc_pass grpcs://127.0.0.1:10009;
        }

        location /lnd-rest/btc/ {
                rewrite ^/lnd-rest/btc/(.*) /$1 break;
                proxy_pass https://127.0.0.1:8080/;
        }

        # Include this stanza if you are planning to set up Ride The Lightning (RTL)
        location /rtl/ {
                proxy_pass http://127.0.0.1:3000/rtl/;
        }
}
~$ sudo systemctl restart nginx
~$ sudo systemctl status nginx

nginx の再起動でエラーが出る場合は、次を試してください。

sudo journalctl -xe --unit nginx
# 確認
# 1. Let's Encrypt を確認

Let's Encrypt のスクリプトが正しく動作するように設定を整えるのは少し難しい場合があります。トラブルシューティングに役立つ追加コマンドを以下に示します。

~$ sudo certbot certificates
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Found the following certs:
  Certificate Name: mainnet.demo.btcpayserver.org
    Domains: mainnet.demo.btcpayserver.org
    Expiry Date: 2019-08-10 18:00:31+00:00 (VALID: 79 days)
    Certificate Path: /etc/letsencrypt/live/mainnet.demo.btcpayserver.org/fullchain.pem
    Private Key Path: /etc/letsencrypt/live/mainnet.demo.btcpayserver.org/privkey.pem
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
~$ cat /etc/cron.d/certbot # (check the cron job exists)
0 */12 * * * root test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(43200))' && certbot -q renew
~$ sudo tail /var/log/letsencrypt/letsencrypt.log # (check for problems)
2019-05-22 19:36:36,062:DEBUG:certbot.main:certbot version: 0.31.0
~$ sudo certbot renew --dry-run # (test renewal)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
** DRY RUN: simulating 'certbot renew' close to cert expiry
**          (The test certificates below have not been saved.)

Congratulations, all renewals succeeded. The following certs have been renewed:
  /etc/letsencrypt/live/mainnet.demo.btcpayserver.org/fullchain.pem (success)
** DRY RUN: simulating 'certbot renew' close to cert expiry
**          (The test certificates above have not been saved.)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# 2. NGINX を確認
~$ sudo nginx -v
nginx version: nginx/1.18.0 (Ubuntu)
~$ sudo netstat -tlnp | grep nginx
tcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      266275/nginx: maste
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      266275/nginx: maste
tcp6       0      0 :::443                  :::*                    LISTEN      266275/nginx: maste
tcp6       0      0 :::80                   :::*                    LISTEN      266275/nginx: maste
~$ sudo journalctl -xe --unit nginx --follow
--
-- A start job for unit nginx.service has finished successfully.
--
-- The job identifier is 19471.

ブラウザで Web サイトを開いてみてください。この時点では 502 Bad Gateway エラーが発生する想定です。接続試行を受信したかどうかは nginx ログで確認できます。

~$ tail /var/log/nginx/access.log
mainnet.demo.btcpayserver.org 127.0.0.1 - - [27/Jul/2020:12:19:57 +0100] "GET / HTTP/2.0" 502 552 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"

問題がある場合は、nginx のエラーログも確認してください。

~$ tail /var/log/nginx/error.log

# Bitcoin Core

BTCPay Server の各コンポーネントが Bitcoin ネットワークに接続するためのゲートウェイです。

# インストール

Bitcoin Core をソースからビルドする完全な手順はこちら (opens new window)です。

ソースからビルドしない場合は、署名済みバイナリ配布物を https://bitcoincore.org/en/download/ (opens new window) からダウンロードできます。

~$ wget https://bitcoincore.org/bin/bitcoin-core-0.20.0/bitcoin-0.20.0-x86_64-linux-gnu.tar.gz
~$ wget https://bitcoincore.org/bin/bitcoin-core-0.20.0/SHA256SUMS.asc
# 1. 前提パッケージと依存関係をインストール

この手順では、BTCPay Server に不要なため Bitcoin Core の GUI コンポーネントはビルドしません。

~$ sudo apt install build-essential libtool autotools-dev automake pkg-config bsdmainutils python3
~$ sudo apt install libevent-dev libboost-system-dev libboost-filesystem-dev libboost-test-dev libboost-thread-dev libminiupnpc-dev libzmq3-dev
# 2. ソースを取得してビルド

Bitcoin Core リポジトリをクローンする前に、最新の安定版を確認してください。簡単な方法は、GitHub リポジトリの「Releases」欄で最新版を確認することです。執筆時点の安定版は 0.20.0 です。下記 git clone コマンドのタグを、ビルドしたい安定版に合わせて調整してください。

~$ cd src
~/src$ git clone --depth 1 --branch v0.20.0 https://github.com/bitcoin/bitcoin.git
~/src$ cd bitcoin

Berkeley DB 依存関係の特定バージョンをインストールする必要があります。

~/src/bitcoin$ ./contrib/install_db4.sh `pwd`

autoconf スクリプトで make ファイルを生成し、その後ビルドします。

~/src/bitcoin$ ./autogen.sh
~/src/bitcoin$ export BDB_PREFIX='/home/admin/src/bitcoin/db4'
~/src/bitcoin$ ./configure BDB_LIBS="-L${BDB_PREFIX}/lib -ldb_cxx-4.8" BDB_CFLAGS="-I${BDB_PREFIX}/include"
~/src/bitcoin$ make
~/src/bitcoin$ sudo make install
~/src/bitcoin$ bitcoind -version
Bitcoin Core version v0.20.0
# 3. 設定ファイルを作成

設定ファイルの例は、Bitcoin Core リポジトリの https://github.com/bitcoin/bitcoin/blob/master/share/examples/bitcoin.conf で参照できます。

用途に合わせて bitcoin.conf ファイルを作成してください。BTCPay Server に適した例を以下に示します。この設定ではブロックのプルーニングを行わないため、2019 年 5 月時点で Bitcoin ブロックチェーン用に 235 GB が必要です。

~$ vi bitcoin.conf
server=1                              # need RPC for btcpay.
rpcbind=127.0.0.1                     # loopback is default for 0.18.0 but no harm making sure.
whitelist=127.0.0.1                   # for nbxplorer.
rpcallowip=127.0.0.1/32               # loopback is default but again no harm.
zmqpubrawblock=tcp://127.0.0.1:28332  # needed for lightning.
zmqpubrawtx=tcp://127.0.0.1:28333     # needed for lightning.
#prune=5000                           # Recommended if not enough disk space for full 600+GB blockchain.

ファイルを systemd サービスファイルで指定したディレクトリにコピーし、すべてのユーザーに読み取り権限を付与します。

~$ sudo mkdir -p /etc/bitcoin
~$ sudo cp bitcoin.conf /etc/bitcoin
~$ sudo chmod 644 /etc/bitcoin/bitcoin.conf
# 5. systemd サービスを作成

systemd サービスファイルの例は、Bitcoin Core リポジトリの https://raw.githubusercontent.com/bitcoin/bitcoin/master/contrib/init/bitcoind.service にあります。

必要に応じてサービスファイルを編集してください。

以下の例では、新しい bitcoin ユーザーを作成せずに済むよう、UserGroupadmin ユーザーに変更しています。システム上の admin ユーザーを BTCPayServer 実行用として使う想定であれば妥当な選択です。そうでない場合は、専用の bitcoin ユーザー作成を検討してください。

~$ vi bitcoind.service
[Unit]
Description=Bitcoin daemon
After=network.target

[Service]
ExecStart=/usr/bin/bitcoind -daemon \
                            -pid=/run/bitcoind/bitcoind.pid \
                            -conf=/etc/bitcoin/bitcoin.conf \
                            -datadir=/var/lib/bitcoind

# Make sure the config directory is readable by the service user
PermissionsStartOnly=true
ExecStartPre=/bin/chgrp admin /etc/bitcoin

# Process management
####################

Type=forking
PIDFile=/run/bitcoind/bitcoind.pid
Restart=on-failure
TimeoutStopSec=600

# Run as admin:admin
User=admin
Group=admin

# /run/bitcoind
RuntimeDirectory=bitcoind
RuntimeDirectoryMode=0710

# /etc/bitcoin
ConfigurationDirectory=bitcoin
ConfigurationDirectoryMode=0710

# /var/lib/bitcoind
StateDirectory=bitcoind
StateDirectoryMode=0710

# Hardening measures
####################
# Provide a private /tmp and /var/tmp.
PrivateTmp=true

# Deny access to /home, /root and /run/user
ProtectHome=true

# Mount /usr, /boot/ and /etc read-only for the process.
ProtectSystem=full

# Disallow the process and all of its children to gain
# new privileges through execve().
NoNewPrivileges=true

# Use a new /dev namespace only populated with API pseudo devices
# such as /dev/null, /dev/zero and /dev/random.
PrivateDevices=true

# Deny the creation of writable and executable memory mappings.
MemoryDenyWriteExecute=true

[Install]
WantedBy=multi-user.target

サービスファイルの準備ができたら、以下のコマンドを実行します。

~$ sudo cp bitcoind.service /etc/systemd/system
~$ sudo systemctl enable --now bitcoind
~$ sudo systemctl status bitcoind
...
Jul 26 21:51:52 ubuntu systemd[1]: Started Bitcoin daemon.

起動時にエラーメッセージが表示された場合は、次でログを確認します。

sudo journalctl -xe --unit bitcoind

bitcoin-cli クライアントが RPC 呼び出しを行うには bitcoind への認証が必要です。最も簡単な方法は、cookie ファイルへのシンボリックリンクを作成することです。

~$ cd ~
~$ ln -s /var/lib/bitcoind/.cookie .bitcoin/.cookie

この手順は必須ではありませんが、実施しない場合は以下のように bitcoin-cli コマンドごとに cookie ファイルのパス指定が必要になります。

~$ bitcoin-cli -rpccookiefile=/var/lib/bitcoind/.cookie getblockchaininfo
# 確認

Bitcoin のブロックチェーン同期には、数時間から数日かかる場合があります。状態確認には以下のコマンドを必要に応じて使用してください。

~$ sudo systemctl status bitcoind
Active: active (running) since Sun 2020-07-26 21:51:52 IST; 2min 47s ago
~$ tail /var/lib/bitcoind/debug.log -f
...
2020-07-26T20:55:09Z UpdateTip: new best=0000000000000361c37dfb6fa905ef967b95411fa96f7dcb4eca5dd4434d9e59 height=126732 version=0x00000001 log2_work=62.952182 tx=560114 date='2011-05-25T21:26:08Z' progress=0.001018 cache=43.6MiB(291168txo)
...
~$ bitcoin-cli getblockchaininfo
{
  "chain": "main",
  "blocks": 133015,
  "headers": 640929,
  "bestblockhash": "0000000000000e81b67de8d61eab726f40585bed954b1dd59f86ab10e4e55398",
  "difficulty": 876954.4935135372,
  "mediantime": 1308897947,
  "verificationprogress": 0.001530462018729556,
  ...
}

verificationprogress0.99.. または 1.0 になれば、ノードの同期は完了しています。念のため、https://blockstream.info/ (opens new window) のような公開ブロックエクスプローラーで最新の Bitcoin ブロックを確認し、bitcoin-cli getblockchaininfoblocks 値と比較することもできます。

# Tor と Bitcoin の確認

Bitcoin デーモンより先に Tor をインストールしていれば、自動的に登録されて torv2 onion アドレスで待ち受けを開始しているはずです(torv3 onion アドレス対応は進行中 (opens new window)です)。

Bitcoin デーモンの torv2 アドレスを確認する最も簡単な方法は bitcoin-cli を使うことです。

bitcoin-cli getnetworkinfo
{
  "version": 200100,
  "subversion": "/Satoshi:0.20.1/",
  "protocolversion": 70015,
  "localservices": "0000000000000409",
  ...
    "localaddresses": [
    {
      "address": "192.168.11.4",
      "port": 8333,
      "score": 1
    },
    {
      "address": "v5j6hfz4xafmeckf.onion",
      "port": 8333,
      "score": 156
    }
  ],
  "warnings": ""
}

別の方法として、Bitcoin デーモンのログファイルを検索することもできます。

~$ cat /var/lib/bitcoind/debug.log | grep onion
2019-05-23T18:24:22Z tor: Got service ID 4d4al7v4hj5p7bb6, advertising service 4d4al7v4hj5p7bb6.onion:8333
2019-05-23T18:24:22Z AddLocal(4d4al7v4hj5p7bb6.onion:8333,4)

問題があり、ログファイル内に onion アドレスが見つからない場合は、Tor 関連のエラーメッセージを確認してください。

~$ cat /var/lib/bitcoind/debug.log | grep tor
2020-07-27T08:03:28Z torcontrol thread start
2020-07-27T08:03:28Z tor: Authentication cookie /run/tor/control.authcookie could not be opened (check permissions)

上記のエラーメッセージは、Bitcoin サービス実行ユーザーが Tor の認証 cookie ファイルを読み取れない場合に発生することがあります(詳細はこちら (opens new window))。このエラーを解消するには、対象ユーザーを debian-tor グループに追加してください。

sudo usermod -a -G debian-tor admin

onion アドレスを変更するには:

~$ rm /var/lib/bitcoind/onion_private_key
~$ sudo systemctl restart bitcoind
~$ bitcoin-cli getnetworkinfo | grep onion
      "name": "onion",
      "address": "qud5iwbntqxlfwjv.onion",

Tor をインストールしたリモートホストから onion アドレスを確認するには:

~$ torsocks --shell
~$ telnet 4d4al7v4hj5p7bb6.onion 8333
 Trying 127.42.42.0...
 Connected to 127.42.42.0.
 Escape character is '^]'.
~$ exit

別の bitcoind インスタンスを新しいノードへ接続するには:

~$ bitcoin-cli addnode "4d4al7v4hj5p7bb6.onion" "add"
~$ bitcoin-cli getaddednodeinfo
{
   "addednode": "4d4al7v4hj5p7bb6.onion",
   "connected": true,
   "addresses": [
     {
       "address": "4d4al7v4hj5p7bb6.onion:8333",
       "connected": "outbound"
     }
   ]
 }

# NBXplorer

NBXplorer は、BTCPay Server に関連するトランザクションを Bitcoin ブロックチェーン上で監視する .NET Core アプリケーションです。

# インストール
# 1. .NET 8.0 SDK をインストール

インストール手順に従ってください (opens new window)

# Add Microsoft package repository
wget https://packages.microsoft.com/config/ubuntu/20.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb
sudo dpkg -i packages-microsoft-prod.deb
rm packages-microsoft-prod.deb

# Install the SDK
sudo apt-get update
sudo apt-get install -y apt-transport-https
sudo apt-get update
sudo apt-get install -y dotnet-sdk-8.0

## Check
dotnet --version
# 2. NBXplorer をビルド
~$ cd ~; mkdir -p src; cd src
~/src$ git clone https://github.com/dgarage/NBXplorer
~/src$ cd NBXplorer
~/src/NBXplorer$ git checkout $(git tag --sort -version:refname | awk 'match($0, /^v[0-9]+\./)' | head -n 1)
~/src/NBXplorer$ ./build.sh
# 3. Postgresql データベースを作成

NBXplorer は --dbtrie によるローカルデータベース保存にも対応していますが、これは非推奨です。ここでは Postgresql で NBXplorer 用のデータベースとユーザーを作成する方法を示します。

~$ sudo -u postgres psql

次を実行します。

CREATE DATABASE nbxplorer TEMPLATE 'template0' LC_CTYPE 'C' LC_COLLATE 'C' ENCODING 'UTF8';
CREATE USER nbxplorer WITH ENCRYPTED PASSWORD 'urpassword';
GRANT ALL PRIVILEGES ON DATABASE nbxplorer TO nbxplorer;

終了します。

postgres=#\q
# 4. 設定ファイルを作成
$ vi nbxplorer.config
### Database ###
postgres=User ID=nbxplorer;Password=urpassword;Application Name=nbxplorer;MaxPoolSize=20;Host=localhost;Port=5432;Database=nbxplorer;
~$ sudo mkdir /etc/nbxplorer
~$ sudo cp nbxplorer.config /etc/nbxplorer
~$ sudo chmod 644 /etc/nbxplorer/nbxplorer.config

注: 以前 NBXplorer で dbtrie バックエンドを使っていて postgres に切り替えたい場合は、このドキュメント (opens new window)を参照してください。

# 5. systemd サービスを作成

以下に systemd サービスファイルの例を示します。パス、User、Group は環境に合わせて調整してください。

~$ vi nbxplorer.service
[Unit]
Description=NBXplorer daemon
Requires=bitcoind.service
After=bitcoind.service

[Service]
WorkingDirectory=/home/admin/src/NBXplorer
ExecStart=/home/admin/src/NBXplorer/run.sh --conf=/etc/nbxplorer/nbxplorer.config
User=admin
Group=admin
Type=simple
PIDFile=/run/nbxplorer/nbxplorer.pid
Restart=on-failure

[Install]
WantedBy=multi-user.target
~$ sudo cp nbxplorer.service /etc/systemd/system
~$ sudo systemctl enable --now nbxplorer
# 確認
~$ sudo journalctl -xe --unit nbxplorer --follow
May 23 19:13:35 btc run.sh[8065]: info: Configuration:  Data Directory: /home/admin/.nbxplorer/Main
May 23 19:13:35 btc run.sh[8065]: info: Configuration:  Configuration File: /home/admin/.nbxplorer/Main/settings.config
May 23 19:13:35 btc run.sh[8065]: info: Configuration:  Network: Mainnet
...
May 23 19:20:04 btc run.sh[8065]: info: Events:         BTC: New block 0000000000000000000c405ba5df5f5533359a4393247a0c52d26c458d4dd989 (577449)

正しく起動しない場合はサービスを停止し、アプリケーションを直接実行してエラーメッセージを確認します。

~$ sudo systemctl stop nbxplorer
~$ cd ~; pushd ./src/NBXplorer; ./run.sh; popd
# 更新

更新によって不具合が起こる可能性があります。本番稼働中のシステムでは注意してください。

# Stop the service
~$ sudo systemctl stop nbxplorer
# Checkout and build latest tag
~$ cd ~; pushd ~/src/NBXplorer; git fetch --tags && git checkout $(git tag --sort -version:refname | awk 'match($0, /^v[0-9]+\./)' | head -n 1) && ./build.sh; popd;
# Restart the service
~$ sudo systemctl start nbxplorer

# BTCPay Server

NBXplorer と同様に、BTCPay Server も .NET Core アプリケーションです。以下のインストール手順は .NET Core が事前にインストール済みである前提です。

# インストール
# 1. BTCPay Server をビルド
~$ cd ~; mkdir -p src; cd src
# Clone the repository
~/src$ git clone https://github.com/btcpayserver/btcpayserver.git
~/src$ cd btcpayserver
# Checkout latest tag
~$ git checkout $(git tag --sort -version:refname | awk 'match($0, /^v[0-9]+\.[0-9]+\.[0-9]+$/)' | head -n 1)
# Build the app
~/src/btcpayserver$ ./build.sh
# 2. Postgresql データベースを作成

BTCPay Server は既定で 1 つの SQLite ファイルにデータを保存します。より堅牢な選択肢として Postgresql を使う場合は、対応するデータベースとユーザーを作成する必要があります。

~$ sudo -u postgres psql

次を実行します。

CREATE DATABASE btcpay TEMPLATE 'template0' LC_CTYPE 'C' LC_COLLATE 'C' ENCODING 'UTF8';
CREATE USER btcpay WITH ENCRYPTED PASSWORD 'urpassword';
GRANT ALL PRIVILEGES ON DATABASE btcpay TO btcpay;

終了します。

postgres=#\q
# 3. 設定ファイルを作成
$ vi btcpay.config
### Database ###
postgres=User ID=btcpay;Password=urpassword;Application Name=btcpayserver;Host=localhost;Port=5432;Database=btcpay;
explorer.postgres=User ID=nbxplorer;Password=urpassword;Application Name=nbxplorer;MaxPoolSize=20;Host=localhost;Port=5432;Database=nbxplorer;
~$ sudo mkdir /etc/btcpay
~$ sudo cp btcpay.config /etc/btcpay
~$ sudo chmod 644 /etc/btcpay/btcpay.config

代替として、設定ファイル、環境変数(BTCPAY_EXPLORERPOSTGRESBTCPAY_POSTGRES)、またはコマンドライン引数(--explorerpostgres--postgres)で BTCPay Server を起動することもできます。

# 4. systemd サービスを作成

以下に systemd サービスファイルの例を示します。パス、User、Group は環境に合わせて調整してください。

~$ vi btcpay.service
[Unit]
Description=BTCPay Server
Requires=nbxplorer.service
After=nbxplorer.service

[Service]
WorkingDirectory=/home/admin/src/btcpayserver
Environment=BTCPAY_BTCEXTERNALRTL="server=https://mainnet.demo.btcpayserver.org/rtl;cookiefile=/var/lib/rtl/.cookie"
ExecStart=/home/admin/src/btcpayserver/run.sh --conf=/etc/btcpay/btcpay.config
User=admin
Group=admin
Type=simple
PIDFile=/run/btcpayserver/btcpayserver.pid
Restart=on-failure

[Install]
WantedBy=multi-user.target
~$ sudo cp btcpay.service /etc/systemd/system
~$ sudo systemctl enable --now btcpay
# 確認
~$ sudo journalctl -xe --unit btcpay --follow
-- The start-up result is RESULT.
May 23 20:01:25 btc run.sh[10263]: info: Configuration:  Data Directory: /home/admin/.btcpayserver/Main
May 23 20:01:25 btc run.sh[10263]: info: Configuration:  Configuration File: /etc/btcpay/btcpay.config
May 23 20:01:25 btc run.sh[10263]: info: Configuration:  Network: Mainnet

正しく起動しない場合はサービスを停止し、アプリケーションを直接実行してエラーメッセージを確認します。

~$ sudo systemctl stop btcpay
~$ cd ~; pushd ~/src/btcpayserver; ./run.sh --conf=/etc/btcpay/btcpay.config; popd;

データベース内の情報を確認する例です。

~$ sudo -u postgres psql
postgres=# \connect btcpay;
btcpay=# \dt
btcpay=# select * from "Invoices";
btcpay=# \q

この時点でブラウザから BTCPay Server のドメインを開くと、「Welcome to your BTCPay Server」ページが表示されるはずです。 Lightning Node を使用しない場合は、ここでインストール完了です。

# 更新

更新によって不具合が起こる可能性があります。本番稼働中のシステムでは注意してください。

# Stop the service
~$ sudo systemctl stop btcpay
# Checkout and build latest tag
~$ cd ~; pushd ~/src/btcpayserver; git fetch --tags && git checkout $(git tag --sort -version:refname | awk 'match($0, /^v[0-9]+\.[0-9]+\.[0-9]+$/)' | head -n 1) && ./build.sh; popd;
# Restart the service
~$ sudo systemctl start btcpay

# Lightning Network Daemon (LND)(Lightning デーモン)

# インストール

完全な手順 (opens new window)はリンク先を参照してください。

# 1. Go をインストール
~$ sudo apt install make
~$ wget https://dl.google.com/go/go1.13.linux-amd64.tar.gz
~$ sha256sum go1.13.linux-amd64.tar.gz
68a2297eb099d1a76097905a2ce334e3155004ec08cdea85f24527be3c48e856  go1.13.linux-amd64.tar.gz
~$ sudo tar -C /usr/local -xzf go1.13.linux-amd64.tar.gz
~$ export PATH=$PATH:/usr/local/go/bin
~$ export GOPATH=~/gocode
~$ export PATH=$PATH:$GOPATH/bin
~$ go version
go version go1.13 linux/amd64
# 2. LND をビルドしてインストール
~$ cd ~; mkdir -p src; cd src
~$ git clone https://github.com/lightningnetwork/lnd
~$ cd lnd
~$ make
~$ make install # installs to a directory in $GOPATH/bin
~$ sudo cp $GOPATH/bin/lnd $GOPATH/bin/lncli /usr/bin
~$ lnd --version
lnd version 0.10.99-beta commit=clock/v1.0.0-229-ge64e71d86dc1ac716c30a80f85a22e8fb544697f
# 3. Bitcoin 設定ファイルへのシンボリックリンクを作成

lnd は必要な RPC と zeromq の情報を取得するため、特定の場所にある bitcoin.conf を参照します。

~$ ln -s ~/.bitcoin/bitcoin.conf /etc/bitcoin/bitcoin.conf
# 4. 設定ファイルを作成
~$ vi lnd.conf
[Application Options]
datadir=/var/lib/lnd/data
tlscertpath=/var/lib/lnd/tls.cert
tlskeypath=/var/lib/lnd/tls.key
logdir=/var/lib/lnd/logs
maxlogfiles=3
maxlogfilesize=10
#externalip=1.1.1.1 # change to your public IP address if required.
alias=i_luv_btcpay
listen=0.0.0.0:9735

[Bitcoin]
bitcoin.active=1
bitcoin.node=bitcoind
bitcoin.mainnet=true

[tor]
tor.active=true
tor.v3=true
~$ sudo mkdir -p /etc/lnd
~$ sudo mkdir -p /var/lib/lnd
~$ sudo chown admin:admin -R /var/lib/lnd
~$ sudo cp lnd.conf /etc/lnd
~$ sudo chmod 644 /etc/lnd/lnd.conf
# 5. systemd サービスを作成

以下に systemd サービスファイルの例を示します。パス、User、Group は環境に合わせて調整してください。

~$ vi lnd.service
[Unit]
Description=LND Lightning Network Daemon
Requires=bitcoind.service
After=bitcoind.service

[Service]
ExecStart=/usr/bin/lnd --configfile=/etc/lnd/lnd.conf
ExecStop=/usr/bin/lncli --lnddir /var/lib/lnd stop
PIDFile= /run/lnd/lnd.pid

User=admin
Group=admin

Type=simple
KillMode=process
TimeoutStartSec=60
TimeoutStopSec=60
Restart=always
RestartSec=60

[Install]
WantedBy=multi-user.target
~$ sudo cp lnd.service /etc/systemd/system
~$ sudo systemctl enable --now lnd
# 設定

DANGER

Bitcoin Lightning デーモンの実行には、BTCPay Server 上のホットウォレットが必要です。

Bitcoin ではプロトコルの進化により、決定的鍵導出によってウォレット鍵を BTCPay Server とは別の場所に保管できます。Lightning デーモンにはこの仕組みがありません。Lightning チャネルにコミットまたは受け取った Bitcoin は、BTCPay Server 上にある秘密鍵で管理されます。

# 1. lnd データディレクトリへのシンボリックリンクを作成

上記のインストール手順では、既定の /home/user/.lnd ではなく /var/lib/lnd をデータディレクトリとして使用しています。lncli クライアント利用時の入力を減らすため、ディレクトリへのシンボリックリンクを作成しておくと便利です。

ln -s /var/lib/lnd .lnd
# 2. Lightning ウォレットを作成

lnd を初めて起動するときは、新しいウォレットを作成し、バックアップ用シードを安全に記録する必要があります(シードを第三者に知られると資金を盗まれる可能性があるため、安全に保管してください)。

~$ lncli create
Input wallet password:
Confirm password:

Do you have an existing cipher seed mnemonic you want to use? (Enter y/n): n

Your cipher seed can optionally be encrypted.
Input your passphrase if you wish to encrypt it (or press enter to proceed without a cipher seed passphrase):

Generating fresh cipher seed...

!!!YOU MUST WRITE DOWN THIS SEED TO BE ABLE TO RESTORE THE WALLET!!!
---------------BEGIN LND CIPHER SEED---------------
 1. above      2. catch    3. start     4. tape
 5. sound      6. friend   7. water     8. royal
 9. solid     10. poet    11. wisdom   12. match
13. virtual   14. zero    15. slender  16. thrive
17. idle      18. catch   19. robot    20. clay
21. resemble  22. angry   23. work     24. until
---------------END LND CIPHER SEED-----------------

!!!YOU MUST WRITE DOWN THIS SEED TO BE ABLE TO RESTORE THE WALLET!!!

lnd successfully initialized!

前の手順でシンボリックディレクトリリンクを作成していない場合は、次のコマンドを使用します。

lncli --lnddir /var/lib/lnd create
# 3. ウォレットをアンロック

lnd を再起動するたびに、ウォレットのアンロックが必要です。無人運用を想定した BTCPay Server には理想的ではありませんが、Lightning はまだ発展途上です。

~$ lncli unlock
# 確認
~$ lncli getinfo
{
    "version": "0.10.99-beta commit=clock/v1.0.0-229-ge64e71d86dc1ac716c30a80f85a22e8fb544697f",
    "commit_hash": "e64e71d86dc1ac716c30a80f85a22e8fb544697f",
   ...
 }

サービスを確認します。

~$ sudo journalctl -xe --unit lnd --follow
...
Jul 27 15:46:29 ubuntu lnd[654474]: 2020-07-27 15:46:29.909 [INF] DISC: Attempting to bootstrap with: BOLT-0010 DNS Seed: [[nodes.lightning.directory soa.nodes.lightning.directory] [lseed.bitcoinstats.com ]]
Jul 27 15:49:41 ubuntu lnd[654474]: 2020-07-27 15:49:41.939 [INF] DISC: Attempting to bootstrap with: Authenticated Channel Graph
Jul 27 15:49:41 ubuntu lnd[654474]: 2020-07-27 15:49:41.940 [ERR] SRVR: Unable to retrieve initial bootstrap peers: no addresses found

BTCPay Server で使用する Lightning Node 接続文字列 は次のとおりです。

type=lnd-rest;server=https://127.0.0.1:8080/;macaroonfilepath=/home/admin/.lnd/data/chain/bitcoin/mainnet/admin.macaroon;allowinsecure=true
# LND を内部ノードとして追加

LND を内部ノードとして追加するには、btcpay.config ファイルを編集します。

cd /etc/btcpay
vi btcpay.config

データベース設定の直下に、BTC.lightning 設定を追加します。

### Lightning ###
BTC.lightning=type=lnd-rest;server=https://127.0.0.1:8080/;macaroonfilepath=/home/admin/.lnd/data/chain/bitcoin/mainnet/admin.macaroon;allowinsecure=true

接続文字列の詳細は、BTCPay Server の Lightning ノード接続設定画面にある「Use custom node」ビューを参照してください。

設定変更を反映するには、BTCPay Server を再起動する必要があります。

~$ sudo systemctl restart btcpay
# Tor と LND の確認

Bitcoin デーモンと同様に、Tor がインストール済みで設定ファイルで有効化されていれば(上記設定では有効)、lnd は自動的に onion アドレスを登録します。lnd では torv3 アドレスに対応しています。

以下の torv3 onion アドレスは、Bitcoin デーモンセクションの torv2 よりかなり長くなります(16 文字に対して 56 文字)。

~$ lncli getinfo | grep onion
"029b0e3c05595074afcffdca0fb22fb68a95a9c4698dd20962f647de4891eceabd@liyuvwbbycrvvuzcrsd5rq7svwckabejlsymcxiwzkj3smvlwcsqpjyd.onion:9735"

lnd が作成した Tor アドレスは、Tor ネットワーク上の他の Lightning ピアへの接続に使用できます。この Tor アドレスは IPv4 または IPv6 アドレスと並行して利用できます。IPv4/IPv6 を登録する場合は、lnd 設定ファイルで externalip が設定されていることを確認してください。

# 更新

更新によって不具合が起こる可能性があります。本番稼働中のシステムでは注意してください。

~$ sudo systemctl stop lnd
~$ export PATH=$PATH:/usr/local/go/bin
~$ export GOPATH=~/gocode
~$ export PATH=$PATH:$GOPATH/bin
~$ cd ~/src/lnd
~$ git pull
~$ make
~$ make install # installs to a directory in $GOPATH/bin
~$ sudo cp $GOPATH/bin/lnd $GOPATH/bin/lncli /usr/bin
~$ lnd --version
lnd version 0.10.99-beta commit=clock/v1.0.0-229-ge64e71d86dc1ac716c30a80f85a22e8fb544697f
~$ sudo systemctl start lnd

デーモンを再起動した後は、ウォレットをアンロックする必要があります。

~$ lncli unlock

Ride The Lightning (RTL) をインストールしている場合(次セクション参照)、lnd 停止時に RTL も停止している可能性があるため、あわせて再起動が必要です。

~$ sudo systemctl start rtl

# Ride The Lightning (RTL)(Lightning 管理UI)

Ride the Lightning は、Lightning のピア、チャネル、ウォレットなどを管理する Node.js アプリケーションです。

BTCPay Server 側の統合作業により、RTL の Web ページは BTCPay サイトと同じ方法で制御・アクセスできます。

# インストール
# 1. 依存関係をインストール
~$ sudo apt install nodejs build-essential npm
# 2. RTL をビルド
~$ cd ~/src
~$ git clone https://github.com/Ride-The-Lightning/RTL.git
~$ cd RTL
~$ npm install --only=prod
# 3. 設定ファイルを作成

sample-RTL-Config.json からサンプル設定ファイルをコピーし、環境に合わせて調整します。このドキュメント内の他の手順と整合する例を以下に示します。

~$ cp src/RTL/sample-RTL-Config.json RTL-Config.json
~$ vi RTL-Config.json
{
  "port": "3000",
  "defaultNodeIndex": 1,
  "SSO": {
    "rtlSSO": 1,
    "rtlCookiePath": "/var/lib/rtl/.cookie",  # Needs to match the value in BTCPay systemd settings.
    "logoutRedirectLink": "https://mainnet.demo.btcpayserver.org/login"
  },
  "nodes": [
    {
      "index": 1,
      "lnNode": "Node 1",
      "lnImplementation": "LND",
      "Authentication": {
        "macaroonPath": "/var/lib/lnd/data/chain/bitcoin/mainnet",
        "configPath": "/etc/lnd/lnd.conf"
      },
      "Settings": {
        "userPersona": "MERCHANT",
        "themeMode": "DAY",
        "themeColor": "PURPLE",
        "channelBackupPath": "/home/admin/rtl/backup/node-1",
        "enableLogging": false,
        "lnServerUrl": "https://localhost:8080/v1",
        "swapServerUrl": "http://localhost:8081/v1",
        "fiatConversion": false
      }
    }
  ]
}

RTL は、この手順で説明している他サービスとは挙動と要件が異なります。主な点は次のとおりです。

  1. 設定ファイルは RTL のデータディレクトリに配置する必要があります。
  2. RTL プロセスが設定ファイルを書き換えることがあります。
~$ sudo mkdir -p /var/lib/rtl
~$ sudo cp ~/RTL-Config.json /var/lib/rtl
~$ sudo chown admin:admin -R /var/lib/rtl
~$ sudo chmod 644 /var/lib/rtl/RTL-Config.json
# 4. systemd サービスを作成
~$ vi rtl.service
[Unit]
Description=Ride The Lightning
Requires=lnd.service
After=lnd.service

[Service]
Environment="RTL_CONFIG_PATH=/var/lib/rtl"
WorkingDirectory=/var/lib/rtl
ExecStart=/usr/bin/node /home/admin/src/RTL/rtl
User=admin
Group=admin
Type=simple
PIDFile=/run/rtl/rtl.pid
Restart=on-failure

[Install]
WantedBy=multi-user.target
~$ sudo cp rtl.service /etc/systemd/system
~$ sudo systemctl enable --now rtl
# 確認

サービスを確認します。

~$ sudo journalctl -xe --unit rtl --follow
...
Jul 27 18:27:52 ubuntu node[988638]: Server is up and running, please open the UI at http://localhost:3000

正しく起動しない場合はサービスを停止し、アプリケーションを直接実行してエラーメッセージを確認します。

~$ sudo systemctl stop rtl
~$ export RTL_CONFIG_PATH=/var/lib/rtl; pushd ~/src/RTL; node rtl; popd;
Server is up and running, please open the UI at http://localhost:3000

BTCPay Server の Web ページでは、Server Settings->Services の「Crypto services exposed by your server」配下から RTL インターフェースにアクセスできるはずです。

# 更新

更新によって不具合が起こる可能性があります。本番稼働中のシステムでは注意してください。

~$ sudo systemctl stop rtl
~$ cd ~; pushd ~/src/RTL; git pull; npm install; popd;
~$ sudo systemctl start rtl

# おわりに

# 質問

Mattermost アプリ (opens new window)をダウンロードして Mattermost のコミュニティチャット (opens new window)に参加するか、Telegram (opens new window) に参加してください。追加のサポートが必要な場合や、同じ関心を持つ人たちと交流したい場合に役立ちます。