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

import (
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
4 5 6 7
	peer "github.com/jbenet/go-ipfs/peer"
	swarm "github.com/jbenet/go-ipfs/swarm"
	u "github.com/jbenet/go-ipfs/util"
	"time"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8 9 10 11 12 13 14
)

// This file implements the Routing interface for the IpfsDHT struct.

// Basic Put/Get

// PutValue adds value corresponding to given Key.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15
func (s *IpfsDHT) PutValue(key u.Key, value []byte) error {
16 17 18 19 20 21 22 23 24 25 26 27 28
	var p *peer.Peer
	p = s.routes.NearestNode(key)

	pmes := new(PutValue)
	pmes.Key = &key
	pmes.Value = value

	mes := new(swarm.Message)
	mes.Data = []byte(pmes.String())
	mes.Peer = p

	s.network.Chan.Outgoing <- mes
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
29 30 31 32
}

// GetValue searches for the value corresponding to given Key.
func (s *IpfsDHT) GetValue(key u.Key, timeout time.Duration) ([]byte, error) {
33 34 35 36 37 38 39 40 41 42 43 44
	var p *peer.Peer
	p = s.routes.NearestNode(key)

	// protobuf structure
	pmes := new(GetValue)
	pmes.Key = &key
	pmes.Id = GenerateMessageID()

	mes := new(swarm.Message)
	mes.Data = []byte(pmes.String())
	mes.Peer = p

45
	response_chan := s.ListenFor(pmes.Id)
46

47
	// Wait for either the response or a timeout
48 49
	timeup := time.After(timeout)
	select {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
50 51 52 53 54
	case <-timeup:
		// TODO: unregister listener
		return nil, timeoutError
	case resp := <-response_chan:
		return resp.Data, nil
55
	}
56 57 58

	// Should never be hit
	return nil, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
59 60 61 62 63 64
}

// Value provider layer of indirection.
// This is what DSHTs (Coral and MainlineDHT) do to store large values in a DHT.

// Announce that this node can provide value for given key
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
65 66
func (s *IpfsDHT) Provide(key u.Key) error {
	return u.ErrNotImplemented
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
67 68 69 70
}

// FindProviders searches for peers who can provide the value for given key.
func (s *IpfsDHT) FindProviders(key u.Key, timeout time.Duration) (*peer.Peer, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
71
	return nil, u.ErrNotImplemented
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
72 73 74 75 76 77
}

// Find specific Peer

// FindPeer searches for a peer with given ID.
func (s *IpfsDHT) FindPeer(id peer.ID, timeout time.Duration) (*peer.Peer, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
78
	return nil, u.ErrNotImplemented
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
79
}