区块链学习(四)truffle部署编译智能合约以太坊私有链

前面我们介绍了以太坊私有链的搭建以及多节点私有链网络,这次我们介绍如何使用truffle框架来部署编译智能合约到我们之前搭建的私有链网络中。

搭建环境及需使用的工具:ubuntu18.04  Truffle v5.0.18  geth 1.8.27  Node v10.16.0

solc  0.5.8+commit.23d335f2.Linux.g++

在我们部署一个简单的合约之前,我们先介绍一些相关的知识。

一、geth 启动节点参数介绍

geth 当中有许多指令,因为之后私有链节点启动需要设置一些参数,我们重点介绍这些:

参数 参数详解
datadir 指明当前区块链私钥和网络数据存放的位置
rpc  开启http-rpc服务,可以进行智能合约的部署和调试
rpcaddr 指定http-rpc服务监听地址,默认为"localhost"
rpcport 指定http-rpc服务监听端口,默认为8545
rpccorsdomain 表示任何链接都可以连接到此节点
rpcapi 设置允许连接的rpc的客户端,一般为db,eth,net,web3
nodiscover 关闭自动连接节点,但是可以手动添加节点,在搭建私有链的时候,为避免其他节点连入私有链,可以使用该命令
maxpeers 设置允许最大连节点数,默认25
networkid 指定以太坊网络id,共有链为1,测试链为3,默认启动1
port 指定以太坊网络监听端口,默认为30303
mine 开启挖矿,默认为cpu挖矿
minerthreads 挖矿占用cpu线程数,默认为4,现命名为miner.threads
etherbase 指定矿工账号
console 启动命令行模式,可以在geth中执行命令

我们可以在终端输入geth -v来查看geth的全部指令

 milo@milo-K46CB:~$ geth -v
