简单投票链码

package main

import (
	"github.com/hyperledger/fabric/core/chaincode/shim"
	"github.com/hyperledger/fabric/protos/peer"
	"encoding/json"
	"bytes"
)

type VoteChaincode struct {

}

type Vote struct {
	Name string `json:"name"`
	VoteNum int `json:"vote_num"`
}

func (v *VoteChaincode) Init(stub shim.ChaincodeStubInterface) peer.Response {
	return shim.Success(nil)
}

func (v *VoteChaincode) Invoke(stub shim.ChaincodeStubInterface) peer.Response {
	fn,args:=stub.GetFunctionAndParameters()
	if fn=="vote" {
		return v.vote(stub,args)
	} else if fn=="getVote" {
		return v.getVote(stub,args)
	}
	return shim.Error("")
}

func (v *VoteChaincode) vote(stub shim.ChaincodeStubInterface,args []string) peer.Response {
	name:=args[0]
	vtjson,err:=stub.GetState(name)
	if err!=nil {
		return shim.Error(err.Error())
	}
	vt:=Vote{}
	if vtjson==nil {
		vt=Vote{name,1}
	} else {
		err=json.Unmarshal(vtjson,&vt)
		if err!=nil {
			return shim.Error(err.Error())
		}
		vt.VoteNum+=1
	}
	vtjson,err=json.Marshal(vt)
	if err!=nil {
		return shim.Error(err.Error())
	}
	err=stub.PutState(name,vtjson)
	if err!=nil {
		return shim.Error(err.Error())
	}
	return shim.Success(nil)
}

func (v *VoteChaincode) getVote(stub shim.ChaincodeStubInterface,args []string) peer.Response {
	iter,err:=stub.GetStateByRange("","")
	if err!=nil {
		return shim.Error(err.Error())
	}
	defer iter.Close()
	var buffer  bytes.Buffer
	buffer.WriteString("[")
	first:=true
	for iter.HasNext() {
		item,err:=iter.Next()
		if err!=nil {
			return shim.Error(err.Error())
		}
		if !first {
			buffer.WriteString(",")
		}
		buffer.WriteString(string(item.Value))
		first=false
	}
	buffer.WriteString("]")
	return shim.Success(buffer.Bytes())
}

func main()  {
	shim.Start(new(VoteChaincode))
}

 

你可能感兴趣的:(简单投票链码)