certichain

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

blocks.go (3500B)


      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 handlers
     16 
     17 import (
     18 	"encoding/hex"
     19 	"errors"
     20 	"net/http"
     21 	"strconv"
     22 	"time"
     23 
     24 	"certichain/api/dto"
     25 	"certichain/api/respond"
     26 	"certichain/internal/blockchain"
     27 	"certichain/internal/storage"
     28 )
     29 
     30 // GetBlock returns a handler for GET /v1/blocks/{hash}
     31 func GetBlock(bc *blockchain.Blockchain) http.HandlerFunc {
     32 	return func(w http.ResponseWriter, r *http.Request) {
     33 		blockHash := r.PathValue("hash")
     34 		hash, err := hex.DecodeString(blockHash)
     35 		if err != nil {
     36 			respond.Error(w, http.StatusBadRequest, "invalid_body", "invalid hex encoding")
     37 			return
     38 		}
     39 
     40 		block, err := bc.GetBlock(hash)
     41 		if err != nil {
     42 			writeStorageError(w, err, "block not found")
     43 			return
     44 		}
     45 		writeBlock(w, block)
     46 	}
     47 }
     48 
     49 // GetBlockByHeight returns a handler for GET /v1/blocks/{height}.
     50 func GetBlockByHeight(bc *blockchain.Blockchain) http.HandlerFunc {
     51 	return func(w http.ResponseWriter, r *http.Request) {
     52 		blockHeight := r.PathValue("height")
     53 
     54 		height, err := strconv.ParseUint(blockHeight, 10, 64)
     55 		if err != nil {
     56 			respond.Error(w, http.StatusBadRequest, "invalid_body", "invalid height: must be non-negative integer")
     57 			return
     58 		}
     59 
     60 		block, err := bc.GetBlockByHeight(uint64(height))
     61 		if err != nil {
     62 			writeStorageError(w, err, "block not found")
     63 			return
     64 		}
     65 		writeBlock(w, block)
     66 	}
     67 }
     68 
     69 // GetLatestBlock returns a handler for GET /v1/blocks/latest.
     70 func GetLatestBlock(bc *blockchain.Blockchain) http.HandlerFunc {
     71 	return func(w http.ResponseWriter, r *http.Request) {
     72 		height := bc.Height()
     73 		block, err := bc.GetBlockByHeight(height)
     74 		if err != nil {
     75 			writeStorageError(w, err, "block not found")
     76 			return
     77 		}
     78 		writeBlock(w, block)
     79 	}
     80 }
     81 
     82 // writeBlock is a helper function to eval block and all the transaction.
     83 func writeBlock(w http.ResponseWriter, block *blockchain.Block) {
     84 	var txs []dto.GetTransactionResponse
     85 	blockhash := block.Hash.String()
     86 	blockTxs := block.Transactions
     87 
     88 	for _, tx := range blockTxs {
     89 		txs = append(txs, dto.GetTransactionResponse{
     90 			TxID:       hex.EncodeToString(tx.TxID),
     91 			IssuerDID:  tx.IssuerDID,
     92 			MerkleRoot: hex.EncodeToString(tx.MerkleRoot),
     93 			Timestamp:  time.Unix(tx.Timestamp, 0).Format(time.DateTime),
     94 			Status:     "confirmed",
     95 			BlockHash:  &blockhash,
     96 		})
     97 	}
     98 
     99 	respond.JSON(w, http.StatusOK, dto.BlockResponse{
    100 		Height:       block.Header.Height,
    101 		Hash:         block.Hash.String(),
    102 		PrevHash:     block.Header.PrevHash.String(),
    103 		MerkleRoot:   block.Header.MerkleRoot.String(),
    104 		Timestamp:    time.Unix(block.Header.TimeStamp, 0).Format(time.DateTime),
    105 		Transactions: txs,
    106 	})
    107 
    108 }
    109 
    110 // writeStorageError checks for 404 or 500 error status code.
    111 func writeStorageError(w http.ResponseWriter, err error, msg string) {
    112 	if errors.Is(err, storage.ErrNotFound) {
    113 		respond.Error(w, http.StatusNotFound, "not_found", msg)
    114 		return
    115 	}
    116 	respond.Error(w, http.StatusInternalServerError, "server_error", "internal server error")
    117 }