Sunteți pe pagina 1din 17

Documentation of the

process of creating a Peatio


Exchange

Table of Contents
Step 1: Provision the servers..................................................... 2
Step 2: Set up Server 1.............................................................. 2
Install bitgod..................................................................................................................................... 2
Set up your BitGo Wallet.................................................................................................................. 3
Connect Server 1 to your BitGo wallet............................................................................................. 3
Create a webhook............................................................................................................................. 4
Get Server 1 to sign Withdrawals..................................................................................................... 4
Troubleshooting Tips........................................................................................................................ 4
Step 3: Set up Server 2.............................................................. 6
Setup deploy user.............................................................................................................................. 6
Install Ruby...................................................................................................................................... 6
Instal Nginx & Passenger................................................................................................................. 7
Install JavaScript Runtime................................................................................................................ 7
Install ImageMagick......................................................................................................................... 8
Setup production environment variable............................................................................................ 8
Clone the Source............................................................................................................................... 8
Install Dependency gems.................................................................................................................. 8
Configure Peatio............................................................................................................................... 8
Config database settings................................................................................................................... 8
Modify currency.yml to point to server 1.......................................................................................... 9
Deposit integration with Server 1..................................................................................................... 9
Precompile assets.............................................................................................................................. 9
Run Daemons................................................................................................................................... 9
Configure Passenger....................................................................................................................... 10
Set up Liability Proof...................................................................................................................... 10
Setting the SSL certificate.............................................................................................................. 10
Steps................................................................................................................................................ 10
1.Modify production.rb................................................................................................................... 10
2.Generate CSR............................................................................................................................... 10
3.Buy and Activate the SSL certificate............................................................................................. 11
4.Install the certificate on Server 2 ................................................................................................. 11
Maintenance stuf................................................................... 13
Recompiling assets......................................................................................................................... 13
Starting bitgod and bitcoind on Server 1 after a restart................................................................... 14
Customising the look and feel of your exchange............................................................................ 14
Setting up automated Github deployments on Server 1.................................................................. 14
Install whiskey_disk gem................................................................................................................. 14
Change user and directory.............................................................................................................. 14
Open the sudoers file for editing..................................................................................................... 15
Add a cron jobs............................................................................................................................... 15
Add liability-proof script................................................................................................................. 16
Add a post-deploy script.................................................................................................................. 16
Add a pre-commit script.................................................................................................................. 16
Add a script to run whisky_disk...................................................................................................... 16
Make all the scripts executable....................................................................................................... 16
Add the whyskey_disk configuration file......................................................................................... 17
Run setup command to complete process........................................................................................ 17

Step 1: Provision the servers


Create 4 servers with the following specs:

Server Name AWS Service Type Specs Purpose


Server 1 EC2 T2.mico  Ubuntu This is where the
14.04 bitcoind and
bitgod will be
running
Server 2 EC2 C4.large  Ubuntu This is where the
14.04 peatio website is
hosted
Server 3 RDS T2.micro - This is the
database

Step 2: Set up Server 1


Log into server 2

Install bitgod

Log into Sever 1

$ ssh -i <LOCATION_TO_PEM_file>.pem ubuntu@<SERVER1>

sudo apt-get update && sudo apt-get upgrade –y

Install NodeJS:
curl -sL https://deb.nodesource.com/setup | sudo bash -
All other commands required as part of this process in sudo and install latest stable
(backwards compatible version of npm) with sudo npm -g install npm@latest

Now install bitgod

$ git clone https://github.com/BitGo/bitgod.git


$ cd bitgod
$ sudo npm -g install bitgod

Set up your BitGo Wallet

1. Create an account on BitGo and create a Bitcoin Wallet.


2. Take note of your Wallet ID, Wallet Address and create a Wallet Password you will
remember.
o You can get your Wallet ID from the URL that points to your wallet. In my
case, the URL shown when I open my wallet is:
https://www.bitgo.com/enterprise/personal/wallets/3L6nxZ5guxZRdhWXZgz7bMUNYY8Fir
JgFy. My Wallet ID is therefore:3L6nxZ5guxZRdhWXZgz7bMUNYY8FirJgFy
3. From your BitGo Account Settings, create a token that allows you to connect to your
from Server 1. You will need the public IP Address of your instance.

Connect Server 1 to your BitGo wallet

Specify your wallet details in the connect-to-bitgo.sh script:


$ pico connect-to-bitgo.sh

