certichain

Blockchain built from scratch for verifying document's legitimacy.
Log | Files | Refs | README | LICENSE

init.go (3160B)


      1 // Copyright 2026 Shivakumar (Certichain)
      2 //
      3 // Licensed under the Apache License, Version 2.0 (the "License");
      4 // you may not use this file except in compliance with the License.
      5 // You may obtain a copy of the License at
      6 //
      7 //     http://www.apache.org/licenses/LICENSE-2.0
      8 //
      9 // Unless required by applicable law or agreed to in writing, software
     10 // distributed under the License is distributed on an "AS IS" BASIS,
     11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12 // See the License for the specific language governing permissions and
     13 // limitations under the License.
     14 
     15 package main
     16 
     17 import (
     18 	"bufio"
     19 	"flag"
     20 	"fmt"
     21 	"os"
     22 	"path/filepath"
     23 	"strings"
     24 
     25 	"certichain/internal/crypto"
     26 )
     27 
     28 const (
     29 	configDir = ".certichain"
     30 	privFile  = "private_key.pem"
     31 	pubFile   = "public_key.pem"
     32 
     33 	dirPremission  = 0o700
     34 	privPremission = 0o600
     35 	pubPremission  = 0o644
     36 )
     37 
     38 func runInit(args []string) {
     39 	fs := flag.NewFlagSet("init", flag.ExitOnError)
     40 	force := fs.Bool("force", false, "overwrite existing keys without prompting")
     41 	fs.Parse(args)
     42 
     43 	home, err := os.UserHomeDir()
     44 	if err != nil {
     45 		fmt.Fprintln(os.Stderr, "resolving HOME path:", err)
     46 		os.Exit(1)
     47 	}
     48 	dir := filepath.Join(home, configDir)
     49 
     50 	privPath := filepath.Join(dir, privFile)
     51 	pubPath := filepath.Join(dir, pubFile)
     52 
     53 	if _, err := os.Stat(privPath); err == nil {
     54 		if !(*force) && !confirmOverwrite(privPath) {
     55 			fmt.Println("aborted - existing keys left untouched")
     56 			return
     57 		}
     58 	}
     59 
     60 	if err := os.MkdirAll(dir, dirPremission); err != nil {
     61 		fmt.Fprintln(os.Stderr, "creating key directory:", err)
     62 		os.Exit(1)
     63 	}
     64 
     65 	pub, priv, err := crypto.GenerateKeyPair()
     66 	if err != nil {
     67 		fmt.Fprintln(os.Stderr, "generating keypair:", err)
     68 		os.Exit(1)
     69 	}
     70 
     71 	privPEM, err := crypto.PrivateKeyToPEM(priv)
     72 	if err != nil {
     73 		fmt.Fprintln(os.Stderr, "encoding private key:", err)
     74 		os.Exit(1)
     75 	}
     76 	pubPEM, err := crypto.PublicKeyToPEM(pub)
     77 	if err != nil {
     78 		fmt.Fprintln(os.Stderr, "encoding public key:", err)
     79 		os.Exit(1)
     80 	}
     81 
     82 	if err := os.WriteFile(privPath, privPEM, privPremission); err != nil {
     83 		fmt.Fprintln(os.Stderr, "writing private key:", err)
     84 		os.Exit(1)
     85 	}
     86 	if err := os.WriteFile(pubPath, pubPEM, pubPremission); err != nil {
     87 		fmt.Fprintln(os.Stderr, "writing public key:", err)
     88 		os.Exit(1)
     89 	}
     90 
     91 	did, err := crypto.NewDID(pub)
     92 	if err != nil {
     93 		fmt.Fprintln(os.Stderr, "deriving DID:", err)
     94 		os.Exit(1)
     95 	}
     96 
     97 	fmt.Println("Institution initilized successfully!")
     98 	fmt.Println("\nDID:\n\t", did)
     99 	fmt.Println("Key:")
    100 	fmt.Println("\t Private:", privPath)
    101 	fmt.Println("\t Public :", pubPath)
    102 	fmt.Println("\nNext Step:")
    103 	fmt.Println("Register this DID with the network:")
    104 	fmt.Println("\n\t curl -X POST localhost:8080/v1/institutions \\")
    105 	fmt.Printf("\t -d '{\"public_key\":\"%x\"}'\n", []byte(pub))
    106 }
    107 
    108 func confirmOverwrite(path string) bool {
    109 	fmt.Printf("Keys already exists at: %s\n", path)
    110 	fmt.Println("Reinitlizing overwrites them - deletes the old DID forever.")
    111 	fmt.Print("Continue [y/N]: ")
    112 
    113 	reader := bufio.NewReader(os.Stdin)
    114 	line, _ := reader.ReadString('\n')
    115 	line = strings.TrimSpace(strings.ToLower(line))
    116 	return line == "y" || line == "yes"
    117 }