知乎專欄 | 多維度架構 | | | 微信號 netkiller-ebook | | | QQ群:128659835 請註明“讀者” |
Chaincode 實現 shim.ChaincodeStubInterface 介面,有三個方法,分別是:Init、Query 和 Invoke
https://github.com/hyperledger-archives/fabric/blob/master/core/chaincode/shim/chaincode.go
這裡需要導入兩個包 "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" )
負責初始化工作,鏈碼首次部署到區塊鏈網絡時調用,將由部署自己的鏈代碼實例的每個對等節點執行。此方法可用於任何與初始化、引導或設置相關的任務。
func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response { }
此方法主要是做修改操作,但是很多例子中一些用戶也在 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)
}