Your connect-to-bitgo.sh script should look like this:

bitcoin-cli -rpcport=9332 settoken <YOUR_TOKEN_ID>


bitcoin-cli -rpcport=9332 setwallet <YOUR_WALLET_ID>
bitcoin-cli -rpcport=9332 walletpassphrase
<YOUR_WALLET_PASSWORD> 32000000

Make script executable

$ chmod +x connect-to-bitgo.sh

Create a start-bitgod.sh script

$ pico start-bitgod.sh

Add the following line as the script content:

nohup bitgod -masqueradeaccount=payment &

Make script executable

$ chmod +x start-bitgod.sh

Start bitgod

$ ./start-bitgod.sh
You may have to wait a few minutes for bitgod to start. Once started, you can check see the
following output when you tail nohup.out:
Validating in loose mode
Connected to proxy bitcoind at <SERVER1>:8332
{ version: 110000,
protocolversion: 70002,
walletversion: 60000,
balance: 0,
blocks: 379051,
timeoffset: -66,
connections: 9,
proxy: '',
difficulty: 60883825480.09828,
testnet: false,
keypoololdest: 1440612908,
keypoolsize: 101,
paytxfee: 0,
relayfee: 0.00001,
errors: '' }

Connect to your bitgo wallet:


$ ./connect-to-bitgo.sh

You know everything has worked when you see output which looks like this:
Authenticated as BitGo user: <YOUR_EMAIL_ADDRESS>
Set wallet: 3L6nxZ5guxZRdhWXZgz7bMUNYY8FirJgFy

Create a webhook
Now add a webhook using the BitGo Webhook API:
https://www.bitgo.com/api/#add-webhooks

Here is an example of how you would do it:

