dht.go 1.24 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
	"sync"
6 7
)

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

15 16
	network *swarm.Swarm

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
17
	listeners  map[uint64]chan swarm.Message
18
	listenLock sync.RWMutex
19 20
}

21 22
// Read in all messages from swarm and handle them appropriately
// NOTE: this function is just a quick sketch
23 24
func (dht *IpfsDHT) handleMessages() {
	for mes := range dht.network.Chan.Incoming {
25 26 27 28 29 30 31 32 33 34 35
		for {
			select {
			case mes := <-dht.network.Chan.Incoming:
				// Unmarshal message
				dht.listenLock.RLock()
				ch, ok := dht.listeners[id]
				dht.listenLock.RUnlock()
				if ok {
					// Send message to waiting goroutine
					ch <- mes
				}
36

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
37
				//case closeChan: or something
38 39
			}
		}
40
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
41
}
42 43 44 45 46 47 48 49 50 51

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