Skip to content

Instantly share code, notes, and snippets.

@whyrusleeping
Last active November 2, 2018 11:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whyrusleeping/9f2c83f3feed340e21ac to your computer and use it in GitHub Desktop.
Save whyrusleeping/9f2c83f3feed340e21ac to your computer and use it in GitHub Desktop.
A program to find ipfs dag roots, NOTE: cannot be run with a live daemon.
package main
import (
"fmt"
key "github.com/ipfs/go-ipfs/blocks/key"
"github.com/ipfs/go-ipfs/core"
fsrepo "github.com/ipfs/go-ipfs/repo/fsrepo"
"golang.org/x/net/context"
)
func FindRoots(nd *core.IpfsNode) ([]key.Key, error) {
blks, err := nd.Blockstore.AllKeysChan(context.Background())
if err != nil {
return nil, err
}
roots := make(map[key.Key]bool)
for blk := range blks {
mdnd, err := nd.DAG.Get(context.TODO(), blk)
if err != nil {
fmt.Println(err)
continue
}
_, found := roots[blk]
if !found {
roots[blk] = true
}
for _, lnk := range mdnd.Links {
roots[key.Key(lnk.Hash)] = false
}
}
var out []key.Key
for k, v := range roots {
if v {
out = append(out, k)
}
}
return out, nil
}
func main() {
fsr, err := fsrepo.Open("~/.go-ipfs")
if err != nil {
fmt.Println(err)
return
}
nd, err := core.NewNode(context.Background(), &core.BuildCfg{
Repo: fsr,
})
if err != nil {
fmt.Println(err)
return
}
roots, err := FindRoots(nd)
if err != nil {
fmt.Println(err)
return
}
for _, k := range roots {
fmt.Println(k)
}
}
@tarekbadrshalaan
Copy link

Hi @whyrusleeping

I made some change because of changes in packages.

package main

import (
	"fmt"

	"github.com/ipfs/go-ipfs/core"
	fsrepo "github.com/ipfs/go-ipfs/repo/fsrepo"
	"golang.org/x/net/context"
)

// FindRoots :
func FindRoots(nd *core.IpfsNode) ([]string, error) {
	blks, err := nd.Blockstore.AllKeysChan(context.Background())
	if err != nil {
		return nil, err
	}

	roots := make(map[string]bool)
	for blk := range blks {
		mdnd, err := nd.DAG.Get(context.TODO(), blk)
		if err != nil {
			fmt.Println(err)
			continue
		}

		_, found := roots[blk.String()]
		if !found {
			roots[blk.String()] = true
		}

		links := mdnd.Links()
		for _, lnk := range links {
			roots[lnk.Cid.String()] = false
		}
	}

	var out []string
	for k, v := range roots {
		if v {
			out = append(out, k)
		}
	}
	return out, nil
}

func main() {
	fsr, err := fsrepo.Open("~/.go-ipfs") 

	if err != nil {
		fmt.Println(err)
		return
	}

	nd, err := core.NewNode(context.Background(), &core.BuildCfg{
		Repo: fsr,
	})
	if err != nil {
		fmt.Println(err)
		return
	}

	roots, err := FindRoots(nd)
	if err != nil {
		fmt.Println(err)
		return
	}

	for _, k := range roots {
		fmt.Println(k)
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment