add schema checks

parent 02170213
...@@ -8,6 +8,7 @@ import ( ...@@ -8,6 +8,7 @@ import (
"fmt" "fmt"
"github.com/hyperledger/fabric/core/chaincode/shim" "github.com/hyperledger/fabric/core/chaincode/shim"
pb "github.com/hyperledger/fabric/protos/peer" pb "github.com/hyperledger/fabric/protos/peer"
"reflect"
"time" "time"
) )
...@@ -29,12 +30,20 @@ type Auth struct { ...@@ -29,12 +30,20 @@ type Auth struct {
type SchemaParameters struct { type SchemaParameters struct {
Value interface{} `json:"val"`//默认值 这里特别说明一下如果这里是backUp 字段,我们不进行更深一步的校验,包括格式 Value interface{} `json:"val"`//默认值 这里特别说明一下如果这里是backUp 字段,我们不进行更深一步的校验,包括格式
PAuth Auth `json:"auth"` PAuth Auth `json:"auth"`
FCheck *Checks `json:"fcheck"`
} }
type Checks struct {
FType string `json:"ftype"` //字段类型
Must bool `json:"must"` //是否必填
Fieldlen int `json:"fieldlen"` //字段长度(如果字段类型是string,表示字段长度,如果是数值类型用0,1表示数据正负)
}
type Schema struct { type Schema struct {
Fields map[string]SchemaParameters `json:"fields"` Fields map[string]SchemaParameters `json:"fields"`
SchemaAuth Auth `json:"schema_auth"`//schema 的写权限,主要是用在 schema update 部分 SchemaAuth Auth `json:"schema_auth"`//schema 的写权限,主要是用在 schema update 部分
SAuth Auth `json:"auth"` SAuth Auth `json:"auth"`
} }
var ( var (
...@@ -66,19 +75,19 @@ func (t *GXHCC) Invoke(stub shim.ChaincodeStubInterface) pb.Response { ...@@ -66,19 +75,19 @@ func (t *GXHCC) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
case "put": case "put":
res, err := put(args, stub) res, err := put(args, stub)
if err != nil { if err != nil {
return shim.Error(fmt.Sprintf("put function err: %s", err)) return shim.Error(fmt.Sprintf("put data function err: %s", err))
} }
return shim.Success([]byte(res)) return shim.Success([]byte(res))
case "get": case "get":
res, err := get(args, stub) res, err := get(args, stub)
if err != nil { if err != nil {
return shim.Error(fmt.Sprintf("get function err: %s", err)) return shim.Error(fmt.Sprintf("get data function err: %s", err))
} }
return shim.Success([]byte(res)) return shim.Success([]byte(res))
case "update": case "update":
res, err := update(args, stub) res, err := update(args, stub)
if err != nil { if err != nil {
return shim.Error(fmt.Sprintf("update function err: %s", err)) return shim.Error(fmt.Sprintf("update data function err: %s", err))
} }
return shim.Success([]byte(res)) return shim.Success([]byte(res))
...@@ -88,16 +97,10 @@ func (t *GXHCC) Invoke(stub shim.ChaincodeStubInterface) pb.Response { ...@@ -88,16 +97,10 @@ func (t *GXHCC) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
return shim.Success([]byte("GXHCC invoke successful ")) return shim.Success([]byte("GXHCC invoke successful "))
} }
/*
put
args 字段说明:
1:args[0]代表我们具体操作的表,
2:args[1:]后面的数据表示要记录到数据库的数据,每一个string 必须是json字符串,并且需要每一个json 字符串都必须包含id 字段
*/
func put(args []string, stub shim.ChaincodeStubInterface) (string, error) { func put(args []string, stub shim.ChaincodeStubInterface) (string, error) {
if len(args) < 2 { if len(args) < 2 {
return "", fmt.Errorf("Expected more than 2 parameters to function put!") return "", fmt.Errorf("put data operation expected more than 2 parameters! ")
} }
var PutDatas []map[string]interface{} var PutDatas []map[string]interface{}
commonName, err := getCertificateCommonName(stub) commonName, err := getCertificateCommonName(stub)
...@@ -110,13 +113,13 @@ func put(args []string, stub shim.ChaincodeStubInterface) (string, error) { ...@@ -110,13 +113,13 @@ func put(args []string, stub shim.ChaincodeStubInterface) (string, error) {
return "", err return "", err
} }
if err := json.Unmarshal([]byte(result), &schema); err != nil { if err := json.Unmarshal([]byte(result), &schema); err != nil {
return "", fmt.Errorf("json Unmarshal schemaRes err: %s ", err) return "", fmt.Errorf("The parameters Unmarshal to a Schema structural fail,err: %s ", err)
} }
if ok,err := authorityCheck(schema.SAuth.Write, commonName);!ok { if ok,err := authorityCheck(schema.SAuth.Write, commonName);!ok {
return "", fmt.Errorf("write %s table fail,err: %s ", args[0],err) return "", fmt.Errorf("write %s table fail,err: %s ", args[0],err)
} }
if err := json.Unmarshal([]byte(args[1]), &PutDatas); err != nil { if err := json.Unmarshal([]byte(args[1]), &PutDatas); err != nil {
return "", fmt.Errorf("parameters Unmarshal fail,args string not json array, err:%s", err) return "", fmt.Errorf("%s table parameters Unmarshal fail,put string not json array, err:%s",args[0], err)
} }
for k, mapres := range PutDatas { for k, mapres := range PutDatas {
Id, ok := mapres["id"] Id, ok := mapres["id"]
...@@ -132,6 +135,9 @@ func put(args []string, stub shim.ChaincodeStubInterface) (string, error) { ...@@ -132,6 +135,9 @@ func put(args []string, stub shim.ChaincodeStubInterface) (string, error) {
if !SchemaCheck(schema.Fields, mapres) { if !SchemaCheck(schema.Fields, mapres) {
return "", fmt.Errorf("SchemaCheck fail,args index %d string doesn't match %s format", k, args[0]) return "", fmt.Errorf("SchemaCheck fail,args index %d string doesn't match %s format", k, args[0])
} }
if err := FiledsCheck(schema.Fields,mapres);err !=nil{
return "",err
}
putDate, _ := json.Marshal(mapres) putDate, _ := json.Marshal(mapres)
if err := stub.PutState(PREFIX+"_"+args[0]+"_"+Id.(string), putDate); err != nil { if err := stub.PutState(PREFIX+"_"+args[0]+"_"+Id.(string), putDate); err != nil {
return "", fmt.Errorf("PutState fail, err :%s", err) return "", fmt.Errorf("PutState fail, err :%s", err)
...@@ -145,7 +151,7 @@ func put(args []string, stub shim.ChaincodeStubInterface) (string, error) { ...@@ -145,7 +151,7 @@ func put(args []string, stub shim.ChaincodeStubInterface) (string, error) {
*/ */
func update(args []string, stub shim.ChaincodeStubInterface) (string, error) { func update(args []string, stub shim.ChaincodeStubInterface) (string, error) {
if len(args) != 2 { if len(args) != 2 {
return "", fmt.Errorf("Expected 2 parameters to function update! ") return "", fmt.Errorf("update data operation expected 2 parameters! ")
} }
commonName, err := getCertificateCommonName(stub) commonName, err := getCertificateCommonName(stub)
if err != nil { if err != nil {
...@@ -157,12 +163,12 @@ func update(args []string, stub shim.ChaincodeStubInterface) (string, error) { ...@@ -157,12 +163,12 @@ func update(args []string, stub shim.ChaincodeStubInterface) (string, error) {
return "", err return "", err
} }
if err := json.Unmarshal([]byte(schemaRes), &schema); err != nil { if err := json.Unmarshal([]byte(schemaRes), &schema); err != nil {
return "", fmt.Errorf("json Unmarshal schemaRes err: %s ", err) return "", fmt.Errorf("The parameters Unmarshal to a Schema structural fail,err: %s ", err)
} }
var Updata map[string]interface{} var Updata map[string]interface{}
var allMap map[string]interface{} var allMap map[string]interface{}
if err := json.Unmarshal([]byte(args[1]), &Updata); err != nil { if err := json.Unmarshal([]byte(args[1]), &Updata); err != nil {
return "", fmt.Errorf("parameters Unmarshal fail,args string not json string,err: %s", err) return "", fmt.Errorf("%s table parameters Unmarshal fail,err: %s",args[0], err)
} }
Id, ok := Updata["id"] Id, ok := Updata["id"]
if !ok { if !ok {
...@@ -170,15 +176,18 @@ func update(args []string, stub shim.ChaincodeStubInterface) (string, error) { ...@@ -170,15 +176,18 @@ func update(args []string, stub shim.ChaincodeStubInterface) (string, error) {
} }
if ok ,_ := authorityCheck(schema.SAuth.Write, commonName);!ok { if ok ,_ := authorityCheck(schema.SAuth.Write, commonName);!ok {
if ok, err := parsauthorityCheck(schema.Fields, Updata, commonName); !ok { if ok, err := parsauthorityCheck(schema.Fields, Updata, commonName); !ok {
return "", fmt.Errorf("parsauthorityCheck err: %s", err) return "", fmt.Errorf("authority Check err: %s", err)
} }
} }
if err := FiledsCheck(schema.Fields,Updata);err !=nil{
return "",err
}
result, err := stub.GetState(PREFIX+"_"+args[0]+"_"+Id.(string)) result, err := stub.GetState(PREFIX+"_"+args[0]+"_"+Id.(string))
if err != nil || result == nil { if err != nil || result == nil {
return "", fmt.Errorf("GetState data fail,please check your parameters ") return "", fmt.Errorf("GetState %s data fail,please check your parameters ",args[0]+"_"+Id.(string))
} }
if err := json.Unmarshal(result, &allMap); err != nil { if err := json.Unmarshal(result, &allMap); err != nil {
return "", fmt.Errorf("result parameters Unmarshal fail err:%s ", err) return "", fmt.Errorf("The original data Unmarshal fail err:%s ", err)
} }
if err := Deassign(Updata, allMap); err != nil { if err := Deassign(Updata, allMap); err != nil {
return "", err return "", err
...@@ -186,7 +195,7 @@ func update(args []string, stub shim.ChaincodeStubInterface) (string, error) { ...@@ -186,7 +195,7 @@ func update(args []string, stub shim.ChaincodeStubInterface) (string, error) {
resultByte, _ := json.Marshal(allMap) resultByte, _ := json.Marshal(allMap)
if err := stub.PutState(PREFIX+"_"+args[0]+"_"+Id.(string), resultByte); err != nil { if err := stub.PutState(PREFIX+"_"+args[0]+"_"+Id.(string), resultByte); err != nil {
return "", fmt.Errorf("updateState date fail, err :%s ", err) return "", fmt.Errorf("Put %s date fail, err :%s ",args[0]+"_"+Id.(string), err)
} }
return fmt.Sprintf("%s update data success!", args[0]), nil return fmt.Sprintf("%s update data success!", args[0]), nil
...@@ -194,7 +203,7 @@ func update(args []string, stub shim.ChaincodeStubInterface) (string, error) { ...@@ -194,7 +203,7 @@ func update(args []string, stub shim.ChaincodeStubInterface) (string, error) {
func get(args []string, stub shim.ChaincodeStubInterface) (string, error) { func get(args []string, stub shim.ChaincodeStubInterface) (string, error) {
if len(args) != 2 { if len(args) != 2 {
return "", fmt.Errorf("Expected 2 parameters to function get!") return "", fmt.Errorf("get data operation expected 2 parameters to function get!")
} }
commonName, err := getCertificateCommonName(stub) commonName, err := getCertificateCommonName(stub)
if err != nil { if err != nil {
...@@ -204,7 +213,7 @@ func get(args []string, stub shim.ChaincodeStubInterface) (string, error) { ...@@ -204,7 +213,7 @@ func get(args []string, stub shim.ChaincodeStubInterface) (string, error) {
var mapResult map[string]interface{} var mapResult map[string]interface{}
if err := json.Unmarshal([]byte(args[1]), &parameters); err != nil { if err := json.Unmarshal([]byte(args[1]), &parameters); err != nil {
return "", fmt.Errorf("parameters Unmarshal fail,args string not json string,err: %s", err) return "", fmt.Errorf("parameters Unmarshal fail,err: %s", err)
} }
Id, ok := parameters["id"] Id, ok := parameters["id"]
...@@ -213,7 +222,7 @@ func get(args []string, stub shim.ChaincodeStubInterface) (string, error) { ...@@ -213,7 +222,7 @@ func get(args []string, stub shim.ChaincodeStubInterface) (string, error) {
} }
result, err := stub.GetState(PREFIX+"_"+args[0]+"_"+Id.(string)) result, err := stub.GetState(PREFIX+"_"+args[0]+"_"+Id.(string))
if err != nil || result == nil { if err != nil || result == nil {
return "", fmt.Errorf("GetState data fail,please check your parameters ") return "", fmt.Errorf("get %s data fail,please check your parameters ",args[0]+"_"+Id.(string))
} }
schema := &Schema{} schema := &Schema{}
schemaRes, err := schema.get(args[0], stub) schemaRes, err := schema.get(args[0], stub)
...@@ -221,14 +230,14 @@ func get(args []string, stub shim.ChaincodeStubInterface) (string, error) { ...@@ -221,14 +230,14 @@ func get(args []string, stub shim.ChaincodeStubInterface) (string, error) {
return "", err return "", err
} }
if err := json.Unmarshal([]byte(schemaRes), &schema); err != nil { if err := json.Unmarshal([]byte(schemaRes), &schema); err != nil {
return "", fmt.Errorf("json Unmarshal schemaRes err: %s ", err) return "", fmt.Errorf("The parameters Unmarshal to a Schema structural fail,err: %s ", err)
} }
if err := json.Unmarshal(result, &mapResult); err != nil { if err := json.Unmarshal(result, &mapResult); err != nil {
return "", fmt.Errorf(" Unmarshal fail,result err: %s", err) return "", fmt.Errorf("The original data Unmarshal fail err:%s ", err)
} }
if ok,_:= authorityCheck(schema.SAuth.Read, commonName);!ok { if ok,_:= authorityCheck(schema.SAuth.Read, commonName);!ok {
if filteredData, err := dataFilter(schema.Fields, mapResult, commonName); err != nil { if filteredData, err := dataFilter(schema.Fields, mapResult, commonName); err != nil {
return "", fmt.Errorf(" dataFilter fail, err: %s", err) return "", fmt.Errorf("get data authority filter fail, err: %s", err)
} else { } else {
result, _ := json.Marshal(filteredData) result, _ := json.Marshal(filteredData)
return string(result), nil return string(result), nil
...@@ -280,24 +289,23 @@ func SchemaCheck(schema map[string]SchemaParameters, checkmap map[string]interfa ...@@ -280,24 +289,23 @@ func SchemaCheck(schema map[string]SchemaParameters, checkmap map[string]interfa
return false return false
} }
} }
//else {
// var backUp map[string]SchemaParameters
// backUpByte,_ := json.Marshal(parameterS)
// if err := json.Unmarshal(backUpByte,&backUp);err != nil{
// return false
// }
// if !SchemaCheck(backUp, parameterC) {
// return false
// }
//}
} }
} }
} }
return true return true
} }
func FiledsCheck(schema map[string]SchemaParameters, checkmap map[string]interface{}) error{
for k, v := range checkmap {
if k != "backup" && schema[k].FCheck!= nil&&schema[k].FCheck.FType != ""{
if err := fieldCheckout(schema[k].FCheck,v);err!=nil{
return fmt.Errorf("%s %s ",k,err)
}
}
}
return nil
}
func BackUpCheck(backUp map[string]interface{}, checkmap map[string]interface{}) bool { func BackUpCheck(backUp map[string]interface{}, checkmap map[string]interface{}) bool {
if len(backUp) != len(checkmap) { if len(backUp) != len(checkmap) {
return false return false
...@@ -306,7 +314,6 @@ func BackUpCheck(backUp map[string]interface{}, checkmap map[string]interface{}) ...@@ -306,7 +314,6 @@ func BackUpCheck(backUp map[string]interface{}, checkmap map[string]interface{})
if _, ok := backUp[k]; !ok { if _, ok := backUp[k]; !ok {
return false return false
} }
} }
return true return true
} }
...@@ -341,40 +348,29 @@ func SchemaProcess(args []string, stub shim.ChaincodeStubInterface) (string, err ...@@ -341,40 +348,29 @@ func SchemaProcess(args []string, stub shim.ChaincodeStubInterface) (string, err
*/ */
func (this *Schema) put(args []string, stub shim.ChaincodeStubInterface) (string, error) { func (this *Schema) put(args []string, stub shim.ChaincodeStubInterface) (string, error) {
if len(args) != 2 { if len(args) != 2 {
return "", fmt.Errorf("Expected 2 parameters to function put!") return "", fmt.Errorf("Schema put operation expected 2 parameters!")
} }
var schema *Schema var schema *Schema
var err error var err error
if schema ,err = NewSchema(args[1]);err != nil{ if schema ,err = NewSchema(args[1]);err != nil{
return "", fmt.Errorf("parameters Unmarshal fail,args string not json string,err: %s", err) return "", fmt.Errorf("The parameters Unmarshal to a Schema structural fail,err: %s ", err)
}else{ }else{
if backupValue, ok := schema.Fields["backup"]; ok { if backupValue, ok := schema.Fields["backup"]; ok {
if _,ok := backupValue.Value.(map[string]interface{}); !ok { if _,ok := backupValue.Value.(map[string]interface{}); !ok {
return "", fmt.Errorf("parameters Unmarshal fail,extra string not json string,err: %s", err) return "", fmt.Errorf("backup parameters Unmarshal fail,it not json string,err: %s", err)
} }
//var backUp map[string]SchemaParameters
//backUpByte, _ := json.Marshal(backupValue.Value)
//if err := json.Unmarshal(backUpByte, &backUp); err != nil {
// return "", fmt.Errorf("backup value parameters struct err %s ", err)
//}
} }
} }
//if err := json.Unmarshal([]byte(args[1]), &schema); err != nil {
// return "", fmt.Errorf("parameters Unmarshal fail,args string not json string,err: %s", err)
//} else {
//
//}
_, ok := schema.Fields["id"] _, ok := schema.Fields["id"]
if !ok { if !ok {
return "", fmt.Errorf("The id field must exist ") return "", fmt.Errorf("The id field must exist ")
} }
if value, _ := stub.GetState(PREFIX+"_"+args[0]); value != nil { if value, _ := stub.GetState(PREFIX+"_"+args[0]); value != nil {
return "", fmt.Errorf("the parameter %s already exists and cannot be added", args[0]) return "", fmt.Errorf("the schema %s already exists and cannot be added", args[0])
} }
putDate, _ := json.Marshal(schema) //处理重复字段 putDate, _ := json.Marshal(schema) //处理重复字段
if err := stub.PutState(PREFIX+"_"+args[0], putDate); err != nil { if err := stub.PutState(PREFIX+"_"+args[0], putDate); err != nil {
return "", fmt.Errorf("PutState fail,err: %s", err) return "", fmt.Errorf("Schema PutState fail,err: %s ", err)
} }
return fmt.Sprintf("%s schema put success!", args[0]), nil return fmt.Sprintf("%s schema put success!", args[0]), nil
} }
...@@ -386,16 +382,16 @@ func (this *Schema) put(args []string, stub shim.ChaincodeStubInterface) (string ...@@ -386,16 +382,16 @@ func (this *Schema) put(args []string, stub shim.ChaincodeStubInterface) (string
*/ */
func (this *Schema) update(args []string, stub shim.ChaincodeStubInterface) (string, error) { func (this *Schema) update(args []string, stub shim.ChaincodeStubInterface) (string, error) {
if len(args) != 2 { if len(args) != 2 {
return "", fmt.Errorf("expected 2 parameters to function put! ") return "", fmt.Errorf("Schema update operation expected 2 parameters! ")
} }
var schema *Schema var schema *Schema
var err error var err error
if schema ,err = NewSchema(args[1]);err != nil{ if schema ,err = NewSchema(args[1]);err != nil{
return "", fmt.Errorf("parameters Unmarshal fail,args string not json string,err: %s", err) return "", fmt.Errorf("The parameters Unmarshal to a Schema structural fail,err: %s ", err)
}else{ }else{
if backupValue, ok := schema.Fields["backup"]; ok { if backupValue, ok := schema.Fields["backup"]; ok {
if _,ok := backupValue.Value.(map[string]interface{}); !ok { if _,ok := backupValue.Value.(map[string]interface{}); !ok {
return "", fmt.Errorf("parameters Unmarshal fail,extra string not json string,err: %s", err) return "", fmt.Errorf("backup parameters Unmarshal fail,it not json string,err: %s", err)
} }
} }
} }
...@@ -409,7 +405,7 @@ func (this *Schema) update(args []string, stub shim.ChaincodeStubInterface) (str ...@@ -409,7 +405,7 @@ func (this *Schema) update(args []string, stub shim.ChaincodeStubInterface) (str
} }
if err := json.Unmarshal([]byte(result), &schema); err != nil { if err := json.Unmarshal([]byte(result), &schema); err != nil {
return "", fmt.Errorf("parameters Unmarshal fail, err: %s", err) return "", fmt.Errorf("The parameters Unmarshal to a Schema structural fail, err: %s ", err)
} }
commonName, err := getCertificateCommonName(stub) commonName, err := getCertificateCommonName(stub)
if err != nil { if err != nil {
...@@ -428,7 +424,7 @@ func (this *Schema) update(args []string, stub shim.ChaincodeStubInterface) (str ...@@ -428,7 +424,7 @@ func (this *Schema) update(args []string, stub shim.ChaincodeStubInterface) (str
func (this *Schema) get(args string, stub shim.ChaincodeStubInterface) (string, error) { func (this *Schema) get(args string, stub shim.ChaincodeStubInterface) (string, error) {
result, err := stub.GetState(PREFIX+"_"+args) result, err := stub.GetState(PREFIX+"_"+args)
if err != nil || result == nil { if err != nil || result == nil {
return "", fmt.Errorf("GetSchema data fail,please check your parameters ") return "", fmt.Errorf("GetSchema %s data fail,please check your parameters:err : %s ",args,err)
} }
return string(result), nil return string(result), nil
} }
...@@ -436,7 +432,7 @@ func (this *Schema) get(args string, stub shim.ChaincodeStubInterface) (string, ...@@ -436,7 +432,7 @@ func (this *Schema) get(args string, stub shim.ChaincodeStubInterface) (string,
func (this *Schema) getSchema(args string, stub shim.ChaincodeStubInterface)(string, error) { func (this *Schema) getSchema(args string, stub shim.ChaincodeStubInterface)(string, error) {
result, err := stub.GetState(PREFIX+"_"+args) result, err := stub.GetState(PREFIX+"_"+args)
if err != nil || result == nil { if err != nil || result == nil {
return "", fmt.Errorf("GetSchema data fail,please check your parameters ") return "", fmt.Errorf("GetSchema %s data fail,please check your parameters:err : %s ",args,err)
} }
if err := json.Unmarshal(result, this); err != nil { if err := json.Unmarshal(result, this); err != nil {
return "", fmt.Errorf("SchemaData Unmarshal fail, err: %s", err) return "", fmt.Errorf("SchemaData Unmarshal fail, err: %s", err)
...@@ -452,7 +448,7 @@ func (this *Schema) getSchema(args string, stub shim.ChaincodeStubInterface)(str ...@@ -452,7 +448,7 @@ func (this *Schema) getSchema(args string, stub shim.ChaincodeStubInterface)(str
} }
func getCertificateCommonName(stub shim.ChaincodeStubInterface) (string, error) { func getCertificateCommonName(stub shim.ChaincodeStubInterface) (string, error) {
return "admin",nil return "Admin@org2.example.com",nil
creatorByte, _ := stub.GetCreator() creatorByte, _ := stub.GetCreator()
certStart := bytes.IndexAny(creatorByte, "-----BEGIN") certStart := bytes.IndexAny(creatorByte, "-----BEGIN")
if certStart == -1 { if certStart == -1 {
...@@ -493,12 +489,11 @@ func parsauthorityCheck(schema map[string]SchemaParameters, checkmap map[string] ...@@ -493,12 +489,11 @@ func parsauthorityCheck(schema map[string]SchemaParameters, checkmap map[string]
// } // }
// } // }
//} else { //} else {
if ok,err := authorityCheck(schemaV.PAuth.Write, commonName);!ok { if ok,err := authorityCheck(schemaV.PAuth.Write, commonName);!ok {
return false, fmt.Errorf("%s field permission check does not match, err: %s ", k,err) return false, fmt.Errorf("%s field permission check does not match, err: %s ", k,err)
} }
//} //}
} }
} }
return true, nil return true, nil
} }
...@@ -557,9 +552,9 @@ func authorityCheck(authority AuthGroup, commonName string) (bool,error) { ...@@ -557,9 +552,9 @@ func authorityCheck(authority AuthGroup, commonName string) (bool,error) {
} }
func NewSchema(arg string)(*Schema,error){ func NewSchema(arg string)(*Schema,error){
schema := &Schema{ schema := &Schema{
Fields:make(map[string]SchemaParameters), Fields:make(map[string]SchemaParameters),
} }
var argMap map[string]interface{} var argMap map[string]interface{}
if err := json.Unmarshal([]byte(arg),&argMap);err!=nil{ if err := json.Unmarshal([]byte(arg),&argMap);err!=nil{
return nil,err return nil,err
...@@ -579,6 +574,45 @@ func NewSchema(arg string)(*Schema,error){ ...@@ -579,6 +574,45 @@ func NewSchema(arg string)(*Schema,error){
return schema,nil return schema,nil
} }
func fieldCheckout(check *Checks,val interface{})error{
fType := reflect.TypeOf(val).String()
switch check.FType {
case "string":
if fType != "string"{
return fmt.Errorf("fields type does not match the defined string type! ")
}
if check.Must && (val == ""){
return fmt.Errorf("fields can not be empty")
}
value := val.(string)
if len([]rune(value))>check.Fieldlen{
return fmt.Errorf("fields length must be greater than %d ",check.Fieldlen)
}
case "int","int16","int32","int64","float32","float64":
if fType != "float64"{
return fmt.Errorf("fields type does not match the defined %s type! ",check.FType )
}
value := val.(float64)
if check.Must && (value == 0){
return fmt.Errorf("fields can not be 0")
}
if check.Fieldlen !=0 && value < 0{
return fmt.Errorf("fields cannot be negative")
}
case "time.Time":
if fType != "string"{
return fmt.Errorf("fields type does not match the defined time.Time type! ")
}
dateStr := reflect.ValueOf(val).String()
if check.Must && (dateStr == "0001-01-01 00:00:00 +0000 UTC"|| dateStr == "0001-01-01T00:00:00Z"){
return fmt.Errorf("fields cannot be initial value")
}
default:
fmt.Errorf("fields type no match! ")
}
return nil
}
func main() { func main() {
err := shim.Start(&GXHCC{}) err := shim.Start(&GXHCC{})
......
package main package main
import ( import (
"encoding/json"
"fmt" "fmt"
"github.com/hyperledger/fabric/core/chaincode/shim" "github.com/hyperledger/fabric/core/chaincode/shim"
"testing" "testing"
...@@ -103,6 +104,7 @@ func TestGXHSchemaAuthBytable(t *testing.T){ ...@@ -103,6 +104,7 @@ func TestGXHSchemaAuthBytable(t *testing.T){
fmt.Printf("Invoke status %d,message %s ,and payload %s \n", fmt.Printf("Invoke status %d,message %s ,and payload %s \n",
responseByupdate.Status,responseByupdate.Message,string(responseByupdate.Payload)) responseByupdate.Status,responseByupdate.Message,string(responseByupdate.Payload))
} }
func TestGXHDataPutAuth(t *testing.T){ func TestGXHDataPutAuth(t *testing.T){
cc := new(GXHCC) cc := new(GXHCC)
stub := shim.NewMockStub("GXHCC",cc) stub := shim.NewMockStub("GXHCC",cc)
...@@ -140,4 +142,135 @@ func TestGXHDataPutAuth(t *testing.T){ ...@@ -140,4 +142,135 @@ func TestGXHDataPutAuth(t *testing.T){
responseByget2 := stub.MockInvoke("invoke1",[][]byte{[]byte("get"), []byte("alibusi"),[]byte(`{"id":"1"}`)}) responseByget2 := stub.MockInvoke("invoke1",[][]byte{[]byte("get"), []byte("alibusi"),[]byte(`{"id":"1"}`)})
fmt.Printf("Invoke status %d,message %s ,and payload %s \n", fmt.Printf("Invoke status %d,message %s ,and payload %s \n",
responseByget2.Status,responseByget2.Message,string(responseByget2.Payload)) responseByget2.Status,responseByget2.Message,string(responseByget2.Payload))
} }
\ No newline at end of file
var testData = `{"float64":10.33,"int":10,"string":"我中国人a!","time.Time":"2020-03-06 18:30:07.49752435 +0800 CST m=+0.000270574"}`
func TestFieldCheck(t *testing.T){
var testmap map[string]interface{}
json.Unmarshal([]byte(testData),&testmap)
intC := &Checks{
FType:"int",
Must:true,
Fieldlen:1,
}
err := fieldCheckout(intC,testmap["int"])
if err != nil{
t.Error(err)
}
floatC := &Checks{
FType:"float64",
Must:true,
Fieldlen:1,
}
err = fieldCheckout(floatC,testmap["float64"])
if err != nil{
t.Error(err)
}
stringC := &Checks{
FType:"string",
Must:true,
Fieldlen:6,
}
err = fieldCheckout(stringC,testmap["string"])
if err != nil{
t.Error(err)
}
timeC := &Checks{
FType:"time.Time",
Must:true,
Fieldlen:1,
}
err = fieldCheckout(timeC,testmap["time.Time"])
if err != nil{
t.Error(err)
}
}
var schemaCheck = `{"fields":{"alinkman":{"val":10.34,"auth":{"read":{"users":{"Admin@org2.example.com":0},"roles":
{"Admin@org2.example.com":1583501961}},"write":{"users":{"Admin@org2.example.com":0},"roles":
{"Admin@org2.example.com":1583501961}}},"fcheck":{"ftype":"float64","must":true,"fieldlen":1}},
"amob":{"val":"0001-01-01T00:00:00Z","auth":{"read":{"users":{"Admin@org2.example.com":0},"roles":
{"Admin@org2.example.com":1583501961}},"write":{"users":{"Admin@org2.example.com":0},"roles":{"Admin@org2.example.com":
1583501961}}},"fcheck":{"ftype":"time.Time","must":true,"fieldlen":0}},"aname":{"val":"Aname","auth":{"read":{"users":
{"Admin@org2.example.com":0},"roles":{"Admin@org2.example.com":1583501961}},"write":{"users":{"Admin@org2.example.com":0},
"roles":{"Admin@org2.example.com":1583501961}}},"fcheck":{"ftype":"string","must":true,"fieldlen":16}},"atype":{"val":100,
"auth":{"read":{"users":{"Admin@org2.example.com":0},"roles":{"Admin@org2.example.com":1583501961}},"write":{"users":
{"Admin@org2.example.com":0},"roles":{"Admin@org2.example.com":1583501961}}},"fcheck":{"ftype":"int",
"must":true,"fieldlen":1}},"backup":{"val":{"aname":"Aname","atype":"Atype"},"auth":{"read":{"users":
{"Admin@org2.example.com":0},"roles":{"Admin@org2.example.com":1583501961}},"write":{"users":{"Admin@org2.example.com":0},
"roles":{"Admin@org2.example.com":1583501961}}},"fcheck":null},"id":{"val":"1","auth":{"read":{"users":null,"roles":null},
"write":{"users":null,"roles":null}},"fcheck":null}},"schema_auth":{"read":{"users":null,"roles":null},"write":{"users":
{"Admin@org2.example.com":0},"roles":{"Admin@org2.example.com":1583501961}}},"auth":{"read":{"users":
{"Admin@org2.example.com":0},"roles":{"Admin@org2.example.com":0}},"write":{"users":{"Admin@org2.example.com":0},
"roles":{"Admin@org2.example.com":0}}}}
`
var (
inputC = `{"id":"1","aname":"alibusi","atype":1000,"alinkman":1.233,
"amob":"new1234567890","backup":{"aname":"alibusi","atype":"type"}}`
inputCs = `[{
"id": "1",
"aname": "alibusi",
"atype": 102,
"alinkman": 10.34,
"amob": "0001-01-01 00:00:00 + UTC",
"backup": {
"aname": "alibusi",
"atype": "type"
}
}, {
"id": "2",
"aname": "alibusi",
"atype": 102,
"alinkman": 10.34,
"amob": "0001-01-01 00:00:00 + UTC",
"backup": {
"aname": "alibusi",
"atype": "type"
}
}]`
)
/*
本测试主要进行data put,update的测试操作,主要进行fieldcheck 的测试。
*/
func TestPut(t *testing.T){
cc := new(GXHCC)
stub := shim.NewMockStub("GXHCC",cc)
stub.MockInit("init",nil)
fmt.Println()
fmt.Println("========================================invoke schema put============================================")
fmt.Println()
fmt.Println()
responseByPutschema := stub.MockInvoke("invoke1",[][]byte{[]byte("schema"), []byte("put"),[]byte("alibusi"),[]byte(inputC)})
//使用schema 数据测试过期时间err,schema right data,使用schema3 测试读取字段时的过滤
fmt.Printf("Invoke status %d,message %s and payload %s\n",
responseByPutschema.Status,responseByPutschema.Message,string(responseByPutschema.Payload))
responseByget := stub.MockInvoke("invoke1",[][]byte{[]byte("schema"), []byte("get"),[]byte("alibusi")})
fmt.Printf("Invoke status %d,message %s ,and payload %s \n",
responseByget.Status,responseByget.Message,string(responseByget.Payload))
fmt.Println()
fmt.Println("========================================invoke data put============================================")
fmt.Println()
fmt.Println()
responseByPut := stub.MockInvoke("invoke1",[][]byte{[]byte("put"), []byte("alibusi"),[]byte(inputCs)})
fmt.Printf("Invoke status %d,message %s ,and payload %s\n",
responseByPut.Status,responseByPut.Message,string(responseByPut.Payload))
responseByget = stub.MockInvoke("invoke1",[][]byte{[]byte("get"), []byte("alibusi"),[]byte(`{"id":"1"}`)})
fmt.Printf("Invoke status %d,message %s ,and payload %s \n",
responseByget.Status,responseByget.Message,string(responseByget.Payload))
fmt.Println()
fmt.Println("========================================invoke data update============================================")
fmt.Println()
fmt.Println()
responseByUpdate := stub.MockInvoke("invoke1",[][]byte{[]byte("update"), []byte("alibusi"),[]byte(inputC)})
fmt.Printf("Invoke status %d,message %s ,and payload %s\n",
responseByUpdate.Status,responseByUpdate.Message,string(responseByUpdate.Payload))
responseByget2 := stub.MockInvoke("invoke1",[][]byte{[]byte("get"), []byte("alibusi"),[]byte(`{"id":"1"}`)})
fmt.Printf("Invoke status %d,message %s ,and payload %s \n",
responseByget2.Status,responseByget2.Message,string(responseByget2.Payload))
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment