以太坊操作入门
简介
- 以比特币为代表的第一代区块链已经稳定运行了好几年,像以太坊这样具有图灵完备,能编写智能合约功能的底层链是第二代区块链技术,下面从源码的角度,简单的操作下以太坊,包括新建用户,挖矿,转账等骚操作….
环境
- vim 8.0
- MacOs 10.13.2
- go 1.10.2(go语言版本)
安装
$ git clone https://github.com/ethereum/go-ethereum.git
cd
到go-ethereum
目录下执行如下操作:
$ make geth
geth
解释(来自官方文档):
Our main Ethereum CLI client. It is the entry point into the Ethereum network (main-, test- or private net), capable of running as a full node (default) archive node (retaining all historical state) or a light node (retrieving data live). It can be used by other processes as a gateway into the Ethereum network via JSON RPC endpoints exposed on top of HTTP, WebSocket and/or IPC transports. geth –help and the CLI Wiki page for command line options.
运行
启动测试环境
以太坊环境分
开发--dev
和测试--testnet
, 在源码中可以看到每个模块都有测试类,可以完美模拟线上的真实环境,说白了,可以不用真钱
体验里面的骚操作,那么下面的操作都是在测试
环境下进行的。创建测试文件存放目录
& mkdir ~/Desktop/ethtest
ps.后面的测试文件日志都会保存在这个目录下,其他目录自行修改
cd 到go-ethereum
目录下
- 方式1(
推荐
):
$ geth --testnet console --datadir "~/Desktop/ethtest" 2>>file_to_log_output
- 方式2(
不推荐
):
$ geth --testnet console --datadir "~/Desktop/ethtest"
原因: 方式二会把日志输出到目录file_to_log_output
中, 而不会一直持续的打印到界面上, 大家试下就知道,非常干扰操作,很难秀
起来。
- 我们可以另开一个窗口,查看
日志
文件的变化:
$ tail -f file_to_log_output
入门操作
通过上面的一套操作之后,咱们把环境搭好了,下面就愉快的
操作
起来。
- 创建账户
$ personal.newAccount('your password')
- 查看账户
$ eth.accounts
- 查看余额
$ user_one = eth.accounts[0]
$ eth.getBalance(user_one)
- 查看区块号
$ eth.blockNumber
- 启动挖矿
$ miner.start()
- 停止挖矿
$ miner.stop()
- 转账
$ eth.sendTransaction({from: 用户1,to: 用户2,value: web3.toWei(值,"单位")})
ps.后面会给例子
怎么用
- 解锁账户
$ personal.unlockAccount("账户地址", "密码")
实战
下面举个例子把这些操作连接起来,假如用户1:
小明
要转账给小王
1以太(ether), 操作过程如下:1 创建小明和小王两个账户
$ personal.newAccount('小明 password') $ personal.newAccount('小王 password')
2 查看两个账户是否存在
$ eth.accounts
3 查看当前余额(应该都是0)
$ xiaoming = eth.accounts[0] $ xiaowang = eth.accounts[1] $ eth.getBalance(xiaoming) $ eth.getBalance(xiaowang)
4 解锁小明账户
$ personal.unlockAccount(xiaoming, "小明账户密码")
5 小明一开始没钱啊,怎么转,
挖矿呗
$ miner.start()
6 在以上过程中,主要关注下开始说的日志文件
file_to_log_output
和 小明的账户余额(怎么操作上面说了), 并且发现区块号是会变的, 最后停止挖矿$ tail -f file_to_log_output $ eth.getBalance(xiaoming) $ eth.blockNumber $ miner.stop()
7 小明终于可以转账给小王了
$ eth.sendTransaction({from: xiaoming,to: xiaowang,value: web3.toWei(1,"ether")})
ps. 如果提示没解锁,重复步骤4
- 8 查看小王账户,应该发现还是0, 因为还要继续挖矿等待矿工确认
# 发现还是0 $ eth.getBalance(xiaowang) $ miner.start() # 查看file_to_log_output日志 $ miner.stop() # 发现钱到账了!!! eth.getBalance(xiaowang)