certichain

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

block.go (3133B)


      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 blockchain
     16 
     17 import (
     18 	"encoding/binary"
     19 	"encoding/json"
     20 	"errors"
     21 	"fmt"
     22 
     23 	"certichain/internal/crypto"
     24 	"certichain/internal/merkle"
     25 	"certichain/internal/transaction"
     26 )
     27 
     28 var emptyHash = crypto.HashBytes(nil)
     29 
     30 // BlockHeader contains the metadata for a block.
     31 type BlockHeader struct {
     32 	Height     uint64
     33 	PrevHash   crypto.Hash
     34 	MerkleRoot crypto.Hash
     35 	TimeStamp  int64
     36 }
     37 
     38 // Block represents a full block in the chain.
     39 type Block struct {
     40 	Header       *BlockHeader
     41 	Transactions []*transaction.Transaction
     42 	Hash         crypto.Hash // Cached
     43 }
     44 
     45 // newBlock is the internal constructor for standard blocks.
     46 func newBlock(prevHash []byte,
     47 	height uint64,
     48 	txs []*transaction.Transaction,
     49 	timestamp int64,
     50 ) (*Block, error) {
     51 	if len(prevHash) != crypto.HashSize {
     52 		return nil, fmt.Errorf("blockchain: newBlock: invalid prevHash length %d", len(prevHash))
     53 	}
     54 
     55 	b := &Block{
     56 		Header: &BlockHeader{
     57 			Height:    height,
     58 			PrevHash:  crypto.Hash(prevHash),
     59 			TimeStamp: timestamp,
     60 		},
     61 		Transactions: txs,
     62 	}
     63 
     64 	// Compute Merkle Root
     65 	root, err := b.hashTransactions()
     66 	if err != nil {
     67 		return nil, err
     68 	}
     69 	// Direct conversion for Merkle root
     70 	b.Header.MerkleRoot = crypto.Hash(root)
     71 
     72 	// Compute Block Hash
     73 	hash, err := b.Header.computeHash()
     74 	if err != nil {
     75 		return nil, err
     76 	}
     77 	b.Hash = hash
     78 
     79 	return b, nil
     80 }
     81 
     82 // hashTransactions builds a Merkle tree from transactions.
     83 func (b *Block) hashTransactions() ([]byte, error) {
     84 	if len(b.Transactions) == 0 {
     85 		return emptyHash[:], nil
     86 	}
     87 
     88 	txBytes := make([][]byte, len(b.Transactions))
     89 	for i, tx := range b.Transactions {
     90 		data, err := tx.Serialize()
     91 		if err != nil {
     92 			return nil, err
     93 		}
     94 		txBytes[i] = data
     95 	}
     96 
     97 	tree, err := merkle.New(txBytes)
     98 	if err != nil {
     99 		return nil, err
    100 	}
    101 	return tree.Root(), nil
    102 }
    103 
    104 // computeHash generates a deterministic canonical hash of the header.
    105 func (h *BlockHeader) computeHash() (crypto.Hash, error) {
    106 	var hBuf, tBuf [8]byte
    107 	binary.BigEndian.PutUint64(hBuf[:], h.Height)
    108 	binary.BigEndian.PutUint64(tBuf[:], uint64(h.TimeStamp))
    109 	return crypto.HashCanonical(hBuf[:], h.PrevHash[:], h.MerkleRoot[:], tBuf[:])
    110 }
    111 
    112 // Serialize encodes the block to JSON.
    113 func (b *Block) Serialize() ([]byte, error) {
    114 	return json.Marshal(b)
    115 }
    116 
    117 // Deserialize decodes a block from JSON.
    118 func Deserialize(data []byte) (*Block, error) {
    119 	var b Block
    120 	if err := json.Unmarshal(data, &b); err != nil {
    121 		return nil, err
    122 	}
    123 	if b.Header == nil {
    124 		return nil, errors.New("blockchain: deserialized block has no header")
    125 	}
    126 	return &b, nil
    127 }