2021-04-12 09:43:54 +00:00
|
|
|
import std/sequtils
|
2021-04-26 15:11:11 +00:00
|
|
|
import std/tables
|
2021-04-12 09:43:54 +00:00
|
|
|
import pkg/libp2p
|
|
|
|
import pkg/chronos
|
2021-04-14 14:07:49 +00:00
|
|
|
import pkg/nitro
|
2021-04-12 09:43:54 +00:00
|
|
|
import pkg/questionable
|
|
|
|
import ./protobuf/bitswap
|
|
|
|
import ./protobuf/payments
|
2021-04-26 15:11:11 +00:00
|
|
|
import ./protobuf/presence
|
2021-04-12 09:43:54 +00:00
|
|
|
|
2021-04-14 14:07:49 +00:00
|
|
|
export payments
|
|
|
|
export nitro
|
|
|
|
|
2021-04-12 09:43:54 +00:00
|
|
|
type
|
|
|
|
BitswapPeerCtx* = ref object of RootObj
|
|
|
|
id*: PeerID
|
2021-04-26 15:11:11 +00:00
|
|
|
peerPrices*: Table[Cid, UInt256] # remote peer have list including price
|
2021-04-14 14:07:49 +00:00
|
|
|
peerHave*: seq[Cid] # remote peers have lists
|
|
|
|
peerWants*: seq[Entry] # remote peers want lists
|
|
|
|
bytesSent*: int # bytes sent to remote
|
|
|
|
bytesRecv*: int # bytes received from remote
|
|
|
|
exchanged*: int # times peer has exchanged with us
|
|
|
|
lastExchange*: Moment # last time peer has exchanged with us
|
|
|
|
pricing*: ?Pricing # optional bandwidth price for this peer
|
|
|
|
paymentChannel*: ?ChannelId # payment channel id
|
2021-04-12 09:43:54 +00:00
|
|
|
|
|
|
|
proc contains*(a: openArray[BitswapPeerCtx], b: PeerID): bool =
|
|
|
|
## Convenience method to check for peer prepense
|
|
|
|
##
|
|
|
|
|
|
|
|
a.anyIt( it.id == b )
|
|
|
|
|
|
|
|
proc debtRatio*(b: BitswapPeerCtx): float =
|
|
|
|
b.bytesSent / (b.bytesRecv + 1)
|
|
|
|
|
|
|
|
proc `<`*(a, b: BitswapPeerCtx): bool =
|
|
|
|
a.debtRatio < b.debtRatio
|
|
|
|
|
2021-04-26 15:11:11 +00:00
|
|
|
func updatePresence*(context: BitswapPeerCtx, presence: Presence) =
|
|
|
|
let cid = presence.cid
|
|
|
|
let price = presence.price
|
|
|
|
|
|
|
|
if cid notin context.peerHave and presence.have:
|
|
|
|
context.peerHave.add(cid)
|
|
|
|
context.peerPrices[cid] = price
|
|
|
|
elif cid in context.peerHave and not presence.have:
|
|
|
|
context.peerHave.keepItIf(it != cid)
|
|
|
|
context.peerPrices.del(cid)
|