ethereum初探五:接入开发

以太坊下载后我们就可以启用geth进行启动节点,然后使用接口接入以太坊区块进行应用层的开发了。

首先安装 看我的文章:ethereum初探一:以太坊安装

在正式开始前,我们要先安装node,到node官网上下载linux64位的二进制包。

$cd /usr/local/src

$wget https://nodejs.org/dist/v8.9.4/node-v8.9.4-linux-x64.tar.xz

下载完了解压:

$xz -d node-v8.9.4-linux-x64.tar.xz

$tar -xvf node-v8.9.4-linux-x64.tar.xz

然后进行链接:

$ln -s /usr/local/src/node-v8.9.4-linux-x64/bin/node /usr/local/bin/node

$ln -s /usr/local/src/node-v8.9.4-linux-x64/bin/npm /usr/local/bin/npm

检查下:

$node -v

$npm -v

启动以太坊:

geth –datadir=/chaindata/.eth –nodiscover –rpc –rpcapi  –rpccorsdomain=’*’ –rpcaddr=”localhost”  –ws –wsorigins=’*’  console

这里先为了测试可以用*号,后续为了安全一定要把各项参数都改下。变内网做安全防火墙策略。具体细节不表。

安装web3,这里有个坑。网上目前资料很少,直接去官网才发现web3已经变成1.0,很多不兼容。而且1.0还是测试阶段。所以我还是选用了0.20.X. 我们先换下npm安装源,国外那源国内能2个小时不带动的。

$npm config set registry http://registry.npm.taobao.org/

查看下:$npm get registry.

$npm install web3@^0.20.1

没有git 先安装下git。截止我发稿最新的是0.20.3

$vi base.js

var Web3 = require(‘web3’);
var web3 = new Web3();
console.log(web3);

