2014-07-23 04:48:30 -07:00
|
|
|
package dht
|
|
|
|
|
2014-07-28 22:14:27 -07:00
|
|
|
import (
|
|
|
|
swarm "github.com/jbenet/go-ipfs/swarm"
|
2014-07-29 19:33:51 -07:00
|
|
|
u "github.com/jbenet/go-ipfs/util"
|
|
|
|
"code.google.com/p/goprotobuf/proto"
|
2014-07-29 14:50:33 -07:00
|
|
|
"sync"
|
2014-07-28 22:14:27 -07:00
|
|
|
)
|
|
|
|
|
2014-07-23 04:48:30 -07:00
|
|
|
// TODO. SEE https://github.com/jbenet/node-ipfs/blob/master/submodules/ipfs-dht/index.js
|
|
|
|
|
|
|
|
// IpfsDHT is an implementation of Kademlia with Coral and S/Kademlia modifications.
|
|
|
|
// It is used to implement the base IpfsRouting module.
|
|
|
|
type IpfsDHT struct {
|
2014-07-29 14:50:33 -07:00
|
|
|
routes RoutingTable
|
2014-07-28 22:14:27 -07:00
|
|
|
|
2014-07-29 14:50:33 -07:00
|
|
|
network *swarm.Swarm
|
|
|
|
|
2014-07-29 19:33:51 -07:00
|
|
|
// map of channels waiting for reply messages
|
|
|
|
listeners map[uint64]chan *swarm.Message
|
2014-07-29 14:50:33 -07:00
|
|
|
listenLock sync.RWMutex
|
2014-07-29 19:33:51 -07:00
|
|
|
|
|
|
|
// Signal to shutdown dht
|
|
|
|
shutdown chan struct{}
|
2014-07-28 22:14:27 -07:00
|
|
|
}
|
|
|
|
|
2014-07-29 14:50:33 -07:00
|
|
|
// Read in all messages from swarm and handle them appropriately
|
|
|
|
// NOTE: this function is just a quick sketch
|
2014-07-28 22:14:27 -07:00
|
|
|
func (dht *IpfsDHT) handleMessages() {
|
2014-07-29 19:33:51 -07:00
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case mes := <-dht.network.Chan.Incoming:
|
|
|
|
pmes := new(DHTMessage)
|
|
|
|
err := proto.Unmarshal(mes.Data, pmes)
|
|
|
|
if err != nil {
|
|
|
|
u.PErr("Failed to decode protobuf message: %s", err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Note: not sure if this is the correct place for this
|
|
|
|
dht.listenLock.RLock()
|
|
|
|
ch, ok := dht.listeners[pmes.GetId()]
|
|
|
|
dht.listenLock.RUnlock()
|
|
|
|
if ok {
|
|
|
|
ch <- mes
|
2014-07-29 14:50:33 -07:00
|
|
|
}
|
2014-07-29 19:33:51 -07:00
|
|
|
//
|
|
|
|
|
|
|
|
// Do something else with the messages?
|
|
|
|
switch pmes.GetType() {
|
|
|
|
case DHTMessage_ADD_PROVIDER:
|
|
|
|
case DHTMessage_FIND_NODE:
|
|
|
|
case DHTMessage_GET_PROVIDERS:
|
|
|
|
case DHTMessage_GET_VALUE:
|
|
|
|
case DHTMessage_PING:
|
|
|
|
case DHTMessage_PUT_VALUE:
|
|
|
|
}
|
|
|
|
|
|
|
|
case <-dht.shutdown:
|
|
|
|
return
|
2014-07-29 14:50:33 -07:00
|
|
|
}
|
2014-07-28 22:14:27 -07:00
|
|
|
}
|
2014-07-23 04:48:30 -07:00
|
|
|
}
|
2014-07-29 14:50:33 -07:00
|
|
|
|
|
|
|
// Register a handler for a specific message ID, used for getting replies
|
|
|
|
// to certain messages (i.e. response to a GET_VALUE message)
|
2014-07-29 19:33:51 -07:00
|
|
|
func (dht *IpfsDHT) ListenFor(mesid uint64) <-chan *swarm.Message {
|
|
|
|
lchan := make(chan *swarm.Message)
|
2014-07-29 14:50:33 -07:00
|
|
|
dht.listenLock.Lock()
|
|
|
|
dht.listeners[mesid] = lchan
|
|
|
|
dht.listenLock.Unlock()
|
|
|
|
return lchan
|
|
|
|
}
|