你離區塊鏈智能合約開發只有一句docker-compose的距離

引言

你須要知道區塊鏈的概念及實現一個無需信任的電子貨幣的運做原理。能夠先看看長版,若是你以爲太長,能夠看看短版git

你須要準備什麼

一個 docker 環境, 還有…… 沒了github

注:Mac下docker集成了docker-compose,其餘系統須要安裝docker-composeweb

開發環境架構

  • Ganache:以太坊測試網絡, 使用Ganache,您能夠快速查看應用程序如何影響區塊鏈,並反應您的賬戶,餘額,合同建立和Gas等詳細信息。
  • Geth:在以太坊智能合約開發中最經常使用的工具(必備開發工具),一個多用途的命令行工具。
  • Truffle:Truffle是Dapp開發框架,他能夠幫咱們處理掉大量可有可無的小事情,讓咱們能夠迅速開始寫代碼-編譯-部署-測試-打包DApp這個流程。

一步搭建智能合約開發環境

$ git clone --branch v1.0 --depth=1 https://github.com/gengxiankun/dockerfiles.git &&\
 docker-compose -f dockerfiles/ethereum/ethereum-stack-compose.yml up -d
複製代碼

因爲須要分別構建(ganache/geth/truffle)三個容器,請耐心等待。 執行成功後,查看以太坊容器:docker

$ 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容器均已運行,證實環境搭建成功了!網絡

瞭解docker-compose.yaml文件再進行開發

以上,咱們能夠看出構建了三個容器來分別運行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鏈接:app

#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開發智能合約了!tcp

相關文章
相關標籤/搜索