超級賬本HyperLedger:Fabric Golang SDK的使用(附視訊)

NO IMAGE

作者: 李佶澳   轉載請保留:原文地址   釋出時間:2018/07/28 13:34:00

說明

HyperLedger Fabric的Golang SDK終於調通了,眼淚嘩嘩地。。 @2018-07-28 13:36:06

操作演示、配置檔案和程式碼講解視訊在網易雲課堂《HyperLeger Fabric進階實戰課》第五章中。

獲取示例程式碼

原始碼託管在github: 原始碼地址fabric-sdk-go

go get github.com/introclass/hyperledger-fabric-sdks-usage
cd $GOPATH/src/github.com/introclass/hyperledger-fabric-sdks-usage/go

準備msp和tls證書

將你自己環境的crypto-config複製到hyperledger-fabric-sdks-usage/go中。

crypto-config中只需要包含需要的msp和tls證書,需要哪些證書在呼叫go-sdk的程式使用的config.yaml中指定了。

查詢合約

01-query中通過go-sdk做了一個最簡單操作:連結peer,呼叫合約,查詢賬本。

$ cd 01-query
$ ./01-query
AdminIdentify is found:
&{Admin peers.member1.example.com [45 45 45 45 45 66 69 71 73 78
...
69 45 45 45 45 45 10] 0xc420329a90}
response is key1value

原始碼如下:

package main
import (
"fmt"
"github.com/hyperledger/fabric-sdk-go/pkg/client/channel"
mspclient "github.com/hyperledger/fabric-sdk-go/pkg/client/msp"
"github.com/hyperledger/fabric-sdk-go/pkg/core/config"
"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"
"log"
)
func main() {
//讀取配置檔案,建立SDK
configProvider := config.FromFile("./config.yaml")
sdk, err := fabsdk.New(configProvider)
if err != nil {
log.Fatalf("create sdk fail: %s\n", err.Error())
}
//讀取配置檔案(config.yaml)中的組織(member1.example.com)的使用者(Admin)
mspClient, err := mspclient.New(sdk.Context(), mspclient.WithOrg("member1.example.com"))
if err != nil {
log.Fatalf("create msp client fail: %s\n", err.Error())
}
adminIdentity, err := mspClient.GetSigningIdentity("Admin")
if err != nil {
log.Fatalf("get admin identify fail: %s\n", err.Error())
} else {
fmt.Println("AdminIdentify is found:")
fmt.Println(adminIdentity)
}
//呼叫合約
channelProvider := sdk.ChannelContext("mychannel",
fabsdk.WithUser("Admin"),
fabsdk.WithOrg("member1.example.com"))
channelClient, err := channel.New(channelProvider)
if err != nil {
log.Fatalf("create channel client fail: %s\n", err.Error())
}
var args [][]byte
args = append(args, []byte("key1"))
request := channel.Request{
ChaincodeID: "mycc",
Fcn:         "query",
Args:        args,
}
response, err := channelClient.Query(request)
if err != nil {
log.Fatal("query fail: ", err.Error())
} else {
fmt.Printf("response is %s\n", response.Payload)
}
}

參考

  1. Tutorial Hyperledger Fabric SDK Go: How to build your first app?

限時活動,每邀請一人即返回25元!