fabric 智能合约开发

1.智能合约状态图

2.实现功能,通过背书,签收机制实现任务在各部门流转

3.相关sdk

  1. Chaincode接口 {Init,Invoke}方法
  2. ChaincodeStubInterface接口

    1.GetTxTimestamp

    2.CreateCompositeKey

         3.GetQueryResult

4.GetHistoryForKey

5.SetEvent  

6.GetStateByPartialCompositeKey

7.GetFunctionAndParameters

8.PutState

9.DelState

10.GetStateByRange

4.代码架构图

5.开发环境(centos7.4,goland)

6.global.go代码

 1 package global
 2
 3 import "github.com/hyperledger/fabric/common/flogging"
 4
 5 const (
 6     PrescriptionBlockchain_State_NewPublish     ="NewPublish"
 7     PrescriptionBlockchain_State_EndrWaitSign   ="EndrWaitSign"
 8     PrescriptionBlockchain_state_EndrSigned     ="EndrSigned"
 9     HospitalNO_DayTime_PrescriptionID_IndexName ="hospitalno~daytime-prescriptionid"
10     PatientID_PrescriptionID_IndexName          ="patientid~prescriptionid"
11     State_PrescriptionID_IndexName              ="state~prescriptionid"
12     PendingReceivePrescriptionDeptID_PrescriptionID_IndexName="pendingreceiveprescriptiondeptid~prescriptionid"
13     ReceivingPrescriptionDeptID_PrescriptionID_IndexName="receivingprescriptiondeptid~prescriptionid"
14     OpenPrescriptionDeptID_PrescriptionID_IndexName="openprescriptiondeptid~prescriptionid"
15 )
16 var(
17     Logger =flogging.MustGetLogger("PrescriptionChaincode")
18 )

7.prescriptionentity.go代码

 1 package model
 2
 3 type PrescriptionBlockchain struct {
 4     PrescriptionID string `json:"PrescriptionID"`
 5     HospitalNO string `json:"HospitalNO"`
 6     PatientID string `json:"PatientID"`
 7     GenerationTime string `json:"GenerationTime"`
 8     PrescriptionSummary string `json:"PrescriptionSummary"`
 9     OpenPrescriptionDeptID string `json:"OpenPrescriptionDeptID"`
10     OpenPrescriptionDoctorID string `json:"OpenPrescriptionDoctorID"`
11     PendingReceivePrescriptionDeptID string `json:"PendingReceivePrescriptionDeptID"`
12     PendingReceivePrescriptionWorkID string `json:"PendingReceivePrescriptionWorkID"`
13     ReceivingPrescriptionDeptID string `json:"ReceivingPrescriptionDeptID"`
14     ReceivingPrescriptionWorkID string `json:"ReceivingPrescriptionWorkID"`
15     State string `json:"State"`
16     History []HistoryItem `json:"History"`
17 }
18 type HistoryItem struct {
19     TxId string `json:"TxId"`
20     PrescriptionBlockchain PrescriptionBlockchain `json:"PrescriptionBlockchain"`
21 }
22 type ChaincodeRet struct {
23     Code int // 0 success otherwise 1
24     Des  string //description
25 }

8.prescriptioninvoke.go代码

  1 package operation
  2
  3 import (
  4     "github.com/hyperledger/fabric/core/chaincode/shim"
  5     "github.com/hyperledger/fabric/protos/peer"
  6     "fmt"
  7     "github.com/prescriptionserver/chaincode/go/prescription/model"
  8     "encoding/json"
  9     "github.com/prescriptionserver/chaincode/go/prescription/global"
 10     "time"
 11 )
 12
 13 type PrescriptionInvoke struct {
 14     Stub shim.ChaincodeStubInterface
 15     Args []string
 16 }
 17 func (p *PrescriptionInvoke) Publish() peer.Response {
 18
 19     if len(p.Args) != 1{
 20         return shim.Error("Incorrect number of arguments. Expecting 1")
 21     }
 22     fmt.Println("- start publish prescription")
 23     var pbcn model.PrescriptionBlockchain
 24     err := json.Unmarshal([]byte(p.Args[0]), &pbcn)
 25     if err != nil{
 26         return shim.Error("PrescriptionChaincode Invoke publish unmarshal failed")
 27     }
 28     pq := PrescriptionQuery{
 29         Stub:p.Stub,
 30     }
 31     _, exists := pq.GetPbcnByPid(pbcn.PrescriptionID)
 32     if exists{
 33         res := GetRetString(1,
 34             "PrescriptionChaincode Invoke publish failed : the PrescriptionID has exist ")
 35         shim.Error(res)
 36     }
 37     timestamp, err := p.Stub.GetTxTimestamp()
 38     if err != nil{
 39         res := GetRetString(1,"PrescriptionChaincode Invoke publish failed :get time stamp failed")
 40         return shim.Error(res)
 41     }
 42     global.Logger.Error("%s",timestamp)
 43     dayTime :=time.Now().Format("2010-11-11")
 44     pbcn.State=global.PrescriptionBlockchain_State_NewPublish
 45      if !p.put(pbcn){
 46          res :=GetRetString(1,"PrescriptionChaincode Invoke publish put prescription failed")
 47          return shim.Error(res)
 48      }
 49     hospitalNODayTimePrescriptionIDIndexKey,err :=p.Stub.CreateCompositeKey(global.HospitalNO_DayTime_PrescriptionID_IndexName,
 50         []string{pbcn.HospitalNO,dayTime,pbcn.PrescriptionID})
 51     if err != nil{
 52         res:=GetRetString(1,"PrescriptionChaincode Invoke publish create"+
 53             " hospitalno_daytime_prescriptionid composite key failed")
 54         return shim.Error(res)
 55     }
 56     err = p.Stub.PutState(hospitalNODayTimePrescriptionIDIndexKey,
 57         []byte(time.Now().Format("2017-11-20 12:56:56")))
 58     if err != nil{
 59         res :=GetRetString(1,"PrescriptionChaincode Invoke publish put"+
 60             " hospitalno_daytime_prescriptionid search table failed")
 61         return shim.Error(res)
 62     }
 63     patientIDPrescriptionIDIndexKey,err:=p.Stub.CreateCompositeKey(global.PatientID_PrescriptionID_IndexName,
 64         []string{pbcn.PatientID,pbcn.PrescriptionID})
 65     if err != nil{
 66         res:=GetRetString(1,"PrescriptionChaincode Invoke publish"+
 67             " create patientid_prescriptionid composite key failed")
 68         return shim.Error(res)
 69     }
 70     err = p.Stub.PutState(patientIDPrescriptionIDIndexKey,[]byte{0x00})
 71     if err != nil{
 72         res :=GetRetString(1,"PrescriptionChaincode Invoke publish put"+
 73             " patientid_prescriptionid search table failed")
 74         return shim.Error(res)
 75     }
 76     statePrescriptionIDIndexKey,err := p.Stub.CreateCompositeKey(global.State_PrescriptionID_IndexName,
 77         []string{pbcn.State,pbcn.PrescriptionID})
 78     if err != nil{
 79         res:=GetRetString(1,"PrescriptionChaincode Invoke publish"+
 80             " create state_prescriptionid composite key failed")
 81         return shim.Error(res)
 82     }
 83     err = p.Stub.PutState(statePrescriptionIDIndexKey,[]byte{0x00})
 84     if err != nil{
 85         res :=GetRetString(1,"PrescriptionChaincode Invoke publish put"+
 86             " state_prescriptionid search table failed")
 87         return shim.Error(res)
 88     }
 89     openPrescriptionDeptIDPrescriptionIDIndexKey,err :=p.Stub.CreateCompositeKey(global.OpenPrescriptionDeptID_PrescriptionID_IndexName,
 90         []string{pbcn.OpenPrescriptionDeptID,pbcn.PrescriptionID})
 91     if err != nil{
 92         res :=GetRetString(1,"PrescriptionChaincode Invoke publish"+
 93             "create openprescriptiondeptid_prescriptionid composite key failed")
 94         return shim.Error(res)
 95     }
 96     err = p.Stub.PutState(openPrescriptionDeptIDPrescriptionIDIndexKey,[]byte{0x00})
 97     if err != nil{
 98         res:=GetRetString(1,"PrescriptionChaincode Invoke putlish put"+
 99             "openprescriptiondeptid_prescriptionid composite key failed")
100         return shim.Error(res)
101     }
102     res :=GetRetByte(0,"invoke publish success")
103     return shim.Success(res)
104 }
105 func (p *PrescriptionInvoke) put(pbcn model.PrescriptionBlockchain) bool {
106     bytes, err := json.Marshal(pbcn)
107     if err != nil{
108         return false
109     }
110     err = p.Stub.PutState(pbcn.PrescriptionID,bytes)
111     if err != nil{
112         return false
113     }
114     return true
115 }
116 func (p *PrescriptionInvoke) Endorse() peer.Response {
117     if len(p.Args)<3{
118         res:=GetRetString(1,"PrescriptionChaincode Invoke endorse args<3")
119         return shim.Error(res)
120     }
121     pq := PrescriptionQuery{
122         Stub:p.Stub,
123     }
124     pbcn, b := pq.GetPbcnByPid(p.Args[0])
125     if !b{
126         res:=GetRetString(1,"PrescriptionChaincode Invoke endorse get prescription error")
127         return shim.Error(res)
128     }
129     if pbcn.OpenPrescriptionDoctorID == p.Args[1]{
130         res:=GetRetString(1,"PrescriptionChaincode Invoke endorse failed:"+
131             "PendingReceivePrescriptionID should not be same with OpenPrescriptionDoctorID")
132         return shim.Error(res)
133     }
134     if pbcn.ReceivingPrescriptionWorkID==p.Args[1]{
135         res:=GetRetString(1,"PrescriptionChaincode Invoke endorse failed:"+
136             "PendingReceivePrescriptionID should not be same with ReceivingPrescriptionWorkID")
137         return shim.Error(res)
138     }
139     pbcn.PendingReceivePrescriptionDeptID=p.Args[1]
140     pbcn.PendingReceivePrescriptionWorkID=p.Args[2]
141     pbcn.State=global.PrescriptionBlockchain_State_EndrWaitSign
142     pbcn.ReceivingPrescriptionDeptID=""
143     pbcn.ReceivingPrescriptionWorkID=""
144     b=p.put(pbcn)
145     if !b{
146         res:=GetRetString(1,"PrescriptionChaincode Invoke endorse put error")
147         return shim.Error(res)
148     }
149     pendingReceivePrescriptionDeptIDPrescriptionIDIndexKey,err:=p.Stub.CreateCompositeKey(global.PendingReceivePrescriptionDeptID_PrescriptionID_IndexName,
150         []string{pbcn.PendingReceivePrescriptionDeptID,pbcn.PrescriptionID})
151     if err != nil{
152         res:=GetRetString(1,"PrescriptionChaincode Invoke endorse"+
153             " create pendingreceiveprescriptiondeptid_prescriptionid composite key failed")
154         return shim.Error(res)
155     }
156     err = p.Stub.PutState(pendingReceivePrescriptionDeptIDPrescriptionIDIndexKey,[]byte{0x00})
157     if err != nil {
158         res :=GetRetString(1,"PrescriptionChaincode Invoke endorse"+
159             " put PendingReceivePrescriptionDeptIDPrescriptionIDIndexKey error")
160         return shim.Error(res)
161     }
162     res:=GetRetByte(0,"invoke endorse success")
163     return shim.Success(res)
164 }
165 func (p *PrescriptionInvoke) Accept() peer.Response {
166     if len(p.Args) <3{
167         res:=GetRetString(1,"PrescriptionChaincode Invoke accept args<3")
168         return shim.Error(res)
169     }
170     pq:= PrescriptionQuery{
171         Stub:p.Stub,
172     }
173     pbcn,b:=pq.GetPbcnByPid(p.Args[0])
174     if !b{
175         res:=GetRetString(1,"PrescriptionChaincode Invoke accept get prescription error")
176         return shim.Error(res)
177     }
178     if pbcn.PendingReceivePrescriptionDeptID != p.Args[1]{
179         res:=GetRetString(1,"PrescriptionChaincode Invoke accept error:"+
180             "PendingReceivePrescriptionDeptID is not consistent with ReceivingPrescriptionDeptID")
181         return shim.Error(res)
182     }
183     if pbcn.PendingReceivePrescriptionWorkID != p.Args[2]{
184         res:=GetRetString(1,"PrescriptionChaincode Invoke accept error:"+
185             "PendingReceivePrescriptionWorkID is not consistent with ReceivingPrescriptionWorkID")
186         return shim.Error(res)
187     }
188     pbcn.PendingReceivePrescriptionDeptID=""
189     pbcn.PendingReceivePrescriptionWorkID=""
190     pbcn.ReceivingPrescriptionDeptID=p.Args[1]
191     pbcn.ReceivingPrescriptionWorkID=p.Args[2]
192     pbcn.State=global.PrescriptionBlockchain_state_EndrSigned
193     b = p.put(pbcn)
194     if !b{
195         res :=GetRetString(1,"PrescriptionChaincode Invoke accept put error")
196         return shim.Error(res)
197     }
198     receivingPrescriptionDeptIDIndexKey,err:=p.Stub.CreateCompositeKey(global.ReceivingPrescriptionDeptID_PrescriptionID_IndexName,
199         []string{pbcn.ReceivingPrescriptionDeptID,pbcn.PrescriptionID})
200     if err != nil{
201         res:=GetRetString(1,"PrescriptionChaincode Invoke accept"+
202             " create receivingprescriptiondeptid_prescriptionid composite key failed")
203         return shim.Error(res)
204     }
205     err=p.Stub.PutState(receivingPrescriptionDeptIDIndexKey,[]byte{0x00})
206     if err != nil{
207         res :=GetRetString(1,"PrescriptionChaincode Invoke accept"+
208             " put ReceivingPrescriptionDeptIDPrescriptionIDIndexKey error")
209         return shim.Error(res)
210     }
211     res:=GetRetByte(0,"invoke accept success")
212     return shim.Success(res)
213 }

