From f4d551c08dba560d1477c71b23acc560cc9c6cd3 Mon Sep 17 00:00:00 2001
From: Dave Collins <davec@conformal.com>
Date: Fri, 19 Feb 2016 15:52:55 -0600
Subject: [PATCH] findcheckpoint: Update to allow first checkpoint.

This updates the findcheckpoint utility to work when there are not
already any checkpoints.  This doesn't really matter for Bitcoin at the
current time, but if a new testnet is created it will not have any
checkpoints to start with and this change also means the utility can
work for alts.

While here, switch a couple of error prints to ensure they contain a
final newline.
---
 cmd/findcheckpoint/findcheckpoint.go | 18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)

diff --git a/cmd/findcheckpoint/findcheckpoint.go b/cmd/findcheckpoint/findcheckpoint.go
index 00ee6f04..99c4bd5e 100644
--- a/cmd/findcheckpoint/findcheckpoint.go
+++ b/cmd/findcheckpoint/findcheckpoint.go
@@ -56,7 +56,12 @@ func findCandidates(db database.Db, latestHash *wire.ShaHash) ([]*chaincfg.Check
 	chain := blockchain.New(db, activeNetParams, nil, nil)
 	latestCheckpoint := chain.LatestCheckpoint()
 	if latestCheckpoint == nil {
-		return nil, fmt.Errorf("unable to retrieve latest checkpoint")
+		// Set the latest checkpoint to the genesis block if there isn't
+		// already one.
+		latestCheckpoint = &chaincfg.Checkpoint{
+			Hash:   activeNetParams.GenesisHash,
+			Height: 0,
+		}
 	}
 
 	// The latest known block must be at least the last known checkpoint
@@ -71,6 +76,13 @@ func findCandidates(db database.Db, latestHash *wire.ShaHash) ([]*chaincfg.Check
 			checkpointConfirmations)
 	}
 
+	// For the first checkpoint, the required height is any block after the
+	// genesis block, so long as the chain has at least the required number
+	// of confirmations (which is enforced above).
+	if len(activeNetParams.Checkpoints) == 0 {
+		requiredHeight = 1
+	}
+
 	// Indeterminate progress setup.
 	numBlocksToTest := block.Height() - requiredHeight
 	progressInterval := (numBlocksToTest / 100) + 1 // min 1
@@ -138,7 +150,7 @@ func main() {
 	// Load the block database.
 	db, err := loadBlockDB()
 	if err != nil {
-		fmt.Fprintf(os.Stderr, "failed to load database: %v\n", err)
+		fmt.Fprintln(os.Stderr, "failed to load database:", err)
 		return
 	}
 	defer db.Close()
@@ -155,7 +167,7 @@ func main() {
 	// Find checkpoint candidates.
 	candidates, err := findCandidates(db, latestHash)
 	if err != nil {
-		fmt.Fprintf(os.Stderr, "Unable to identify candidates: %v", err)
+		fmt.Fprintln(os.Stderr, "Unable to identify candidates:", err)
 		return
 	}