checkpoints.go raw

   1  package checkpoints
   2  
   3  import (
   4  	"fmt"
   5  	"github.com/p9c/p9/pkg/chaincfg"
   6  	"github.com/p9c/p9/pkg/chainhash"
   7  	"strconv"
   8  	"strings"
   9  )
  10  
  11  // Parse checks the checkpoint strings for valid syntax ( '<height>:<hash>') and parses them to
  12  // chaincfg.Checkpoint instances.
  13  func Parse(checkpointStrings []string) ([]chaincfg.Checkpoint, error) {
  14  	if len(checkpointStrings) == 0 {
  15  		return nil, nil
  16  	}
  17  	checkpoints := make([]chaincfg.Checkpoint, len(checkpointStrings))
  18  	for i, cpString := range checkpointStrings {
  19  		checkpoint, e := newCheckpointFromStr(cpString)
  20  		if e != nil {
  21  			return nil, e
  22  		}
  23  		checkpoints[i] = checkpoint
  24  	}
  25  	return checkpoints, nil
  26  }
  27  
  28  // newCheckpointFromStr parses checkpoints in the '<height>:<hash>' format.
  29  func newCheckpointFromStr(checkpoint string) (chaincfg.Checkpoint, error) {
  30  	parts := strings.Split(checkpoint, ":")
  31  	if len(parts) != 2 {
  32  		return chaincfg.Checkpoint{}, fmt.Errorf(
  33  			"unable to parse "+
  34  				"checkpoint %q -- use the syntax <height>:<hash>",
  35  			checkpoint,
  36  		)
  37  	}
  38  	height, e := strconv.ParseInt(parts[0], 10, 32)
  39  	if e != nil {
  40  		return chaincfg.Checkpoint{}, fmt.Errorf(
  41  			"unable to parse "+
  42  				"checkpoint %q due to malformed height", checkpoint,
  43  		)
  44  	}
  45  	if len(parts[1]) == 0 {
  46  		return chaincfg.Checkpoint{}, fmt.Errorf(
  47  			"unable to parse "+
  48  				"checkpoint %q due to missing hash", checkpoint,
  49  		)
  50  	}
  51  	hash, e := chainhash.NewHashFromStr(parts[1])
  52  	if e != nil {
  53  		return chaincfg.Checkpoint{}, fmt.Errorf(
  54  			"unable to parse "+
  55  				"checkpoint %q due to malformed hash", checkpoint,
  56  		)
  57  	}
  58  	return chaincfg.Checkpoint{
  59  			Height: int32(height),
  60  			Hash:   hash,
  61  		},
  62  		nil
  63  }
  64