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

3
import (
4
	"sync"
5
	"time"
6
	"encoding/json"
7

Jeromy's avatar
Jeromy committed
8 9 10
	peer	"github.com/jbenet/go-ipfs/peer"
	swarm	"github.com/jbenet/go-ipfs/swarm"
	u		"github.com/jbenet/go-ipfs/util"
11 12 13
	identify "github.com/jbenet/go-ipfs/identify"

	ma "github.com/jbenet/go-multiaddr"
Jeromy's avatar
Jeromy committed
14 15 16

	ds "github.com/jbenet/datastore.go"

17
	"code.google.com/p/goprotobuf/proto"
18 19
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
20 21 22 23 24
// 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 {
25
	routes *RoutingTable
26

27 28
	network *swarm.Swarm

Jeromy's avatar
Jeromy committed
29 30 31 32 33
	// Local peer (yourself)
	self *peer.Peer

	// Local data
	datastore ds.Datastore
34

35 36 37
	// Map keys to peers that can provide their value
	// TODO: implement a TTL on each of these keys
	providers map[u.Key][]*peer.Peer
38
	providerLock sync.RWMutex
39

40 41
	// map of channels waiting for reply messages
	listeners  map[uint64]chan *swarm.Message
42
	listenLock sync.RWMutex
43 44 45

	// Signal to shutdown dht
	shutdown chan struct{}
46 47
}

48 49
// Create a new DHT object with the given peer as the 'local' host
func NewDHT(p *peer.Peer) (*IpfsDHT, error) {
50 51 52
	if p == nil {
		panic("Tried to create new dht with nil peer")
	}
53 54 55 56 57
	network := swarm.NewSwarm(p)
	err := network.Listen()
	if err != nil {
		return nil,err
	}
58

59 60
	dht := new(IpfsDHT)
	dht.network = network
61 62
	dht.datastore = ds.NewMapDatastore()
	dht.self = p
Jeromy's avatar
Jeromy committed
63
	dht.listeners = make(map[uint64]chan *swarm.Message)
64
	dht.providers = make(map[u.Key][]*peer.Peer)
Jeromy's avatar
Jeromy committed
65
	dht.shutdown = make(chan struct{})
66
	dht.routes = NewRoutingTable(20, convertPeerID(p.ID))
67 68 69
	return dht, nil
}

70
// Start up background goroutines needed by the DHT
71 72 73 74
func (dht *IpfsDHT) Start() {
	go dht.handleMessages()
}

75
// Connect to a new peer at the given address
Jeromy's avatar
Jeromy committed
76
// TODO: move this into swarm
77 78 79 80
func (dht *IpfsDHT) Connect(addr *ma.Multiaddr) (*peer.Peer, error) {
	if addr == nil {
		panic("addr was nil!")
	}
81 82 83 84 85
	peer := new(peer.Peer)
	peer.AddAddress(addr)

	conn,err := swarm.Dial("tcp", peer)
	if err != nil {
86
		return nil, err
87 88
	}

89
	err = identify.Handshake(dht.self, peer, conn.Incoming.MsgChan, conn.Outgoing.MsgChan)
90
	if err != nil {
91
		return nil, err
92 93
	}

Jeromy's avatar
Jeromy committed
94 95 96 97 98 99 100 101 102
	// Send node an address that you can be reached on
	myaddr := dht.self.NetAddress("tcp")
	mastr,err := myaddr.String()
	if err != nil {
		panic("No local address to send")
	}

	conn.Outgoing.MsgChan <- []byte(mastr)

103
	dht.network.StartConn(conn)
104

Jeromy's avatar
Jeromy committed
105 106 107 108
	removed := dht.routes.Update(peer)
	if removed != nil {
		panic("need to remove this peer.")
	}
109
	return peer, nil
Jeromy's avatar
Jeromy committed
110 111
}

112 113
// Read in all messages from swarm and handle them appropriately
// NOTE: this function is just a quick sketch
114
func (dht *IpfsDHT) handleMessages() {
115
	u.DOut("Begin message handling routine")
116 117
	for {
		select {
118 119 120 121 122
		case mes,ok := <-dht.network.Chan.Incoming:
			if !ok {
				u.DOut("handleMessages closing, bad recv on incoming")
				return
			}
123 124 125 126 127 128 129
			pmes := new(DHTMessage)
			err := proto.Unmarshal(mes.Data, pmes)
			if err != nil {
				u.PErr("Failed to decode protobuf message: %s", err)
				continue
			}

130
			// Update peers latest visit in routing table
Jeromy's avatar
Jeromy committed
131 132 133 134
			removed := dht.routes.Update(mes.Peer)
			if removed != nil {
				panic("Need to handle removed peer.")
			}
135

136
			// Note: not sure if this is the correct place for this
137 138 139 140 141 142
			if pmes.GetResponse() {
				dht.listenLock.RLock()
				ch, ok := dht.listeners[pmes.GetId()]
				dht.listenLock.RUnlock()
				if ok {
					ch <- mes
143 144 145
				} else {
					// this is expected behaviour during a timeout
					u.DOut("Received response with nobody listening...")
146 147 148
				}

				continue
149
			}
150 151
			//

152
			u.DOut("Got message type: '%s' [id = %x]", mesNames[pmes.GetType()], pmes.GetId())
153
			switch pmes.GetType() {
154 155 156
			case DHTMessage_GET_VALUE:
				dht.handleGetValue(mes.Peer, pmes)
			case DHTMessage_PUT_VALUE:
Jeromy's avatar
Jeromy committed
157
				dht.handlePutValue(mes.Peer, pmes)
158
			case DHTMessage_FIND_NODE:
Jeromy's avatar
Jeromy committed
159
				dht.handleFindPeer(mes.Peer, pmes)
160
			case DHTMessage_ADD_PROVIDER:
161
				dht.handleAddProvider(mes.Peer, pmes)
162
			case DHTMessage_GET_PROVIDERS:
163
				dht.handleGetProviders(mes.Peer, pmes)
164
			case DHTMessage_PING:
165
				dht.handlePing(mes.Peer, pmes)
166 167
			}

168
		case err := <-dht.network.Chan.Errors:
169
			u.DErr("dht err: %s", err)
170 171
		case <-dht.shutdown:
			return
172
		}
173
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
174
}
175

176
func (dht *IpfsDHT) handleGetValue(p *peer.Peer, pmes *DHTMessage) {
Jeromy's avatar
Jeromy committed
177 178 179
	dskey := ds.NewKey(pmes.GetKey())
	i_val, err := dht.datastore.Get(dskey)
	if err == nil {
180 181 182 183 184 185 186 187 188
		resp := &pDHTMessage{
			Response: true,
			Id: *pmes.Id,
			Key: *pmes.Key,
			Value: i_val.([]byte),
		}

		mes := swarm.NewMessage(p, resp.ToProtobuf())
		dht.network.Chan.Outgoing <- mes
Jeromy's avatar
Jeromy committed
189
	} else if err == ds.ErrNotFound {
Jeromy's avatar
Jeromy committed
190
		// Find closest peer(s) to desired key and reply with that info
191
		// TODO: this will need some other metadata in the protobuf message
Jeromy's avatar
Jeromy committed
192 193
		//			to signal to the querying peer that the data its receiving
		//			is actually a list of other peer
194 195 196
	}
}

Jeromy's avatar
Jeromy committed
197
// Store a value in this peer local storage
198
func (dht *IpfsDHT) handlePutValue(p *peer.Peer, pmes *DHTMessage) {
Jeromy's avatar
Jeromy committed
199 200 201 202 203 204
	dskey := ds.NewKey(pmes.GetKey())
	err := dht.datastore.Put(dskey, pmes.GetValue())
	if err != nil {
		// For now, just panic, handle this better later maybe
		panic(err)
	}
205 206 207
}

func (dht *IpfsDHT) handlePing(p *peer.Peer, pmes *DHTMessage) {
Jeromy's avatar
Jeromy committed
208
	resp := pDHTMessage{
209 210 211 212
		Type: pmes.GetType(),
		Response: true,
		Id: pmes.GetId(),
	}
213

214
	dht.network.Chan.Outgoing <-swarm.NewMessage(p, resp.ToProtobuf())
215 216
}

Jeromy's avatar
Jeromy committed
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
func (dht *IpfsDHT) handleFindPeer(p *peer.Peer, pmes *DHTMessage) {
	closest := dht.routes.NearestPeer(convertKey(u.Key(pmes.GetKey())))
	if closest == nil {
	}

	if len(closest.Addresses) == 0 {
		panic("no addresses for connected peer...")
	}

	addr,err := closest.Addresses[0].String()
	if err != nil {
		panic(err)
	}

	resp := pDHTMessage{
		Type: pmes.GetType(),
		Response: true,
		Id: pmes.GetId(),
		Value: []byte(addr),
	}

	mes := swarm.NewMessage(p, resp.ToProtobuf())
	dht.network.Chan.Outgoing <-mes
240 241 242
}

func (dht *IpfsDHT) handleGetProviders(p *peer.Peer, pmes *DHTMessage) {
243
	dht.providerLock.RLock()
244
	providers := dht.providers[u.Key(pmes.GetKey())]
245
	dht.providerLock.RUnlock()
246 247
	if providers == nil || len(providers) == 0 {
		// ?????
248
		u.DOut("No known providers for requested key.")
249 250
	}

251
	// This is just a quick hack, formalize method of sending addrs later
252
	addrs := make(map[u.Key]string)
253 254 255 256 257 258 259 260
	for _,prov := range providers {
		ma := prov.NetAddress("tcp")
		str,err := ma.String()
		if err != nil {
			u.PErr("Error: %s", err)
			continue
		}

261
		addrs[prov.Key()] = str
262 263 264 265 266 267 268 269 270 271 272 273
	}

	data,err := json.Marshal(addrs)
	if err != nil {
		panic(err)
	}

	resp := pDHTMessage{
		Type: DHTMessage_GET_PROVIDERS,
		Key: pmes.GetKey(),
		Value: data,
		Id: pmes.GetId(),
274
		Response: true,
275 276 277 278
	}

	mes := swarm.NewMessage(p, resp.ToProtobuf())
	dht.network.Chan.Outgoing <-mes
279 280 281
}

func (dht *IpfsDHT) handleAddProvider(p *peer.Peer, pmes *DHTMessage) {
282 283
	//TODO: need to implement TTLs on providers
	key := u.Key(pmes.GetKey())
284
	dht.addProviderEntry(key, p)
285 286
}

287

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

298
// Unregister the given message id from the listener map
Jeromy's avatar
Jeromy committed
299 300 301 302 303 304 305 306 307 308
func (dht *IpfsDHT) Unlisten(mesid uint64) {
	dht.listenLock.Lock()
	ch, ok := dht.listeners[mesid]
	if ok {
		delete(dht.listeners, mesid)
	}
	dht.listenLock.Unlock()
	close(ch)
}

Jeromy's avatar
Jeromy committed
309
// Stop all communications from this peer and shut down
310 311 312 313
func (dht *IpfsDHT) Halt() {
	dht.shutdown <- struct{}{}
	dht.network.Close()
}
314

Jeromy's avatar
Jeromy committed
315
// Ping a peer, log the time it took
316
func (dht *IpfsDHT) Ping(p *peer.Peer, timeout time.Duration) error {
317
	// Thoughts: maybe this should accept an ID and do a peer lookup?
318 319
	u.DOut("Enter Ping.")

320 321
	pmes := pDHTMessage{Id: GenerateMessageID(), Type: DHTMessage_PING}
	mes := swarm.NewMessage(p, pmes.ToProtobuf())
322 323

	before := time.Now()
324
	response_chan := dht.ListenFor(pmes.Id)
325 326 327 328 329 330
	dht.network.Chan.Outgoing <- mes

	tout := time.After(timeout)
	select {
	case <-response_chan:
		roundtrip := time.Since(before)
331 332
		u.POut("Ping took %s.", roundtrip.String())
		return nil
333
	case <-tout:
Jeromy's avatar
Jeromy committed
334 335
		// Timed out, think about removing peer from network
		u.DOut("Ping peer timed out.")
336
		return u.ErrTimeout
337 338
	}
}
339 340 341 342 343 344 345 346

func (dht *IpfsDHT) addProviderEntry(key u.Key, p *peer.Peer) {
	u.DOut("Adding %s as provider for '%s'", p.Key().Pretty(), key)
	dht.providerLock.Lock()
	provs := dht.providers[key]
	dht.providers[key] = append(provs, p)
	dht.providerLock.Unlock()
}