9.prescriptionquery.go代码

  1 package operation
  2
  3 import (
  4     "github.com/prescriptionserver/chaincode/go/prescription/model"
  5     "github.com/hyperledger/fabric/core/chaincode/shim"
  6     "encoding/json"
  7     "github.com/hyperledger/fabric/protos/peer"
  8     "github.com/prescriptionserver/chaincode/go/prescription/global"
  9     "bytes"
 10     "fmt"
 11 )
 12
 13 type PrescriptionQuery struct {
 14     Stub shim.ChaincodeStubInterface
 15     Args []string
 16 }
 17
 18 func (p *PrescriptionQuery) GetPbcnByPid(pid string)(model.PrescriptionBlockchain,bool) {
 19     var pbcn model.PrescriptionBlockchain
 20     bytes, err := p.Stub.GetState(pid)
 21     if bytes == nil {
 22         return pbcn, false
 23     }
 24     err =json.Unmarshal(bytes,&pbcn)
 25     if err != nil{
 26         return pbcn,false
 27     }
 28     return pbcn,true
 29 }
 30 func (p *PrescriptionQuery) GetPbcnsByOpdid() peer.Response {
 31     if len(p.Args) != 1{
 32         res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyopdid args!=1")
 33         return shim.Error(res)
 34     }
 35     pspnsIterator,err :=p.Stub.GetStateByPartialCompositeKey(global.OpenPrescriptionDeptID_PrescriptionID_IndexName,
 36         []string{p.Args[0]})
 37     if err != nil{
 38         res:=GetRetString(1,"PrescriptionChaincode query getpbcnsbyopdid"+
 39             "getstatebypartialcompositekey error")
 40         return shim.Error(res)
 41     }
 42     defer pspnsIterator.Close()
 43     var pbcns []model.PrescriptionBlockchain
 44     for pspnsIterator.HasNext() {
 45         kv,err:=pspnsIterator.Next()
 46         if err != nil{
 47             res:=GetRetString(1,"PrescriptionChaincode query getpbcnsbyopdid iterator.next error")
 48             return shim.Error(res)
 49         }
 50         _, compositeKey, err := p.Stub.SplitCompositeKey(kv.Key)
 51         if err != nil{
 52             res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyopdid"+
 53                 "split composite key error")
 54             return shim.Error(res)
 55         }
 56         if len(compositeKey) <2{
 57             res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyopdid"+
 58                 "composite keys len<2")
 59             return shim.Error(res)
 60         }
 61         pbcn, b := p.GetPbcnByPid(compositeKey[1])
 62         if !b{
 63             res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyopdid getpbcnbypid error")
 64             return shim.Error(res)
 65         }
 66         pbcns =append(pbcns,pbcn)
 67     }
 68     pbcndata,err :=json.Marshal(pbcns)
 69     if err != nil{
 70         res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyopdid json marshal error")
 71         return shim.Error(res)
 72     }
 73     return shim.Success(pbcndata)
 74 }
 75 func (p *PrescriptionQuery) GetPbcnsByPrpdid() peer.Response {
 76     if len(p.Args) != 1{
 77         res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyprpdid args!=1")
 78         return shim.Error(res)
 79     }
 80     pspnsIterator,err :=p.Stub.GetStateByPartialCompositeKey(
 81         global.PendingReceivePrescriptionDeptID_PrescriptionID_IndexName,
 82         []string{p.Args[0]})
 83     if err != nil{
 84         res:=GetRetString(1,"PrescriptionChaincode query getpbcnsbyprpdid"+
 85             "getstatebypartialcompositekey error")
 86         return shim.Error(res)
 87     }
 88     defer pspnsIterator.Close()
 89     var pbcns []model.PrescriptionBlockchain
 90     for pspnsIterator.HasNext() {
 91         kv,err:=pspnsIterator.Next()
 92         if err != nil{
 93             res:=GetRetString(1,"PrescriptionChaincode query getpbcnsbyprpdid iterator.next error")
 94             return shim.Error(res)
 95         }
 96         _, compositeKey, err := p.Stub.SplitCompositeKey(kv.Key)
 97         if err != nil{
 98             res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyprpdid"+
 99                 "split composite key error")
100             return shim.Error(res)
101         }
102         if len(compositeKey) <2{
103             res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyprpdid"+
104                 "composite keys len<2")
105             return shim.Error(res)
106         }
107         pbcn, b := p.GetPbcnByPid(compositeKey[1])
108         if !b{
109             res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyprpdid getpbcnbypid error")
110             return shim.Error(res)
111         }
112         pbcns =append(pbcns,pbcn)
113     }
114     pbcndata,err :=json.Marshal(pbcns)
115     if err != nil{
116         res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyprpdid json marshal error")
117         return shim.Error(res)
118     }
119     return shim.Success(pbcndata)
120 }
121 func (p *PrescriptionQuery) GetPbcnsByState() peer.Response {
122     if len(p.Args) != 1{
123         res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbystate args!=1")
124         return shim.Error(res)
125     }
126     pspnsIterator,err :=p.Stub.GetStateByPartialCompositeKey(global.State_PrescriptionID_IndexName,
127         []string{p.Args[0]})
128     if err != nil{
129         res:=GetRetString(1,"PrescriptionChaincode query getpbcnsbystate"+
130             "getstatebypartialcompositekey error")
131         return shim.Error(res)
132     }
133     defer pspnsIterator.Close()
134     var pbcns []model.PrescriptionBlockchain
135     for pspnsIterator.HasNext() {
136         kv,err:=pspnsIterator.Next()
137         if err != nil{
138             res:=GetRetString(1,"PrescriptionChaincode query getpbcnsbystate iterator.next error")
139             return shim.Error(res)
140         }
141         _, compositeKey, err := p.Stub.SplitCompositeKey(kv.Key)
142         if err != nil{
143             res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbystate"+
144                 "split composite key error")
145             return shim.Error(res)
146         }
147         if len(compositeKey) <2{
148             res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbystate"+
149                 "composite keys len<2")
150             return shim.Error(res)
151         }
152         pbcn, b := p.GetPbcnByPid(compositeKey[1])
153         if !b{
154             res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbystate getpbcnbypid error")
155             return shim.Error(res)
156         }
157         pbcns =append(pbcns,pbcn)
158     }
159     pbcndata,err :=json.Marshal(pbcns)
160     if err != nil{
161         res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbystate json marshal error")
162         return shim.Error(res)
163     }
164     return shim.Success(pbcndata)
165 }
166 func (p *PrescriptionQuery) GetPbcnsByPtnid() peer.Response {
167     if len(p.Args) != 1{
168         res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyptnid args!=1")
169         return shim.Error(res)
170     }
171     pspnsIterator,err :=p.Stub.GetStateByPartialCompositeKey(global.PatientID_PrescriptionID_IndexName,
172         []string{p.Args[0]})
173     if err != nil{
174         res:=GetRetString(1,"PrescriptionChaincode query getpbcnsbyptnid"+
175             "getstatebypartialcompositekey error")
176         return shim.Error(res)
177     }
178     defer pspnsIterator.Close()
179     var pbcns []model.PrescriptionBlockchain
180     for pspnsIterator.HasNext() {
181         kv,err:=pspnsIterator.Next()
182         if err != nil{
183             res:=GetRetString(1,"PrescriptionChaincode query getpbcnsbyptnid iterator.next error")
184             return shim.Error(res)
185         }
186         _, compositeKey, err := p.Stub.SplitCompositeKey(kv.Key)
187         if err != nil{
188             res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyptnid"+
189                 "split composite key error")
190             return shim.Error(res)
191         }
192         if len(compositeKey) <2{
193             res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyptnid"+
194                 "composite keys len<2")
195             return shim.Error(res)
196         }
197         pbcn, b := p.GetPbcnByPid(compositeKey[1])
198         if !b{
199             res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyptnid getpbcnbypid error")
200             return shim.Error(res)
201         }
202         pbcns =append(pbcns,pbcn)
203     }
204     pbcndata,err :=json.Marshal(pbcns)
205     if err != nil{
206         res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyptnid json marshal error")
207         return shim.Error(res)
208     }
209     return shim.Success(pbcndata)
210 }
211 func (p *PrescriptionQuery) GetPbcnsByRpdid() peer.Response {
212     if len(p.Args) != 1{
213         res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyrpdid args!=1")
214         return shim.Error(res)
215     }
216     pspnsIterator,err :=p.Stub.GetStateByPartialCompositeKey(
217         global.ReceivingPrescriptionDeptID_PrescriptionID_IndexName,
218         []string{p.Args[0]})
219     if err != nil{
220         res:=GetRetString(1,"PrescriptionChaincode query getpbcnsbyrpdid"+
221             "getstatebypartialcompositekey error")
222         return shim.Error(res)
223     }
224     defer pspnsIterator.Close()
225     var pbcns []model.PrescriptionBlockchain
226     for pspnsIterator.HasNext() {
227         kv,err:=pspnsIterator.Next()
228         if err != nil{
229             res:=GetRetString(1,"PrescriptionChaincode query getpbcnsbyrpdid iterator.next error")
230             return shim.Error(res)
231         }
232         _, compositeKey, err := p.Stub.SplitCompositeKey(kv.Key)
233         if err != nil{
234             res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyrpdid"+
235                 "split composite key error")
236             return shim.Error(res)
237         }
238         if len(compositeKey) <2{
239             res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyrpdid"+
240                 "composite keys len<2")
241             return shim.Error(res)
242         }
243         pbcn, b := p.GetPbcnByPid(compositeKey[1])
244         if !b{
245             res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyrpdid getpbcnbypid error")
246             return shim.Error(res)
247         }
248         pbcns =append(pbcns,pbcn)
249     }
250     pbcndata,err :=json.Marshal(pbcns)
251     if err != nil{
252         res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyrpdid json marshal error")
253         return shim.Error(res)
254     }
255     return shim.Success(pbcndata)
256 }
257 func (p *PrescriptionQuery) GetPbcnsByHndt() peer.Response {
258     if len(p.Args) !=2{
259         res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyhndt args !=2")
260         return shim.Error(res)
261     }
262     pspnsIterator,err :=p.Stub.GetStateByPartialCompositeKey(global.HospitalNO_DayTime_PrescriptionID_IndexName,
263         []string{p.Args[0],p.Args[1]})
264     if err != nil{
265         res:=GetRetString(1,"PrescriptionChaincode query getpbcnsbyhndt"+
266             "getstatebypartialcompositekey error")
267         return shim.Error(res)
268     }
269     defer pspnsIterator.Close()
270     var pbcns []model.PrescriptionBlockchain
271     for pspnsIterator.HasNext() {
272         kv,err:=pspnsIterator.Next()
273         if err != nil{
274             res:=GetRetString(1,"PrescriptionChaincode query getpbcnsbyhndt iterator.next error")
275             return shim.Error(res)
276         }
277         _, compositeKey, err := p.Stub.SplitCompositeKey(kv.Key)
278         if err != nil{
279             res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyhndt"+
280                 "split composite key error")
281             return shim.Error(res)
282         }
283         if len(compositeKey) <3{
284             res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyhndt"+
285                 "composite keys len<3")
286             return shim.Error(res)
287         }
288         pbcn, b := p.GetPbcnByPid(compositeKey[2])
289         if !b{
290             res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyhndt getpbcnbypid error")
291             return shim.Error(res)
292         }
293         pbcns =append(pbcns,pbcn)
294     }
295     pbcndata,err :=json.Marshal(pbcns)
296     if err != nil{
297         res :=GetRetString(1,"PrescriptionChaincode query getpbcnsbyhndt json marshal error")
298         return shim.Error(res)
299     }
300     return shim.Success(pbcndata)
301 }
302 func (p *PrescriptionQuery) GetHistoryByPid() peer.Response  {
303     if len(p.Args) != 1{
304         res :=GetRetString(1,"PrescriptionChaincode query gethistorybypid args!=1")
305         return shim.Error(res)
306     }
307     pbcn, b := p.GetPbcnByPid(p.Args[0])
308     if !b{
309         res :=GetRetString(1,"PrescriptionChaincode query gethistorybypid get prescription error")
310         return shim.Error(res)
311     }
312     historyIterator, err := p.Stub.GetHistoryForKey(p.Args[0])
313     if err != nil{
314         res:=GetRetString(1,"PrescriptionChaincode query gethistorybypid"+
315             "get history for key error")
316         return shim.Error(res)
317     }
318     defer historyIterator.Close()
319     var historyItems []model.HistoryItem
320     var hispbcn model.PrescriptionBlockchain
321     for historyIterator.HasNext(){
322         hisData, err := historyIterator.Next()
323         if err != nil{
324             res :=GetRetString(1,"PrescriptionChaincode query gethistorybypid"+
325                 "history iterator next error")
326             return shim.Error(res)
327         }
328         hisItem :=model.HistoryItem{
329             TxId:hisData.TxId,
330         }
331         if hisData.Value ==nil{
332             hisItem.PrescriptionBlockchain=hispbcn
333         }else {
334             err = json.Unmarshal(hisData.Value, &hispbcn)
335             if err != nil {
336                 res := GetRetString(1, "PrescriptionChaincode query gethistorybypid"+
337                     "json unmarshal error")
338                 return shim.Error(res)
339             }
340             hisItem.PrescriptionBlockchain=hispbcn
341         }
342         historyItems = append(historyItems,hisItem)
343     }
344     pbcn.History=historyItems
345     pbcndata,err :=json.Marshal(pbcn)
346     if err != nil{
347         res := GetRetString(1, "PrescriptionChaincode query gethistorybypid"+
348             "json marshal error")
349         return shim.Error(res)
350     }
351     return shim.Success(pbcndata)
352 }
353 func (p *PrescriptionQuery) GetPbcnByPrescriptionID() peer.Response {
354     pbcn,b:=p.GetPbcnByPid(p.Args[0])
355     if !b{
356         res :=GetRetString(1,"PrescriptionChaincode query getpbcnbyprescriptionid get pbcn error")
357         return shim.Error(res)
358     }
359     pbcnData, err := json.Marshal(pbcn)
360     if err != nil{
361         res :=GetRetString(1,"PrescriptionChaincode query getpbcnbyprescriptionid json marshal error")
362         return shim.Error(res)
363     }
364     return shim.Success(pbcnData)
365 }
366 func (p *PrescriptionQuery) GetResultByQueryString() peer.Response {
367     if len(p.Args) != 1{
368         res :=GetRetString(1,"PrescriptionChaincode query getresultbyquerystring args!=1")
369         return shim.Error(res)
370     }
371     resultsIterator, err := p.Stub.GetQueryResult(p.Args[0])
372     if err != nil {
373         res :=GetRetString(1,"PrescriptionChaincode query getresultbyquerystring"+
374             "get query result error")
375         return shim.Error(res)
376     }
377     defer resultsIterator.Close()
378
379     var datas bytes.Buffer
380     datas.WriteString("[")
381
382     arrayState := false
383     for resultsIterator.HasNext() {
384         queryData, err := resultsIterator.Next()
385         if err != nil {
386             res :=GetRetString(1,"PrescriptionChaincode query getresultbyquerystring"+
387                 "results iterator next error")
388             return shim.Error(res)
389         }
390         if arrayState == true {
391             datas.WriteString(",")
392         }
393         datas.WriteString("{\"Key\":")
394         datas.WriteString("\"")
395         datas.WriteString(queryData.Key)
396         datas.WriteString("\"")
397
398         datas.WriteString(", \"Record\":")
399         // Record is a JSON object, so we write as-is
400         datas.WriteString(string(queryData.Value))
401         datas.WriteString("}")
402         arrayState = true
403     }
404     datas.WriteString("]")
405
406     fmt.Printf("- getQueryResultForQueryString queryResult:\n%s\n", datas.String())
407     return shim.Success(datas.Bytes())
408 }

