main.go raw

   1  // Command ftool fills an instance from another instance's service, or makes
   2  // the key a service signs its manifest with.
   3  //
   4  //	ftool keygen -out instance.key
   5  //	ftool sync -from http://host:port -chain btc -from-height 0 -to-height 250000 -data ./data
   6  //
   7  // sync fetches chunks, checks each one against its name, and files blocks in
   8  // the body store under the hash their own header gives. It does not fill the
   9  // header store: headers are authenticated by the chain's rules, not by content
  10  // names, and the header sync is the chain client's job.
  11  package main
  12  
  13  import (
  14  	"context"
  15  	"crypto/ed25519"
  16  	"crypto/rand"
  17  	"encoding/hex"
  18  	"flag"
  19  	"fmt"
  20  	"os"
  21  	"path/filepath"
  22  	"strconv"
  23  	"strings"
  24  	"time"
  25  
  26  	"git.smesh.lol/btcd-lite/internal/chains"
  27  	"git.smesh.lol/btcd-lite/internal/fetch"
  28  	"git.smesh.lol/btcd-lite/internal/store"
  29  )
  30  
  31  func main() {
  32  	if len(os.Args) < 2 {
  33  		usage()
  34  	}
  35  	switch os.Args[1] {
  36  	case "keygen":
  37  		keygen(os.Args[2:])
  38  	case "sync":
  39  		sync(os.Args[2:])
  40  	case "utxo":
  41  		utxo(os.Args[2:])
  42  	default:
  43  		usage()
  44  	}
  45  }
  46  
  47  func usage() {
  48  	fmt.Fprint(os.Stderr, `ftool: fill an instance from a btcd-lite service
  49  
  50    ftool keygen -out instance.key
  51    ftool sync -from URL -chain btc -from-height N -to-height M [-key FILE] -data DIR
  52    ftool utxo -from URL -chain btc -data DIR
  53  
  54    -from is the service's base URL, no trailing slash.
  55    -chain is btc or xbt.
  56    -from-height and -to-height are a half-open range, in heights.
  57    -key, when given, is an Ed25519 seed in hex: a manifest not signed by it is
  58    refused before a chunk is fetched.
  59  `)
  60  	os.Exit(2)
  61  }
  62  
  63  func keygen(args []string) {
  64  	fs := flag.NewFlagSet("keygen", flag.ExitOnError)
  65  	out := fs.String("out", "instance.key", "file to write the seed to")
  66  	_ = fs.Parse(args)
  67  	seed := make([]byte, ed25519.SeedSize)
  68  	if _, err := rand.Read(seed); err != nil {
  69  		fail("keygen: %v", err)
  70  	}
  71  	if err := os.WriteFile(*out, []byte(hex.EncodeToString(seed)+"\n"), 0o600); err != nil {
  72  		fail("keygen: %v", err)
  73  	}
  74  	pub := ed25519.NewKeyFromSeed(seed).Public().(ed25519.PublicKey)
  75  	fmt.Printf("seed written to %s\npublic key: %x\n", *out, pub)
  76  }
  77  
  78  func sync(args []string) {
  79  	fs := flag.NewFlagSet("sync", flag.ExitOnError)
  80  	from := fs.String("from", "", "service base URL")
  81  	chainName := fs.String("chain", chains.Parent, "btc or xbt")
  82  	fromHeight := fs.String("from-height", "0", "first height")
  83  	toHeight := fs.String("to-height", "", "height past the last (required)")
  84  	keyFile := fs.String("key", "", "Ed25519 seed file the manifest must be signed with")
  85  	data := fs.String("data", "", "instance data directory")
  86  	_ = fs.Parse(args)
  87  	if *from == "" || *data == "" || *toHeight == "" {
  88  		usage()
  89  	}
  90  	if _, err := chains.ByName(*chainName); err != nil {
  91  		fail("%v", err)
  92  	}
  93  	lo, err := strconv.ParseUint(*fromHeight, 10, 32)
  94  	if err != nil {
  95  		fail("from-height: %v", err)
  96  	}
  97  	hi, err := strconv.ParseUint(*toHeight, 10, 32)
  98  	if err != nil || hi <= lo {
  99  		fail("to-height must be above from-height")
 100  	}
 101  	var pub ed25519.PublicKey
 102  	if *keyFile != "" {
 103  		seed, err := os.ReadFile(*keyFile)
 104  		if err != nil {
 105  			fail("key: %v", err)
 106  		}
 107  		raw, err := hex.DecodeString(strings.TrimSpace(string(seed)))
 108  		if err != nil || len(raw) != ed25519.SeedSize {
 109  			fail("key: %s is not a 32-byte hex seed", *keyFile)
 110  		}
 111  		pub = ed25519.NewKeyFromSeed(raw).Public().(ed25519.PublicKey)
 112  	}
 113  
 114  	bodies, err := store.NewBlockStore(filepath.Join(*data, "blocks"))
 115  	if err != nil {
 116  		fail("blocks: %v", err)
 117  	}
 118  	defer bodies.Close()
 119  
 120  	ctx, cancel := context.WithTimeout(context.Background(), 24*time.Hour)
 121  	defer cancel()
 122  	c := &fetch.Client{Base: strings.TrimRight(*from, "/")}
 123  	if _, err := c.Manifest(ctx, pub); err != nil {
 124  		fail("manifest: %v", err)
 125  	}
 126  	start := time.Now()
 127  	n, err := c.Blocks(ctx, *chainName, uint32(lo), uint32(hi), bodies)
 128  	if err != nil {
 129  		fail("sync: %v", err)
 130  	}
 131  	fmt.Printf("filed %d blocks for %s %d..%d in %s; the store holds %d\n",
 132  		n, *chainName, lo, hi-1, time.Since(start).Round(time.Second), bodies.Len())
 133  }
 134  
 135  // utxo fills a data directory's checkpoint chain from a service: the base
 136  // set, then each diff, verified at every boundary against the name the
 137  // service published.
 138  func utxo(args []string) {
 139  	fs := flag.NewFlagSet("utxo", flag.ExitOnError)
 140  	from := fs.String("from", "", "service base URL")
 141  	chainName := fs.String("chain", chains.Parent, "btc or xbt")
 142  	data := fs.String("data", "", "instance data directory")
 143  	_ = fs.Parse(args)
 144  	if *from == "" || *data == "" {
 145  		usage()
 146  	}
 147  	ctx, cancel := context.WithTimeout(context.Background(), 24*time.Hour)
 148  	defer cancel()
 149  	c := &fetch.Client{Base: strings.TrimRight(*from, "/")}
 150  	if _, err := chains.ByName(*chainName); err != nil {
 151  		fail("%v", err)
 152  	}
 153  	dir := filepath.Join(*data, "utxo", *chainName)
 154  	start := time.Now()
 155  	n, err := c.UTXO(ctx, *chainName, dir)
 156  	if err != nil {
 157  		fail("utxo: %v (reached %d checkpoints)", err, n)
 158  	}
 159  	fmt.Printf("reached %d checkpoints in %s, in %s\n", n, dir, time.Since(start).Round(time.Second))
 160  }
 161  
 162  func fail(format string, args ...any) {
 163  	fmt.Fprintf(os.Stderr, "ftool: "+format+"\n", args...)
 164  	os.Exit(1)
 165  }
 166