Example #1
0
func ImportChain(chainmgr *core.ChainManager, fn string) error {
	fmt.Printf("importing blockchain '%s'\n", fn)
	fh, err := os.OpenFile(fn, os.O_RDONLY, os.ModePerm)
	if err != nil {
		return err
	}
	defer fh.Close()

	chainmgr.Reset()
	stream := rlp.NewStream(fh, 0)
	var i, n int

	batchSize := 2500
	blocks := make(types.Blocks, batchSize)

	for ; ; i++ {
		var b types.Block
		if err := stream.Decode(&b); err == io.EOF {
			break
		} else if err != nil {
			return fmt.Errorf("at block %d: %v", i, err)
		}

		blocks[n] = &b
		n++

		if n == batchSize {
			if _, err := chainmgr.InsertChain(blocks); err != nil {
				return fmt.Errorf("invalid block %v", err)
			}
			n = 0
			blocks = make(types.Blocks, batchSize)
		}
	}

	if n > 0 {
		if _, err := chainmgr.InsertChain(blocks[:n]); err != nil {
			return fmt.Errorf("invalid block %v", err)
		}
	}

	fmt.Printf("imported %d blocks\n", i)
	return nil
}