certichain

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

main.go (2802B)


      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 	"context"
     19 	"log"
     20 	"net/http"
     21 	"os"
     22 	"os/signal"
     23 	"syscall"
     24 	"time"
     25 
     26 	"certichain/api"
     27 	"certichain/internal/blockchain"
     28 	"certichain/internal/mempool"
     29 	"certichain/internal/registry"
     30 	"certichain/internal/storage"
     31 
     32 	"golang.org/x/sync/errgroup"
     33 )
     34 
     35 const (
     36 	dataPath        = "./data"
     37 	addr            = ":8080"
     38 	blockInterval   = 30 * time.Second
     39 	shutdownTimeout = 10 * time.Second
     40 )
     41 
     42 func main() {
     43 	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
     44 	defer stop()
     45 
     46 	store, err := storage.NewBadgerStore(dataPath)
     47 	if err != nil {
     48 		log.Fatal(err)
     49 	}
     50 	defer store.Close()
     51 
     52 	reg := registry.New(store)
     53 	mem := mempool.New()
     54 
     55 	bc, err := blockchain.New(store, blockchain.WithKeyResolver(reg))
     56 	if err != nil {
     57 		log.Fatal(err)
     58 	}
     59 
     60 	deps := api.Deps{
     61 		Blockchain: bc,
     62 		Registry:   reg,
     63 		Mempool:    mem,
     64 	}
     65 	srv := api.NewServer(addr, deps)
     66 
     67 	g, gCtx := errgroup.WithContext(ctx)
     68 
     69 	g.Go(func() error {
     70 		log.Printf("certichain node listening on %s", addr)
     71 		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
     72 			return err
     73 		}
     74 		return nil
     75 	})
     76 
     77 	g.Go(func() error {
     78 		return startBlockProducer(ctx, bc, mem, blockInterval)
     79 	})
     80 
     81 	g.Go(func() error {
     82 		<-gCtx.Done()
     83 		log.Println("shutting down http server")
     84 
     85 		shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
     86 		defer cancel()
     87 
     88 		return srv.Shutdown(shutdownCtx)
     89 	})
     90 
     91 	if err := g.Wait(); err != nil {
     92 		log.Printf("shutdown with error: %v", err)
     93 	}
     94 	log.Println("shutdown complete")
     95 }
     96 
     97 func startBlockProducer(
     98 	ctx context.Context,
     99 	bc *blockchain.Blockchain,
    100 	mp *mempool.Mempool,
    101 	interval time.Duration,
    102 ) error {
    103 	ticker := time.NewTicker(interval)
    104 	defer ticker.Stop()
    105 
    106 	for {
    107 		select {
    108 		case <-ticker.C:
    109 			txs := mp.Flush(0)
    110 			if len(txs) == 0 {
    111 				continue
    112 			}
    113 
    114 			if _, err := bc.AddBlock(txs); err != nil {
    115 				log.Printf("block production failed: %v", err)
    116 
    117 				for _, tx := range txs {
    118 					if reErr := mp.Add(tx); reErr != nil {
    119 						log.Printf("failed to re-queue tx %x after failed block: %v", tx, reErr)
    120 					}
    121 				}
    122 			}
    123 		case <-ctx.Done():
    124 			log.Println("stopping block producer")
    125 			return nil
    126 		}
    127 	}
    128 }