This repository has been archived by the owner on Aug 9, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
77 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
package ipld | ||
|
||
import ( | ||
"github.com/ipfs/go-ipfs/blocks" | ||
"github.com/ipfs/go-ipfs/blocks/key" | ||
"github.com/ipfs/go-ipfs/blockservice" | ||
"github.com/ipfs/go-ipfs/util" | ||
"github.com/ipfs/go-ipld/coding" | ||
"github.com/ipfs/go-ipld/memory" | ||
"github.com/ipfs/go-ipld/stream" | ||
"golang.org/x/net/context" | ||
|
||
mh "github.com/jbenet/go-multihash" | ||
) | ||
|
||
var ErrNotFound error = blockservice.ErrNotFound | ||
|
||
type Node struct { | ||
stream.NodeReader | ||
Key key.Key | ||
} | ||
|
||
func (n *Node) Multihash() mh.Multihash { | ||
return mh.Multihash(n.Key.ToMultihash()) | ||
} | ||
|
||
type DAGService interface { | ||
|
||
// Add a memory Node to the BlockService | ||
Add(node memory.Node) (key.Key, error) | ||
|
||
// Get a node from the BlockService | ||
Get(ctx context.Context, key key.Key) (*Node, error) | ||
|
||
// Removes a node thom the BlockService | ||
Remove(key key.Key) error | ||
} | ||
|
||
type dagService struct { | ||
bs *blockservice.BlockService | ||
} | ||
|
||
func NewDAGService(bs *blockservice.BlockService) DAGService { | ||
return &dagService{bs} | ||
} | ||
|
||
func (ds *dagService) Add(node memory.Node) (key.Key, error) { | ||
data, err := coding.EncodeBytes(coding.CodecProtobuf, node) | ||
if err != nil { | ||
return "", err | ||
} | ||
|
||
return ds.bs.AddBlock(&blocks.Block{ | ||
Data: data, | ||
Multihash: util.Hash(data), | ||
}) | ||
} | ||
|
||
func (ds *dagService) Get(ctx context.Context, key key.Key) (*Node, error) { | ||
ctx, cancel := context.WithCancel(ctx) | ||
defer cancel() | ||
|
||
b, err := ds.bs.GetBlock(ctx, key) | ||
if err != nil { | ||
if err == blockservice.ErrNotFound { | ||
return nil, ErrNotFound | ||
} | ||
return nil, err | ||
} | ||
|
||
n, err := coding.DecodeBytes(b.Data) | ||
return &Node{n, key}, err | ||
} | ||
|
||
func (ds *dagService) Remove(key key.Key) error { | ||
return ds.bs.DeleteBlock(key) | ||
} |