10.prescriptionchaincode.go代码

 1 package main
 2
 3 import (
 4     "github.com/hyperledger/fabric/core/chaincode/shim"
 5     "log"
 6     "github.com/hyperledger/fabric/protos/peer"
 7     "github.com/prescriptionserver/chaincode/go/prescription/global"
 8     "github.com/prescriptionserver/chaincode/go/prescription/operation"
 9 )
10 type PrescriptionChaincode struct {
11
12 }
13
14 func (p PrescriptionChaincode) Init(stub shim.ChaincodeStubInterface) peer.Response {
15     return shim.Success(nil)
16 }
17 func (p *PrescriptionChaincode) Invoke(stub shim.ChaincodeStubInterface) peer.Response  {
18     function,args := stub.GetFunctionAndParameters()
19     global.Logger.Info("%s%s","PrescriptionChaincode function=",function)
20     global.Logger.Info("%s%s","PrescriptionChaincode args=",args)
21     pi :=operation.PrescriptionInvoke{
22         Stub:stub,
23         Args:args,
24     }
25     pq := operation.PrescriptionQuery{
26         Stub:stub,
27         Args:args,
28     }
29     if function == "publish" {
30         return pi.Publish()
31     } else if function == "endorse" {
32         return pi.Endorse()
33     } else if function == "accept" {
34         return pi.Accept()
35     }
36
37     if function == "getpbcnbypid" {
38         return pq.GetPbcnByPrescriptionID()
39     } else if function == "getpbcnsbyopdid" {
40         return pq.GetPbcnsByOpdid()
41     } else if function == "getpbcnsbyprpdid" {
42         return pq.GetPbcnsByPrpdid()
43     }else if function == "getpbcnsbystate" {
44         return pq.GetPbcnsByState()
45     }else if function == "getpbcnsbyptnid" {
46         return pq.GetPbcnsByPtnid()
47     }else if function == "getpbcnsbyrpdid" {
48         return pq.GetPbcnsByRpdid()
49     }else if function == "getpbcnsbyhndt" {
50         return pq.GetPbcnsByHndt()
51     }else if function == "gethistorybypid" {
52         return pq.GetHistoryByPid()
53     }else if function == "getresultbyquerystring" {
54         return pq.GetResultByQueryString()
55     }
56
57     res := operation.GetRetString(1,"PrescriptionChaincode Unkown method!")
58     global.Logger.Info("%s",res)
59     global.Logger.Infof("%s",res)
60     return shim.Error(res)
61 }
62
63
64 func main() {
65     if err := shim.Start(new (PrescriptionChaincode));err != nil{
66         log.Printf("error starting prescription chaincode: %v",err)
67     }
68 }

