routing.go 1.96 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
package namesys

import (
	"fmt"
	"time"

	"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"
)

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

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

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

34 35 36
func (r *RoutingResolver) Resolve(name string) (string, error) {
	hash, err := mh.FromB58String(name)
	if err != nil {
Jeromy's avatar
Jeromy committed
37
		u.DOut("RoutingResolve: bad input hash: [%s]\n", name)
38 39 40 41 42 43
		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
44
	h, err := u.Hash([]byte("/ipns/" + name))
45 46 47 48
	if err != nil {
		return "", err
	}

Jeromy's avatar
Jeromy committed
49 50
	ipnsKey := u.Key(h)
	val, err := r.routing.GetValue(ipnsKey, time.Second*10)
51
	if err != nil {
Jeromy's avatar
Jeromy committed
52
		u.DOut("RoutingResolve get failed.\n")
53 54 55
		return "", err
	}

Jeromy's avatar
Jeromy committed
56
	entry := new(IpnsEntry)
57 58 59 60 61 62 63 64
	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)
Jeromy's avatar
Jeromy committed
65
	pkval, err := r.routing.GetValue(key, time.Second*10)
66
	if err != nil {
Jeromy's avatar
Jeromy committed
67
		u.DOut("RoutingResolve PubKey Get failed.\n")
68 69 70 71
		return "", err
	}

	// get PublicKey from node.Data
Jeromy's avatar
Jeromy committed
72
	pk, err := ci.UnmarshalPublicKey(pkval)
73 74 75 76 77
	if err != nil {
		return "", err
	}

	// check sig with pk
Jeromy's avatar
Jeromy committed
78
	if ok, err := pk.Verify(entry.GetValue(), entry.GetSignature()); err != nil || !ok {
79 80 81 82 83 84
		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
}