Skip to content

Commit 60b7ccc

Browse files
more ipfs api
1 parent 6568fff commit 60b7ccc

File tree

4 files changed

+75
-1
lines changed

4 files changed

+75
-1
lines changed

api/ipfs.go

+18
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,21 @@ func IPFSListPeers(f *file_system.FileSystem) func(http.ResponseWriter, *http.Re
2222
}
2323
}
2424
}
25+
26+
func IPFSListCids(f *file_system.FileSystem) func(http.ResponseWriter, *http.Request) {
27+
return func(w http.ResponseWriter, req *http.Request) {
28+
cids, err := f.ListCids()
29+
if err != nil {
30+
handleErr(err, w, http.StatusInternalServerError)
31+
return
32+
}
33+
34+
f := types.CidResponse{
35+
Cids: cids,
36+
}
37+
err = json.NewEncoder(w).Encode(f)
38+
if err != nil {
39+
log.Error().Err(err)
40+
}
41+
}
42+
}

api/server.go

+1
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ func (a *API) Serve(f *file_system.FileSystem, p *proofs.Prover, wallet *wallet.
4545
r.HandleFunc("/api/data/fids", LegacyListFilesHandler(f))
4646

4747
r.HandleFunc("/ipfs/peers", IPFSListPeers(f))
48+
r.HandleFunc("/ipfs/cids", IPFSListCids(f))
4849

4950
r.HandleFunc("/dump", DumpDBHandler(f))
5051

api/types/responses.go

+4
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,7 @@ type LegacyAPIListResponse struct {
4141
type PeersResponse struct {
4242
Peers peer.IDSlice `json:"peers"`
4343
}
44+
45+
type CidResponse struct {
46+
Cids []string `json:"cids"`
47+
}

file_system/ipfs.go

+52-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,58 @@
11
package file_system
22

3-
import "github.com/libp2p/go-libp2p/core/peer"
3+
import (
4+
"fmt"
5+
6+
"github.com/dgraph-io/badger/v4"
7+
"github.com/libp2p/go-libp2p/core/peer"
8+
)
49

510
func (f *FileSystem) ListPeers() peer.IDSlice {
611
return f.ipfsHost.Peerstore().PeersWithAddrs()
712
}
13+
14+
func (f *FileSystem) GetCIDFromMerkle(merkle []byte) (cid string, err error) {
15+
err = f.db.View(func(txn *badger.Txn) error {
16+
c, err := txn.Get([]byte(fmt.Sprintf("cid/%x", merkle)))
17+
if err != nil {
18+
return err
19+
}
20+
err = c.Value(func(val []byte) error {
21+
cid = string(val)
22+
return nil
23+
})
24+
if err != nil {
25+
return err
26+
}
27+
return nil
28+
})
29+
if err != nil {
30+
return "", err
31+
}
32+
33+
return
34+
}
35+
36+
func (f *FileSystem) ListCids() ([]string, error) {
37+
cids := make([]string, 0)
38+
39+
err := f.db.View(func(txn *badger.Txn) error {
40+
it := txn.NewIterator(badger.DefaultIteratorOptions)
41+
defer it.Close()
42+
prefix := []byte("cid/")
43+
for it.Seek(prefix); it.ValidForPrefix(prefix); it.Next() {
44+
item := it.Item()
45+
err := item.Value(func(v []byte) error {
46+
cids = append(cids, string(v))
47+
48+
return nil
49+
})
50+
if err != nil {
51+
return err
52+
}
53+
}
54+
return nil
55+
})
56+
57+
return cids, err
58+
}

0 commit comments

Comments
 (0)