Skip to content

Commit ebe6fea

Browse files
committed
Pinned videos until the limit was reached and unpinned videos if the total pinned storage exceeded the limit.
1 parent 17f424e commit ebe6fea

File tree

11 files changed

+87
-91
lines changed

11 files changed

+87
-91
lines changed

Rewards/rewards.go

Lines changed: 66 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ import (
1111
"net/url"
1212
"proofofaccess/ipfs"
1313
"proofofaccess/localdata"
14-
"strconv"
1514
"strings"
1615
"time"
1716
)
@@ -21,7 +20,6 @@ type APIResponse struct {
2120
VideoV2 string `json:"video_v2"`
2221
} `json:"recommended"`
2322
}
24-
2523
type ProofMessage struct {
2624
Status string `json:"Status"`
2725
Message string `json:"Message"`
@@ -216,93 +214,87 @@ type CIDSize struct {
216214
}
217215

218216
func PinVideos(gb int, ctx context.Context) error {
219-
// Connect to the local IPFS node
217+
fmt.Println("Pinning videos")
220218
sh := ipfs.Shell
221-
222-
// Calculate total pinned storage
219+
const GB = 1024 * 1024 * 1024
220+
limit := int64(gb * GB)
223221
totalPinned := int64(0)
224-
fmt.Println("Getting pins")
225-
pins, err := sh.Pins()
226-
if err != nil {
227-
fmt.Println("Error getting pins")
228-
fmt.Println(err)
222+
223+
// Convert ThreeSpeakVideos to a map for quicker lookups
224+
videoMap := make(map[string]bool)
225+
for _, cid := range localdata.ThreeSpeakVideos {
226+
videoMap[cid] = true
229227
}
230-
fmt.Println("Got pins")
231228

232-
// Define the limit for the pinned storage
233-
const GB = 1024 * 1024 * 1024
234-
limit := int64(gb * GB)
235-
fmt.Println("Limit: ", strconv.FormatInt(limit, 10))
236-
// Generate list of CIDs with size
237-
cidList := make([]CIDSize, len(localdata.ThreeSpeakVideos))
238-
fmt.Println("Making CID list")
239-
fmt.Println("Length of localdata.ThreeSpeakVideos: ")
240-
fmt.Println(len(localdata.ThreeSpeakVideos))
241-
242-
for i, cid := range localdata.ThreeSpeakVideos {
243-
select {
244-
case <-ctx.Done():
245-
return ctx.Err()
246-
default:
247-
if cid == "" {
248-
fmt.Printf("Empty CID at index %d, skipping\n", i)
249-
continue
250-
}
251-
fmt.Println("CID: " + cid)
252-
stat, err := sh.ObjectStat(cid)
253-
fmt.Println("Got object stats ", stat)
254-
if err != nil {
255-
fmt.Printf("Failed to get object stats for CID %s: %v, skipping\n", cid, err)
256-
continue
257-
}
229+
// Check all the currently pinned CIDs
230+
fmt.Println("Checking currently pinned CIDs")
231+
allPinsData, _ := sh.Pins()
258232

259-
cidList[i] = CIDSize{
260-
CID: cid,
261-
Size: int64(stat.CumulativeSize),
262-
}
263-
totalPinned += int64(stat.CumulativeSize)
264-
fmt.Println("Total pinned: " + strconv.FormatInt(totalPinned, 10))
265-
}
233+
// Map the allPins to only CIDs
234+
allPins := make(map[string]bool)
235+
for cid := range allPinsData {
236+
allPins[cid] = true
266237
}
267238

268-
fmt.Println("Got CID list")
269-
270-
// Pin new videos until limit is reached
271-
for _, video := range cidList {
272-
select {
273-
case <-ctx.Done():
274-
return ctx.Err()
275-
default:
276-
if totalPinned+video.Size > limit {
277-
fmt.Println("Total pinned storage exceeds limit")
278-
break
279-
}
280-
fmt.Println("Pinning CID: " + video.CID)
281-
if err := sh.Pin(video.CID); err != nil {
282-
fmt.Println("failed to pin CID %s: %w", video.CID, err)
239+
for cid, pinInfo := range allPinsData {
240+
// Filter only the direct pins
241+
if pinInfo.Type == "recursive" {
242+
if videoMap[cid] {
243+
fmt.Println("CID is in the video list", cid)
244+
// If the CID is in the video list, get its size and add to totalPinned
245+
stat, err := sh.ObjectStat(cid)
246+
if err != nil {
247+
fmt.Printf("Error getting stats for CID %s: %s\n", cid, err)
248+
continue
249+
}
250+
size := int64(stat.CumulativeSize)
251+
totalPinned += size
252+
fmt.Println("Total pinned: ", totalPinned)
253+
} else {
254+
// If the CID is not in the video list, unpin it
255+
fmt.Println("Unpinning CID: ", cid)
256+
if err := sh.Unpin(cid); err != nil {
257+
fmt.Printf("Error unpinning CID %s: %s\n", cid, err)
258+
continue
259+
}
260+
fmt.Println("Unpinned CID: ", cid)
283261
}
284-
fmt.Println("Pinned CID: " + video.CID)
285-
totalPinned += video.Size
286262
}
287263
}
264+
fmt.Println("Total pinned: ", totalPinned)
288265

289-
// Remove older videos if total pinned storage exceeds limit
290-
for cid := range pins {
291-
select {
292-
case <-ctx.Done():
293-
return ctx.Err()
294-
default:
266+
// Pin videos from ThreeSpeak until the limit is reached
267+
for _, cid := range localdata.ThreeSpeakVideos {
268+
if totalPinned >= limit {
269+
fmt.Println("Total pinned is greater than limit")
270+
break
271+
}
272+
fmt.Println("Getting stats for CID: ", cid)
273+
// If CID isn't already in allPins, then it's not pinned
274+
if _, pinned := allPins[cid]; !pinned {
295275
stat, err := sh.ObjectStat(cid)
296276
if err != nil {
297-
fmt.Println("failed to get object stats for CID %s: %w", cid, err)
298-
}
299-
if totalPinned <= limit {
300-
break
277+
fmt.Printf("Error getting stats for CID %s: %s\n", cid, err)
278+
continue
301279
}
302-
if err := sh.Unpin(cid); err != nil {
303-
fmt.Println("failed to unpin CID %s: %w", cid, err)
280+
281+
size := int64(stat.CumulativeSize)
282+
fmt.Println("Size: ", size)
283+
fmt.Println("Total pinned: ", totalPinned)
284+
fmt.Println("Limit: ", limit)
285+
if totalPinned+size-1000000 <= limit {
286+
fmt.Println("Pinning CID: ", cid)
287+
if err := sh.Pin(cid); err != nil {
288+
fmt.Printf("Failed to pin CID %s: %s\n", cid, err)
289+
continue
290+
}
291+
totalPinned += size
292+
// Once pinned, add it to the allPins
293+
allPins[cid] = true
294+
fmt.Println("Pinned CID: ", cid)
304295
}
305-
totalPinned -= int64(stat.CumulativeSize) // Use actual size of the unpinned video
296+
} else {
297+
fmt.Println("CID is already pinned")
306298
}
307299
}
308300

api/handlers.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ func handleStats(c *gin.Context) {
252252
return
253253
}
254254
defer closeWebSocket(conn)
255-
log.Info("Entering handleStats")
255+
//log.Info("Entering handleStats")
256256
stats(conn)
257257
return
258258
}

api/stats.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,11 @@ func stats(c *websocket.Conn) {
2727
peerSizes[peerName] = fmt.Sprintf("%d", localdata.PeerSize[peerName]/1024/1024/1024)
2828
peerSynced[peerName] = fmt.Sprintf("%v", localdata.NodesStatus[peerName])
2929
}
30-
fmt.Println("Network Storage: ", NetworkStorage)
30+
// fmt.Println("Network Storage: ", NetworkStorage)
3131
// Print the Network Storage in GB
3232
NetworkStorage = NetworkStorage / 1024 / 1024 / 1024
33-
fmt.Println("Size: ", NetworkStorage, "GB")
34-
fmt.Println("NodeType: ", localdata.NodeType)
33+
// fmt.Println("Size: ", NetworkStorage, "GB")
34+
// fmt.Println("NodeType: ", localdata.NodeType)
3535
NodeType := ""
3636
if localdata.NodeType == 1 {
3737
NodeType = "Validator"
@@ -55,6 +55,7 @@ func stats(c *websocket.Conn) {
5555
"PeerProofs": localdata.PeerProofs,
5656
"PeerSynced": peerSynced,
5757
"PeerHiveRewards": localdata.HiveRewarded,
58+
"PeerCids": len(localdata.PeerCids),
5859
}
5960
localdata.Lock.Unlock()
6061
jsonData, err := json.Marshal(data)

api/websocket.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,19 +35,19 @@ var wsMutex = &sync.Mutex{}
3535

3636
func upgradeToWebSocket(c *gin.Context) *websocket.Conn {
3737
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
38-
fmt.Println("upgradeToWebSocket")
38+
//fmt.Println("upgradeToWebSocket")
3939
if err != nil {
4040
log.Error(err)
4141
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to upgrade connection"})
4242
return nil
4343
}
44-
fmt.Println("upgradeToWebSocket2")
44+
//fmt.Println("upgradeToWebSocket2")
4545

4646
return conn
4747
}
4848

4949
func closeWebSocket(conn *websocket.Conn) {
50-
log.Info("Closing WebSocket connection")
50+
// log.Info("Closing WebSocket connection")
5151
err := conn.Close()
5252
if err != nil {
5353
return
@@ -67,6 +67,7 @@ func readWebSocketMessage(conn *websocket.Conn) (*message, error) {
6767

6868
func sendWsResponse(status string, message string, elapsed string, conn *websocket.Conn) {
6969
localdata.Lock.Lock()
70+
fmt.Println("sendWsResponse", status, message, elapsed)
7071
err := conn.WriteJSON(ExampleResponse{
7172
Status: status,
7273
Message: message,

ipfs/ipfs.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -301,7 +301,6 @@ func SyncNode(NewPins map[string]interface{}, name string) {
301301
if localdata.NodesStatus[name] != "Synced" {
302302
localdata.Lock.Lock()
303303
localdata.PeerSize[name] = peersize
304-
fmt.Println("Peer size: ", peersize)
305304
localdata.Lock.Unlock()
306305
}
307306
fmt.Println("Key not found: ", key)
@@ -339,7 +338,6 @@ func SyncNode(NewPins map[string]interface{}, name string) {
339338
if localdata.NodesStatus[name] != "Synced" {
340339
localdata.Lock.Lock()
341340
localdata.PeerSize[name] = peersize
342-
fmt.Println("Peer size: ", peersize)
343341
localdata.Lock.Unlock()
344342
}
345343
fmt.Println("Key found: ", key)

localdata/localdata.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ var Lock sync.Mutex
5050
var PeerProofs = map[string]int{}
5151
var PeerLastActive = map[string]time.Time{}
5252
var HiveRewarded = map[string]float64{}
53+
var PiningVideos = false
5354

5455
type NetworkRecord struct {
5556
Peers int `json:"Peers"`

main.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,6 @@ func initialize(ctx context.Context) {
7676
fmt.Println("Pinning and unpinning videos")
7777
go Rewards.PinVideos(*storageLimit, ctx)
7878
}
79-
fmt.Println("Done pinning and unpinning videos")
8079
}
8180

8281
database.Init()
@@ -218,7 +217,7 @@ func fetchPins(ctx context.Context) {
218217
size, _ := ipfs.FileSize(key)
219218
localdata.Lock.Lock()
220219
PeerSize += size
221-
fmt.Println("Peer size: ", localdata.PeerSize[localdata.NodeName])
220+
//fmt.Println("Peer size: ", localdata.PeerSize[localdata.NodeName])
222221
localdata.Lock.Unlock()
223222
if !ipfs.IsPinnedInDB(key) {
224223
localdata.Lock.Lock()

messaging/messaging.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,14 +68,15 @@ func SendProof(req Request, hash string, seed string, user string) {
6868
nodeType := localdata.NodeType
6969
localdata.Lock.Unlock()
7070
if wsPeers == req.User && nodeType == 1 {
71-
wsMutex.Lock()
71+
localdata.Lock.Lock()
7272
ws := localdata.WsClients[req.User]
73+
localdata.Lock.Unlock()
7374
ws.WriteMessage(websocket.TextMessage, jsonData)
7475
wsMutex.Unlock()
7576
} else if localdata.UseWS == true && localdata.NodeType == 2 {
76-
wsMutex.Lock()
77+
localdata.Lock.Lock()
7778
localdata.WsValidators["Validator1"].WriteMessage(websocket.TextMessage, jsonData)
78-
wsMutex.Unlock()
79+
localdata.Lock.Unlock()
7980
} else {
8081
pubsub.Publish(string(jsonData), user)
8182
}
@@ -163,6 +164,7 @@ func HandleRequestProof(req Request) {
163164
validationHash := validation.CreatProofHash(hash, CID)
164165
SendProof(req, validationHash, hash, localdata.NodeName)
165166
} else {
167+
fmt.Println("Sending proof of access to validation node")
166168
SendProof(req, hash, req.Seed, localdata.NodeName)
167169
}
168170

messaging/ws.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ func StartWsClient() {
3737
continue
3838
}
3939
go HandleMessage(string(message))
40-
fmt.Println("Client recv: ", string(message))
40+
//fmt.Println("Client recv: ", string(message))
4141
} else {
4242
log.Println("Connection is not established.")
4343
time.Sleep(1 * time.Second) // Sleep for a second before next reconnection attempt

public/node-stats.html

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,18 +51,20 @@
5151
var peerProofs = stats.PeerProofs; // get PeerProofs
5252
var peerStatus = stats.PeerSynced; // get PeerStatus
5353
var PeerHiveRewards = stats.PeerHiveRewards; // get PeerHiveRewards
54+
var PeerCids = stats.PeerCids; // get PeerCids
5455
var peerList = "";
5556
for (var peer in peerSizes) {
5657
var size = peerSizes[peer] || "N/A";
5758
var lastActive = peerLastActive[peer] || "N/A";
5859
var peerProof = peerProofs[peer] || "N/A";
5960
var rawPeerHiveRewards = PeerHiveRewards[peer];
61+
var rawPeerCids = PeerCids[peer];
6062

6163
var peerHiveRewards = "N/A";
6264
if (rawPeerHiveRewards !== undefined && !isNaN(rawPeerHiveRewards)) {
6365
peerHiveRewards = parseFloat(rawPeerHiveRewards).toFixed(3);
6466
}
65-
peerList += `${peer}: ${size} GB (Last Active: ${lastActive}) (Proof: ${peerProof}/10) (Status: ${peerStatus[peer]})(Hive Rewards: ${peerHiveRewards})<br />`;
67+
peerList += `${peer}: ${size} GB (Last Active: ${lastActive}) (Proof: ${peerProof}/10) (Status: ${peerStatus[peer]})(Hive Rewards: ${peerHiveRewards}) (CidsPinned: ${rawPeerCids})<br>`;
6668
}
6769
document.getElementById("sync-status").innerHTML = syncStatus === "true" ? 'Synced' : 'Not Synced';
6870
document.getElementById("sync-status").style.color = syncStatus === "true" ? 'green' : 'red';

0 commit comments

Comments
 (0)