-
Notifications
You must be signed in to change notification settings - Fork 91
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
2b8ae26
commit 748ac3f
Showing
48 changed files
with
5,176 additions
and
0 deletions.
There are no files selected for viewing
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
# Use an official Golang runtime as a parent image | ||
FROM golang:1.19-alpine AS build | ||
|
||
ENV PATH="${PATH}:/usr/bin/" | ||
|
||
RUN apk update | ||
|
||
RUN apk add \ | ||
docker \ | ||
openrc \ | ||
git \ | ||
gcc \ | ||
gcompat \ | ||
libc-dev \ | ||
libc6-compat \ | ||
libstdc++ && \ | ||
ln -s /lib/libc.so.6 /usr/lib/libresolv.so.2 | ||
|
||
# Set the working directory to /rest-server | ||
WORKDIR /rest-server | ||
|
||
# Copy the go.mod and go.sum files for dependency management | ||
COPY go.mod go.sum ./ | ||
|
||
# Install go dependencies | ||
RUN go mod download | ||
|
||
RUN go mod vendor | ||
|
||
# Copy the current directory contents into the container at /rest-server | ||
COPY . . | ||
|
||
# Build the Go ccapi | ||
RUN go build -o ccapi | ||
|
||
# Use an official Alpine runtime as a parent image | ||
FROM alpine:latest | ||
|
||
ENV PATH="${PATH}:/usr/bin/" | ||
|
||
RUN apk update | ||
|
||
RUN apk add \ | ||
docker \ | ||
openrc \ | ||
git \ | ||
gcc \ | ||
gcompat \ | ||
libc-dev \ | ||
libc6-compat \ | ||
libstdc++ && \ | ||
ln -s /lib/libc.so.6 /usr/lib/libresolv.so.2 | ||
|
||
# Set the working directory to /rest-server | ||
WORKDIR /rest-server | ||
|
||
# Copy the ccapi binary from the build container to the current directory in the Alpine container | ||
COPY --from=build /rest-server/ccapi /usr/bin/ccapi | ||
|
||
# Run the ccapi binary | ||
CMD ["ccapi"] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
# CCAPI - A web server developed to interface with CC-tools chaincode | ||
|
||
## Motivation | ||
|
||
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. | ||
|
||
## Architecture | ||
|
||
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. | ||
|
||
The transaction client invocation process, as illustrated in the diagram, consists of several key steps that require careful integration between FPC and cc-tools. | ||
|
||
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. | ||
2. Step 3: The handler starts by determining the appropriate transaction invocation based on the requested endpoint and calling the corresponding chaincode API. | ||
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. | ||
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. | ||
|
||
![CCAPIFlow](./CCAPIFlow.png) | ||
|
||
## User Experience | ||
|
||
CCAPI is using docker and docker-compose for spinning up all the required components needed to work. | ||
|
||
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. | ||
|
||
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. | ||
|
||
## Future work | ||
|
||
CCAPI have another component for the dashboard frontend application but it's not yet utilized with |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,145 @@ | ||
package chaincode | ||
|
||
import ( | ||
"encoding/json" | ||
"fmt" | ||
"log" | ||
"os" | ||
"regexp" | ||
|
||
"github.com/hyperledger-labs/ccapi/common" | ||
ev "github.com/hyperledger/fabric-sdk-go/pkg/client/event" | ||
"github.com/hyperledger/fabric-sdk-go/pkg/common/providers/fab" | ||
) | ||
|
||
func getEventClient(channelName string) (*ev.Client, error) { | ||
// create channel manager | ||
fabMngr, err := common.NewFabricChClient(channelName, os.Getenv("USER"), os.Getenv("ORG")) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
// Create event client | ||
ec, err := ev.New(fabMngr.Provider, ev.WithBlockEvents()) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
return ec, nil | ||
} | ||
|
||
func WaitForEvent(channelName, ccName, eventName string, fn func(*fab.CCEvent)) { | ||
ec, err := getEventClient(channelName) | ||
if err != nil { | ||
log.Println("error getting event client: ", err) | ||
return | ||
} | ||
|
||
for { | ||
// Register chaincode event | ||
registration, notifier, err := ec.RegisterChaincodeEvent(ccName, eventName) | ||
if err != nil { | ||
log.Println("error registering chaincode event: ", err) | ||
return | ||
} | ||
|
||
// Execute handler function on event notification | ||
ccEvent := <-notifier | ||
fmt.Printf("Received CC event: %v\n", ccEvent) | ||
fn(ccEvent) | ||
|
||
ec.Unregister(registration) | ||
} | ||
} | ||
|
||
func HandleEvent(channelName, ccName string, event EventHandler) { | ||
ec, err := getEventClient(channelName) | ||
if err != nil { | ||
log.Println("error getting event client: ", err) | ||
return | ||
} | ||
|
||
for { | ||
// Register chaincode event | ||
registration, notifier, err := ec.RegisterChaincodeEvent(ccName, event.Tag) | ||
if err != nil { | ||
log.Println("error registering chaincode event: ", err) | ||
return | ||
} | ||
|
||
// Execute handler function on event notification | ||
ccEvent := <-notifier | ||
fmt.Printf("Received CC event: %v\n", ccEvent) | ||
event.Execute(ccEvent) | ||
|
||
ec.Unregister(registration) | ||
} | ||
} | ||
|
||
func RegisterForEvents() { | ||
// Get registered events on the chaincode | ||
res, _, err := Invoke(os.Getenv("CHANNEL"), os.Getenv("CCNAME"), "getEvents", os.Getenv("USER"), nil, nil) | ||
if err != nil { | ||
fmt.Println("error registering for events: ", err) | ||
return | ||
} | ||
|
||
var events []interface{} | ||
nerr := json.Unmarshal(res.Payload, &events) | ||
if nerr != nil { | ||
fmt.Println("error unmarshalling events: ", nerr) | ||
return | ||
} | ||
|
||
msp := common.GetClientOrg() + "MSP" | ||
|
||
for _, event := range events { | ||
eventMap := event.(map[string]interface{}) | ||
receiverArr, ok := eventMap["receivers"] | ||
|
||
isReceiver := true | ||
// Verify if the MSP is a receiver for the event | ||
if ok { | ||
isReceiver = false | ||
receivers := receiverArr.([]interface{}) | ||
for _, r := range receivers { | ||
receiver := r.(string) | ||
|
||
if len(receiver) <= 1 { | ||
continue | ||
} | ||
if receiver[0] == '$' { | ||
match, err := regexp.MatchString(receiver[1:], msp) | ||
if err != nil { | ||
fmt.Println("error matching regexp: ", err) | ||
return | ||
} | ||
if match { | ||
isReceiver = true | ||
break | ||
} | ||
} else { | ||
if receiver == msp { | ||
isReceiver = true | ||
break | ||
} | ||
} | ||
} | ||
} | ||
|
||
if isReceiver { | ||
eventHandler := EventHandler{ | ||
Tag: eventMap["tag"].(string), | ||
Type: EventType(eventMap["type"].(float64)), | ||
Transaction: eventMap["transaction"].(string), | ||
Channel: eventMap["channel"].(string), | ||
Chaincode: eventMap["chaincode"].(string), | ||
Label: eventMap["label"].(string), | ||
BaseLog: eventMap["baseLog"].(string), | ||
ReadOnly: eventMap["readOnly"].(bool), | ||
} | ||
|
||
go HandleEvent(os.Getenv("CHANNEL"), os.Getenv("CCNAME"), eventHandler) | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
package chaincode | ||
|
||
import ( | ||
b64 "encoding/base64" | ||
"encoding/json" | ||
"fmt" | ||
"os" | ||
|
||
"github.com/hyperledger/fabric-sdk-go/pkg/common/providers/fab" | ||
) | ||
|
||
type EventType float64 | ||
|
||
const ( | ||
EventLog EventType = iota | ||
EventTransaction | ||
EventCustom | ||
) | ||
|
||
type EventHandler struct { | ||
Tag string | ||
Label string | ||
Type EventType | ||
Transaction string | ||
Channel string | ||
Chaincode string | ||
BaseLog string | ||
ReadOnly bool | ||
} | ||
|
||
func (event EventHandler) Execute(ccEvent *fab.CCEvent) { | ||
if len(event.BaseLog) > 0 { | ||
fmt.Println(event.BaseLog) | ||
} | ||
|
||
if event.Type == EventLog { | ||
var logStr string | ||
nerr := json.Unmarshal(ccEvent.Payload, &logStr) | ||
if nerr != nil { | ||
fmt.Println("error unmarshalling log: ", nerr) | ||
return | ||
} | ||
|
||
if len(logStr) > 0 { | ||
fmt.Println("Event '", event.Label, "' log: ", logStr) | ||
} | ||
} else if event.Type == EventTransaction { | ||
ch := os.Getenv("CHANNEL") | ||
if event.Channel != "" { | ||
ch = event.Channel | ||
} | ||
cc := os.Getenv("CCNAME") | ||
if event.Chaincode != "" { | ||
cc = event.Chaincode | ||
} | ||
|
||
res, _, err := Invoke(ch, cc, event.Transaction, os.Getenv("USER"), [][]byte{ccEvent.Payload}, nil) | ||
if err != nil { | ||
fmt.Println("error invoking transaction: ", err) | ||
return | ||
} | ||
|
||
var response map[string]interface{} | ||
nerr := json.Unmarshal(res.Payload, &response) | ||
if nerr != nil { | ||
fmt.Println("error unmarshalling response: ", nerr) | ||
return | ||
} | ||
fmt.Println("Response: ", response) | ||
} else if event.Type == EventCustom { | ||
// Encode payload to base64 | ||
b64Encode := b64.StdEncoding.EncodeToString([]byte(ccEvent.Payload)) | ||
|
||
args, ok := json.Marshal(map[string]interface{}{ | ||
"eventTag": event.Tag, | ||
"payload": b64Encode, | ||
}) | ||
if ok != nil { | ||
fmt.Println("failed to encode args to JSON format") | ||
return | ||
} | ||
|
||
// Invoke tx | ||
txName := "executeEvent" | ||
if event.ReadOnly { | ||
txName = "runEvent" | ||
} | ||
|
||
_, _, err := Invoke(os.Getenv("CHANNEL"), os.Getenv("CCNAME"), txName, os.Getenv("USER"), [][]byte{args}, nil) | ||
if err != nil { | ||
fmt.Println("error invoking transaction: ", err) | ||
return | ||
} | ||
} else { | ||
fmt.Println("Event type not supported") | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
package chaincode | ||
|
||
import ( | ||
"net/http" | ||
"os" | ||
|
||
"github.com/hyperledger-labs/ccapi/common" | ||
"github.com/hyperledger/fabric-sdk-go/pkg/client/channel" | ||
"github.com/hyperledger/fabric-sdk-go/pkg/common/errors/retry" | ||
) | ||
|
||
func Invoke(channelName, ccName, txName, user string, txArgs [][]byte, transientRequest []byte) (*channel.Response, int, error) { | ||
// create channel manager | ||
fabMngr, err := common.NewFabricChClient(channelName, user, os.Getenv("ORG")) | ||
if err != nil { | ||
return nil, http.StatusInternalServerError, err | ||
} | ||
|
||
// Execute chaincode with channel's client | ||
rq := channel.Request{ChaincodeID: ccName, Fcn: txName} | ||
if len(txArgs) > 0 { | ||
rq.Args = txArgs | ||
} | ||
|
||
if len(transientRequest) != 0 { | ||
transientMap := make(map[string][]byte) | ||
transientMap["@request"] = transientRequest | ||
rq.TransientMap = transientMap | ||
} | ||
|
||
res, err := fabMngr.Client.Execute(rq, channel.WithRetry(retry.DefaultChannelOpts)) | ||
if err != nil { | ||
return nil, extractStatusCode(err.Error()), err | ||
} | ||
|
||
return &res, http.StatusOK, nil | ||
} |
Oops, something went wrong.