Incorrect Usage. flag provided but not defined: -v NAME:
geth - the go-ethereum command line interface Copyright 2013-2018 The go-ethereum Authors USAGE:
geth [options] command [command options] [arguments...] VERSION:
1.8.27-stable-4bcc0a37 COMMANDS:
account Manage accounts
attach Start an interactive JavaScript environment (connect to node)
bug opens a window to report a bug on the geth repo
console Start an interactive JavaScript environment
copydb Create a local chain from a target chaindata folder
dump Dump a specific block from storage
dumpconfig Show configuration values
export Export blockchain into file
export-preimages Export the preimage database into an RLP stream
import Import a blockchain file
import-preimages Import the preimage database from an RLP stream
init Bootstrap and initialize a new genesis block
js Execute the specified JavaScript files
license Display license information
makecache Generate ethash verification cache (for testing)
makedag Generate ethash mining DAG (for testing)
monitor Monitor and visualize node metrics
removedb Remove blockchain and state databases
version Print version numbers
wallet Manage Ethereum presale wallets
help, h Shows a list of commands or help for one command ETHEREUM OPTIONS:
--config value TOML configuration file
--datadir "/home/milo/.ethereum" Data directory for the databases and keystore
--keystore Directory for the keystore (default = inside the datadir)
--nousb Disables monitoring for and managing USB hardware wallets
--networkid value Network identifier (integer, 1=Frontier, 2=Morden (disused), 3=Ropsten, 4=Rinkeby) (default: 1)
--testnet Ropsten network: pre-configured proof-of-work test network
--rinkeby Rinkeby network: pre-configured proof-of-authority test network
--goerli Görli network: pre-configured proof-of-authority test network
--syncmode "fast" Blockchain sync mode ("fast", "full", or "light")
--gcmode value Blockchain garbage collection mode ("full", "archive") (default: "full")
--ethstats value Reporting URL of a ethstats service (nodename:secret@host:port)
--identity value Custom node name
--lightserv value Maximum percentage of time allowed for serving LES requests (0-90) (default: 0)
--lightpeers value Maximum number of LES client peers (default: 100)
--lightkdf Reduce key-derivation RAM & CPU usage at some expense of KDF strength
--whitelist value Comma separated block number-to-hash mappings to enforce (<number>=<hash>) DEVELOPER CHAIN OPTIONS:
--dev Ephemeral proof-of-authority network with a pre-funded developer account, mining enabled
--dev.period value Block period to use in developer mode (0 = mine only if transaction pending) (default: 0) ETHASH OPTIONS:
--ethash.cachedir Directory to store the ethash verification caches (default = inside the datadir)
--ethash.cachesinmem value Number of recent ethash caches to keep in memory (16MB each) (default: 2)
--ethash.cachesondisk value Number of recent ethash caches to keep on disk (16MB each) (default: 3)
--ethash.dagdir "/home/milo/.ethash" Directory to store the ethash mining DAGs (default = inside home folder)
--ethash.dagsinmem value Number of recent ethash mining DAGs to keep in memory (1+GB each) (default: 1)
--ethash.dagsondisk value Number of recent ethash mining DAGs to keep on disk (1+GB each) (default: 2) TRANSACTION POOL OPTIONS:
--txpool.locals value Comma separated accounts to treat as locals (no flush, priority inclusion)
--txpool.nolocals Disables price exemptions for locally submitted transactions
--txpool.journal value Disk journal for local transaction to survive node restarts (default: "transactions.rlp")
--txpool.rejournal value Time interval to regenerate the local transaction journal (default: 1h0m0s)
--txpool.pricelimit value Minimum gas price limit to enforce for acceptance into the pool (default: 1)
--txpool.pricebump value Price bump percentage to replace an already existing transaction (default: 10)
--txpool.accountslots value Minimum number of executable transaction slots guaranteed per account (default: 16)
--txpool.globalslots value Maximum number of executable transaction slots for all accounts (default: 4096)
--txpool.accountqueue value Maximum number of non-executable transaction slots permitted per account (default: 64)
--txpool.globalqueue value Maximum number of non-executable transaction slots for all accounts (default: 1024)
--txpool.lifetime value Maximum amount of time non-executable transaction are queued (default: 3h0m0s) PERFORMANCE TUNING OPTIONS:
--cache value Megabytes of memory allocated to internal caching (default: 1024)
--cache.database value Percentage of cache memory allowance to use for database io (default: 50)
--cache.trie value Percentage of cache memory allowance to use for trie caching (default: 25)
--cache.gc value Percentage of cache memory allowance to use for trie pruning (default: 25)
--trie-cache-gens value Number of trie node generations to keep in memory (default: 120) ACCOUNT OPTIONS:
--unlock value Comma separated list of accounts to unlock
--password value Password file to use for non-interactive password input API AND CONSOLE OPTIONS:
--rpc Enable the HTTP-RPC server
--rpcaddr value HTTP-RPC server listening interface (default: "localhost")
--rpcport value HTTP-RPC server listening port (default: 8545)
--rpcapi value API's offered over the HTTP-RPC interface
--rpc.gascap value Sets a cap on gas that can be used in eth_call/estimateGas (default: 0)
--ws Enable the WS-RPC server
--wsaddr value WS-RPC server listening interface (default: "localhost")
--wsport value WS-RPC server listening port (default: 8546)
--wsapi value API's offered over the WS-RPC interface
--wsorigins value Origins from which to accept websockets requests
--ipcdisable Disable the IPC-RPC server
--ipcpath Filename for IPC socket/pipe within the datadir (explicit paths escape it)
--rpccorsdomain value Comma separated list of domains from which to accept cross origin requests (browser enforced)
--rpcvhosts value Comma separated list of virtual hostnames from which to accept requests (server enforced). Accepts '*' wildcard. (default: "localhost")
--jspath loadScript JavaScript root path for loadScript (default: ".")
--exec value Execute JavaScript statement
--preload value Comma separated list of JavaScript files to preload into the console NETWORKING OPTIONS:
--bootnodes value Comma separated enode URLs for P2P discovery bootstrap (set v4+v5 instead for light servers)
--bootnodesv4 value Comma separated enode URLs for P2P v4 discovery bootstrap (light server, full nodes)
--bootnodesv5 value Comma separated enode URLs for P2P v5 discovery bootstrap (light server, light nodes)
--port value Network listening port (default: 30303)
--maxpeers value Maximum number of network peers (network disabled if set to 0) (default: 25)
--maxpendpeers value Maximum number of pending connection attempts (defaults used if set to 0) (default: 0)
--nat value NAT port mapping mechanism (any|none|upnp|pmp|extip:<IP>) (default: "any")
--nodiscover Disables the peer discovery mechanism (manual peer addition)
--v5disc Enables the experimental RLPx V5 (Topic Discovery) mechanism
--netrestrict value Restricts network communication to the given IP networks (CIDR masks)
--nodekey value P2P node key file
--nodekeyhex value P2P node key as hex (for testing) MINER OPTIONS:
--mine Enable mining
--miner.threads value Number of CPU threads to use for mining (default: 0)
--miner.notify value Comma separated HTTP URL list to notify of new work packages
--miner.gasprice "" Minimum gas price for mining a transaction
--miner.gastarget value Target gas floor for mined blocks (default: 8000000)
--miner.gaslimit value Target gas ceiling for mined blocks (default: 8000000)
--miner.etherbase value Public address for block mining rewards (default = first account) (default: "")
--miner.extradata value Block extra data set by the miner (default = client version)
--miner.recommit value Time interval to recreate the block being mined (default: 3s)
--miner.noverify Disable remote sealing verification GAS PRICE ORACLE OPTIONS:
--gpoblocks value Number of recent blocks to check for gas prices (default: 20)
--gpopercentile value Suggested gas price is the given percentile of a set of recent transaction gas prices (default: 60) VIRTUAL MACHINE OPTIONS:
--vmdebug Record information useful for VM and contract debugging
--vm.evm value External EVM configuration (default = built-in interpreter)
--vm.ewasm value External ewasm configuration (default = built-in interpreter) LOGGING AND DEBUGGING OPTIONS:
--fakepow Disables proof-of-work verification
--nocompaction Disables db compaction after import
--verbosity value Logging verbosity: 0=silent, 1=error, 2=warn, 3=info, 4=debug, 5=detail (default: 3)
--vmodule value Per-module verbosity: comma-separated list of <pattern>=<level> (e.g. eth/*=5,p2p=4)
--backtrace value Request a stack trace at a specific logging statement (e.g. "block.go:271")
--debug Prepends log messages with call-site location (file and line number)
--pprof Enable the pprof HTTP server
--pprofaddr value pprof HTTP server listening interface (default: "127.0.0.1")
--pprofport value pprof HTTP server listening port (default: 6060)
--memprofilerate value Turn on memory profiling with the given rate (default: 524288)
--blockprofilerate value Turn on block profiling with the given rate (default: 0)
--cpuprofile value Write CPU profile to the given file
--trace value Write execution trace to the given file METRICS AND STATS OPTIONS:
--metrics Enable metrics collection and reporting
--metrics.influxdb Enable metrics export/push to an external InfluxDB database
--metrics.influxdb.endpoint value InfluxDB API endpoint to report metrics to (default: "http://localhost:8086")
--metrics.influxdb.database value InfluxDB database name to push reported metrics to (default: "geth")
--metrics.influxdb.username value Username to authorize access to the database (default: "test")
--metrics.influxdb.password value Password to authorize access to the database (default: "test")
--metrics.influxdb.tags value Comma-separated InfluxDB tags (key/values) attached to all measurements (default: "host=localhost") WHISPER (EXPERIMENTAL) OPTIONS:
--shh Enable Whisper
--shh.maxmessagesize value Max message size accepted (default: 1048576)
--shh.pow value Minimum POW accepted (default: 0.2)
--shh.restrict-light Restrict connection between two whisper light clients DEPRECATED OPTIONS:
--minerthreads value Number of CPU threads to use for mining (deprecated, use --miner.threads) (default: 0)
--targetgaslimit value Target gas floor for mined blocks (deprecated, use --miner.gastarget) (default: 8000000)
--gasprice "" Minimum gas price for mining a transaction (deprecated, use --miner.gasprice)
--etherbase value Public address for block mining rewards (default = first account, deprecated, use --miner.etherbase) (default: "")
--extradata value Block extra data set by the miner (default = client version, deprecated, use --miner.extradata) MISC OPTIONS:
--override.constantinople value Manually specify constantinople fork-block, overriding the bundled setting (default: 0)
--help, -h show help COPYRIGHT:
Copyright 2013-2018 The go-ethereum Authors

二、truffle框架介绍

终端输入truffle -v

 milo@milo-K46CB:~$ truffle -v
Truffle v5.0.18 - a development framework for Ethereum Usage: truffle <command> [options] Commands:
build Execute build pipeline (if configuration present)
compile Compile contract source files
config Set user-level configuration options
console Run a console with contract abstractions and commands available
create Helper to create new contracts, migrations and tests
debug Interactively debug any transaction on the blockchain (experimental)
deploy (alias for migrate)
develop Open a console with a local development blockchain
exec Execute a JS module within this Truffle environment
help List all commands or provide information about a specific command
init Initialize new and empty Ethereum project
install Install a package from the Ethereum Package Registry
migrate Run migrations to deploy contracts
networks Show addresses for deployed contracts on each network
obtain Fetch and cache a specified compiler
opcode Print the compiled opcodes for a given contract
publish Publish a package to the Ethereum Package Registry
run Run a third-party command
test Run JavaScript and Solidity tests
unbox Download a Truffle Box, a pre-built Truffle project
version Show version number and exit
watch Watch filesystem for changes and rebuild the project automatically

truffle是一套以太坊的开发测试框架,使用solidity开发语言,类似于javascript

这里我们就不将truffle的安装了

下面进入主要内容

三、启动私有链节点

进入私有链文件夹打开一个终端,后面我们以终端1代指它,在终端1输入以下命令

 milo@milo-K46CB:~/private-geth$ geth --rpc --rpccorsdomain "*" --datadir ./data/00 --port 61910 --rpcport 8545 --rpcapi "db,eth,net,web3" --networkid 100  console

需要注意的是我们这里的启动节点命令与之前我们搭建的节点启动命令略有不同,其中:

--rpc是开启http-rpc服务,可以进行智能合约的部署和调试

--rpccorsdomain "*"表示任何链接都可以连接到此节点

--port 指定以太坊网络监听端口,默认为30303,这里随意选一个就好

--rpcport是指定http-rpc服务监听端口,默认为8545,但也可以自己更改,这里我们就用8545

(敲黑板,这里有个重点,我们这里设置的rpcport要与之后truffle-config.js文件中的port相对应)

--rpcapi是设置允许连接的rpc的客户端,一般为db,eth,net,web3,貌似这里也可以不用加

四、truffle合约编译部署

1、首先我们创建一个项目文件夹truffle_Project,然后打开一个新的终端,之后我们我们用终端2代之它,在终端2输入以下命令创建文件夹并初始化truffle环境

 milo@milo-K46CB:~$ mkdir truffleProject
milo@milo-K46CB:~$ cd truffleProject/
milo@milo-K46CB:~/truffleProject$ truffle init

输出以下结果:

 ✔ Preparing to download
✔ Downloading
✔ Cleaning up temporary files
✔ Setting up box Unbox successful. Sweet! Commands: Compile: truffle compile
Migrate: truffle migrate
Test contracts: truffle test

经过初始化后,我们创建的truffle_Project文件夹下会多出contracts,migrations,test三个文件夹和treffle_config.js文件

2、编写合约

进入到contracts文件夹中,我们建立一个简单的智能合约Test.sol,在端口2输入以下命令

 milo@milo-K46CB:~/truffleProject$ cd contracts/
milo@milo-K46CB:~/truffleProject/contracts$ vim Test.sol

输入以上命令出现以下结果:

区块链学习(四)truffle部署编译智能合约以太坊私有链输入以下内容到文件内,wq保存退出

pragma solidity ^0.5.0;
contract Test {
function multiply(uint a) pure public returns(uint d) {
return a * 7;
}
}

3、修改配置

终端输入指令进入migrateions文件中,创建2_deploy_contracys.js文件,具体操作如下:

 milo@milo-K46CB:~/truffleProgect$ cd migrations/
milo@milo-K46CB:~/truffleProgect/migrations$ vim 2_deploy_contracys.js

输入以下内容:

 var Test = artifacts.require("./Test.sol");

 module.exports = function(deployer) {
deployer.deploy(Test);
};

之后我们在回到trifflr_Project文件夹,修改truffle-config.js文件,如下

 milo@milo-K46CB:~/truffleProgect$ vim truffle-config.js
  networks: {
live: {
host: "localhost", //本地地址,因为是在本机上建立的节点
port: 8545, //Ethereum的rpc监听的端口号,默认是8545
network_id: 100 // 自定义网络号
}

此处的port要与启动节点参数rpcport相同

4、编译

输入以下指令进行合约编译

milo@milo-K46CB:~/truffleProject$ truffle compile

编译成功输出以下结果:

 Compiling your contracts...
===========================
> Compiling ./contracts/Test.sol
> Artifacts written to /home/milo/truffleProgect/build/contracts
> Compiled successfully using:
- solc: 0.5.0+commit.1d4f565a.Emscripten.clang

这个时候我们就准备将合约部署到区块链中了,之前我们已经在终端1开启了私有链节点,在部署前,我们最好先开始挖矿,因为有有可能挖出矿的时间太长超过部署时间导致部署失败,在终端1输入:

 > miner.start(3)
INFO [06-30|14:41:52.571] Updated mining threads threads=3
INFO [06-30|14:41:52.571] Transaction pool price threshold updated price=1000000000
INFO [06-30|14:56:17.263] Commit new mining work number=57 sealhash=8af97d…82bbb5 uncles=0 txs=1 gas=284908 fees=0.00569816 elapsed=29.717ms

然后我们在到终端2输入以下命令开始部署:

 milo@milo-K46CB:~/truffleProject$ truffle migrate --network live

此时终端1会出现:

 INFO [06-30|14:56:15.134] Submitted contract creation              
fullhash=0xf429d7cb5f31287af7328ad699c883ddabc346c03d778dbd3adc100de4d53967 contract=0x66C64c5dcacE473aD26497781df1E63d6Dd95688

输入部署命令后,当挖到一个矿时,成功时会出现以下结果:

 Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile. Starting migrations...
======================
> Network name: 'live'
> Network id: 100
> Block gas limit: 0xf25e94c2 1_initial_migration.js
====================== Deploying 'Migrations'
----------------------
> transaction hash: 0xf429d7cb5f31287af7328ad699c883ddabc346c03d778dbd3adc100de4d53967
> Blocks: 1 Seconds: 554
> contract address: 0x66C64c5dcacE473aD26497781df1E63d6Dd95688
> block number: 57
> block timestamp: 1561877762
> account: 0x8830397771710ADE101f0080f0da076181Bad374
> balance: 284
> gas used: 284908
> gas price: 20 gwei
> value sent: 0 ETH
> total cost: 0.00569816 ETH ⠦ Saving migration to chain.

需要注意的是这个时候我们需要继续挖矿才能往下进行,只有挖到新的区块才能将合约部署到区块中

终端1:

 INFO [06-30|14:56:17.263] Commit new mining work                   number=57 sealhash=8af97d…82bbb5 uncles=0 txs=1 gas=284908 fees=0.00569816 elapsed=29.717ms
INFO [06-30|15:05:26.447] Successfully sealed new block number=57 sealhash=8af97d…82bbb5 hash=f75699…3cd3f8 elapsed=9m9.184s
INFO [06-30|15:05:26.645]
上一篇:DirectX 11游戏编程学习笔记之8: 第6章Drawing in Direct3D(在Direct3D中绘制)(习题解答)


下一篇:boos直聘扫码直接登陆js代码