本文整理汇总了Golang中github.com/ipfs/go-ipfs/blocks/key.Key函数的典型用法代码示例。如果您正苦于以下问题:Golang Key函数的具体用法?Golang Key怎么用?Golang Key使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Key函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: walkItems
func walkItems(ctx context.Context, dag merkledag.DAGService, n *merkledag.Node, fn walkerFunc, children keyObserver) error {
hdr, buf, err := readHdr(n)
if err != nil {
return err
}
// readHdr guarantees fanout is a safe value
fanout := hdr.GetFanout()
for i, l := range n.Links[fanout:] {
if err := fn(buf, i, l); err != nil {
return err
}
}
for _, l := range n.Links[:fanout] {
children(key.Key(l.Hash))
if key.Key(l.Hash) == emptyKey {
continue
}
subtree, err := l.GetNode(ctx, dag)
if err != nil {
return err
}
if err := walkItems(ctx, dag, subtree, fn, children); err != nil {
return err
}
}
return nil
}
示例2: ResolveToKey
// ResolveToKey resolves a path to a key.
//
// It first checks if the path is already in the form of just a key (<key> or
// /ipfs/<key>) and returns immediately if so. Otherwise, it falls back onto
// Resolve to perform resolution of the dagnode being referenced.
func ResolveToKey(ctx context.Context, n *IpfsNode, p path.Path) (key.Key, error) {
// If the path is simply a key, parse and return it. Parsed paths are already
// normalized (read: prepended with /ipfs/ if needed), so segment[1] should
// always be the key.
if p.IsJustAKey() {
return key.B58KeyDecode(p.Segments()[1]), nil
}
// Fall back onto regular dagnode resolution. Retrieve the second-to-last
// segment of the path and resolve its link to the last segment.
head, tail, err := p.PopLastSegment()
if err != nil {
return key.Key(""), err
}
dagnode, err := Resolve(ctx, n, head)
if err != nil {
return key.Key(""), err
}
// Extract and return the key of the link to the target dag node.
link, err := dagnode.GetNodeLink(tail)
if err != nil {
return key.Key(""), err
}
return key.Key(link.Hash), nil
}
示例3: TestClientFindProviders
func TestClientFindProviders(t *testing.T) {
pi := testutil.RandIdentityOrFatal(t)
rs := NewServer()
client := rs.Client(pi)
k := key.Key("hello")
err := client.Provide(context.Background(), k)
if err != nil {
t.Fatal(err)
}
// This is bad... but simulating networks is hard
time.Sleep(time.Millisecond * 300)
max := 100
providersFromClient := client.FindProvidersAsync(context.Background(), key.Key("hello"), max)
isInClient := false
for pi := range providersFromClient {
if pi.ID == pi.ID {
isInClient = true
}
}
if !isInClient {
t.Fatal("Despite client providing key, client didn't receive peer when finding providers")
}
}
示例4: TestToNetFromNetPreservesWantList
func TestToNetFromNetPreservesWantList(t *testing.T) {
original := New(true)
original.AddEntry(key.Key("M"), 1)
original.AddEntry(key.Key("B"), 1)
original.AddEntry(key.Key("D"), 1)
original.AddEntry(key.Key("T"), 1)
original.AddEntry(key.Key("F"), 1)
buf := new(bytes.Buffer)
if err := original.ToNet(buf); err != nil {
t.Fatal(err)
}
copied, err := FromNet(buf)
if err != nil {
t.Fatal(err)
}
keys := make(map[key.Key]bool)
for _, k := range copied.Wantlist() {
keys[k.Key] = true
}
for _, k := range original.Wantlist() {
if _, ok := keys[k.Key]; !ok {
t.Fatalf("Key Missing: \"%v\"", k)
}
}
}
示例5: Diff
func Diff(ctx context.Context, ds dag.DAGService, a, b *dag.Node) []*Change {
if len(a.Links) == 0 && len(b.Links) == 0 {
ak, _ := a.Key()
bk, _ := b.Key()
return []*Change{
&Change{
Type: Mod,
Before: ak,
After: bk,
},
}
}
var out []*Change
clean_a := a.Copy()
clean_b := b.Copy()
// strip out unchanged stuff
for _, lnk := range a.Links {
l, err := b.GetNodeLink(lnk.Name)
if err == nil {
if bytes.Equal(l.Hash, lnk.Hash) {
// no change... ignore it
} else {
anode, _ := lnk.GetNode(ctx, ds)
bnode, _ := l.GetNode(ctx, ds)
sub := Diff(ctx, ds, anode, bnode)
for _, subc := range sub {
subc.Path = path.Join(lnk.Name, subc.Path)
out = append(out, subc)
}
}
clean_a.RemoveNodeLink(l.Name)
clean_b.RemoveNodeLink(l.Name)
}
}
for _, lnk := range clean_a.Links {
out = append(out, &Change{
Type: Remove,
Path: lnk.Name,
Before: key.Key(lnk.Hash),
})
}
for _, lnk := range clean_b.Links {
out = append(out, &Change{
Type: Add,
Path: lnk.Name,
After: key.Key(lnk.Hash),
})
}
return out
}
示例6: resolveOnce
// resolveOnce implements resolver. Uses the IPFS routing system to
// resolve SFS-like names.
func (r *routingResolver) resolveOnce(ctx context.Context, name string) (path.Path, error) {
log.Debugf("RoutingResolve: '%s'", name)
hash, err := mh.FromB58String(name)
if err != nil {
log.Warning("RoutingResolve: bad input hash: [%s]\n", name)
return "", err
}
// name should be a multihash. if it isn't, error out here.
// use the routing system to get the name.
// /ipns/<name>
h := []byte("/ipns/" + string(hash))
ipnsKey := key.Key(h)
val, err := r.routing.GetValue(ctx, ipnsKey)
if err != nil {
log.Warning("RoutingResolve get failed.")
return "", err
}
entry := new(pb.IpnsEntry)
err = proto.Unmarshal(val, entry)
if err != nil {
return "", err
}
// name should be a public key retrievable from ipfs
pubkey, err := routing.GetPublicKey(r.routing, ctx, hash)
if err != nil {
return "", err
}
hsh, _ := pubkey.Hash()
log.Debugf("pk hash = %s", key.Key(hsh))
// check sig with pk
if ok, err := pubkey.Verify(ipnsEntryDataForSig(entry), entry.GetSignature()); err != nil || !ok {
return "", fmt.Errorf("Invalid value. Not signed by PrivateKey corresponding to %v", pubkey)
}
// ok sig checks out. this is a valid name.
// check for old style record:
valh, err := mh.Cast(entry.GetValue())
if err != nil {
// Not a multihash, probably a new record
return path.ParsePath(string(entry.GetValue()))
} else {
// Its an old style multihash record
log.Warning("Detected old style multihash record")
return path.FromKey(key.Key(valh)), nil
}
}
示例7: TestPushPop
func TestPushPop(t *testing.T) {
prq := newPRQ()
partner := testutil.RandPeerIDFatal(t)
alphabet := strings.Split("abcdefghijklmnopqrstuvwxyz", "")
vowels := strings.Split("aeiou", "")
consonants := func() []string {
var out []string
for _, letter := range alphabet {
skip := false
for _, vowel := range vowels {
if letter == vowel {
skip = true
}
}
if !skip {
out = append(out, letter)
}
}
return out
}()
sort.Strings(alphabet)
sort.Strings(vowels)
sort.Strings(consonants)
// add a bunch of blocks. cancel some. drain the queue. the queue should only have the kept entries
for _, index := range rand.Perm(len(alphabet)) { // add blocks for all letters
letter := alphabet[index]
t.Log(partner.String())
prq.Push(wantlist.Entry{Key: key.Key(letter), Priority: math.MaxInt32 - index}, partner)
}
for _, consonant := range consonants {
prq.Remove(key.Key(consonant), partner)
}
var out []string
for {
received := prq.Pop()
if received == nil {
break
}
out = append(out, string(received.Entry.Key))
}
// Entries popped should already be in correct order
for i, expected := range vowels {
if out[i] != expected {
t.Fatal("received", out[i], "expected", expected)
}
}
}
示例8: TestPeerRepeats
// This test checks that peers wont starve out other peers
func TestPeerRepeats(t *testing.T) {
prq := newPRQ()
a := testutil.RandPeerIDFatal(t)
b := testutil.RandPeerIDFatal(t)
c := testutil.RandPeerIDFatal(t)
d := testutil.RandPeerIDFatal(t)
// Have each push some blocks
for i := 0; i < 5; i++ {
prq.Push(wantlist.Entry{Key: key.Key(i)}, a)
prq.Push(wantlist.Entry{Key: key.Key(i)}, b)
prq.Push(wantlist.Entry{Key: key.Key(i)}, c)
prq.Push(wantlist.Entry{Key: key.Key(i)}, d)
}
// now, pop off four entries, there should be one from each
var targets []string
var tasks []*peerRequestTask
for i := 0; i < 4; i++ {
t := prq.Pop()
targets = append(targets, t.Target.Pretty())
tasks = append(tasks, t)
}
expected := []string{a.Pretty(), b.Pretty(), c.Pretty(), d.Pretty()}
sort.Strings(expected)
sort.Strings(targets)
t.Log(targets)
t.Log(expected)
for i, s := range targets {
if expected[i] != s {
t.Fatal("unexpected peer", s, expected[i])
}
}
// Now, if one of the tasks gets finished, the next task off the queue should
// be for the same peer
for blockI := 0; blockI < 4; blockI++ {
for i := 0; i < 4; i++ {
// its okay to mark the same task done multiple times here (JUST FOR TESTING)
tasks[i].Done()
ntask := prq.Pop()
if ntask.Target != tasks[i].Target {
t.Fatal("Expected task from peer with lowest active count")
}
}
}
}
示例9: ReadRecent
//ReadRecent reads recent key of Peer p.
func (p *Peer) ReadRecent() (key.Key, error) {
var recent NodeProto
if err := p.readDAG(config.RecentPath, &recent); log.If(err) {
return "", err
}
return key.Key(recent.Id), nil
}
示例10: TestClientOverMax
func TestClientOverMax(t *testing.T) {
rs := NewServer()
k := key.Key("hello")
numProvidersForHelloKey := 100
for i := 0; i < numProvidersForHelloKey; i++ {
pi := testutil.RandIdentityOrFatal(t)
err := rs.Client(pi).Provide(context.Background(), k)
if err != nil {
t.Fatal(err)
}
}
max := 10
pi := testutil.RandIdentityOrFatal(t)
client := rs.Client(pi)
providersFromClient := client.FindProvidersAsync(context.Background(), k, max)
i := 0
for _ = range providersFromClient {
i++
}
if i != max {
t.Fatal("Too many providers returned")
}
}
示例11: TestValidAfter
func TestValidAfter(t *testing.T) {
pi := testutil.RandIdentityOrFatal(t)
var key = key.Key("mock key")
var ctx = context.Background()
conf := DelayConfig{
ValueVisibility: delay.Fixed(1 * time.Hour),
Query: delay.Fixed(0),
}
rs := NewServerWithDelay(conf)
rs.Client(pi).Provide(ctx, key)
var providers []peer.PeerInfo
providers, err := rs.Client(pi).FindProviders(ctx, key)
if err != nil {
t.Fatal(err)
}
if len(providers) > 0 {
t.Fail()
}
conf.ValueVisibility.Set(0)
providers, err = rs.Client(pi).FindProviders(ctx, key)
if err != nil {
t.Fatal(err)
}
t.Log("providers", providers)
if len(providers) != 1 {
t.Fail()
}
}
示例12: TestRoutingResolve
func TestRoutingResolve(t *testing.T) {
d := mockrouting.NewServer().Client(testutil.RandIdentityOrFatal(t))
dstore := ds.NewMapDatastore()
resolver := NewRoutingResolver(d, 0)
publisher := NewRoutingPublisher(d, dstore)
privk, pubk, err := testutil.RandTestKeyPair(512)
if err != nil {
t.Fatal(err)
}
h := path.FromString("/ipfs/QmZULkCELmmk5XNfCgTnCyFgAVxBRBXyDHGGMVoLFLiXEN")
err = publisher.Publish(context.Background(), privk, h)
if err != nil {
t.Fatal(err)
}
pubkb, err := pubk.Bytes()
if err != nil {
t.Fatal(err)
}
pkhash := u.Hash(pubkb)
res, err := resolver.Resolve(context.Background(), key.Key(pkhash).Pretty())
if err != nil {
t.Fatal(err)
}
if res != h {
t.Fatal("Got back incorrect value.")
}
}
示例13: TestEnumerateChildren
func TestEnumerateChildren(t *testing.T) {
bsi := bstest.Mocks(1)
ds := NewDAGService(bsi[0])
read := io.LimitReader(u.NewTimeSeededRand(), 1024*1024)
root, err := imp.BuildDagFromReader(ds, chunk.NewSizeSplitter(read, 512))
if err != nil {
t.Fatal(err)
}
ks := key.NewKeySet()
err = EnumerateChildren(context.Background(), ds, root, ks, false)
if err != nil {
t.Fatal(err)
}
var traverse func(n *Node)
traverse = func(n *Node) {
// traverse dag and check
for _, lnk := range n.Links {
k := key.Key(lnk.Hash)
if !ks.Has(k) {
t.Fatal("missing key in set!")
}
child, err := ds.Get(context.Background(), k)
if err != nil {
t.Fatal(err)
}
traverse(child)
}
}
traverse(root)
}
示例14: TestEmptyKey
func TestEmptyKey(t *testing.T) {
ds := dstest.Mock()
_, err := ds.Get(context.Background(), key.Key(""))
if err != ErrNotFound {
t.Error("dag service should error when key is nil", err)
}
}
示例15: publish
func publish(ctx context.Context, n *core.IpfsNode, k crypto.PrivKey, ref path.Path, opts *publishOpts) (*IpnsEntry, error) {
if opts.verifyExists {
// verify the path exists
_, err := core.Resolve(ctx, n, ref)
if err != nil {
return nil, err
}
}
eol := time.Now().Add(opts.pubValidTime)
err := n.Namesys.PublishWithEOL(ctx, k, ref, eol)
if err != nil {
return nil, err
}
hash, err := k.GetPublic().Hash()
if err != nil {
return nil, err
}
return &IpnsEntry{
Name: key.Key(hash).String(),
Value: ref.String(),
}, nil
}