第一个chaincode :HelloWorld!
chaincode01.go:
package main
import(
"fmt"
"github.com/hyperledger/fabric-chaincode-go/shim"
"github.com/hyperledger/fabric-protos-go/peer"
)
type HelloWorld struct {
}
func (s *HelloWorld) Init(stub shim.ChaincodeStubInterface) peer.Response {
args := stub.GetStringArgs()
if len(args) != 2 {
return shim.Error("要输入键和值")
}
err := stub.PutState(args[0], []byte(args[1]))
if err != nil {
shim.Error(err.Error())
}
return shim.Success(nil)
}
func (s *HelloWorld) Invoke(stub shim.ChaincodeStubInterface) peer.Response {
fn, args := stub.GetFunctionAndParameters()
if fn == "set" {
return s.set(stub, args)
}else if fn =="get" {
return s.get(stub, args)
}
return shim.Error("方法不存在")
}
func (s *HelloWorld) set(stub shim.ChaincodeStubInterface, args []string) peer.Response {
if len(args) != 2 {
return shim.Error("要输入键和值")
}
err := stub.PutState(args[0], []byte(args[1]))
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(nil)
}
func (s *HelloWorld) get(stub shim.ChaincodeStubInterface, args []string) peer.Response {
if len(args) != 1 {
return shim.Error("请输入一个键")
}
value, err := stub.GetState(args[0])
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(value)
}
func main() {
err := shim.Start(new(HelloWorld))
if err != nil {
fmt.Println("start error")
}
}
同目录下创建chaincode01_test.go(必须_test结尾)
package main
import(
"fmt"
"github.com/hyperledger/fabric-chaincode-go/shim"
"github.com/hyperledger/fabric-chaincode-go/shimtest"
"testing"
)
var stub *shimtest.MockStub
func testInit(t *testing.T, args [][]byte) {
res := stub.MockInit("1", args)
if res.Status != shim.OK {
fmt.Println("Init failed: ", string(res.Message))
t.FailNow()
}
}
func testSet(t *testing.T, key string, value string) {
res := stub.MockInvoke("1", [][]byte{[]byte("set"), []byte(key), []byte(value)})
if res.Status != shim.OK {
fmt.Println("set", key, "failed: ", string(res.Message))
t.FailNow()
}
}
func testGet(t *testing.T, key string) {
res := stub.MockInvoke("1", [][]byte{[]byte("get"), []byte(key)})
if res.Status != shim.OK {
fmt.Println("get", key, "failed: ", string(res.Message))
t.FailNow()
}
if res.Payload == nil {
fmt.Println("get", key, "failed to get")
t.FailNow()
}
fmt.Println("get value", key, ":", string(res.Payload))
}
func TestHelloWorld(t *testing.T) {
stub =shimtest.NewMockStub("helloworld", new(HelloWorld))
testInit(t, [][]byte{[]byte("hi"), []byte("world")})
testGet(t, "hi")
testSet(t, "say", "helloworld")
testGet(t, "say")
}
最后在当前目录下,终端输入:
go test -v chaincode01_test.go chaincode01.go
总结:
1.引入的包需要先从github下载到本地,目录就按引入的创建
2.有bug先看提示信息,对着解决