publisher.go 1.74 KB
Newer Older
Jeromy's avatar
Jeromy committed
1 2 3
package namesys

import (
4 5
	"time"

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6 7
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto"
Jeromy's avatar
Jeromy committed
8 9 10 11 12 13 14

	ci "github.com/jbenet/go-ipfs/crypto"
	mdag "github.com/jbenet/go-ipfs/merkledag"
	routing "github.com/jbenet/go-ipfs/routing"
	u "github.com/jbenet/go-ipfs/util"
)

15
type ipnsPublisher struct {
Jeromy's avatar
Jeromy committed
16 17 18 19
	dag     *mdag.DAGService
	routing routing.IpfsRouting
}

20 21 22 23 24 25
type Publisher interface {
	Publish(ci.PrivKey, string) error
}

func NewPublisher(dag *mdag.DAGService, route routing.IpfsRouting) Publisher {
	return &ipnsPublisher{
26 27 28 29 30
		dag:     dag,
		routing: route,
	}
}

Jeromy's avatar
Jeromy committed
31
// Publish accepts a keypair and a value,
32
func (p *ipnsPublisher) Publish(k ci.PrivKey, value string) error {
33
	log.Debug("namesys: Publish %s", value)
34
	ctx := context.TODO()
Jeromy's avatar
Jeromy committed
35 36 37 38 39 40 41 42 43 44
	data, err := CreateEntryData(k, value)
	if err != nil {
		return err
	}
	pubkey := k.GetPublic()
	pkbytes, err := pubkey.Bytes()
	if err != nil {
		return nil
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
45
	nameb := u.Hash(pkbytes)
Jeromy's avatar
Jeromy committed
46
	namekey := u.Key(nameb).Pretty()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
47
	ipnskey := u.Hash([]byte("/ipns/" + namekey))
Jeromy's avatar
Jeromy committed
48 49

	// Store associated public key
50 51
	timectx, _ := context.WithDeadline(ctx, time.Now().Add(time.Second*4))
	err = p.routing.PutValue(timectx, u.Key(nameb), pkbytes)
Jeromy's avatar
Jeromy committed
52 53 54 55
	if err != nil {
		return err
	}

Jeromy's avatar
Jeromy committed
56
	// Store ipns entry at h("/ipns/"+b58(h(pubkey)))
57 58
	timectx, _ = context.WithDeadline(ctx, time.Now().Add(time.Second*4))
	err = p.routing.PutValue(timectx, u.Key(ipnskey), data)
Jeromy's avatar
Jeromy committed
59 60 61 62 63 64 65
	if err != nil {
		return err
	}

	return nil
}

66
func CreateEntryData(pk ci.PrivKey, val string) ([]byte, error) {
Jeromy's avatar
Jeromy committed
67 68 69 70 71 72 73 74 75
	entry := new(IpnsEntry)
	sig, err := pk.Sign([]byte(val))
	if err != nil {
		return nil, err
	}
	entry.Signature = sig
	entry.Value = []byte(val)
	return proto.Marshal(entry)
}