说明
我计划构建一个基于Fabric的记帐DAPP,同时也是一个学习的过程,在此分享。
以下内容全部基于Fabric V1.1.0
摘要
下面实现第一个Chaincode 用于用户登陆验证。该Chaincode非常简单,以用户名作为Key 以其密码作为Value,这样当用户登陆时就可以检查其密码是否正确。
Chaincode
package main
/**
* file:authentication_chaincode.go
* 用于用户登陆验证
**/
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"github.com/hyperledger/fabric/core/chaincode/shim"
pb "github.com/hyperledger/fabric/protos/peer"
)
type AuthenticationChaincode struct{}
type ResInfo struct {
Status bool `json:"status"`
Msg string `json:"msg"`
}
func (t *ResInfo) error(msg string) {
t.Status = false
t.Msg = msg
}
func (t *ResInfo) ok(msg string) {
t.Status = true
t.Msg = msg
}
func (t *ResInfo) response() pb.Response {
resJson, err := json.Marshal(t)
if err != nil {
return shim.Error("Failed to generate json result " + err.Error())
}
return shim.Success(resJson)
}
func main() {
err := shim.Start(new(AuthenticationChaincode))
if err != nil {
fmt.Printf("Error starting Simple chaincode: %s", err)
}
}
// Init initializes chaincode
// ===========================
func (t *AuthenticationChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {
return shim.Success(nil)
}
func (t *AuthenticationChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
function, args := stub.GetFunctionAndParameters()
fmt.Println("invoke is running " + function)
// Handle different functions
if function == "add" { //create a new marble
return t.add(stub, args)
} else if function == "del" { //change owner of a specific marble
return t.del(stub, args)
} else if function == "update" {
return t.update(stub, args)
} else if function == "authenticate" { //transfer all marbles of a certain color
return t.authenticate