go client sdk的相关开发以后有时间补全吧,chaincode sdk相关的内容有时间了再补

 

原文地址:https://www.cnblogs.com/apolov-fabric/p/9670265.html

时间: 2024-11-10 07:00:53

fabric 智能合约开发的相关文章

hyperledger fabric 智能合约开发

智能合约部分 太困了,休假的时候再把图贴上 ..... 运行在docker容器里面,如果需要调试只能通过打日志log方式 一个合约,就是一个用户用go/java/ node编写的文件(包括:字符,方法,返回信息) 块中 (chaincode目录下),一个合约只能对应一个目录 下面目录有用go/java/node语言开发智能合约的代码 下面网址可以查看channel跟存入的数据等(一个合约跟一个channel会生成一个库) 一个channel下可以安装多个合约,每个合约都会生成一个数据库 安装合约

HyperLeger Fabric开发(六)——HyperLeger Fabric智能合约(链码)

HyperLeger Fabric开发(六)--HyperLeger Fabric智能合约(ChainCode) 一.链码(Chaincode)简介 1.链码简介 在Fabric中,智能合约也称为链码(chaincode),分为用户链码和系统链码.系统链码用来实现系统层面的功能,包括系统的配置,用户链码的部署.升级,用户交易的签名和验证策略等:用户链码用于实现用户的应用功能,开发者编写链码应用程序并将其部署到区块链网络上,终端用户通过与网络节点交互的客户端应用程序调用链码.链码被编译成一个独立的

