routing.go 2.07 KB
Newer Older
1 2 3 4 5
package namesys

import (
	"fmt"

6
	"code.google.com/p/go.net/context"
7 8 9 10 11 12 13
	"code.google.com/p/goprotobuf/proto"

	ci "github.com/jbenet/go-ipfs/crypto"
	mdag "github.com/jbenet/go-ipfs/merkledag"
	"github.com/jbenet/go-ipfs/routing"
	u "github.com/jbenet/go-ipfs/util"
	mh "github.com/jbenet/go-multihash"
14
	"github.com/op/go-logging"
15 16
)

17 18
var log = logging.MustGetLogger("namesys")

19 20 21
// RoutingResolver implements NSResolver for the main IPFS SFS-like naming
type RoutingResolver struct {
	routing routing.IpfsRouting
Jeromy's avatar
Jeromy committed
22 23 24 25 26 27 28 29
	dag     *mdag.DAGService
}

func NewRoutingResolver(route routing.IpfsRouting, dagservice *mdag.DAGService) *RoutingResolver {
	return &RoutingResolver{
		routing: route,
		dag:     dagservice,
	}
30 31
}

Jeromy's avatar
Jeromy committed
32 33 34 35 36
func (r *RoutingResolver) Matches(name string) bool {
	_, err := mh.FromB58String(name)
	return err == nil
}

37
func (r *RoutingResolver) Resolve(name string) (string, error) {
38
	ctx := context.TODO()
39 40
	hash, err := mh.FromB58String(name)
	if err != nil {
41
		log.Warning("RoutingResolve: bad input hash: [%s]\n", name)
42 43 44 45 46 47
		return "", err
	}
	// name should be a multihash. if it isn't, error out here.

	// use the routing system to get the name.
	// /ipns/<name>
Jeromy's avatar
Jeromy committed
48
	h, err := u.Hash([]byte("/ipns/" + name))
49 50 51 52
	if err != nil {
		return "", err
	}

Jeromy's avatar
Jeromy committed
53
	ipnsKey := u.Key(h)
54
	val, err := r.routing.GetValue(ctx, ipnsKey)
55
	if err != nil {
56
		log.Warning("RoutingResolve get failed.")
57 58 59
		return "", err
	}

Jeromy's avatar
Jeromy committed
60
	entry := new(IpnsEntry)
61 62 63 64 65 66 67 68
	err = proto.Unmarshal(val, entry)
	if err != nil {
		return "", err
	}

	// name should be a public key retrievable from ipfs
	// /ipfs/<name>
	key := u.Key(hash)
69
	pkval, err := r.routing.GetValue(ctx, key)
70
	if err != nil {
71
		log.Warning("RoutingResolve PubKey Get failed.")
72 73 74 75
		return "", err
	}

	// get PublicKey from node.Data
Jeromy's avatar
Jeromy committed
76
	pk, err := ci.UnmarshalPublicKey(pkval)
77 78 79 80 81
	if err != nil {
		return "", err
	}

	// check sig with pk
Jeromy's avatar
Jeromy committed
82
	if ok, err := pk.Verify(entry.GetValue(), entry.GetSignature()); err != nil || !ok {
83 84 85 86 87 88
		return "", fmt.Errorf("Invalid value. Not signed by PrivateKey corresponding to %v", pk)
	}

	// ok sig checks out. this is a valid name.
	return string(entry.GetValue()), nil
}