零起點玩轉基於以太坊的聯盟鏈Quorum系列02

作者: 魏緒文 
編輯:KC

零起點玩轉基於以太坊的聯盟鏈Quorum系列02

 : 上一節未完成了本地3結點網絡的搭建工作, 基於raft共識模式. 本節主要講解在3結點網絡上的完成智能合約的部署與測試

智能合約

一個簡單的智能合約實現

pragma solidity ^0.4.17;

contract SimpleStorage {
    uint public storedData;

    function SimpleStorage(uint initVal) public {
        storedData = initVal;
    }

    function set(uint x) public {
        storedData = x;
    }

    function get() public constant returns (uint retVal) {
        return storedData;
    }
}

Truffle 部署智能合約

  1. 新建一個Truffle工程

 : truffle 是目前以太坊開發的主要工具鏈之一, 由CONSENSYS公司開發.

mkdir test
cd test
truffle init

完成上述操作之後, 目錄結構如下所示:

文件結構

  1. 將上面的智能合約示例保存到test/contracts目錄爲SimpleContract.sol

  2. 編譯智能合約

truffle compile --all

執行之後會生成build目錄, 內容如下:

build目錄結構

  1. 編寫部署文件migrations/2_deploy_simplestorage.js
var simple_storage = artifacts.require("SimpleStorage");

module.exports = function(deployer) {
    deployer.deploy(simple_storage, 42, {privateFor:["3znvmFqqc63FyiW/bhxIlTHfAZ6xnuhMgPaxTchgJlg="]});
};

 : privateFor表明這是一個私有合約, 不是所有結點可見

  1. 修改truffle.js文件
module.exports = {
    networks: {
        development: {
            host: "localhost",
            port: 22000,
            network_id: "*",
            gas: 4600000,
            gasPrice: 0
        },
        second_node: {
            host: "localhost",
            port: 22001,
            network_id: "*",
            gas: 4600000,
            gasPrice: 0
        },
        third_node: {
            host: "localhost",
            port: 22002,
            network_id: "*",
            gas: 4600000,
            gasPrice: 0
        }
    }
};

 : 端口號一定要與你本地實驗網絡的各結點的端口號對應起來

  1. 部署智能合約到鏈上
truffle migrate --reset

輸出如下所示:

部署命令輸出

驗證

私有合約只有允許的結點可以看到

var abi = 智能合約編譯生成的abi
var private = eth.contract(abi).at(智能合約的地址)

將上述命令在三個結點上分別執行, 前面我們在node1上通過privateFor字段指定只有node3可以看到智能合約.所以通過private訪問智能合約的時候, 也只有node1和node2 可以看到數據狀態.執行效果如下:

private執行效果1

private執行效果2

private執行效果3

驗證在私有合約的基礎只有privateFor的結點可以收到

在node1上發佈一個privateFor["node2", "node3"]的智能合約, 然後在node1中執行

private.set(199, {from:eth.coinbase, privateFor:["3znvmFqqc63FyiW/bhxIlTHfAZ6xnuhMgPaxTchgJlg="]})

上面的意思是這個交易只有node3可見, 雖然node2, node3都是可見到智能合約

在node3中執行private.get()結果如下:

node3 private.get

在node2中執行private.get()結果如下: node2 private.get

Next : 下一篇將完成一個完整的基於這個本地測試網絡的示例:積分聯盟系統

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章