dht.go 1.78 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2
package dht

3 4
import (
	swarm "github.com/jbenet/go-ipfs/swarm"
5 6
	u "github.com/jbenet/go-ipfs/util"
	"code.google.com/p/goprotobuf/proto"
7
	"sync"
8 9
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
10 11 12 13 14
// 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 {
15
	routes RoutingTable
16

17 18
	network *swarm.Swarm

19 20
	// map of channels waiting for reply messages
	listeners  map[uint64]chan *swarm.Message
21
	listenLock sync.RWMutex
22 23 24

	// Signal to shutdown dht
	shutdown chan struct{}
25 26
}

27 28
// Read in all messages from swarm and handle them appropriately
// NOTE: this function is just a quick sketch
29
func (dht *IpfsDHT) handleMessages() {
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
	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
46
			}
47 48 49 50 51 52 53 54 55 56 57 58 59 60
			//

			// 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
61
		}
62
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
63
}
64 65 66

// Register a handler for a specific message ID, used for getting replies
// to certain messages (i.e. response to a GET_VALUE message)
67 68
func (dht *IpfsDHT) ListenFor(mesid uint64) <-chan *swarm.Message {
	lchan := make(chan *swarm.Message)
69 70 71 72 73
	dht.listenLock.Lock()
	dht.listeners[mesid] = lchan
	dht.listenLock.Unlock()
	return lchan
}