Hyperledger fabric Chaincode API使用說明
Hyperledger fabric Chaincode API:https://godoc.org/github.com/hyperledger/fabric/core/chaincode/shim
Chaincode 結構
shim.ChaincodeStubInterface 介面有三個方法,分別是:Init、Query 和 Invoke
1. 包
下載地址:https://github.com/hyperledger/fabric
package main
2. 匯入庫
import ( "fmt" "strconv" "github.com/hyperledger/fabric/core/chaincode/shim" pb "github.com/hyperledger/fabric/protos/peer" //pb 是對後面包的命名 )
3. 定義類
//定義一個結構體,繼承ChainCode介面 type SimpleChaincode struct { } /***************** ChainCode介面型別 *********************** type Chaincode interface { Init(stub ChaincodeStubInterface) pb.Response Invoke(stub ChaincodeStubInterface) pb.Response } ************************************************************** */
4. Init 方法
負責初始化工作,鏈碼首次部署到區塊鏈網路時呼叫,將由部署自己的鏈程式碼例項的每個對等節點執行。此方法可用於任何與初始化、引導或設定相關的任務。
func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {
}
5. Query(自定義方法)
只要在區塊鏈狀態上執行任何讀取/獲取/查詢操作,就需要呼叫 Query 方法。如果嘗試在 Query 方法內修改區塊鏈的狀態,將會丟擲異常。
6. Invoke
此方法主要是做修改操作,但是很多例子中一些使用者也在 Invoke 做查詢。
put, get, del 等操作都在可以在 Invoke 中執行
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
}
參考例子
func (s *SmartContract) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
// Retrieve the requested Smart Contract function and arguments
function, args := stub.GetFunctionAndParameters()
// Route to the appropriate handler function to interact with the ledger appropriately
if function == "balanceToken" {
return s.balanceToken(stub, args) //balanceToken為自定義的屬於SmartContract的方法
} else if function == "initLedger" {
return s.initLedger(stub) //initLedger為自定義的屬於SmartContract的方法
} else if function == "transferToken" {
return s.transferToken(stub, args) //transferToken為自定義的屬於SmartContract的方法
}
return shim.Error("Invalid Smart Contract function name.")
}
在 Invoke 函式中,首先使用 stub.GetFunctionAndParameters() 獲取合約函式 function, args := stub.GetFunctionAndParameters() 然後判斷函式名稱,實現對應的邏輯關係。
if function == "balanceToken" { return s.balanceToken(stub, args) } else if function == "initLedger" {
return s.initLedger(stub)
} else if function == "transferToken" {
return s.transferToken(stub, args)
}
7. func main()
任何 Go 程式的都需要 main 函式,他是程式的入口,因此該函式被用於引導/啟動鏈程式碼。當對peer節點部署chaincode並例項化時,就會執行 main 函式。
func main() {
err := shim.Start(new(SimpleChaincode))
if err != nil {
fmt.Printf("Error starting Simple chaincode: %s", err)
}
}
shim.Start(new(SampleChaincode)) 啟動鏈程式碼並註冊到peer 節點。
8. shim.ChaincodeStubInterface 介面
Hyperledger提供基於key/value的資料儲存,其中key是字串,value則是二進位制位元組陣列,Hyperledger的Go API提供了三個方法用於資料存取:PutState(key, value)用於向Hyperledger中儲存資料, GetState(key)用於從Hyperledger中提取資料,而DelState(key)則從Hyperledger中刪除資料。
寫入資料如果是 struct 結構體,需要序列化,通常使用 json,其他形式的序列化也可以,只要能反序列化即可。
8.1. 曾,刪,查 操作
8.1.1. PutState(key, value)寫入區塊
寫入區塊
func (s *SmartContract) initLedger(stub shim.ChaincodeStubInterface) sc.Response {
token := &Token{
Owner: "netkiller",
TotalSupply: 10000,
TokenName: "財富通正",
TokenSymbol: "COIN",
BalanceOf: map[string]uint{}}
token.initialSupply()
tokenAsBytes, _ := json.Marshal(token)
stub.PutState("Token", tokenAsBytes)
fmt.Println("Added", tokenAsBytes)
return shim.Success(nil)
}
8.1.2. GetState(key) 讀取區塊
通過key獲取區塊資訊
func (s *SmartContract) balanceToken(stub shim.ChaincodeStubInterface, args []string) sc.Response {
if len(args) != 1 {
return shim.Error("Incorrect number of arguments. Expecting 1")
}
tokenAsBytes, _ := stub.GetState(args[0])
token := Token{}
json.Unmarshal(tokenAsBytes, &token)
amount := token.balance(args[1])
return shim.Success(amount)
}
8.1.3. DelState(key) 刪除區塊
刪除區塊資訊(注:區塊鏈是不能引數資料的,刪除資料在區塊鏈中只是新新增一條資料,記錄某一條資料被刪除。)
func (s *SmartContract) deleteData(stub shim.ChaincodeStubInterface, args []string) sc.Response {
if len(args) != 1 {
return shim.Error("Incorrect number of arguments. Expecting 1")
}
err= stub.DelState(args[0])
if err != nil {
return shim.Error("Failed to delete Student from DB, key is: "+key)
}
return shim.Success(nil)
}
8.1.4. 修改資料
State 資料庫並沒有提供修改功能,修改資料可以先讀取,再修改,最後寫入
func (s *SmartContract) transferToken(stub shim.ChaincodeStubInterface, args []string) sc.Response {
if len(args) != 3 {
return shim.Error("Incorrect number of arguments. Expecting 2")
}
tokenAsBytes, _ := stub.GetState(args[0])
token := Token{}
json.Unmarshal(tokenAsBytes, &token)
token.transfer(args[1],args[2],args[3])
tokenAsBytes, _ = json.Marshal(token)
stub.PutState(args[0], tokenAsBytes)
return shim.Success(nil)
}
8.1.5. GetStateByRange(startKey, endKey) 範圍查詢
區塊鏈是一個線性的資料結構,只要知道開始位置,結束位置,就能夠取出中間部分的資料。
func (s *SmartContract) queryAllCars(APIstub shim.ChaincodeStubInterface) sc.Response {
startKey := "CAR0"
endKey := "CAR999"
resultsIterator, err := APIstub.GetStateByRange(startKey, endKey)
if err != nil {
return shim.Error(err.Error())
}
defer resultsIterator.Close()
// buffer is a JSON array containing QueryResults
var buffer bytes.Buffer
buffer.WriteString("[")
bArrayMemberAlreadyWritten := false
for resultsIterator.HasNext() {
queryResponse, err := resultsIterator.Next()
if err != nil {
return shim.Error(err.Error())
}
// Add a comma before array members, suppress it for the first array member
if bArrayMemberAlreadyWritten == true {
buffer.WriteString(",")
}
buffer.WriteString("{\"Key\":")
buffer.WriteString("\"")
buffer.WriteString(queryResponse.Key)
buffer.WriteString("\"")
buffer.WriteString(", \"Record\":")
// Record is a JSON object, so we write as-is
buffer.WriteString(string(queryResponse.Value))
buffer.WriteString("}")
bArrayMemberAlreadyWritten = true
}
buffer.WriteString("]")
fmt.Printf("- queryAllCars:\n%s\n", buffer.String())
return shim.Success(buffer.Bytes())
}
8.1.6. GetQueryResult(query string) CouchDB 查詢
//<<<<<<<<<<<<<<<<<<<<<<<<<< CouchDB簡單介紹 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
CouchDB特點:
面向文件資料庫,不需要正規化,直接儲存JSON就可以,CouchDB預設會生成 _id,_rev 兩個鍵,_id是一條記錄(文件)的唯一標識,如果不提供_id,_id會自動生成,也可以手動指定_id,比如用手機號做主鍵:
{'_id' : '+86186*****', name: '' }
_rev是其版本號,每更新一次 _rev就會自動發生變化,格式為
5-6a8617596d2adfea245662df0df611ao
////<<<<<<<<<<<<<<<<<<<<<<<<<< >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
GetQueryResult 能查詢 json 裡面的資料
下面例子是 Name = Neo Chen 的所有資料。
func (t *SimpleChaincode) getQueryResult(stub shim.ChaincodeStubInterface, args []string) pb.Response{
name:="Neo Chen" //需要查詢的名字
queryString := fmt.Sprintf("{\"selector\":{\"Name\":\"%s\"}}", name)
resultsIterator,err:= stub.GetQueryResult(queryString)//必須是CouchDB才行
if err!=nil{
return shim.Error("query failed")
}
person,err:=getListResult(resultsIterator)
if err!=nil{
return shim.Error("query failed")
}
return shim.Success(person)
}
8.1.7. stub.GetHistoryForKey
通過key獲取歷史資料
func (t *SimpleChaincode) historyQuery(stub shim.ChaincodeStubInterface, args []string) pb.Response{
if len(args) != 1 {
return shim.Error("Incorrect number of arguments. Expecting 1")
}
it,err:= stub.GetHistoryForKey(args[0])
if err!=nil{
return shim.Error(err.Error())
}
var result,_= getHistoryListResult(it)
return shim.Success(result)
}
8.1.8. shim.HistoryQueryIteratorInterface 介面
func getHistoryListResult(resultsIterator shim.HistoryQueryIteratorInterface) ([]byte,error){
defer resultsIterator.Close()
// buffer is a JSON array containing QueryRecords
var buffer bytes.Buffer
buffer.WriteString("[")
bArrayMemberAlreadyWritten := false
for resultsIterator.HasNext() {
queryResponse, err := resultsIterator.Next()
if err != nil {
return nil, err
}
// Add a comma before array members, suppress it for the first array member
if bArrayMemberAlreadyWritten == true {
buffer.WriteString(",")
}
item,_:= json.Marshal( queryResponse)
buffer.Write(item)
bArrayMemberAlreadyWritten = true
}
buffer.WriteString("]")
fmt.Printf("queryResult:\n%s\n", buffer.String())
return buffer.Bytes(), nil
}
8.2. 複合鍵
16.8.2.1. 建立複合鍵
// maintain the index
indexName := "color~name"
colorNameIndexKey, err := stub.CreateCompositeKey(indexName, []string{marbleJSON.Color, marbleJSON.Name})
if err != nil {
return shim.Error(err.Error())
}
// Delete index entry to state.
err = stub.DelState(colorNameIndexKey)
if err != nil {
return shim.Error("Failed to delete state:" + err.Error())
}
8.2.2. 分解複合鍵
// get the color and name from color~name composite key
objectType, compositeKeyParts, err := stub.SplitCompositeKey(responseRange.Key)
if err != nil {
return shim.Error(err.Error())
}
returnedColor := compositeKeyParts[0]
returnedMarbleName := compositeKeyParts[1]
8.3. stub.SetEvent(key, value) 事件
Hyperledger Fabic 事件實現了釋出/訂閱訊息佇列。您可以自由地在鏈碼中建立和發出自定義事件。例如,區塊鏈的狀態發生改變,就會生成一個事件。通過向區塊鏈上的事件中心註冊一個事件介面卡,客戶端應用程式可以訂閱和使用這些事件。
func (t *SimpleChaincode) testEvent(stub shim.ChaincodeStubInterface, args []string) pb.Response{
message := "Event send data is here!"
err := stub.SetEvent("evtsender", []byte(message))
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(nil)
}
func (t *SimpleChaincode) testEvent(stub shim.ChaincodeStubInterface, args []string) pb.Response{
event := &Token{
Owner: "netkiller",
TotalSupply: 10000,
TokenName: "代幣通正",
TokenSymbol: "COIN",
BalanceOf: map[string]uint{}}
eventBytes, err ;= json.Marshal(&event)
if err != nil {
return nil, err
}
err := stub.SetEvent("evtSender", eventBytes)
if err != nil {
fmt.Println("Could not set event for loan application creation", err)
}
}
8.4. 呼叫其他鏈碼
在當前連碼中呼叫另一個連碼,呼叫連碼需要提供連碼名和通道名 stub.InvokeChaincode("連碼名",呼叫函式,"通道")
//InvokeChaincode(chaincodeName string, args [][]byte, channel string) pb.Response 呼叫其他鏈碼
func (t *SimpleChaincode) testInvokeChainCode(stub shim.ChaincodeStubInterface, args []string) pb.Response{
trans:=[][]byte{[]byte("invoke"),[]byte("transfer"),[]byte("netkiller"),[]byte("neo"),[]byte("100")}
response:= stub.InvokeChaincode("token",trans,"mychannel")
fmt.Println(response.Message)
return shim.Success([]byte( response.Message))
}
//溯源
//溯源:(1)首先根據 Sale的ID找到對應的值 值中有廠家ID(FormId)
// (2)根據廠家的ID,在MachainInfo中找到 牛奶廠家的ID(FormId)
// (3)根據牛奶廠家的ID,找到對應的牛奶資訊
// 根據keyID查詢歷史記錄
func(t* Sale)trace(stub shim.ChaincodeStubInterface, args []string) peer.Response {
text := t.query(stub, args)
if text.Status != shim.OK {
return shim.Error("query error ......")
}
var myList []string
var fromID string
// 獲取需要的資訊
var saleItem SaleInfo
json.Unmarshal(text.Payload, &saleItem)
fromID = saleItem.FromId
myList = append(myList, saleItem.Name)
// 找奶牛場
myArgs := [][]byte{[]byte("query"), []byte(fromID)}
response := stub.InvokeChaincode("machincc", myArgs, "tracechannel")
if response.Status != shim.OK {
return shim.Error("InvokeChaincode error ......")
}
var machItem MachinInfo
json.Unmarshal(response.Payload, &machItem)
fromID = machItem.FromId
myList = append(myList, machItem.Name)
// 搜尋奶牛場資訊
response = stub.InvokeChaincode("dairycc", myArgs, "tracechannel")
if response.Status != shim.OK {
return shim.Error("InvokeChaincode error ......")
}
var farmIitem FarmInfo
json.Unmarshal(response.Payload, &farmIitem)
myList = append(myList, farmIitem.Name)
// 資料格式化為json
jsonText, error := json.Marshal(myList)
if error != nil {
return shim.Error("json.Marshal(myList) fail...")
}
return shim.Success(jsonText)
}
9. 案例
9.1. 模仿以太坊 ERC20 規範的 Hyperledger Fabric 實現
package main
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"github.com/hyperledger/fabric/core/chaincode/shim"
sc "github.com/hyperledger/fabric/protos/peer"
)
// Define the Smart Contract structure
type SmartContract struct {
}
type Token struct {
Owner string `json:"Owner"`
TotalSupply uint `json:"TotalSupply"`
TokenName string `json:"TokenName"`
TokenSymbol string `json:"TokenSymbol"`
BalanceOf map[string]uint `json:"BalanceOf"`
}
func (token *Token) initialSupply(){
token.BalanceOf[token.Owner] = token.TotalSupply;
}
func (token *Token) transfer (_from string, _to string, _value uint){
if(token.BalanceOf[_from] >= _value){
token.BalanceOf[_from] -= _value;
token.BalanceOf[_to] += _value;
}
}
func (token *Token) balance (_from string) uint{
return token.BalanceOf[_from]
}
func (token *Token) burn(_value uint) {
if(token.BalanceOf[token.Owner] >= _value){
token.BalanceOf[token.Owner] -= _value;
token.TotalSupply -= _value;
}
}
func (token *Token) burnFrom(_from string, _value uint) {
if(token.BalanceOf[_from] >= _value){
token.BalanceOf[_from] -= _value;
token.TotalSupply -= _value;
}
}
func (token *Token) mint(_value uint) {
token.BalanceOf[token.Owner] += _value;
token.TotalSupply += _value;
}
func (s *SmartContract) Init(stub shim.ChaincodeStubInterface) sc.Response {
return shim.Success(nil)
}
func (s *SmartContract) initLedger(stub shim.ChaincodeStubInterface) sc.Response {
token := &Token{
Owner: "netkiller",
TotalSupply: 10000,
TokenName: "財富通正",
TokenSymbol: "COIN",
BalanceOf: map[string]uint{}}
token.initialSupply()
tokenAsBytes, _ := json.Marshal(token)
stub.PutState("Token", tokenAsBytes)
fmt.Println("Added", tokenAsBytes)
return shim.Success(nil)
}
func (s *SmartContract) transferToken(stub shim.ChaincodeStubInterface, args []string) sc.Response {
if len(args) != 3 {
return shim.Error("Incorrect number of arguments. Expecting 2")
}
tokenAsBytes, _ := stub.GetState(args[0])
token := Token{}
json.Unmarshal(tokenAsBytes, &token)
token.transfer(args[1],args[2],args[3])
tokenAsBytes, _ = json.Marshal(token)
stub.PutState(args[0], tokenAsBytes)
return shim.Success(nil)
}
func (s *SmartContract) balanceToken(stub shim.ChaincodeStubInterface, args []string) sc.Response {
if len(args) != 1 {
return shim.Error("Incorrect number of arguments. Expecting 1")
}
tokenAsBytes, _ := stub.GetState(args[0])
token := Token{}
json.Unmarshal(tokenAsBytes, &token)
amount := token.balance(args[1])
return shim.Success(amount)
}
func (s *SmartContract) Invoke(stub shim.ChaincodeStubInterface) sc.Response {
// Retrieve the requested Smart Contract function and arguments
function, args := stub.GetFunctionAndParameters()
// Route to the appropriate handler function to interact with the ledger appropriately
if function == "balanceToken" {
return s.balanceToken(stub, args)
} else if function == "initLedger" {
return s.initLedger(stub)
} else if function == "transferToken" {
return s.transferToken(stub, args)
}
return shim.Error("Invalid Smart Contract function name.")
}
// The main function is only relevant in unit test mode. Only included here for completeness.
func main() {
// Create a new Smart Contract
err := shim.Start(new(SmartContract))
if err != nil {
fmt.Printf("Error creating new Smart Contract: %s", err)
}
}