预备知识
你需要知道区块链的概念及实现一个无需信任的电子货币的运作原理. 可以先看看长版 https://www.youtube.com/watch?v=bBC-nXj3Ng4 , 如果你觉得太长, 可以看看短版 https://www.youtube.com/watch?v=l9jOJk30eQs .
以太坊是什么 https://www.cnblogs.com/tinyxiong/p/7878468.html
系统准备
因为 docker 的跨平台特性, 所以可以在主流的 win/linux/macos 上搭建智能合约的开发环境. 点击此链接安装 https://download.docker.com/ .
Compose 是定义和运行多容器 Docker 应用程序的工具. 使用 Compose, 您可以使用 YAML 文件来配置应用程序的服务. 然后, 使用单个命令, 您可以创建并启动配置中的所有服务. 您可以访问 Install Compose https://docs.docker.com/compose/install/#install-compose , 来为您的环境安装 docker-compose.
开发环境架构
Ganache: 以太坊测试网络, 使用 Ganache, 您可以快速查看应用程序如何影响区块链, 并反应您的帐户, 余额, 合同创建和 Gas 等详细信息.
Geth: 在以太坊智能合约开发中最常用的工具(必备开发工具), 一个多用途的命令行工具.
Truffle:Truffle 是 Dapp 开发框架, 他可以帮我们处理掉大量无关紧要的小事情, 让我们可以迅速开始写代码 - 编译 - 部署 - 测试 - 打包 DApp 这个流程.
一步搭建智能合约开发环境
$ git clone --depth=1 https://github.com/gengxiankun/dockerfiles.git &&\
docker-compose -f dockerfiles/ethereum/ethereum-stack-compose.yml up -d
由于需要分别构建 (ganache/geth/truffle) 三个容器, 请耐心等待. 执行成功后, 查看以太坊容器:
$ docker-compose -f dockerfiles/ethereum/ethereum-stack-compose.yml ps
Name Command State Ports
- -------------------------------------------------------------------------
- ganache docker-entrypoint.sh Up 0.0.0.0:7454->7454/tcp, 9454/tcp
geth /usr/sbin/init Up
truffle /usr/sbin/init Up
可以看到, truffle,ganache 及 geth 容器均已运行, 证明环境搭建成功了!
了解这些再进行开发
以上, 我们可以看出构建了三个容器来分别运行 ganache,geth 及 truffle. 通过
dockerfiles/ethereum/ethereum-stack-compose.yml
来看一下它们是如何相互运作的:
$ cat dockerfiles/ethereum/ethereum-stack-compose.yml
- version: '2'
- services:
- ganache:
- container_name: ganache
- build: ./Ganache/
- expose:
- - "7454"
- ports:
- - "7454:7454"
- environment:
- - NETWORKID=6
- - PORT=7454
- restart: always
- truffle:
- container_name: truffle
- build: ./Truffle/
- volumes:
- - ~/data/ethereum/:/data/
- working_dir: /data
- links:
- - ganache:ganache
- restart: always
- geth:
- container_name: geth
- build: ./Geth/
- restart: always
- links:
- - ganache:ganache
可以看到, Ganache 开放出了 network_id 为 6, 端口是 7454 的以太坊网络接口 triffle 及 geth 通过 docker 内部链路 links 连接 ganache 服务, 直接访问 host 为 ganache 无序指定 IP, 比如 truffle 的网络配置及 geth 连接:
- #truffle.js
- module.exports = {
- networks: {
- development: {
- host: "ganache",
- port: 7454,
- network_id: "6" // Match any network id
- }
- }
- };
- #geth 连接本地 ganache 网络
- $ docker exec -it geth geth attach http://ganache:7454
- Welcome to the Geth JavaScript console!
- instance: EthereumJS TestRPC/v2.1.0/ethereum-js
- coinbase: 0xd08734d6ca10a2acb464d26ed033df08dd93acc3
- at block: 0 (Sun, 15 Apr 2018 03:54:12 UTC)
- modules: eth:1.0 evm:1.0 net:1.0 personal:1.0 rpc:1.0 web3:1.0
- >
truffle 容器的工作目录 / data 与本地的~/data/ethereum 目录挂载, 执行 truffle 初始化, 可以看到本地同步了容器的代码:
$ docker exec -it truffle truffle init
$ cd ~/data/ethereum
- $ tree
- .
- contracts
- Migrations.sol
- migrations
- 1_initial_migration.js
- test
truffle-config.js
truffle.js
3 directories, 4 files
如此, 便可方便的在本地使用 IDE 开发智能合约了!
来源: https://juejin.im/post/5ad2da0e6fb9a028c8134d29