$ WALLETID=2NEE9QHKPB2GNQLB3HFFMUDCOFKZFJHYJYX
ACCESS_TOKEN=9E1194FD035E2C8D5268E648C796425429FC2BD57BB5DA7FBEBBF09E1711A6B6
CURL -X POST \
-H “CONTENT-TYPE: APPLICATION/JSON” \
-H “AUTHORIZATION: BEARER $ACCESS_TOKEN” \
-D “{ \”URL\”: \”HTTP://<SERVER_1_URL>/WEBHOOKS/TX\", \”TYPE\”: \”TRANSACTION\” }” \
HTTPS://WWW.BITGO.COM/API/V1/WALLET/$WALLETID/WEBHOOKS

Get Server 1 to sign Withdrawals

Give BitGoD the wallet passphrase (used when creating the BitGo multi-
sig wallet):

$ bitcoin-cli -rpcport=19332 walletpassphrase [passphrase] 1500000


Troubleshooting Tips

 Run the following command to check if bitgod is running:

$ ps -ef |grep bitgod

You will see a line/output which looks like this:

 To kill that particular process you run the following command:


$ kill -9

 Tail the .nohup.out file to check if there are any issues


$ tail -f nohup.out

bitgod runs in verbose mode and all output is printed at the end of the file. It's the first
place you want to check to make sure everything is running smoothly

 Check that bitcoind is running. bitgod will attempt to connect to a local bitcoind
instance. You can check that one is running by using the following commmand:
$ bitcoin-cli getblockcount

If it's not running you will likely get an error.


To start bitcoind run the following command:
$ bitcoind
Step 3: Set up Server 2
Setup deploy user

Create (if it doesn’t exist) deploy user, and assign it to the sudo group:

$ sudo adduser deploy


$ sudo usermod -a -G sudo deploy

Re-login as deploy user using the following command:

$ sudo su - deploy

Install Ruby

Make sure your system is up-to-date.

$ sudo apt-get update


$ sudo apt-get upgrade

Installing rbenv using a Installer

$ sudo apt-get install git-core curl zlib1g-dev build-essential \


libssl-dev libreadline-dev libyaml-dev libsqlite3-dev
sqlite3 \
libxml2-dev libxslt1-dev libcurl4-openssl-dev \
python-software-properties libffi-dev

$ cd
$ git clone git://github.com/sstephenson/rbenv.git .rbenv
$ echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
$ echo 'eval "$(rbenv init -)"' >> ~/.bashrc
$ exec $SHELL

$ git clone git://github.com/sstephenson/ruby-build.git


~/.rbenv/plugins/ruby-build
$ echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >>
~/.bashrc
$ exec $SHELL

Install Ruby through rbenv:

$ rbenv install 2.2.1


$ rbenv global 2.2.1

Install bundler
$ echo "gem: --no-ri --no-rdoc" > ~/.gemrc
$ gem install bundler
$ rbenv rehash

Instal Nginx & Passenger

Install Phusion's PGP key to verify packages

$ sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys


561F9B9CAC40B2F7

Add HTTPS support to APT

$ sudo apt-get install apt-transport-https ca-certificates

Add the passenger repository

$ sudo add-apt-repository 'deb https://oss-


binaries.phusionpassenger.com/apt/passenger trusty main'
$ sudo apt-get update

Install nginx and passenger

$ sudo apt-get install nginx-extras passenger

Next, we need to update the Nginx configuration to point Passenger to the version of Ruby
that we're using. You'll want to open up /etc/nginx/nginx.conf in your favorite editor,

$ sudo vim /etc/nginx/nginx.conf

find the following lines, and uncomment them:

passenger_root /usr/lib/ruby/vendor_ruby/phusion_passenger/locations.ini;
passenger_ruby /usr/bin/ruby;

update the second line to read:

passenger_ruby /home/deploy/.rbenv/shims/ruby;

Install JavaScript Runtime


A JavaScript Runtime is needed for Asset Pipeline to work. Any runtime will do but Node.js
is recommended.

$ curl -sL https://deb.nodesource.com/setup | sudo bash -


$ sudo apt-get install nodejs

Install ImageMagick

$ sudo apt-get -y install imagemagick gsfonts

Setup production environment variable

$ echo "export RAILS_ENV=production" >> ~/.bashrc


$ source ~/.bashrc

Clone the Source

$ mkdir -p ~/peatio
$ git clone git://github.com/peatio/peatio.git ~/ peatio/current
$ cd peatio/current

Install Dependency gems


$ bundle install --without development test --path vendor/bundle

Configure Peatio

Prepare configure files


$ bin/init_config

Setup Pusher by uncommenting Pusher related settings


$ vim config/application.yml

Config database settings

The settings in database.yml should point to Server 3

$ vim config/database.yml

Initialise the database and load seed data


$ bundle exec rake db:setup
Modify currency.yml to point to server 1

Open currency.yml for editing

$ vim config/currency.yml

The modify the following line to look like this

- id: 2
coin: true
quick_withdraw_max: 1000
key: satoshi
code: btc
rpc:
Error! Hyperlink reference not valid.19332

Deposit integration with Server 1

To inform Peatio about the new coin deposits when they occurred, I added
app/controllers/webhooks_controller.js to accept an incoming webhook:

class WebhooksController < ApplicationController


before_action :auth_anybody!
skip_before_filter :verify_authenticity_token
def tx
if params[:type] == "transaction" && params[:hash].present?
AMQPQueue.enqueue(:deposit_coin, txid: params[:hash], channel_key:
"satoshi")
render :json => { :status => "queued" }
end
end

(Note how Peatio only accepts the Transaction ID— the deposit_coins daemon uses this to
kick off checks on the deposit address and then verifies the transaction amount)
Here is the new route in config/routes.rb:

post '/webhooks/tx' => 'webhooks#tx'

Precompile assets

$ bundle exec rake assets:precompile

Run Daemons

The following command will start all the daemons


$ bundle exec rake daemons:start
Configure Passenger

$ sudo rm /etc/nginx/sites-enabled/default
$ sudo ln -s /home/deploy/peatio/current/config/nginx.conf
/etc/nginx/conf.d/peatio.conf
$ sudo service nginx restart

Set up Liability Proof

Add the following line to your crontab so that it runs regularly

RAILS_ENV=production rake solvency:liability_proof

Setting the SSL certificate

I bought my SSL certificate on namecheap.com so I assume you are going


to buy the same SSL certificate on namecheap.com so it’s going to be a
Comodo PositiveSSL (the one for which these steps were built).

Steps
1. Modify production.rb
2. Generate a CSR
3. Buy and Activate the certificate
4. Install certificate on Server 2

1. Modify production.rb
For security reason, you must setup SSL Certificate for production
environment, if your SSL Certificated is been configured, please change
the following line in config/environments/production.rb

config.force_ssl = true

2. Generate CSR

First create a folder called ssl in your home folder

$ cd ~
$ mkdir ssl

Run the following command to generate your CSR

$ openssl req -new -newkey rsa:2048 -nodes -keyout server.key -out


server.csr
You will be asked a bunch of questions. Answer them.

This creates two files. The file myserver.key contains a private key; do not disclose this file to
anyone. Carefully protect the private key.
In particular, be sure to backup the private key, as there is no means to recover it should it be
lost. The private key is used as input in the command to generate a Certificate Signing
Request (CSR).
just make sure that the file containing the private key is readable only to the system account
which runs the server (chown and chmod on Unix-like systems)
chmod 0400 server.key
chmod 0400 cert_chain.crt

3. Buy and Activate the SSL certificate

In the step above, a file called server.csr was created. It’s in the path /home/deploy/server.csr.
When you activate the SSL certificate you will be asked for a CSR. When that time comes,
paste the contents of the server.csr file.

4. Install the certificate on Server 2

After you activate your certificate on namecheap.com, you will get the following files
emailed to you:
1. *youdomainname*.crt
2. ComodoRSADomainValidationSecureServerCA.crt
3. COMODORSAAddTrustCA.crt
4. AddTrustExternalCARoot.crt

Sometimes you will get the last 3 files bundled into one file so you will have the following 2
files instead of 4 files:
1. *youdomainname*.crt
2. COMODO_DV_SHA-256_bundle.crt

The goal is to combine the files into one file. That file will be your SSL certificate. We shall
name this file cert_chain.crt. You need to upload them to Server 2 and put them in the path
/home/deploy/ssl/. You do this using the following command:

$ cat *yourdomainname*.crt ComodoRSADomainValidationSecureServerCA.crt


COMODORSAAddTrustCA.crt AddTrustExternalCARoot.crt >> cert_chain.crt

or if you got the bundled file you run:

$ cat *yourdomainname*.crt COMODO_DV_SHA-256_bundle.crt >> cert_chain.crt

chmod 0400 server.key


chmod 0400 cert_chain.crt
Now edit your nginx.conf file

Open the file for editing

$ cd ~/peatio/current
$ sudo pico config/nginx.conf

If you do not have a record for port 443 in your VirtualHost, you should add it manually.
To simplify the process, you can duplicate the record for port 80 (should be in your
VirtualHost file by default) and change port 80 to port 443. Simply add it below the non-
secure module. In addition to port changes you will need to add the special lines in the
record:

ssl on;
ssl_certificate /home/deploy/ssl/cert_chain.crt;
ssl_certificate_key / home/deploy/ssl/sever.key;

How to harden Nginx SSL


https://weakdh.org/sysadmin.html

The file to change is this one sudo pico peatio/current/config/nginx.conf


server {
listen 80 default;
server_name yourdomainname.co.uk;
passenger_enabled on;
gzip on;

root /home/deploy/peatio/current/public;

location = /favicon.png {
expires max;
add_header Cache-Control public;
}

location = /ZeroClipboard.swf {
expires max;
add_header Cache-Control public;
}

location ~ ^/(assets)/ {
gzip_static on;
expires max;
add_header Cache-Control public;
}

# disable gzip on all omniauth paths to prevent BREACH


location ~ ^/auth/ {
gzip off;
passenger_enabled on;
}
}
server {
listen 443 ssl http2;
server_name yourdomainname.co.uk;
add_header Strict-Transport-Security "max-age=31536000;
includeSubDomains";
passenger_enabled on;
gzip on;

root /home/deploy/peatio/current/public;

ssl on;
ssl_certificate /home/deploy/ssl/cert_chain.crt;
ssl_certificate_key /home/deploy/ssl/server.key;
ssl_dhparam dhparams.pem;

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;


ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-
SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-
SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-
SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES12$
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
ssl_stapling on; # Requires nginx >= 1.3.7
ssl_stapling_verify on; # Requires nginx => 1.3.7
resolver 8.8.4.4 8.8.8.8 valid=300s;
resolver_timeout 5s;

Test SSL certificate and ciphers and shit:


https://www.ssllabs.com/ssltest/

Now restart your web server

$ sudo nginx restart

Maintenance stuf
Recompiling assets

Usually you want to do this after making a change to the translation file or a change to an
asset that controls the appearance of the site. You should run the following commands:

$ cd ~/peatio/current
$ bundle exec rake assets:clean
$ bundle exec rake assets:clobber
$ bundle exec rake tmp:clear
$ bundle exec rake assets:precompile
Starting bitgod and bitcoind on Server 1 after a restart

Starting bitcond

$ bitcoind

Running bitgod in background

$ nohup bitgod -masqueradeaccount=payment &

Killing bitgod

$ ps -ef |grep bitgod


deploy 33725 33641 0 16:46 pts/5 00:00:01 node /usr/local/bin/bitgod
deploy 34075 33990 0 16:52 pts/3 00:00:00 grep --color=auto bitgod
$ kill -9 33725

Now you need to restart daemons

$ bundle exec rake daemons:stop


$ bundle exec rake daemons:start

Customising the look and feel of your exchange

The Peatio front-end is based Bootstrap 3.0 version and Sass, and you can custom exchange
style for your mind.
change bootstrap default variables in vars/_bootstrap.css.scss
change peatio custom default variables in vars/_basic.css.scss
add your custom variables in vars/_custom.css.scss
add your custom css style in layouts/_custom.css.scss
add or change features style in `features/_xyz.css.scss'
vars/_custom.css.scss can overwrite vars/_basic.css.scss defined
variables layout/_custom.css.scss can
overwrite layout/_basic.css.scss and layouts/_header.css.scss style

Setting up automated Github deployments on Server 1

Install whiskey_disk gem

The first step is to install the whiskey_disk gem. Automated deployments depends on that
gem.

$ gem install whiskey_disk

Change user and directory

$ sudo su - deploy
$ cd peatio/current/
Open the sudoers file for editing

$ sudo visudo

Add the following line:

deploy ALL=(ALL) NOPASSWD: ALL

Add a cron jobs

$ crontab –e

Your cron file should look like this:

PATH=/home/deploy/.rbenv/plugins/ruby-
build/bin:/home/deploy/.rbenv/shims:/home/deploy/.rbenv/bin:/usr/local/bin:
/usr/bin:/bin:/usr/local/games:/usr/games
PWD=/home/deploy/peatio/current
LANG=en_US.UTF-8
NODE_PATH=/usr/lib/nodejs:/usr/lib/node_modules:/usr/share/javascript
RBENV_SHELL=bash
SHLVL=1
HOME=/home/deploy
RAILS_ENV=production
LOGNAME=deploy
LESSOPEN=| /usr/bin/lesspipe %s
XDG_RUNTIME_DIR=/run/user/1000
LESSCLOSE=/usr/bin/lesspipe %s %s
_=/usr/bin/env
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow commands
*/15 * * * * /home/deploy/peatio/current/script/liability_proof.sh >
/home/deploy/peatio/current/log/cron.log
* * * * * /home/deploy/peatio/current/script/run_whiskey_disk.sh >
/home/deploy/peatio/current/log/deployments.log
Add liability-proof script

$ vim script/liability_proof.sh

It should contain the following information

$ cd /home/deploy/peatio/current && RAILS_ENV=production bundle exec rake


solvency:liability_proof

Add a post-deploy script

$ vim script/post_wd_deploy.sh

Make sure it has the following contents:

cd /home/deploy/peatip/current
bundle install
bundle exec rake db:migrate
bundle exec rake daemons:stop
bundle exec rake assets:clean
bundle exec rake assets:clobber
bundle exec rake tmp:clear
bundle exec rake assets:precompile
bundle exec rake daemons:start
echo "2wsx#EDC4rfv" | sudo -S service nginx restart

Add a pre-commit script

$ vim script/pre-commit.sh

Make sure it has the following contents

git stash -q --keep-index


echo 'running all tests...'
rspec spec
echo 'done'
RESULT=$?
git stash pop -q
[ $RESULT -ne 0 ] && exit 1
exit 0

Add a script to run whisky_disk

$ vim script/run_whiskey_disk.sh

The script should have the following contents:

cd /home/deploy/peatio/current
bundle exec wd --debug --check --to=prod
--path=/home/deploy/peatio/current/config/deploy.yml deploy

Make all the scripts executable

$ chmod +x script/liability_proof.sh
$ chmod +x script/post_wd_deploy.sh
$ chmod +x script/pre-commit.sh
$ chmod +x script/run_whiskey_disk.sh

Add the whyskey_disk configuration file

$ vim config/deploy.yml

Make sure it has the following contents

prod:
domain: "local"
deploy_to: "/home/deploy/peatio/current"
repository: "git@github.com:peatio/peatio.git"
branch: "prod"
post_deploy_script: "/home/deploy/peatio/current/script/post_wd_deploy.sh"
rake_env:
RAILS_ENV: 'production'

Run setup command to complete process

$ bundle exec wd setup --to=prod

S-ar putea să vă placă și