以太坊智能合约开发工具 Truffle 最佳入门指导1

Truffle是以太坊(Ethereum)智能合约开发的瑞士军刀,小巧好用,上手简单. 本篇文章主要展示如何用Truffle 开发第一个Ethereum智能合约. 1.准备工作:(本人针对window环境,如果是mac 或linux可以自行搜索其他教程) a.安装git bash :http://gitforwindows.org/ b.安装npm:https://jingyan.baidu.com/article/a17d528506d7f58098c8f2b0.html 2.安装Truffl

NEO智能合约开发(二)再续不可能的任务

? NEO智能合约开发中,应用合约比较简单,是的你没看错,应用合约比较简单. 应用合约三部曲,发布.调用.看结果.除了看结果工具比较缺乏,发布调用neogui最起码可以支撑你测试. ? 鉴权合约比较麻烦,因为neogui不能支持你很好的测试鉴权合约. ? 这是一个难点,上一次我们让你试着用鉴权合约往外取钱了,一个密码,有了密码谁都能取钱.就那,用neogui去取并不容易,对吧. ? 这一次我们继续探讨这个话题,一个更有价值的应用场景. 如何限制一个用户能从智能合约里取出多少钱? ? 不用担心,如

智能合约开发环境搭建及Hello World合约

如果你对于以太坊智能合约开发还没有概念(本文会假设你已经知道这些概念),建议先阅读入门篇.就先学习任何编程语言一样,入门的第一个程序都是Hello World.今天我们来一步一步从搭建以太坊智能合约开发环境开始,讲解智能合约的Hello World如何编写. 开发环境搭建 Solidity安装 强烈建议新手使用Browser-Solidity来进行开发.Browser-Solidity是一个基于浏览器的Solidity,就可以不用安装Solidity,本文的Hello World教程也将基于Br

