/
DataGetters.go
442 lines (354 loc) · 14.5 KB
/
DataGetters.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
package remote
import (
"encoding/json"
"errors"
"fmt"
"strconv"
client "github.com/GitofTruth/got/client"
"github.com/GitofTruth/got/datastructures"
"github.com/hyperledger/fabric/core/chaincode/shim"
"github.com/hyperledger/fabric/protos/peer"
)
func (contract *RepoContract) getRepoInstance(stub shim.ChaincodeStubInterface, args []string) (datastructures.Repo, error) {
// repoAuthor, repoName
fmt.Println("\n---------------------------\nQuerying the ledger .. getRepoInstance", args)
defer fmt.Println("---------------------------")
if len(args) < 2 {
var repo datastructures.Repo
fmt.Println("Incorrect number of arguments. Expecting 2")
return repo, errors.New("Incorrect number of arguments. Expecting 2")
}
// getting the required information from first table.
repoHash := getRepoKey(args[0], args[1])
repoData, err := stub.GetState(string(repoHash))
if err != nil {
var repo datastructures.Repo
fmt.Println("Could not find requested Repo: ", err)
return repo, errors.New("Could not find requested Repo")
}
fmt.Println("Found this repo:", string(repoData))
// unmarashaling the data
structuredRepoData := map[string]string{}
err = json.Unmarshal([]byte(repoData), &structuredRepoData)
if err != nil {
var repo datastructures.Repo
fmt.Println("Could not unmarashal requested repo: ", err)
return repo, errors.New("Could not unmarashal requested repo")
}
timestamp, _ := strconv.Atoi(structuredRepoData["timeStamp"])
users, _ := contract.getRepoUsers(stub, repoHash)
encryptionKey, _ := datastructures.UnmarashalKeyAnnouncement(structuredRepoData["encryptionKey"])
keyAnnouncements, _ := datastructures.UnmarashalKeyAnnouncements(structuredRepoData["keyAnnouncements"])
repo, _ := datastructures.CreateNewRepo(structuredRepoData["repoName"], structuredRepoData["author"], structuredRepoData["directoryCID"], timestamp, nil, encryptionKey, users)
// fmt.Println("Bos hen keda\n\n")
// fmt.Println(structuredRepoData["keyAnnouncements"])
// fmt.Println(repo.KeyAnnouncements)
repo.KeyAnnouncements = keyAnnouncements
// getting the repo branches
branchQueryString := fmt.Sprintf("{\"selector\": {\"docName\": \"branch\", \"repoID\": \"%s\"},\"fields\": [\"repoID\", \"branchName\", \"author\", \"timeStamp\"]}", repoHash)
branchResultsIterator, err := stub.GetQueryResult(branchQueryString)
if err != nil {
fmt.Println("Couldnot find Requested Branch: ", err)
var repo datastructures.Repo
return repo, err
}
defer branchResultsIterator.Close()
//iterating over branches
for branchResultsIterator.HasNext() {
branchString, err := branchResultsIterator.Next()
if err != nil {
fmt.Println("Couldnot proceed to next branch: ", err)
var repo datastructures.Repo
return repo, err
}
structuredBranchData := map[string]string{}
err = json.Unmarshal([]byte(branchString.Value), &structuredBranchData)
fmt.Println("Found This Branch: ", structuredBranchData)
if err != nil {
var repo datastructures.Repo
fmt.Println("Could not unmarashal requested Branch: ", err)
return repo, errors.New("Could not unmarashal requested Branch")
}
branchTimestamp, _ := strconv.Atoi(structuredBranchData["timeStamp"])
branch, _ := datastructures.CreateNewRepoBranch(structuredBranchData["branchName"], structuredBranchData["author"], branchTimestamp, nil)
repo.AddBranch(branch)
//adding branch commits
commitsQueryString := fmt.Sprintf("{\"selector\": {\"docName\": \"commit\", \"repoID\": \"%s\", \"branchName\": \"%s\"},\"fields\": [\"repoID\", \"branchName\",\"hash\", \"message\", \"author\", \"committer\", \"committerTimestamp\", \"CommitParenthashes\", \"signature\", \"storageHashes\", \"encryptionKey\"]}", repoHash, branch.Name)
commitsResultsIterator, err := stub.GetQueryResult(commitsQueryString)
if err != nil {
var repo datastructures.Repo
fmt.Println("Could not find requested commit: ", err)
return repo, err
}
defer commitsResultsIterator.Close()
//iterating over branches
for commitsResultsIterator.HasNext() {
commitString, err := commitsResultsIterator.Next()
if err != nil {
fmt.Println("Could not proceed to requested commit: ", err)
var repo datastructures.Repo
return repo, err
}
structuredCommitData := map[string]string{}
err = json.Unmarshal([]byte(commitString.Value), &structuredCommitData)
fmt.Println("Found This Commit: ", structuredCommitData)
if err != nil {
var repo datastructures.Repo
fmt.Println("Could not unmarashal requested commit: ", err)
return repo, errors.New("Could not unmarashal requested commit")
}
committerTimestamp, _ := strconv.Atoi(structuredCommitData["committerTimestamp"])
var ph []string
_ = json.Unmarshal([]byte(structuredCommitData["parentHashes"]), &ph)
var s []byte
_ = json.Unmarshal([]byte(structuredCommitData["signature"]), &s)
// var enc string
// _ = json.Unmarshal([]byte(structuredCommitData["encryptionKey"]), &enc)
var sh map[string]string
_ = json.Unmarshal([]byte(structuredCommitData["storageHashes"]), &sh)
commit, _ := datastructures.CreateNewCommitLog(structuredCommitData["message"], structuredCommitData["author"], structuredCommitData["commiter"], committerTimestamp, structuredCommitData["hash"], ph, s, structuredCommitData["encryptionKey"], sh)
fmt.Println("and the comit became \t", commit)
repo.AddCommitLog(commit, branch.Name, true)
}
}
fmt.Println("This is the final fetched Repo: ", repo)
return repo, nil
}
func (contract *RepoContract) queryRepo(stub shim.ChaincodeStubInterface, args []string) peer.Response {
// repoAuthor, repoName
fmt.Println("Querying the ledger .. getRepo", args)
if len(args) != 2 {
return shim.Error("Incorrect number of arguments. Expecting 2.")
}
repoHash := getRepoKey(args[0], args[1])
// key := map[string]interface{}{"repoID": repoHash}
// jsonKey, _ := json.Marshal(key)
repoData, err := stub.GetState(string(repoHash))
if err != nil {
return shim.Error("Repo does not exist")
}
fmt.Println("Found this repo:", string(repoData))
return shim.Success(repoData)
}
func (contract *RepoContract) clone(stub shim.ChaincodeStubInterface, args []string) peer.Response {
// repoAuthor, repoName, currentUserName
fmt.Println("Querying the ledger .. clone", args)
if len(args) != 3 {
return shim.Error("Incorrect number of arguments. Expecting 3.")
}
repo, err := contract.getRepoInstance(stub, args)
if err != nil {
return shim.Error("Repo does not exist")
}
repo.UpdateCommitsForUser(args[2])
fmt.Println("Found this repo:", repo)
j, _ := json.Marshal(repo)
return shim.Success([]byte(string(j)))
}
func (contract *RepoContract) queryBranches(stub shim.ChaincodeStubInterface, args []string) peer.Response {
// repoAuthor, repoName, currentUserName
fmt.Println("Querying the ledger .. queryBranches", args)
if len(args) != 3 {
return shim.Error("Incorrect number of arguments. Expecting 3.")
}
repo, err := contract.getRepoInstance(stub, args)
if err != nil {
return shim.Error("Repo does not exist")
}
repo.UpdateCommitsForUser(args[2])
fmt.Println("Found these branches:", repo.GetBranches())
j, _ := json.Marshal(repo.GetBranches())
return shim.Success([]byte(string(j)))
}
func (contract *RepoContract) queryBranch(stub shim.ChaincodeStubInterface, args []string) peer.Response {
// repoAuthor, repoName, branchName, currentUserName
fmt.Println("Querying the ledger .. queryBranch", args)
if len(args) != 4 {
return shim.Error("Incorrect number of arguments. Expecting 4.")
}
repo, err := contract.getRepoInstance(stub, args)
if err != nil {
return shim.Error("Repo does not exist")
}
if !repo.IsBranch(args[2]) {
fmt.Println("Requested Branch Not found")
return shim.Error("Requested Branch Not found")
}
repo.UpdateCommitsForUser(args[3])
branch := repo.Branches[args[2]]
fmt.Println("Found these branches:", branch)
seralized, _ := json.Marshal(branch)
return shim.Success([]byte(string(seralized)))
}
func (contract *RepoContract) queryBranchCommits(stub shim.ChaincodeStubInterface, args []string) peer.Response {
// repoAuthor, repoName, branchName, lastcommit, currentUserName
fmt.Println("Querying the ledger .. queryBranchCommits", args)
if len(args) != 5 {
return shim.Error("Incorrect number of arguments. Expecting 5.")
}
repo, err := contract.getRepoInstance(stub, args)
if err != nil {
return shim.Error("Repo does not exist")
}
if !repo.IsBranch(args[2]) {
fmt.Println("Requested Branch Not found")
return shim.Error("Requested Branch Not found")
}
repo.UpdateCommitsForUser(args[4])
branch := repo.Branches[args[2]]
fmt.Println("Found this branch:", branch)
commits := make([]datastructures.CommitLog, 0)
//last commit exist?
t := 0
if !repo.IsCommitHash(args[3]) && args[3] != "" {
fmt.Println("Requested BranchCommit Not found")
return shim.Error("Requested BranchCommit Not found")
}
if args[3] != "" {
t = branch.Logs[args[3]].CommitterTimestamp
}
// get all commits after this time
for _, log := range branch.Logs {
if log.CommitterTimestamp > t {
commits = append(commits, log)
}
}
seralized, _ := json.Marshal(commits)
return shim.Success([]byte(string(seralized)))
}
func (contract *RepoContract) queryLastBranchCommit(stub shim.ChaincodeStubInterface, args []string) peer.Response {
// repoAuthor, repoName, branchName
fmt.Println("Querying the ledger .. queryBranchCommits", args)
if len(args) != 3 {
return shim.Error("Incorrect number of arguments. Expecting 3.")
}
repo, err := contract.getRepoInstance(stub, args)
if err != nil {
return shim.Error("Repo does not exist")
}
if !repo.IsBranch(args[2]) {
fmt.Println("Requested Branch Not found")
return shim.Error("Requested Branch Not found")
}
branch := repo.Branches[args[2]]
fmt.Println("Found this branch:", branch)
t := 0
hash := ""
// get all commits after this time
for _, log := range branch.Logs {
if log.CommitterTimestamp >= t {
t = log.CommitterTimestamp
hash = log.Hash
}
}
return shim.Success([]byte(hash))
}
func (contract *RepoContract) getUserInfo(stub shim.ChaincodeStubInterface, userName string) (client.UserInfo, peer.Response) {
var userInfo client.UserInfo
userQueryString := fmt.Sprintf("{\"selector\": {\"docName\": \"user\", \"userName\": \"%s\"},\"fields\": [\"userName\", \"publicKey\"]}", userName)
userResultsIterator, err := stub.GetQueryResult(userQueryString)
if err != nil {
fmt.Println("Could not find Requested User: ", err)
return userInfo, shim.Error("User does not exist")
}
defer userResultsIterator.Close()
for userResultsIterator.HasNext() {
userString, err := userResultsIterator.Next()
if err != nil {
fmt.Println("Could not proceed to next user: ", err)
return userInfo, shim.Error("Could not proceed to next user")
}
structuredUserData := map[string]string{}
err = json.Unmarshal([]byte(userString.Value), &structuredUserData)
fmt.Println("Found This User: \t", structuredUserData)
if err != nil {
fmt.Println("Could not unmarashal requested Branch: ", err)
return userInfo, shim.Error("Could not unmarashal requested Branch")
}
userInfo.UserName = structuredUserData["userName"]
userInfo.PublicKey = structuredUserData["publicKey"]
}
return userInfo, shim.Success([]byte(""))
}
func (contract *RepoContract) queryUser(stub shim.ChaincodeStubInterface, args []string) peer.Response {
// userName
fmt.Println("Querying the ledger .. queryUser", args)
if len(args) != 1 {
return shim.Error("Incorrect number of arguments. Expecting 1.")
}
userInfo, failMessage := contract.getUserInfo(stub, args[0])
if failMessage.Message != "" {
return failMessage
}
seralized, _ := json.Marshal(userInfo)
return shim.Success([]byte(string(seralized)))
}
func (contract *RepoContract) queryUsers(stub shim.ChaincodeStubInterface, args []string) peer.Response {
// [userName1 userName2]
fmt.Println("Querying the ledger .. queryUser", args)
if len(args) != 1 {
return shim.Error("Incorrect number of arguments. Expecting 1.")
}
userInfos := make([]client.UserInfo, 0)
var userNames []string
_ = json.Unmarshal([]byte(args[0]), &userNames)
for _, username := range userNames {
userInfo, failMessage := contract.getUserInfo(stub, username)
if failMessage.Message != "" {
continue
}
userInfos = append(userInfos, userInfo)
}
seralized, _ := json.Marshal(userInfos)
return shim.Success([]byte(string(seralized)))
}
func (contract *RepoContract) getRepoUsers(stub shim.ChaincodeStubInterface, repoHash string) (map[string]datastructures.UserAccess, peer.Response) {
users := make(map[string]datastructures.UserAccess, 0)
accessQueryString := fmt.Sprintf("{\"selector\": {\"docName\": \"userAccess\", \"repoHash\": \"%s\"},\"fields\": [\"authorized\", \"userAccess\", \"authorizer\"]}", repoHash)
accessResultsIterator, err := stub.GetQueryResult(accessQueryString)
if err != nil {
fmt.Println("Could not find Repo Access: ", err)
return users, shim.Error("Repo Access does not exist")
}
defer accessResultsIterator.Close()
for accessResultsIterator.HasNext() {
accessString, err := accessResultsIterator.Next()
if err != nil {
fmt.Println("Could not proceed to user access: ", err)
return users, shim.Error("Could not proceed to next user access")
}
structuredAccessData := map[string]string{}
err = json.Unmarshal([]byte(accessString.Value), &structuredAccessData)
fmt.Println("Found This User: \t", structuredAccessData)
if err != nil {
fmt.Println("Could not unmarashal requested Branch: ", err)
return users, shim.Error("Could not unmarashal requested Branch")
}
access, err := strconv.Atoi(structuredAccessData["userAccess"])
if err != nil {
fmt.Println("Could not parse UserAcess: ", access, err)
return users, shim.Error("Could not parse UserAcess")
} else {
users[structuredAccessData["authorized"]] = datastructures.UserAccess(access)
}
}
return users, shim.Success([]byte(""))
}
func (contract *RepoContract) queryRepoUserAccess(stub shim.ChaincodeStubInterface, args []string) peer.Response {
// repoAuthor, repoName
fmt.Println("Querying the ledger .. queryRepoUserAccess", args)
if len(args) != 2 {
return shim.Error("Incorrect number of arguments. Expecting 2.")
}
repoHash := getRepoKey(args[0], args[1])
users, failMessage := contract.getRepoUsers(stub, repoHash)
if failMessage.Message != "" {
return failMessage
}
seralized, _ := json.Marshal(users)
return shim.Success([]byte(string(seralized)))
}
// indexName := "index-Branch"
// branchIndexKey, _ := stub.CreateCompositeKey(indexName, []string{repoHash, args[2]})
// // jsonKey, _ := json.Marshal(key)
// branchData, err := stub.GetState(string(branchIndexKey))