Home | 簡體中文 | 繁體中文 | 雜文 | 知乎專欄 | Github | OSChina 博客 | 雲社區 | 雲棲社區 | Facebook | Linkedin | 視頻教程 | 打賞(Donations) | About
知乎專欄多維度架構 | 微信號 netkiller-ebook | QQ群:128659835 請註明“讀者”

26.2. Chaincode 結構

Chaincode 實現 shim.ChaincodeStubInterface 介面,有三個方法,分別是:Init、Query 和 Invoke

https://github.com/hyperledger-archives/fabric/blob/master/core/chaincode/shim/chaincode.go

26.2.1. 包

由於需要編譯為執行檔,所以需要 main 包

		
package main		
		
		

26.2.2. 導入庫

這裡需要導入兩個包 "github.com/hyperledger/fabric/core/chaincode/shim" 和 "github.com/hyperledger/fabric/protos/peer" 其他包,根據實際需要而定。

		
import (
	"fmt"
	"strconv"

	"github.com/hyperledger/fabric/core/chaincode/shim"
	pb "github.com/hyperledger/fabric/protos/peer"
)
		
		
		

26.2.3. 定義類

		
type SimpleChaincode struct {
}		
		
		

26.2.4. Init 方法

負責初始化工作,鏈碼首次部署到區塊鏈網絡時調用,將由部署自己的鏈代碼實例的每個對等節點執行。此方法可用於任何與初始化、引導或設置相關的任務。

		
func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {
}		
		
		

26.2.5. Query

只要在區塊鏈狀態上執行任何讀取/獲取/查詢操作,就需要調用 Query 方法。如果嘗試在 Query 方法內修改區塊鏈的狀態,將會拋出異常。

26.2.6. Invoke

此方法主要是做修改操作,但是很多例子中一些用戶也在 Invoke 做查詢。

put, get, del 等操作都在可以在 Invoke 中運行

		
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
}		
		
		

參考例子

		
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.")
}		
		
		



在 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)
}


26.2.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 節點。