Skip to content

Commit d4d237d

Browse files
committed
feat: add ccapi
Signed-off-by: osamamagdy <osamamagdy174@gmail.com>
1 parent 2b8ae26 commit d4d237d

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

48 files changed

+5176
-0
lines changed
18.3 KB
Loading
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Use an official Golang runtime as a parent image
2+
FROM golang:1.19-alpine AS build
3+
4+
ENV PATH="${PATH}:/usr/bin/"
5+
6+
RUN apk update
7+
8+
RUN apk add \
9+
docker \
10+
openrc \
11+
git \
12+
gcc \
13+
gcompat \
14+
libc-dev \
15+
libc6-compat \
16+
libstdc++ && \
17+
ln -s /lib/libc.so.6 /usr/lib/libresolv.so.2
18+
19+
# Set the working directory to /rest-server
20+
WORKDIR /rest-server
21+
22+
# Copy the go.mod and go.sum files for dependency management
23+
COPY go.mod go.sum ./
24+
25+
# Install go dependencies
26+
RUN go mod download
27+
28+
RUN go mod vendor
29+
30+
# Copy the current directory contents into the container at /rest-server
31+
COPY . .
32+
33+
# Build the Go ccapi
34+
RUN go build -o ccapi
35+
36+
# Use an official Alpine runtime as a parent image
37+
FROM alpine:latest
38+
39+
ENV PATH="${PATH}:/usr/bin/"
40+
41+
RUN apk update
42+
43+
RUN apk add \
44+
docker \
45+
openrc \
46+
git \
47+
gcc \
48+
gcompat \
49+
libc-dev \
50+
libc6-compat \
51+
libstdc++ && \
52+
ln -s /lib/libc.so.6 /usr/lib/libresolv.so.2
53+
54+
# Set the working directory to /rest-server
55+
WORKDIR /rest-server
56+
57+
# Copy the ccapi binary from the build container to the current directory in the Alpine container
58+
COPY --from=build /rest-server/ccapi /usr/bin/ccapi
59+
60+
# Run the ccapi binary
61+
CMD ["ccapi"]
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# CCAPI - A web server developed to interface with CC-tools chaincode
2+
3+
## Motivation
4+
5+
As continuation to the [cc-tools-demo]() tutorial on how to integrate the cc-tools project with FPC chaincodes, we start by utilizing another powerful solution offered by cc-tools is the CCAPI. It's a complete web server that simplifies the communication with the peers and Fabric components to replace the need to deal with CLI applications.
6+
7+
## Architecture
8+
9+
The following diagram explains the process where we modified the API server developed for a demo on cc-tools ([CCAPI](https://github.com/hyperledger-labs/cc-tools-demo/tree/main/ccapi)) and modified it to communicate with FPC code.
10+
11+
The transaction client invocation process, as illustrated in the diagram, consists of several key steps that require careful integration between FPC and cc-tools.
12+
13+
1. Step 1-2: The API server is listening for requests on a specified port over an HTTP channel and sends it to the handler.
14+
2. Step 3: The handler starts by determining the appropriate transaction invocation based on the requested endpoint and calling the corresponding chaincode API.
15+
3. Step 4: The chaincode API is responsible for parsing and ensuring the payload is correctly parsed into a format that is FPC-friendly. This parsing step is crucial, as it prepares the data to meet FPC’s privacy and security requirements before it reaches the peer.
16+
4. Step 5: FPCUtils is the step where the actual transaction invocation happens and it follows the steps explained in the previous diagram as it builds on top of the FPC Client SDK.
17+
18+
![CCAPIFlow](./CCAPIFlow.png)
19+
20+
## User Experience
21+
22+
CCAPI is using docker and docker-compose for spinning up all the required components needed to work.
23+
24+
Have a look at the [fpc-docker-compose.yaml](./fpc-docker-compose.yaml) to see how we use different env vars. Most of these environment variables are required by any client application to work and communicate with FPC. If you followed the [cc-tools-demo](../../chaincode/cc-tools-demo/README.md) tutorial, the values should be the same.
25+
26+
Start by running `docker-compose -f fpc-docker-compose.yaml up` then go to the browser and type `localhost:80` to open the swagger api and start executing functions.
27+
28+
## Future work
29+
30+
CCAPI have another component for the dashboard frontend application but it's not yet utilized with
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
package chaincode
2+
3+
import (
4+
"encoding/json"
5+
"fmt"
6+
"log"
7+
"os"
8+
"regexp"
9+
10+
"github.com/hyperledger-labs/ccapi/common"
11+
ev "github.com/hyperledger/fabric-sdk-go/pkg/client/event"
12+
"github.com/hyperledger/fabric-sdk-go/pkg/common/providers/fab"
13+
)
14+
15+
func getEventClient(channelName string) (*ev.Client, error) {
16+
// create channel manager
17+
fabMngr, err := common.NewFabricChClient(channelName, os.Getenv("USER"), os.Getenv("ORG"))
18+
if err != nil {
19+
return nil, err
20+
}
21+
22+
// Create event client
23+
ec, err := ev.New(fabMngr.Provider, ev.WithBlockEvents())
24+
if err != nil {
25+
return nil, err
26+
}
27+
28+
return ec, nil
29+
}
30+
31+
func WaitForEvent(channelName, ccName, eventName string, fn func(*fab.CCEvent)) {
32+
ec, err := getEventClient(channelName)
33+
if err != nil {
34+
log.Println("error getting event client: ", err)
35+
return
36+
}
37+
38+
for {
39+
// Register chaincode event
40+
registration, notifier, err := ec.RegisterChaincodeEvent(ccName, eventName)
41+
if err != nil {
42+
log.Println("error registering chaincode event: ", err)
43+
return
44+
}
45+
46+
// Execute handler function on event notification
47+
ccEvent := <-notifier
48+
fmt.Printf("Received CC event: %v\n", ccEvent)
49+
fn(ccEvent)
50+
51+
ec.Unregister(registration)
52+
}
53+
}
54+
55+
func HandleEvent(channelName, ccName string, event EventHandler) {
56+
ec, err := getEventClient(channelName)
57+
if err != nil {
58+
log.Println("error getting event client: ", err)
59+
return
60+
}
61+
62+
for {
63+
// Register chaincode event
64+
registration, notifier, err := ec.RegisterChaincodeEvent(ccName, event.Tag)
65+
if err != nil {
66+
log.Println("error registering chaincode event: ", err)
67+
return
68+
}
69+
70+
// Execute handler function on event notification
71+
ccEvent := <-notifier
72+
fmt.Printf("Received CC event: %v\n", ccEvent)
73+
event.Execute(ccEvent)
74+
75+
ec.Unregister(registration)
76+
}
77+
}
78+
79+
func RegisterForEvents() {
80+
// Get registered events on the chaincode
81+
res, _, err := Invoke(os.Getenv("CHANNEL"), os.Getenv("CCNAME"), "getEvents", os.Getenv("USER"), nil, nil)
82+
if err != nil {
83+
fmt.Println("error registering for events: ", err)
84+
return
85+
}
86+
87+
var events []interface{}
88+
nerr := json.Unmarshal(res.Payload, &events)
89+
if nerr != nil {
90+
fmt.Println("error unmarshalling events: ", nerr)
91+
return
92+
}
93+
94+
msp := common.GetClientOrg() + "MSP"
95+
96+
for _, event := range events {
97+
eventMap := event.(map[string]interface{})
98+
receiverArr, ok := eventMap["receivers"]
99+
100+
isReceiver := true
101+
// Verify if the MSP is a receiver for the event
102+
if ok {
103+
isReceiver = false
104+
receivers := receiverArr.([]interface{})
105+
for _, r := range receivers {
106+
receiver := r.(string)
107+
108+
if len(receiver) <= 1 {
109+
continue
110+
}
111+
if receiver[0] == '$' {
112+
match, err := regexp.MatchString(receiver[1:], msp)
113+
if err != nil {
114+
fmt.Println("error matching regexp: ", err)
115+
return
116+
}
117+
if match {
118+
isReceiver = true
119+
break
120+
}
121+
} else {
122+
if receiver == msp {
123+
isReceiver = true
124+
break
125+
}
126+
}
127+
}
128+
}
129+
130+
if isReceiver {
131+
eventHandler := EventHandler{
132+
Tag: eventMap["tag"].(string),
133+
Type: EventType(eventMap["type"].(float64)),
134+
Transaction: eventMap["transaction"].(string),
135+
Channel: eventMap["channel"].(string),
136+
Chaincode: eventMap["chaincode"].(string),
137+
Label: eventMap["label"].(string),
138+
BaseLog: eventMap["baseLog"].(string),
139+
ReadOnly: eventMap["readOnly"].(bool),
140+
}
141+
142+
go HandleEvent(os.Getenv("CHANNEL"), os.Getenv("CCNAME"), eventHandler)
143+
}
144+
}
145+
}
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
package chaincode
2+
3+
import (
4+
b64 "encoding/base64"
5+
"encoding/json"
6+
"fmt"
7+
"os"
8+
9+
"github.com/hyperledger/fabric-sdk-go/pkg/common/providers/fab"
10+
)
11+
12+
type EventType float64
13+
14+
const (
15+
EventLog EventType = iota
16+
EventTransaction
17+
EventCustom
18+
)
19+
20+
type EventHandler struct {
21+
Tag string
22+
Label string
23+
Type EventType
24+
Transaction string
25+
Channel string
26+
Chaincode string
27+
BaseLog string
28+
ReadOnly bool
29+
}
30+
31+
func (event EventHandler) Execute(ccEvent *fab.CCEvent) {
32+
if len(event.BaseLog) > 0 {
33+
fmt.Println(event.BaseLog)
34+
}
35+
36+
if event.Type == EventLog {
37+
var logStr string
38+
nerr := json.Unmarshal(ccEvent.Payload, &logStr)
39+
if nerr != nil {
40+
fmt.Println("error unmarshalling log: ", nerr)
41+
return
42+
}
43+
44+
if len(logStr) > 0 {
45+
fmt.Println("Event '", event.Label, "' log: ", logStr)
46+
}
47+
} else if event.Type == EventTransaction {
48+
ch := os.Getenv("CHANNEL")
49+
if event.Channel != "" {
50+
ch = event.Channel
51+
}
52+
cc := os.Getenv("CCNAME")
53+
if event.Chaincode != "" {
54+
cc = event.Chaincode
55+
}
56+
57+
res, _, err := Invoke(ch, cc, event.Transaction, os.Getenv("USER"), [][]byte{ccEvent.Payload}, nil)
58+
if err != nil {
59+
fmt.Println("error invoking transaction: ", err)
60+
return
61+
}
62+
63+
var response map[string]interface{}
64+
nerr := json.Unmarshal(res.Payload, &response)
65+
if nerr != nil {
66+
fmt.Println("error unmarshalling response: ", nerr)
67+
return
68+
}
69+
fmt.Println("Response: ", response)
70+
} else if event.Type == EventCustom {
71+
// Encode payload to base64
72+
b64Encode := b64.StdEncoding.EncodeToString([]byte(ccEvent.Payload))
73+
74+
args, ok := json.Marshal(map[string]interface{}{
75+
"eventTag": event.Tag,
76+
"payload": b64Encode,
77+
})
78+
if ok != nil {
79+
fmt.Println("failed to encode args to JSON format")
80+
return
81+
}
82+
83+
// Invoke tx
84+
txName := "executeEvent"
85+
if event.ReadOnly {
86+
txName = "runEvent"
87+
}
88+
89+
_, _, err := Invoke(os.Getenv("CHANNEL"), os.Getenv("CCNAME"), txName, os.Getenv("USER"), [][]byte{args}, nil)
90+
if err != nil {
91+
fmt.Println("error invoking transaction: ", err)
92+
return
93+
}
94+
} else {
95+
fmt.Println("Event type not supported")
96+
}
97+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package chaincode
2+
3+
import (
4+
"net/http"
5+
"os"
6+
7+
"github.com/hyperledger-labs/ccapi/common"
8+
"github.com/hyperledger/fabric-sdk-go/pkg/client/channel"
9+
"github.com/hyperledger/fabric-sdk-go/pkg/common/errors/retry"
10+
)
11+
12+
func Invoke(channelName, ccName, txName, user string, txArgs [][]byte, transientRequest []byte) (*channel.Response, int, error) {
13+
// create channel manager
14+
fabMngr, err := common.NewFabricChClient(channelName, user, os.Getenv("ORG"))
15+
if err != nil {
16+
return nil, http.StatusInternalServerError, err
17+
}
18+
19+
// Execute chaincode with channel's client
20+
rq := channel.Request{ChaincodeID: ccName, Fcn: txName}
21+
if len(txArgs) > 0 {
22+
rq.Args = txArgs
23+
}
24+
25+
if len(transientRequest) != 0 {
26+
transientMap := make(map[string][]byte)
27+
transientMap["@request"] = transientRequest
28+
rq.TransientMap = transientMap
29+
}
30+
31+
res, err := fabMngr.Client.Execute(rq, channel.WithRetry(retry.DefaultChannelOpts))
32+
if err != nil {
33+
return nil, extractStatusCode(err.Error()), err
34+
}
35+
36+
return &res, http.StatusOK, nil
37+
}

0 commit comments

Comments
 (0)