汽车信息记录
汽车信息的链码结构
1、引入依赖包
package main
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"github.com/hyperledger/fabric/core/chaincode/shim"
sc "github.com/hyperledger/fabric/protos/peer"
)
2、声明一个结构体
type SimpleChaincode struct {
}
3、声明Init() 和 Invoke() 函数
// 在链码初始化过程中调用 Init 来数据,此处不做任何操作
func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {
return shim.Success(nil)
}
// query 和 invoke 时被自动调用
func (s *SmartContract) Invoke(APIstub shim.ChaincodeStubInterface) sc.Response {
// 解析用户调用链码传递的函数名及参数
function, args := APIstub.GetFunctionAndParameters()
// 调用不同的函数
if function == "queryCar" {
return s.queryCar(APIstub, args)
} else if function == "initLedger" {
return s.initLedger(APIstub)
} else if function == "createCar" {
return s.createCar(APIstub, args)
} else if function == "queryAllCars" {
return s.queryAllCars(APIstub)
} else if function == "changeCarOwner" {
return s.changeCarOwner(APIstub, args)
}
return shim.Error("Invalid Smart Contract function name.")
}
4、对Invoke() 函数中的各个函数就是进行声明
// 初始化账本数据
func (s *SmartContract) initLedger(APIstub shim.ChaincodeStubInterface) sc.Response {
cars := []Car{
Car{
Make: "Toyota", Model: "Prius", Colour: "blue", Owner: "Tomoko"},
Car{
Make: "Ford", Model: "Mustang", Colour: "red", Owner: "Brad"},
Car{
Make: "Hyundai", Model: "Tucson", Colour: "green", Owner: "Jin Soo"},
Car{
Make: "Volkswagen", Model: "Passat", Colour: "yellow", Owner: "Max"},
Car{
Make: "Tesla", Model: "S", Colour: "black",</