web3.setProvider(new web3.providers.HttpProvider(‘http://localhost:8545’));
console.log(web3.version);
var coinbase = web3.eth.accounts[0];
console.log(coinbase);

$node base.js

ethereum初探四:geth命令详解

命令用法

geth [选项] 命令 [命令选项] [参数…]

版本:

1.7.3-stable

命令:

account    管理账户
attach     启动交互式JavaScript环境(连接到节点)
bug        上报bug Issues
console    启动交互式JavaScript环境
copydb     从文件夹创建本地链
dump       Dump(分析)一个特定的块存储
dumpconfig 显示配置值
export     导出区块链到文件
import     导入一个区块链文件
init       启动并初始化一个新的创世纪块
js         执行指定的JavaScript文件(多个)
license    显示许可信息
makecache  生成ethash验证缓存(用于测试)
makedag    生成ethash 挖矿DAG(用于测试)
monitor    监控和可视化节点指标
removedb   删除区块链和状态数据库
version    打印版本号
wallet     管理Ethereum预售钱包
help,h     显示一个命令或帮助一个命令列表

ETHEREUM选项:

--config value          TOML 配置文件
--datadir “xxx”         数据库和keystore密钥的数据目录
--keystore              keystore存放目录(默认在datadir内)
--nousb                 禁用监控和管理USB硬件钱包
--networkid value       网络标识符(整型, 1=Frontier, 2=Morden (弃用), 3=Ropsten, 4=Rinkeby) (默认: 1)
--testnet               Ropsten网络:预先配置的POW(proof-of-work)测试网络
--rinkeby               Rinkeby网络: 预先配置的POA(proof-of-authority)测试网络
--syncmode "fast"       同步模式 ("fast", "full", or "light")
--ethstats value        上报ethstats service  URL (nodename:secret@host:port)
--identity value        自定义节点名
--lightserv value       允许LES请求时间最大百分比(0 – 90)(默认值:0) 
--lightpeers value      最大LES client peers数量(默认值:20)
--lightkdf              在KDF强度消费时降低key-derivation RAM&CPU使用

开发者(模式)选项:

--dev               使用POA共识网络,默认预分配一个开发者账户并且会自动开启挖矿。
--dev.period value  开发者模式下挖矿周期 (0 = 仅在交易时) (默认: 0)

ETHASH 选项:

--ethash.cachedir                        ethash验证缓存目录(默认 = datadir目录内)
--ethash.cachesinmem value               在内存保存的最近的ethash缓存个数  (每个缓存16MB ) (默认: 2)
--ethash.cachesondisk value              在磁盘保存的最近的ethash缓存个数 (每个缓存16MB) (默认: 3)
--ethash.dagdir ""                       存ethash DAGs目录 (默认 = 用户hom目录)
--ethash.dagsinmem value                 在内存保存的最近的ethash DAGs 个数 (每个1GB以上) (默认: 1)
--ethash.dagsondisk value                在磁盘保存的最近的ethash DAGs 个数 (每个1GB以上) (默认: 2)

 

交易池选项:

--txpool.nolocals            为本地提交交易禁用价格豁免
--txpool.journal value       本地交易的磁盘日志:用于节点重启 (默认: "transactions.rlp")
--txpool.rejournal value     重新生成本地交易日志的时间间隔 (默认: 1小时)
--txpool.pricelimit value    加入交易池的最小的gas价格限制(默认: 1)
--txpool.pricebump value     价格波动百分比(相对之前已有交易) (默认: 10)
--txpool.accountslots value  每个帐户保证可执行的最少交易槽数量  (默认: 16)
--txpool.globalslots value   所有帐户可执行的最大交易槽数量 (默认: 4096)
--txpool.accountqueue value  每个帐户允许的最多非可执行交易槽数量 (默认: 64)
--txpool.globalqueue value   所有帐户非可执行交易最大槽数量  (默认: 1024)
--txpool.lifetime value      非可执行交易最大入队时间(默认: 3小时)

 

性能调优的选项:

--cache value                分配给内部缓存的内存MB数量,缓存值(最低16 mb /数据库强制要求)(默认:128)
--trie-cache-gens value      保持在内存中产生的trie node数量(默认:120)

 

帐户选项:

--unlock value              需解锁账户用逗号分隔
--password value            用于非交互式密码输入的密码文件

 

API和控制台选项:

--rpc                       启用HTTP-RPC服务器
--rpcaddr value             HTTP-RPC服务器接口地址(默认值:“localhost”)
--rpcport value             HTTP-RPC服务器监听端口(默认值:8545)
--rpcapi value              基于HTTP-RPC接口提供的API
--ws                        启用WS-RPC服务器
--wsaddr value              WS-RPC服务器监听接口地址(默认值:“localhost”)
--wsport value              WS-RPC服务器监听端口(默认值:8546)
--wsapi  value              基于WS-RPC的接口提供的API
--wsorigins value           websockets请求允许的源
--ipcdisable                禁用IPC-RPC服务器
--ipcpath                   包含在datadir里的IPC socket/pipe文件名(转义过的显式路径)
--rpccorsdomain value       允许跨域请求的域名列表(逗号分隔)(浏览器强制)
--jspath loadScript         JavaScript加载脚本的根路径(默认值:“.”)
--exec value                执行JavaScript语句(只能结合console/attach使用)
--preload value             预加载到控制台的JavaScript文件列表(逗号分隔)

 

网络选项:

--bootnodes value    用于P2P发现引导的enode urls(逗号分隔)(对于light servers用v4+v5代替)
--bootnodesv4 value  用于P2P v4发现引导的enode urls(逗号分隔) (light server, 全节点)
--bootnodesv5 value  用于P2P v5发现引导的enode urls(逗号分隔) (light server, 轻节点)
--port value         网卡监听端口(默认值:30303)
--maxpeers value     最大的网络节点数量(如果设置为0,网络将被禁用)(默认值:25)
--maxpendpeers value    最大尝试连接的数量(如果设置为0,则将使用默认值)(默认值:0)
--nat value             NAT端口映射机制 (any|none|upnp|pmp|extip:<IP>) (默认: “any”)
--nodiscover            禁用节点发现机制(手动添加节点)
--v5disc                启用实验性的RLPx V5(Topic发现)机制
--nodekey value         P2P节点密钥文件
--nodekeyhex value      十六进制的P2P节点密钥(用于测试)

 

矿工选项:

--mine                  打开挖矿
--minerthreads value    挖矿使用的CPU线程数量(默认值:8)
--etherbase value       挖矿奖励地址(默认=第一个创建的帐户)(默认值:“0”)
--targetgaslimit value  目标gas限制:设置最低gas限制(低于这个不会被挖?) (默认值:“4712388”)
--gasprice value        挖矿接受交易的最低gas价格
--extradata value       矿工设置的额外块数据(默认=client version)

 

GAS价格选项:

--gpoblocks value      用于检查gas价格的最近块的个数  (默认: 10)
--gpopercentile value  建议gas价参考最近交易的gas价的百分位数,(默认: 50)

 

虚拟机的选项:

--vmdebug        记录VM及合约调试信息

 

日志和调试选项:

--metrics            启用metrics收集和报告
--fakepow            禁用proof-of-work验证
--verbosity value    日志详细度:0=silent, 1=error, 2=warn, 3=info, 4=debug, 5=detail (default: 3)
--vmodule value      每个模块详细度:以 <pattern>=<level>的逗号分隔列表 (比如 eth/*=6,p2p=5)
--backtrace value    请求特定日志记录堆栈跟踪 (比如 “block.go:271”)
--debug                     突出显示调用位置日志(文件名及行号)
--pprof                     启用pprof HTTP服务器
--pprofaddr value           pprof HTTP服务器监听接口(默认值:127.0.0.1)
--pprofport value           pprof HTTP服务器监听端口(默认值:6060)
--memprofilerate value      按指定频率打开memory profiling    (默认:524288)
--blockprofilerate value    按指定频率打开block profiling    (默认值:0)
--cpuprofile value          将CPU profile写入指定文件
--trace value               将execution trace写入指定文件

 

WHISPER实验选项:

--shh                        启用Whisper
--shh.maxmessagesize value   可接受的最大的消息大小 (默认值: 1048576)
--shh.pow value              可接受的最小的POW (默认值: 0.2)

 

弃用选项:

--fast     开启快速同步
--light    启用轻客户端模式

 

其他选项:

–help, -h    显示帮助

 

版权:

Copyright 2013-2017 The go-ethereum Authors

ECS挂载数据盘

运行 fdisk -l 命令查看实例是否有数据盘。

创建一个单分区数据盘,依次执行以下命令:

  1. 运行 fdisk /dev/vdb:对数据盘进行分区。
  2. 输入 n 并按回车键:创建一个新分区。
  3. 输入 p 并按回车键:选择主分区。因为创建的是一个单分区数据盘,所以只需要创建主分区。

    说明:如果要创建 4 个以上的分区,您应该创建至少一个扩展分区,即选择 e

  4. 输入分区编号并按回车键。因为这里仅创建一个分区,可以输入 1。
  5. 输入第一个可用的扇区编号:按回车键采用默认值 1(ECS是2048)。
  6. 输入最后一个扇区编号:因为这里仅创建一个分区,所以按回车键采用默认值。
  7. 输入 wq 并按回车键,开始分区。

查看新的分区:运行命令 fdisk -l。如果出现以下信息,说明已经成功创建了新分区 /dev/vdb1

在新分区上创建一个文件系统:运行命令 mkfs.ext3 /dev/vdb1

/etc/fstab 写入新分区信息:运行命令 echo /dev/vdb1 /mnt ext3 defaults 0 0 >> /etc/fstab

注意:Ubuntu 12.04 不支持 barrier,所以对该系统正确的命令是:echo '/dev/vdb1 /mnt ext3 barrier=0 0 0' >> /etc/fstab

如果需要把数据盘单独挂载到某个文件夹,比如单独用来存放网页,请将以上命令 /mnt 替换成所需的挂载点路径。

查看 /etc/fstab 中的新分区信息:运行命令 cat /etc/fstab

挂载文件系统:运行命令 mount /dev/vdb1 /mnt

查看目前磁盘空间和使用情况:运行命令 df -h。如果出现新建文件系统的信息,说明挂载成功,可以使用新的文件系统了。

vsftpd ubuntu下实践

安装:

apt-get install vsftpd

配置:

1、useradd -d /var/www test //增加用户test,并制定test用户的主目录为/var/www
2、passwd test //为test设置密码
3、更改用户相应的权限设置:

usermod -s /sbin/nologin test //限定用户test不能telnet,只能ftp
usermod -s /sbin/bash test //用户test恢复正常
usermod -d /var/www/website1 test //更改用户test的主目录为website1

4、限制用户只能访问/home/test,不能访问其他路径
chroot_list_enable=YES //限制访问自身目录
# (default follows)
chroot_list_file=/etc/vsftpd/vsftpd.chroot_list
编辑 vsftpd.chroot_list文件,将受限制的用户添加进去,每个用户名一行

对于chroot_local_user与chroot_list_enable的组合效果,可以参考下表:

chroot_local_user=YES chroot_local_user=NO
chroot_list_enable=YES 1.所有用户都被限制在其主目录下 2.使用chroot_list_file指定的用户列表,这些用户作为“例外”,不受限制 1.所有用户都不被限制其主目录下 2.使用chroot_list_file指定的用户列表,这些用户作为“例外”,受到限制
chroot_list_enable=NO 1.所有用户都被限制在其主目录下 2.不使用chroot_list_file指定的用户列表,没有任何“例外”用户 1.所有用户都不被限制其主目录下 2.不使用chroot_list_file指定的用户列表,没有任何“例外”用户

5、重启vsFTPd服务器: service vsftpd restart

错误:

vsftpd 530 Login incorrect 解决
解决:pam_service_name=vsftpd // ubuntu是pam_service_name=ftp

550 Permission denied.
解决:1). write_enable=YES
2). 设置目录权限 chmod -R 775 /var/www/website1

vsftpd: refusing to run with writable root inside chroot()
解决:vi /etc/vsftpd.conf  增加一行: allow_writeable_chroot=YES

Deploy production server on Ubuntu 14.04

Overview

  1. Setup deploy user
  2. Install Ruby
  3. Install MySQL
  4. Install Redis
  5. Install RabbitMQ
  6. Install Bitcoind
  7. Install Nginx with Passenger
  8. Install JavaScript Runtime
  9. Install ImageMagick
  10. Configure Peatio

1. 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

2. 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

3. Install MySQL

sudo apt-get install mysql-server  mysql-client  libmysqlclient-dev

4. Install Redis

Be sure to install the latest stable Redis, as the package in the distro may be a bit old:

sudo apt-add-repository -y ppa:rwky/redis
sudo apt-get update
sudo apt-get install redis-server

5. Install RabbitMQ

Please follow instructions here: https://www.rabbitmq.com/install-debian.html

curl http://www.rabbitmq.com/rabbitmq-signing-key-public.asc | sudo apt-key add -
sudo apt-add-repository 'deb http://www.rabbitmq.com/debian/ testing main'
sudo apt-get update
sudo apt-get install rabbitmq-server

sudo rabbitmq-plugins enable rabbitmq_management
sudo service rabbitmq-server restart
wget http://localhost:15672/cli/rabbitmqadmin
chmod +x rabbitmqadmin
sudo mv rabbitmqadmin /usr/local/sbin

6. Install Bitcoind

sudo add-apt-repository ppa:bitcoin/bitcoin
sudo apt-get update
sudo apt-get install bitcoind

Configure

mkdir -p ~/.bitcoin
touch ~/.bitcoin/bitcoin.conf
vim ~/.bitcoin/bitcoin.conf

Insert the following lines into the bitcoin.conf, and replce with your username and password.

server=1
daemon=1

# If run on the test network instead of the real bitcoin network
testnet=1

# You must set rpcuser and rpcpassword to secure the JSON-RPC api
# Please make rpcpassword to something secure, `5gKAgrJv8CQr2CGUhjVbBFLSj29HnE6YGXvfykHJzS3k` for example.
# Listen for JSON-RPC connections on <port> (default: 8332 or testnet: 18332)
rpcuser=INVENT_A_UNIQUE_USERNAME
rpcpassword=INVENT_A_UNIQUE_PASSWORD
rpcport=18332

# Notify when receiving coins
walletnotify=/usr/local/sbin/rabbitmqadmin publish routing_key=peatio.deposit.coin payload='{"txid":"%s", "channel_key":"satoshi"}'

Start bitcoin

bitcoind

7. Installing 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. Note that this only works for Ubuntu 14.04. For other versions of Ubuntu, you have to add the appropriate repository according to Section 2.3.1 of this link.

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;

8. 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

9. Install ImageMagick

sudo apt-get -y install imagemagick gsfonts

10. 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

  • Peatio depends on Pusher. A development key/secret pair for development/test is provided in config/application.yml(uncomment to use). PLEASE USE IT IN DEVELOPMENT/TEST ENVIRONMENT ONLY!

More details to visit pusher official website

# uncomment Pusher related settings
vim config/application.yml

Setup bitcoind rpc endpoint

# replace username:password and port with the one you set in
# username and password should only contain letters and numbers, do not use email as username
# bitcoin.conf in previous step
vim config/currencies.yml

Config database settings

vim config/database.yml

# Initialize the database and load the seed data
bundle exec rake db:setup

Precompile assets

bundle exec rake assets:precompile

Run Daemons

# start all daemons
bundle exec rake daemons:start

# or start daemon one by one
bundle exec rake daemon:matching:start
...

# Daemon trade_executor can be run concurrently, e.g. below
# line will start four trade executors, each with its own logfile.
# Default to 1.
TRADE_EXECUTOR=4 rake daemon:trade_executor:start

# You can do the same when you start all daemons:
TRADE_EXECUTOR=4 rake daemons:start

When daemons don’t work, check log/#{daemon name}.rb.output or log/peatio:amqp:#{daemon name}.output for more information (suffix is ‘.output’, not ‘.log’).

SSL Certificate setting

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

config.force_ssl = true

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

Liability Proof

# Add this rake task to your crontab so it runs regularly
RAILS_ENV=production rake solvency:liability_proof

负载均衡slb下后端服务器无法访问负载IP的问题

在阿里云SLB的一台后端服务器,今天部署了脚本,访问一直是 curl: (7) couldn’t connect to host

看了安全策略和防火墙都没问题。诡异的要死。后来问了阿里客服才知道。监听时默认的是四层协议,是不支持后端ECS服务器做为客户端访问SLB的,要想访问,只能将监听修改为七层https或者http

这里要注意下,修改是看不到这个选项的。需要删除原监听端口,再新添加前端协议时选择 http 或者 https。

 

TrustAsia DV SSL CA 在curl下失败的问题

阿里云的CA免费证书到期了,却无法购买。阿里云真是坑人。去新浪云申请了TrustAsia的免费证书,下发访问没啥问题。但是一天后发现 curl访问出现如下错误:

SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

郁闷,然后去腾讯云又重新申请了,也是TrustAsia的免费DV,下发后验证通过,curl访问也通过了。真是无语了。。。

SSLEngine on

# A self-signed (snakeoil) certificate can be created by installing
# the ssl-cert package. See
# /usr/share/doc/apache2/README.Debian.gz for more info.
# If both key and certificate are stored in the same file, only the
# SSLCertificateFile directive is needed.
SSLCertificateFile /home/cert/2018/2_yourdomain.cn.crt
SSLCertificateKeyFile /home/cert/2018/3_yourdomain.cn.key

# Server Certificate Chain:
# Point SSLCertificateChainFile at a file containing the
# concatenation of PEM encoded CA certificates which form the
# certificate chain for the server certificate. Alternatively
# the referenced file can be the same as SSLCertificateFile
# when the CA certificates are directly appended to the server
# certificate for convinience.
SSLCertificateChainFile /home/cert/2018/1_root_bundle.crt