certichain

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

commit 7e4e71c92f63a0d3624202a637bbc429313a5fdf
parent e91fe525bbce827f135685958e34ebdee1bdb892
Author: Shivakumar <[email protected]>
Date:   Thu,  6 Aug 2026 00:43:34 +0530

feat: add cmd to make transaction tests easier

Signed-off-by: Shivakumar <[email protected]>

Diffstat:
Acmd/institution/anchor.go | 135+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/institution/main.go | 141+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 276 insertions(+), 0 deletions(-)

diff --git a/cmd/institution/anchor.go b/cmd/institution/anchor.go @@ -0,0 +1,135 @@ +// Copyright 2026 Shivakumar (Certichain) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package main + +import ( + "bytes" + "crypto/ed25519" + "encoding/hex" + "encoding/json" + "flag" + "fmt" + "net/http" + "os" + "path" + + "certichain/api/dto" + "certichain/internal/crypto" + "certichain/internal/transaction" +) + +func runAnchor(args []string) { + fs := flag.NewFlagSet("anchor", flag.ExitOnError) + url := fs.String("url", "http://localhost:8080", "certichain node base url") + fs.Parse(args) + + if fs.NArg() != 1 { + fmt.Fprintln(os.Stderr, "usage: certi anchor [flags] <merkle-root>") + os.Exit(1) + } + + merkleRoot, err := hex.DecodeString(fs.Arg(0)) + if err != nil { + fmt.Fprintln(os.Stderr, "decoding merkle root:", err) + os.Exit(1) + } + + pub, priv, err := loadKeys() + if err != nil { + fmt.Fprintln(os.Stderr, "loading keys:", err) + fmt.Fprintln(os.Stderr, "hint: run 'certi init' first") + os.Exit(1) + } + + did, err := crypto.NewDID(pub) + if err != nil { + fmt.Fprintln(os.Stderr, "deriving DID:", err) + os.Exit(1) + } + + tx, err := transaction.New(did, merkleRoot) + if err != nil { + fmt.Fprintln(os.Stderr, "creating transaction:", err) + os.Exit(1) + } + + if err := tx.Sign(priv); err != nil { + fmt.Fprintln(os.Stderr, "signing transaction:", err) + os.Exit(1) + } + + payload := dto.SubmitTransactionRequest{ + TxID: hex.EncodeToString(tx.TxID), + IssuerDID: tx.IssuerDID, + MerkleRoot: hex.EncodeToString(tx.MerkleRoot), + Nonce: hex.EncodeToString(tx.Nonce), + Timestamp: tx.Timestamp, + Signature: hex.EncodeToString(tx.Signature), + } + + prettyJSON, _ := json.MarshalIndent(payload, "", " ") + fmt.Println(string(prettyJSON)) + + body, err := json.Marshal(payload) + if err != nil { + fmt.Fprintln(os.Stderr, "encoding request:", err) + os.Exit(1) + } + + txURL := *url + "/v1/transactions" + resp, err := http.Post(txURL, "application/json", bytes.NewReader(body)) + if err != nil { + fmt.Fprintln(os.Stderr, "submitting transaction:", err) + os.Exit(1) + } + defer resp.Body.Close() + + var respBody dto.SubmitTransactionResponse + if err := json.NewDecoder(resp.Body).Decode(&respBody); err != nil { + fmt.Fprintln(os.Stderr, "decoding response:", err) + os.Exit(1) + } + + fmt.Println("status:\n\t", resp.Status) + fmt.Printf("response:\n\t{\n\t\t\"status\":\"%s\",\n\t\t\"tx_id\" :\"%s\"\n\t}\n", respBody.Status, respBody.TxID) +} + +func loadKeys() (ed25519.PublicKey, ed25519.PrivateKey, error) { + home, err := os.UserHomeDir() + if err != nil { + return nil, nil, err + } + dir := path.Join(home, configDir) + + privPEM, err := os.ReadFile(path.Join(dir, privFile)) + if err != nil { + return nil, nil, fmt.Errorf("reading private key:%w", err) + } + pubPEM, err := os.ReadFile(path.Join(dir, pubFile)) + if err != nil { + return nil, nil, fmt.Errorf("reading public key:%w", err) + } + + priv, err := crypto.PrivateKeyFromPEM(privPEM) + if err != nil { + return nil, nil, fmt.Errorf("parsing private key:%w", err) + } + pub, err := crypto.PublicKeyFromPEM(pubPEM) + if err != nil { + return nil, nil, fmt.Errorf("parsing public key:%w", err) + } + + return pub, priv, nil +} diff --git a/cmd/institution/main.go b/cmd/institution/main.go @@ -0,0 +1,141 @@ +// Copyright 2026 Shivakumar (Certichain) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package main + +import ( + "bufio" + "certichain/internal/crypto" + "flag" + "fmt" + "os" + "path/filepath" + "strings" +) + +const ( + configDir = ".certichain" + privFile = "private_key.pem" + pubFile = "public_key.pem" + + dirPremission = 0o700 + privPremission = 0o600 + pubPremission = 0o644 +) + +func main() { + if len(os.Args) < 2 { + printUsage() + os.Exit(1) + } + + switch os.Args[1] { + case "init": + runInit(os.Args[2:]) + case "anchor": + runAnchor(os.Args[2:]) + default: + fmt.Fprintf(os.Stderr, "unknown command: %s\n", os.Args[1]) + os.Exit(1) + } +} + +func printUsage() { + fmt.Fprintln(os.Stdout, "usage: certi <command> [flags]") + fmt.Fprintln(os.Stdout, "commands:") + fmt.Fprintln(os.Stdout, "\tinit\tgenerate and store a new institution keypair") + fmt.Fprintln(os.Stdout, "flags:") + fmt.Fprintln(os.Stdout, "\t-force\toverwrite existing key without prompting") +} + +func runInit(args []string) { + fs := flag.NewFlagSet("init", flag.ExitOnError) + force := fs.Bool("force", false, "overwrite existing keys without prompting") + fs.Parse(args) + + home, err := os.UserHomeDir() + if err != nil { + fmt.Fprintln(os.Stderr, "resolving HOME path:", err) + os.Exit(1) + } + dir := filepath.Join(home, configDir) + + privPath := filepath.Join(dir, privFile) + pubPath := filepath.Join(dir, pubFile) + + if _, err := os.Stat(privPath); err == nil { + if !(*force) && !confirmOverwrite(privPath) { + fmt.Println("aborted - existing keys left untouched") + return + } + } + + if err := os.MkdirAll(dir, dirPremission); err != nil { + fmt.Fprintln(os.Stderr, "creating key directory:", err) + os.Exit(1) + } + + pub, priv, err := crypto.GenerateKeyPair() + if err != nil { + fmt.Fprintln(os.Stderr, "generating keypair:", err) + os.Exit(1) + } + + privPEM, err := crypto.PrivateKeyToPEM(priv) + if err != nil { + fmt.Fprintln(os.Stderr, "encoding private key:", err) + os.Exit(1) + } + pubPEM, err := crypto.PublicKeyToPEM(pub) + if err != nil { + fmt.Fprintln(os.Stderr, "encoding public key:", err) + os.Exit(1) + } + + if err := os.WriteFile(privPath, privPEM, privPremission); err != nil { + fmt.Fprintln(os.Stderr, "writing private key:", err) + os.Exit(1) + } + if err := os.WriteFile(pubPath, pubPEM, pubPremission); err != nil { + fmt.Fprintln(os.Stderr, "writing public key:", err) + os.Exit(1) + } + + did, err := crypto.NewDID(pub) + if err != nil { + fmt.Fprintln(os.Stderr, "deriving DID:", err) + os.Exit(1) + } + + fmt.Println("Institution initilized successfully!") + fmt.Println("\nDID:\n\t", did) + fmt.Println("Key:") + fmt.Println("\t Private:", privPath) + fmt.Println("\t Public :", pubPath) + fmt.Println("\nNext Step:") + fmt.Println("Register this DID with the network:") + fmt.Println("\n\t curl -X POST localhost:8080/v1/institutions \\") + fmt.Printf("\t -d '{\"public_key\":\"%x\"}'\n", []byte(pub)) +} + +func confirmOverwrite(path string) bool { + fmt.Printf("Keys already exists at: %s\n", path) + fmt.Println("Reinitlizing overwrites them - deletes the old DID forever.") + fmt.Print("Continue [y/N]: ") + + reader := bufio.NewReader(os.Stdin) + line, _ := reader.ReadString('\n') + line = strings.TrimSpace(strings.ToLower(line)) + return line == "y" || line == "yes" +}