Commit 54ff6ea4 authored by Jeromy's avatar Jeromy

bitswap first working commit!

parent ffc60abb
...@@ -2,6 +2,7 @@ package blockservice ...@@ -2,6 +2,7 @@ package blockservice
import ( import (
"fmt" "fmt"
"time"
ds "github.com/jbenet/datastore.go" ds "github.com/jbenet/datastore.go"
bitswap "github.com/jbenet/go-ipfs/bitswap" bitswap "github.com/jbenet/go-ipfs/bitswap"
...@@ -19,18 +20,27 @@ type BlockService struct { ...@@ -19,18 +20,27 @@ type BlockService struct {
} }
// NewBlockService creates a BlockService with given datastore instance. // NewBlockService creates a BlockService with given datastore instance.
func NewBlockService(d ds.Datastore) (*BlockService, error) { func NewBlockService(d ds.Datastore, rem *bitswap.BitSwap) (*BlockService, error) {
if d == nil { if d == nil {
return nil, fmt.Errorf("BlockService requires valid datastore") return nil, fmt.Errorf("BlockService requires valid datastore")
} }
return &BlockService{Datastore: d}, nil if rem == nil {
return nil, fmt.Errorf("BlockService requires a valid bitswap")
}
return &BlockService{Datastore: d, Remote: rem}, nil
} }
// AddBlock adds a particular block to the service, Putting it into the datastore. // AddBlock adds a particular block to the service, Putting it into the datastore.
func (s *BlockService) AddBlock(b *blocks.Block) (u.Key, error) { func (s *BlockService) AddBlock(b *blocks.Block) (u.Key, error) {
k := b.Key() k := b.Key()
dsk := ds.NewKey(string(k)) dsk := ds.NewKey(string(k))
return k, s.Datastore.Put(dsk, b.Data) u.DOut("storing [%s] in datastore\n", k.Pretty())
err := s.Datastore.Put(dsk, b.Data)
if err != nil {
return k, err
}
err = s.Remote.HaveBlock(b.Key())
return k, err
} }
// GetBlock retrieves a particular block from the service, // GetBlock retrieves a particular block from the service,
...@@ -38,17 +48,22 @@ func (s *BlockService) AddBlock(b *blocks.Block) (u.Key, error) { ...@@ -38,17 +48,22 @@ func (s *BlockService) AddBlock(b *blocks.Block) (u.Key, error) {
func (s *BlockService) GetBlock(k u.Key) (*blocks.Block, error) { func (s *BlockService) GetBlock(k u.Key) (*blocks.Block, error) {
dsk := ds.NewKey(string(k)) dsk := ds.NewKey(string(k))
datai, err := s.Datastore.Get(dsk) datai, err := s.Datastore.Get(dsk)
if err != nil { if err == nil {
return nil, err bdata, ok := datai.([]byte)
if !ok {
return nil, fmt.Errorf("data associated with %s is not a []byte", k)
}
return &blocks.Block{
Multihash: mh.Multihash(k),
Data: bdata,
}, nil
} else if err == ds.ErrNotFound {
blk, err := s.Remote.GetBlock(k, time.Second*5)
if err != nil {
return nil, err
}
return blk, nil
} else {
return nil, u.ErrNotFound
} }
data, ok := datai.([]byte)
if !ok {
return nil, fmt.Errorf("data associated with %s is not a []byte", k)
}
return &blocks.Block{
Multihash: mh.Multihash(k),
Data: data,
}, nil
} }
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment