-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.go
237 lines (212 loc) · 7.99 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/balance-transfer-go/utils"
jwt "github.com/dgrijalva/jwt-go"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/hyperledger/fabric-sdk-go/pkg/client/ledger"
"github.com/hyperledger/fabric-sdk-go/pkg/client/resmgmt"
"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"
)
var hfc utils.FabricSetup
func main() {
hfc = utils.FabricSetup{
AdminUser: "Admin",
OrdererOrgName: "ordererorg",
ConfigFileName: "config.yaml",
Secret: []byte("thisismysecret"),
IdentityTypeUser: "user",
RegistrarUsername: "admin",
RegistrarPassword: "adminpw",
ChannelID: "mychannel",
}
hfc.Init()
r := mux.NewRouter()
r.HandleFunc("/users", login).Methods("POST")
r.Handle("/channels/{channelName}/chaincodes/{chaincodeName}", authMiddleware(http.HandlerFunc(queryCC))).Methods("GET")
r.Handle("/channels/{channelName}/chaincodes/{chaincodeName}", authMiddleware(http.HandlerFunc(invokeCC))).Methods("POST")
r.Handle("/channels/{channelName}/blocks/{blockID}", authMiddleware(http.HandlerFunc(getBlockByNumber))).Methods("GET")
r.Handle("/channels/{channelName}/transactions/{transactionID}", authMiddleware(http.HandlerFunc(getTransactionByID))).Methods("GET")
r.Handle("/channels/{channelName}", authMiddleware(http.HandlerFunc(getChainInfo))).Methods("GET")
r.Handle("/chaincodes", authMiddleware(http.HandlerFunc(getInstalledChaincodes))).Methods("GET")
r.Handle("/channels/{channelName}/chaincodes", authMiddleware(http.HandlerFunc(getInstantiatedChaincodes))).Methods("GET")
r.Handle("/channels", authMiddleware(http.HandlerFunc(getChannels))).Methods("GET")
http.ListenAndServe(":4000", handlers.LoggingHandler(os.Stdout, r))
}
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tokenString := r.Header.Get("authorization")
if tokenString != "" {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return hfc.Secret, nil
})
if err == nil {
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
r.Header.Add("username", claims["username"].(string))
r.Header.Add("orgName", claims["orgName"].(string))
next.ServeHTTP(w, r)
}
} else {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(err.Error()))
}
} else {
w.WriteHeader(http.StatusUnauthorized)
}
})
}
func login(w http.ResponseWriter, r *http.Request) {
log.Print("==================== LOGIN ==================")
// define response
type response struct {
Success bool
Message string
Token string
}
err := r.ParseForm()
if err != nil {
panic(err)
}
username := r.Form.Get("username")
orgName := r.Form.Get("orgName")
secret := r.Form.Get("secret")
if username != "" && orgName != "" {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"username": username,
"orgName": orgName,
"exp": time.Now().Unix() + 360000,
})
tokenString, err := token.SignedString(hfc.Secret)
fmt.Println(tokenString, err)
message, success := utils.GetRegisteredUser(strings.ToLower(username), strings.ToLower(orgName), secret, hfc.IdentityTypeUser, hfc.Sdk)
res := response{
Success: success,
Message: message,
}
if success {
res.Token = tokenString
}
out, err := json.Marshal(res)
w.Header().Set("Content-Type", "application/json")
w.Write(out)
} else {
w.WriteHeader(http.StatusNotFound)
}
}
func queryCC(w http.ResponseWriter, r *http.Request) {
log.Print("==================== QUERY BY CHAINCODE ==================")
type args struct {
array []string
}
username := r.Header.Get("username")
orgName := r.Header.Get("orgName")
vars := mux.Vars(r)
fcn := r.URL.Query().Get("fcn")
tmp := args{}
json.Unmarshal([]byte(r.URL.Query().Get("args")), &tmp.array)
client := utils.GetClient(hfc.Sdk, vars["channelName"], username, orgName)
res := utils.QueryCC(client, vars["chaincodeName"], fcn, utils.GetArgs(tmp.array), r.URL.Query().Get("peer"))
w.Write(res)
}
func invokeCC(w http.ResponseWriter, r *http.Request) {
log.Print("==================== INVOKE ON CHAINCODE ==================")
type invokeBody struct {
Peers []string
Fcn string
Args []string
}
type response struct {
TxID string
}
vars := mux.Vars(r)
username := r.Header.Get("username")
orgName := r.Header.Get("orgName")
decoder := json.NewDecoder(r.Body)
body := invokeBody{}
decoder.Decode(&body)
client := utils.GetClient(hfc.Sdk, vars["channelName"], username, orgName)
res := utils.ExecuteCC(client, vars["chaincodeName"], body.Fcn, utils.GetArgs(body.Args), body.Peers)
w.Write(res)
}
func getBlockByNumber(w http.ResponseWriter, r *http.Request) {
log.Print("==================== GET BLOCK BY NUMBER ==================")
vars := mux.Vars(r)
username := r.Header.Get("username")
orgName := r.Header.Get("orgName")
blockID, _ := strconv.ParseUint(vars["blockID"], 10, 64)
channelContext := hfc.Sdk.ChannelContext(vars["channelName"], fabsdk.WithUser(username), fabsdk.WithOrg(orgName))
// ledger client
client, err := ledger.New(channelContext)
if err != nil {
log.Fatalf("Failed to create new ledger client: %s", err)
}
w.Write(utils.QueryBlockByNumber(client, blockID, r.URL.Query().Get("peer")))
}
func getTransactionByID(w http.ResponseWriter, r *http.Request) {
log.Print("================ GET TRANSACTION BY TRANSACTION_ID ======================")
vars := mux.Vars(r)
username := r.Header.Get("username")
orgName := r.Header.Get("orgName")
channelContext := hfc.Sdk.ChannelContext(vars["channelName"], fabsdk.WithUser(username), fabsdk.WithOrg(orgName))
client, err := ledger.New(channelContext)
if err != nil {
log.Printf("Failed to create new ledger client: %s", err)
}
res := utils.QueryTransactionByID(client, vars["transactionID"], r.URL.Query().Get("peer"))
w.Write(res)
}
func getChainInfo(w http.ResponseWriter, r *http.Request) {
log.Print("================ GET CHANNEL INFORMATION ======================")
vars := mux.Vars(r)
username := r.Header.Get("username")
orgName := r.Header.Get("orgName")
channelContext := hfc.Sdk.ChannelContext(vars["channelName"], fabsdk.WithUser(username), fabsdk.WithOrg(orgName))
client, err := ledger.New(channelContext)
if err != nil {
log.Printf("Failed to create new ledger client: %s", err)
}
res := utils.QueryChainInfo(client, r.URL.Query().Get("peer"))
w.Write(res)
}
func getInstalledChaincodes(w http.ResponseWriter, r *http.Request) {
log.Print("================ GET INSTALLED CHAINCODES ======================")
org1AdminClientContext := hfc.Sdk.Context(fabsdk.WithUser("AdminOrg1"), fabsdk.WithOrg("Org1"))
client, err := resmgmt.New(org1AdminClientContext)
if err != nil {
log.Fatalf("Failed to create new resource management client: %s", err)
}
out := utils.QueryInstalledChaincodes(client, r.URL.Query().Get("peer"))
w.Write(out)
}
func getInstantiatedChaincodes(w http.ResponseWriter, r *http.Request) {
log.Print("================ GET INSTANTIATED CHAINCODES ======================")
vars := mux.Vars(r)
org1AdminClientContext := hfc.Sdk.Context(fabsdk.WithUser("AdminOrg1"), fabsdk.WithOrg("Org1"))
client, err := resmgmt.New(org1AdminClientContext)
if err != nil {
log.Fatalf("Failed to create new resource management client: %s", err)
}
out := utils.QueryInstantiatedChaincodes(client, vars["channelName"], r.URL.Query().Get("peer"))
w.Write(out)
}
func getChannels(w http.ResponseWriter, r *http.Request) {
log.Print("================ GET CHANNELS ======================")
org1AdminClientContext := hfc.Sdk.Context(fabsdk.WithUser("AdminOrg1"), fabsdk.WithOrg("Org1"))
client, err := resmgmt.New(org1AdminClientContext)
if err != nil {
log.Fatalf("Failed to create new resource management client: %s", err)
}
out := utils.QueryChannels(client, r.URL.Query().Get("peer"))
w.Write(out)
}