使用Node.JS訪問Hyperledger Fabric的gRPC服務

在即將正式發佈的Hyperledger Fabric SDK 1.0中,Hyperledger Fabric經過gRPC提供服務接口以取代現有的REST API。本文介紹瞭如何使用Node.JS訪問Hyperledger Fabric的gRPC服務。node

Hyperledger Fabric的gRPC服務接口能夠經過安裝Hyperledger fabric Client (HFC)獲取。npm

在工做目錄下運行以下npm命令以安裝HFC。api

npm install hfc

gRPC接口定義文件(.proto)都在HFC的lib\protos網絡

api.proto
    ca.proto
    chaincode.proto
    chaincodeevent.proto
    devops.proto
    events.proto
    fabric.proto
    server_admin.proto

其中的api.proto定義了名爲Openchain的服務, 該服務提供了若干個接口以獲取Hyperledger Fabric區塊網絡的具體信息。數據結構

// Interface exported by the server.
    service Openchain {

        // GetBlockchainInfo returns information about the blockchain ledger such as
        // height, current block hash, and previous block hash.
        rpc GetBlockchainInfo(google.protobuf.Empty) returns (BlockchainInfo) {}

        // GetBlockByNumber returns the data contained within a specific block in the
        // blockchain. The genesis block is block zero.
        rpc GetBlockByNumber(BlockNumber) returns (Block) {}

        // GetBlockCount returns the current number of blocks in the blockchain data
        // structure.
        rpc GetBlockCount(google.protobuf.Empty) returns (BlockCount) {}

        // GetPeers returns a list of all peer nodes currently connected to the target
        // peer.
        rpc GetPeers(google.protobuf.Empty) returns (PeersMessage) {}
    }

如下代碼使用GetBlockCount接口獲取區塊總數。ui

var fs = require('fs');
    var grpc = require('grpc');
    var ProtoBuf = require("protobufjs");

    var apiProto = grpc.load("./protos/api.proto").protos;

    var client = new apiProto.Openchain('192.168.99.100:7051',  grpc.credentials.createInsecure());

    client.getBlockCount({}, function(err, blockCount) {
        if (err) {
            console.log("Error :" + err); 
        } else if (blockCount) {
            console.dir(blockCount, { depth: null }); 
        }
    });

GetBlockCount接口返回一個BlockCount消息, 該消息包含一個count成員, 也就是當前網絡中的區塊總數。google

message BlockCount {

        uint64 count = 1;

    }

如下代碼則使用GetBlockByNumber接口獲取某個區塊的信息。code

function callbackForBlock(blockNumber) {
            return function(err, block) {
                console.log("Block[" + blockNumber.number + "]");
                if (err) {
                    console.log("Error :" , err); 
                } else if (block) {
                    console.dir(block, { depth: null }); 
                }
                console.log("=======================");
            };
        }

        for (var n=0; n<blockCount.count; n++) {
            
            var blockNumber = {
                number : n
            };

            client.getBlockByNumber(blockNumber, callbackForBlock(blockNumber));
        }

GetBlockByNumber接口須要一個輸入參數, 用於指定區塊號碼,其返回消息則是一個Block消息, 其數據結構定義在fabric.proto中。orm

總結

本文介紹了一個使用Node.JS訪問Hyperledger Fabric gRPC服務的示例程序。server

相關文章
相關標籤/搜索