天天看點

【fabric 4】chaincode開發 - shim.ChaincodeStubInterface

shim.ChaincodeStubInterface

提供了一些API,使chaincode與底層區塊鍊網絡進行互動。

在上一篇文章中,我們已經簡單的使用了一些

shim.ChaincodeStubInterface

的接口,完成了一個簡單的讀寫賬本的chaincode,本章會繼續就

shim.ChaincodeStubInterface

的一些常用接口進行一些練習。

  • 獲得調用參數

    shim.ChaincodeStubInterface

    提供了多種擷取參數的方法:
GetArgs() [][]byte      //以 [][]byte 形式擷取參數清單
GetStringArgs() []string    //以 []string形式擷取參數清單
GetFunctionAndParameters() (string, []string)   //将字元串數組分為兩部分,第一個參數是函數名,第二個參數是函數參數,這個函數在chaincode中最為常用
GetArgsSlice() ([]byte, error)      //以byte切片的形式擷取參數清單
           
  • 增删改查state DB

    這是chaincode的核心操作

PutState(string,[]byte) error   //增改DB,第一個參數為key,第二個參數為value。
GetState(string) ([]byte,error) //讀取DB,參數為key,傳回value
DelState(string) error      //删除DB中key對應的資料,參數為key
           
  • 曆史資料查詢
GetHistoryForKey(string) (HistoryQueryIteratorInterface,error)  // 查詢對某個key的所有操作
/* an example for traversal HistoryQueryIteratorInterface */
func queryHistory(results shim.HistoryQueryIteratorInterface) ([]byte, error) {
    defer results.Close()

    var buffer bytes.Buffer
    buffer.WriteString("[")

    bWrittenFlag := false

    for results.HasNext() {
        queryResponse, err := results.Next()
        if err != nil {
            return nil, err
        }
        if bWrittenFlag == true {
            buffer.WriteString(",")
        }
        item, _ := json.Marshal(queryResponse)
        buffer.Write(item)
        bWrittenFlag = true
    }
    buffer.WriteString("]")
    fmt.Printf("queryQresult:\n%s\n", buffer.String())
    return buffer.Bytes(), nil
}
           
  • 調用其它chaincode
//以調用example02為例
trans := [][]byte{[]byte("invoke"), []byte("a"), []byte("b"), []byte("11")} //example 02的invoke指令
res := stub.InvokeChaincode("mycc", trans, "mychannel") //1st param: install指令的-n參數;2st parm:指令 3st param:所在channel
           
  • 擷取目前使用者身份
/* 擷取調用這個chaincode的使用者的證書。 */
func testCert(stub shim.ChaincodeStubInterface) (string, error) {
    creatorByte, _ := stub.GetCreator()
    certStart := bytes.IndexAny(creatorByte, "-----BEGIN")
    if certStart == - {
        return "", fmt.Errorf("invalid cert")
    }
    certText := creatorByte[certStart:]
    bl, _ := pem.Decode(certText)
    if bl == nil {
        return "", fmt.Errorf("pem decode error")
    }
    cert, err := x509.ParseCertificate(bl.Bytes)
    if err != nil {
        return "", fmt.Errorf("x509 parse error")
    }
    uname := cert.Subject.CommonName
    fmt.Printf("name = %s", uname)
    return uname, nil
}