ledger.go 1.26 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3
package bitswap

import (
Brian Tiger Chow's avatar
Brian Tiger Chow committed
4 5
	"time"

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6 7 8 9 10 11 12
	peer "github.com/jbenet/go-ipfs/peer"
	u "github.com/jbenet/go-ipfs/util"
)

// Ledger stores the data exchange relationship between two peers.
type Ledger struct {

13 14
	// Partner is the remote Peer.
	Partner *peer.Peer
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15

16 17
	// Accounting tracks bytes sent and recieved.
	Accounting debtRatio
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
18

Brian Tiger Chow's avatar
Brian Tiger Chow committed
19 20
	// firstExchnage is the time of the first data exchange.
	firstExchange time.Time
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
21

Brian Tiger Chow's avatar
Brian Tiger Chow committed
22 23
	// lastExchange is the time of the last data exchange.
	lastExchange time.Time
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
24

Brian Tiger Chow's avatar
Brian Tiger Chow committed
25 26
	// exchangeCount is the number of exchanges with this peer
	exchangeCount uint64
27

Brian Tiger Chow's avatar
Brian Tiger Chow committed
28 29
	// wantList is a (bounded, small) set of keys that Partner desires.
	wantList KeySet
Jeromy's avatar
Jeromy committed
30 31

	Strategy StrategyFunc
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
32 33 34 35
}

// LedgerMap lists Ledgers by their Partner key.
type LedgerMap map[u.Key]*Ledger
36 37

func (l *Ledger) ShouldSend() bool {
38
	return l.Strategy(l)
39 40
}

41
func (l *Ledger) SentBytes(n int) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
42 43
	l.exchangeCount++
	l.lastExchange = time.Now()
44
	l.Accounting.BytesSent += uint64(n)
45 46
}

47
func (l *Ledger) ReceivedBytes(n int) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
48 49
	l.exchangeCount++
	l.lastExchange = time.Now()
50
	l.Accounting.BytesRecv += uint64(n)
51
}
52 53 54

// TODO: this needs to be different. We need timeouts.
func (l *Ledger) Wants(k u.Key) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
55
	l.wantList[k] = struct{}{}
56 57 58
}

func (l *Ledger) WantListContains(k u.Key) bool {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
59
	_, ok := l.wantList[k]
60 61
	return ok
}