publisher.go 1.76 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 15 16 17 18 19

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

type IpnsPublisher struct {
	dag     *mdag.DAGService
	routing routing.IpfsRouting
}

20 21 22 23 24 25 26
func NewPublisher(dag *mdag.DAGService, route routing.IpfsRouting) *IpnsPublisher {
	return &IpnsPublisher{
		dag:     dag,
		routing: route,
	}
}

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

	nameb, err := u.Hash(pkbytes)
	if err != nil {
		return nil
	}
	namekey := u.Key(nameb).Pretty()

Jeromy's avatar
Jeromy committed
47
	ipnskey, err := u.Hash([]byte("/ipns/" + namekey))
Jeromy's avatar
Jeromy committed
48 49 50 51 52
	if err != nil {
		return err
	}

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

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

	return nil
}

69
func CreateEntryData(pk ci.PrivKey, val string) ([]byte, error) {
Jeromy's avatar
Jeromy committed
70 71 72 73 74 75 76 77 78
	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)
}