智能合约实例
接下来我们将使用geth的控制台开发一个简单的智能合约并编译部署在私链上,最后与之交互。完成这些后,我们就能对智能合约的运行机制理解得更加深刻。本例子结合了汪晓明关于以太坊的开发的演示视频和以太坊项目有关交易和合约的wiki。
打开测试网络的控制台
输入以下命令:
geth --datadir "~/ethdev" --dev console 2>> geth.log
1
显示如下:
zcc@ubuntu:~$ geth --datadir "~/ethdev" --dev console 2>> geth.log
Welcome to the Geth JavaScript console!
instance: Geth/v1.4.18-stable/linux/go1.6.2
coinbase: 0xb005804a49e73acb17d1e7645dfd0a33dde6eb0e
at block: 217 (Tue, 01 Nov 2016 05:21:38 PDT)
datadir: /home/zcc/ethdev
modules: admin:1.0 debug:1.0 eth:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 shh:1.0 txpool:1.0 web3:1.0
这样我们就打开了测试网的控制台,之后的步骤如无特别说明都将在控制台中完成。
检查编译器
我们接下来的智能合约的例子是使用solidity语言开发的。因此,至此之前我们要确保solidity编译器已经正确安装了。输入以下命令检查:
eth.getCompilers()
["Solidity"]
1
2
我们发现solidity的编译器已经正确安装了。如果返回值为空数组,那么输入以下命令安装:
sudo add-apt-repository ppa:ethereum/ethereum
sudo apt-get update
sudo apt-get install solc
1
2
3
如果输入第一条命令的时候返回错误,请尝试重启系统。
编写智能合约
我们编写一个求解与7相乘结果的函数,即输入一个值a,返回a*7的值。
source = "contract test { function multiply(uint a) returns(uint d) { return a * 7; }}"
"contract test { function multiply(uint a) returns(uint d) { return a * 7; }}"
1
2
编译智能合约
contract = eth.compile.solidity(source).test
{
code: "0x606060405260388060106000396000f3606060405260e060020a6000350463c6888fa18114601c575b6002565b3460025760076004350260408051918252519081900360200190f3",
info: {
abiDefinition: [{
constant: false,
inputs: [...],
name: "multiply",
outputs: [...],
payable: false,
type: "function"
}],
compilerOptions: "--bin --abi --userdoc --devdoc --add-std --optimize -o /tmp/solc359648392",
compilerVersion: "0.4.3",
developerDoc: {
methods: {}
},
language: "Solidity",
languageVersion: "0.4.3",
source: "contract test { function multiply(uint a) returns(uint d) { return a * 7; }}",
userDoc: {
methods: {}
}
}
}
准备一个创建合约的账户
在以太坊上创建智能合约就是使用一个外部账户(EOA)向区块链中发送一个交易。因此,我们需要准备一个有余额并被激活的以太坊外部账户。
查看是否有可用账户:
personal.listAccounts
[]
返回为空,说明没有可用账户。创建一个外部账户:personal.newAccount('123456')
"0x62b1746767522b36f6421e630fa0198151d72964"
注意:personal.newAccount()函数里的参数是账号密码,返回值是创建的新账号地址。
这个时候,我们再次使用personal.listAccounts命令查看可用账户:
personal.listAccounts
["0x62b1746767522b36f6421e630fa0198151d72964"]
我们看到函数返回值为一个数组,数组目前只有一个元素,就是我们刚才创建的账号。
我们查看一下刚才创建的账户余额:
web3.eth.getBalance(personal.listAccounts[0])
返回值为0,说明新创建的账户没有以太币。这个时候我们就可以开启挖矿来获得以太币。
首先开启挖矿:
miner.start()
true
为了检测挖矿的状态,我们可以再另开起一个终端用于检测挖矿的状态。在新开起的终端中输入以下命令实时显示挖矿的状态:
tail -f geth.log
这样我们就能看到如下所示的挖矿状态:
zcc@ubuntu:~$ tail -f geth.log
I1102 10:10:21.382666 eth/backend.go:201] Blockchain DB Version: 3
I1102 10:10:21.382691 eth/backend.go:226] ethash used in test mode
I1102 10:10:21.384471 core/blockchain.go:214] Last header: #219 [7a2335e9…] TD=28838912
I1102 10:10:21.384501 core/blockchain.go:215] Last block: #219 [7a2335e9…] TD=28838912
I1102 10:10:21.384507 core/blockchain.go:216] Fast block: #219 [7a2335e9…] TD=28838912
I1102 10:10:21.389663 p2p/server.go:313] Starting Server
I1102 10:10:23.428074 p2p/discover/udp.go:217] Listening, enode://c7afa32e281c06bb529b9c0f0d9537ab4386cac1b2ba7de6bd777bdb15e3b7d0cbd260fc57f82b8f33b0c0ff83772b7d4da7c68017f8e05a2c08c77754d6ed62@[::]:39428
I1102 10:10:23.429805 whisper/whisper.go:176] Whisper started
I1102 10:10:23.439973 p2p/server.go:556] Listening on [::]:46364
I1102 10:10:23.440985 node/node.go:296] IPC endpoint opened: /home/zcc/ethdev/geth.ipc
I1102 10:13:11.541025 miner/miner.go:119] Starting mining operation (CPU=1 TOT=2)
I1102 10:13:11.541389 miner/worker.go:539] commit new work on block 220 with 0 txs & 0 uncles. Took 196.057µs
I1102 10:13:11.541464 ethash.go:259] Generating DAG for epoch 0 (size 32768) (0000000000000000000000000000000000000000000000000000000000000000)
I1102 10:13:11.541625 ethash.go:291] Generating DAG: 0%
I1102 10:13:11.541678 ethash.go:291] Generating DAG: 1%
I1102 10:13:11.541716 ethash.go:291] Generating DAG: 2%
I1102 10:13:11.541751 ethash.go:291] Generating DAG: 3%
I1102 10:13:11.541787 ethash.go:291] Generating DAG: 4%
I1102 10:13:11.541822 ethash.go:291] Generating DAG: 5%
...
I1102 10:13:11.547403 ethash.go:291] Generating DAG: 95%
I1102 10:13:11.547450 ethash.go:291] Generating DAG: 96%
I1102 10:13:11.547497 ethash.go:291] Generating DAG: 97%
I1102 10:13:11.547543 ethash.go:291] Generating DAG: 98%
I1102 10:13:11.547590 ethash.go:291] Generating DAG: 99%
I1102 10:13:11.547646 ethash.go:291] Generating DAG: 100%
I1102 10:13:11.547691 ethash.go:276] Done generating DAG for epoch 0, it took 6.229048ms
I1102 10:13:11.548248 eth/backend.go:454] Automatic pregeneration of ethash DAG ON (ethash dir: /home/zcc/.ethash)
I1102 10:13:11.548375 eth/backend.go:461] checking DAG (ethash dir: /home/zcc/.ethash)
I1102 10:13:24.938687 miner/worker.go:342] �� Mined block (#220 / 1fdebe6d). Wait 5 blocks for confirmation
I1102 10:13:24.938953 miner/worker.go:539] commit new work on block 221 with 0 txs & 0 uncles. Took 86.067µs
I1102 10:13:24.939156 miner/worker.go:539] commit new work on block 221 with 0 txs & 0 uncles. Took 66.063µs
I1102 10:13:29.874128 miner/worker.go:342] �� Mined block (#221 / ff995b19). Wait 5 blocks for confirmation
因为我之前已经挖过矿了,所以可以看到现在开始挖的区块编号为220。
再次使用web3.eth.getBalance(personal.listAccounts[0])命令来查看新建立的账号的余额:
web3.eth.getBalance(personal.listAccounts[0])
65000000000000000000
这时我们看到当前账户余额为6.5e19wei,即65ether。我们可以参看Denominations来互相转换以太币的几种单位。
至此,用于创建合约的外部账户已经准备完毕。
指定创建合约的外部账户
我们首先需要从当前的账户里选择一个作为创建智能合约的外部账户:
address = eth.accounts[0]
"0x62b1746767522b36f6421e630fa0198151d72964"
1
2
然后将该账户激活:personal.unlockAccount(address)
Unlock account 0x62b1746767522b36f6421e630fa0198151d72964
Passphrase:
true
我们在使用personal.unlockAccount()函数的时候,可以选择指定一个解锁时间(以秒为单位),超出这个时间后会自动上锁。如果不指定的话,那么用户的账户就会在一定时间后自动上锁。例如:
personal.unlockAccount(address,'123456',10000)
true
personal.unlockAccount()函数里第一个参数是要解锁的账户,第二个参数是账号密码,第三个是需要解锁的时间。在这个例子中,我们设定在10000秒内账户都处于激活状态。设定账号的解锁时间是个好方式,尤其是之后我们需要使用这个账号再次进行交易操作时,这样就省去了再次解锁账号的麻烦。不过,解锁时间不应设定过长,否则可能有安全隐患。
部署合约
部署合约就是将编译好的合约字节码通过外部账号发送交易的形式部署到以太坊区块链上。输入以下命令:
abi = [{constant:false,inputs:{name:'a',type:'uint256'}}]
[{
constant: false,
inputs: {
name: "a",
type: "uint256"
}
}]
MyContract = eth.contract(abi)
{
abi: [{
constant: false,
inputs: {
name: "a",
type: "uint256"
}
}],
eth: {
accounts: ["0x62b1746767522b36f6421e630fa0198151d72964"],
blockNumber: 292,
coinbase: "0x62b1746767522b36f6421e630fa0198151d72964",
compile: {
lll: function(),
serpent: function(),
solidity: function()
},
defaultAccount: undefined,
defaultBlock: "latest",
gasPrice: 20000000000,
hashrate: 3498,
mining: true,
pendingTransactions: [],
syncing: false,
call: function(),
contract: function(abi),
estimateGas: function(),
filter: function(fil, callback),
getAccounts: function(callback),
getBalance: function(),
getBlock: function(),
getBlockNumber: function(callback),
getBlockTransactionCount: function(),
getBlockUncleCount: function(),
getCode: function(),
getCoinbase: function(callback),
getCompilers: function(),
getGasPrice: function(callback),
getHashrate: function(callback),
getMining: function(callback),
getNatSpec: function(),
getPendingTransactions: function(callback),
getStorageAt: function(),
getSyncing: function(callback),
getTransaction: function(),
getTransactionCount: function(),
getTransactionFromBlock: function(),
getTransactionReceipt: function(),
getUncle: function(),
getWork: function(),
iban: function(iban),
icapNamereg: function(),
isSyncing: function(callback),
namereg: function(),
resend: function(),
sendIBANTransaction: function(),
sendRawTransaction: function(),
sendTransaction: function(),
sign: function(),
signTransaction: function(),
submitTransaction: function(),
submitWork: function()
},
at: function(address, callback),
getData: function(),
new: function()
}
myContract = MyContract.new({from:address,data:contract.code})
{
abi: [{
constant: false,
inputs: {
name: "a",
type: "uint256"
}
}],
address: undefined,
transactionHash: "0xd10602e2099ab5873c762f070eb90a9fd559270484fbcebd4170d441848b9232"
}
这时,我们可以检查一下交易池,查看当前交易的待处理状况:
txpool.status
{
pending: 1,
queued: 0
}
我们可以看到当前的交易池中有一个交易正在等待确认。然后,我们查看待确认交易的详细内容:eth.getBlock("pending",true).transactions
[{
blockHash: "0x0299731121321b817206fb07187f94cd4537e3196e940b45e95b4e1709aadbf4",
blockNumber: 294,
from: "0x62b1746767522b36f6421e630fa0198151d72964",
gas: 90000,
gasPrice: 20000000000,
hash: "0xd10602e2099ab5873c762f070eb90a9fd559270484fbcebd4170d441848b9232",
input: "0x606060405260388060106000396000f3606060405260e060020a6000350463c6888fa18114601c575b6002565b3460025760076004350260408051918252519081900360200190f3",
nonce: 0,
to: null,
transactionIndex: 0,
value: 0
}]
我们从显示出来的结果可以看出当前交易的一些内容。例如,from数据项就是我们发送交易的地址,input就是合约编译完成的字节码,这些内容均与我们之前的设定相同。而且,我们可以看到新的交易创建在第294号区块中。
与此同时,我们也可以查看一下刚才在新的终端中创建的挖矿日志。我们在日志中找到这样的一行信息:
I1102 11:37:46.573298 eth/api.go:1183] Tx(0xd10602e2099ab5873c762f070eb90a9fd559270484fbcebd4170d441848b9232) created: 0x115ced3f8b7ea92d324902e3a3a421a07540eb2b
1
这说明交易已经发送到区块链中了,正在等待矿工的确认。