郑重告之:智能合约开发实训营第4期学员招募正式启动!

各位同学,抱歉久等了- 这是终于到来的<以太坊智能合约全栈开发>实战特训营第四期的正式招募通知. <以太坊智能合约全栈开发>实战特训营是由硅谷密探和 celer network 共同打造的全球第一档·智能合约全栈开发实战课程,也是目前唯一一个实现来自中.美.澳.英.日.韩等多国学员在线互动学习的区块链技术实战特训课程. 为了保证教学质量,如今已调整为每期仅招募100人,参与有门槛,需经过层层审核,录取通过率一度不到10%,并非所有人都适合参与. 拉至文末可直接进行报名. 请点击此处

EOS智能合约开发(三):EOS创建和管理账号

没有看前面文章的小伙伴可以看一下 EOS智能合约开发(一):EOS环境搭建和启动节点 EOS智能合约开发(二):EOS创建和管理钱包 创建好钱包.密钥之后,接下来你就可以创建账号了,账号是什么?账号保存在区块链上的人类可读的标志符. 创建账号的命令: $ cleos createaccount eosio ${new_account} ${owner_key} ${active_key} 其中eosio是超级用户,需要靠超级用户来创建其它的新用户,eosio后面就是你的新用户的用户名. 除了新的

2018年以太坊智能合约开发语言Solidity最佳IDEs

Solidity是一种以智能合约为导向的编程语言.这是一种只有四年的年轻语言,旨在帮助开发基于以太坊数字货币的智能合约. 理解它官方文档应该是学习Solidity的最佳来源:solidity.readthedocs.io 想在以太坊的网络上建立自己的加密货币吗?想拥有自己的初始代码产品吗?以下是您今天可以使用的最佳Solidity IDE. Remix IDE Remix IDE是基于浏览器的,并且集成了编译器.没有服务器端组件. 官网: https://remix.ethereum.orggi

如何用python和flask以太坊智能合约开发

将数据存储在数据库中是任何软件应用程序不可或缺的一部分.无论如何控制该数据库都有一个该数据的主控.区块链技术将数据存储到区块链网络内的区块中.因此,只要某个节点与网络同步,它们就会获得区块中数据的副本.因此,该技术中没有特定的数据主控. 在本教程中,我们将编写一份智能合约(我将进一步解释),以便在区块链上保留用户数据.我们将使用python web3(web3的python库)来开发和部署智能合约.一旦我们在区块链上部署了智能合约.我们将使用flask API与智能合约进行交互以存储一些数据/信