certichain

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

commit 6ccda1ac21cff250560afa00a8d1da53059ceba3
parent 432858d716472d4c25193d55441c2b3bd6677fe9
Author: Shivakumar <[email protected]>
Date:   Tue, 16 Jun 2026 03:34:48 +0530

feat(blockchain): add core functions of blockchain

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

Diffstat:
Ainternal/blockchain/block.go | 127+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ainternal/blockchain/blockchain.go | 343+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ainternal/blockchain/iterator.go | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 549 insertions(+), 0 deletions(-)

diff --git a/internal/blockchain/block.go b/internal/blockchain/block.go @@ -0,0 +1,127 @@ +// 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 blockchain + +import ( + "encoding/binary" + "encoding/json" + "errors" + "fmt" + + "certichain/internal/crypto" + "certichain/internal/merkle" + "certichain/internal/transaction" +) + +var emptyHash = crypto.HashBytes(nil) + +// BlockHeader contains the metadata for a block. +type BlockHeader struct { + Height uint64 + PrevHash crypto.Hash + MerkleRoot crypto.Hash + TimeStamp int64 +} + +// Block represents a full block in the chain. +type Block struct { + Header *BlockHeader + Transactions []*transaction.Transaction + Hash crypto.Hash // Cached +} + +// newBlock is the internal constructor for standard blocks. +func newBlock(prevHash []byte, + height uint64, + txs []*transaction.Transaction, + timestamp int64, +) (*Block, error) { + if len(prevHash) != crypto.HashSize { + return nil, fmt.Errorf("blockchain: newBlock: invalid prevHash length %d", len(prevHash)) + } + + b := &Block{ + Header: &BlockHeader{ + Height: height, + PrevHash: crypto.Hash(prevHash), + TimeStamp: timestamp, + }, + Transactions: txs, + } + + // Compute Merkle Root + root, err := b.hashTransactions() + if err != nil { + return nil, err + } + // Direct conversion for Merkle root + b.Header.MerkleRoot = crypto.Hash(root) + + // Compute Block Hash + hash, err := b.Header.computeHash() + if err != nil { + return nil, err + } + b.Hash = hash + + return b, nil +} + +// hashTransactions builds a Merkle tree from transactions. +func (b *Block) hashTransactions() ([]byte, error) { + if len(b.Transactions) == 0 { + return emptyHash[:], nil + } + + txBytes := make([][]byte, len(b.Transactions)) + for i, tx := range b.Transactions { + data, err := tx.Serialize() + if err != nil { + return nil, err + } + txBytes[i] = data + } + + tree, err := merkle.New(txBytes) + if err != nil { + return nil, err + } + return tree.Root(), nil +} + +// computeHash generates a deterministic canonical hash of the header. +func (h *BlockHeader) computeHash() (crypto.Hash, error) { + var hBuf, tBuf [8]byte + binary.BigEndian.PutUint64(hBuf[:], h.Height) + binary.BigEndian.PutUint64(tBuf[:], uint64(h.TimeStamp)) + return crypto.HashCanonical(hBuf[:], h.PrevHash[:], h.MerkleRoot[:], tBuf[:]) +} + +// Serialize encodes the block to JSON. +func (b *Block) Serialize() ([]byte, error) { + return json.Marshal(b) +} + +// Deserialize decodes a block from JSON. +func Deserialize(data []byte) (*Block, error) { + var b Block + if err := json.Unmarshal(data, &b); err != nil { + return nil, err + } + if b.Header == nil { + return nil, errors.New("blockchain: deserialized block has no header") + } + return &b, nil +} diff --git a/internal/blockchain/blockchain.go b/internal/blockchain/blockchain.go @@ -0,0 +1,343 @@ +// 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 blockchain + +import ( + "bytes" + "errors" + "fmt" + "iter" + "sync" + "time" + + "certichain/internal/crypto" + "certichain/internal/storage" + "certichain/internal/transaction" +) + +// Custom Errors +var ( + ErrNilTransactions = errors.New("blockchain: transaction slice cannot be nil") // for Tx Slice + ErrNilTransactionEntry = errors.New("blockchain: cannot add nil transaction") // for single Tx + ErrEmptyBlock = errors.New("blockchain: cannot add block with zero transaction") + ErrInvalidHash = errors.New("blockchain: invalid hash length") + ErrUnsignedTx = errors.New("blockchain: cannot add block with unsigned transaction") + ErrInvalidTxID = errors.New("blockchain: transaction has invalid TxID") +) + +// Blockchain manages the chain of blocks and provides a high-level API for +// storage and retrieval. +type Blockchain struct { + mu sync.RWMutex + store storage.Store + lastHash []byte + height uint64 +} + +// Option defines a function signature for configuring the Blockchain. +type Option func(*config) + +type config struct { + genesisTime int64 +} + +// WithGenesisTime sets a custom timestamp for the Genesis block. +// This is useful for maintaining a consistent Genesis hash across different networks. +func WithGenesisTime(t int64) Option { + return func(c *config) { + c.genesisTime = t + } +} + +// New initializes a new Blockchain instance. +// If the store is empty, it creates and persists the Genesis block. +func New(store storage.Store, opts ...Option) (*Blockchain, error) { + cfg := &config{ + // Default Genesis time: 2014-02-26 00:00:00 UTC + genesisTime: time.Date(2014, 2, 26, 0, 0, 0, 0, time.UTC).Unix(), + } + for _, opt := range opts { + opt(cfg) + } + + lastHash, err := store.Get(storage.LastHash()) + + // Database is empty, create and persist Genesis + if errors.Is(err, storage.ErrNotFound) { + genesis, err := createGenesisBlock(cfg.genesisTime) + if err != nil { + return nil, fmt.Errorf("blockchain: failed to create genesis block: %w", err) + } + + data, err := genesis.Serialize() + if err != nil { + return nil, err + } + + batch, err := store.NewBatch() + if err != nil { + return nil, err + } + defer batch.Discard() + + // Persist Genesis block and its indexes + if err := batch.Set(storage.BlockKey(genesis.Hash[:]), data); err != nil { + return nil, fmt.Errorf("blockchain: failed to persist genesis block: %w", err) + } + if err := batch.Set(storage.HeightKey(0), genesis.Hash[:]); err != nil { + return nil, fmt.Errorf("blockchain: failed to persist genesis block: %w", err) + } + if err := batch.Set(storage.LastHash(), genesis.Hash[:]); err != nil { + return nil, fmt.Errorf("blockchain: failed to persist genesis block: %w", err) + } + + // Commit the batch + if err := batch.Commit(); err != nil { + return nil, fmt.Errorf("blockchain: failed to commit genesis: %w", err) + } + + return &Blockchain{ + store: store, + lastHash: bytes.Clone(genesis.Hash[:]), + height: 0, + }, nil + } + + if err != nil { + return nil, fmt.Errorf("blockchain: failed to load tip: %w", err) + } + + // Fetch the last block + data, err := store.Get(storage.BlockKey(lastHash)) + if err != nil { + return nil, fmt.Errorf("blockchain: failed to load last block: %w", err) + } + lastBlock, err := Deserialize(data) + if err != nil { + return nil, err + } + + return &Blockchain{ + store: store, + lastHash: bytes.Clone(lastHash), + height: lastBlock.Header.Height, + }, nil +} + +// createGenesisBlock creates a deterministic first block for the chain. +func createGenesisBlock(timestamp int64) (*Block, error) { + block := &Block{ + Header: &BlockHeader{ + Height: 0, + PrevHash: crypto.Hash{}, + TimeStamp: timestamp, + }, + Transactions: []*transaction.Transaction{}, + } + + // Compute the Merkle root of the transactions + root, err := block.hashTransactions() + if err != nil { + return nil, err + } + block.Header.MerkleRoot = crypto.Hash(root) + + // Compute the block hash + hash, err := block.Header.computeHash() + if err != nil { + return nil, err + } + block.Hash = hash + + return block, nil +} + +// AddBlock validates transactions and appends a new block to the chain. +// Returns ErrEmptyBlock for empty transaction, to reduce bloat in the blockchain. +func (bc *Blockchain) AddBlock(txs []*transaction.Transaction) (*Block, error) { + if txs == nil { + return nil, ErrNilTransactions + } + if len(txs) == 0 { + return nil, ErrEmptyBlock + } + + for _, tx := range txs { + if tx == nil { + return nil, ErrNilTransactionEntry + } + + if !tx.IsSigned() { + return nil, ErrUnsignedTx + } + + if len(tx.TxID) != crypto.HashSize { + return nil, ErrInvalidTxID + } + } + + bc.mu.Lock() + defer bc.mu.Unlock() + + nextHeight := bc.height + 1 + now := time.Now().Unix() + block, err := newBlock(bc.lastHash, nextHeight, txs, now) + if err != nil { + return nil, fmt.Errorf("blockchain: failed to create block: %w", err) + } + + data, err := block.Serialize() + if err != nil { + return nil, err + } + + // Persist the changes atomically + batch, err := bc.store.NewBatch() + if err != nil { + return nil, err + } + defer batch.Discard() + + // Persist the block data + if err := batch.Set(storage.BlockKey(block.Hash[:]), data); err != nil { + return nil, err + } + // Index by height for O(1) retrieval + if err := batch.Set(storage.HeightKey(nextHeight), block.Hash[:]); err != nil { + return nil, err + } + + // Index individual transactions + for _, tx := range txs { + if err := batch.Set(storage.TxIndexKey(tx.TxID), block.Hash[:]); err != nil { + return nil, err + } + } + + // Update the chain tip + if err := batch.Set(storage.LastHash(), block.Hash[:]); err != nil { + return nil, err + } + + // Commit the batch + if err := batch.Commit(); err != nil { + return nil, fmt.Errorf("blockchain: failed to commit block: %w", err) + } + + // Update the in-memory cache + bc.lastHash = bytes.Clone(block.Hash[:]) + bc.height = nextHeight + + return block, nil +} + +// GetBlock retrieves a block by its hash from storage. +func (bc *Blockchain) GetBlock(hash []byte) (*Block, error) { + if len(hash) != crypto.HashSize { + return nil, ErrInvalidHash + } + + bc.mu.RLock() + defer bc.mu.RUnlock() + + data, err := bc.store.Get(storage.BlockKey(hash)) + if err != nil { + return nil, err + } + + return Deserialize(data) +} + +// GetBlockByHeight retrieves a block by its height using the height index. +func (bc *Blockchain) GetBlockByHeight(height uint64) (*Block, error) { + bc.mu.RLock() + hash, err := bc.store.Get(storage.HeightKey(height)) + bc.mu.RUnlock() // Release lock before calling GetBlock to prevent potential deadlocks + + if err != nil { + return nil, err + } + + return bc.GetBlock(hash) +} + +// GetTransaction locates a transaction by its ID across the entire blockchain. +func (bc *Blockchain) GetTransaction(txID []byte) (*transaction.Transaction, error) { + if len(txID) != crypto.HashSize { + return nil, ErrInvalidTxID + } + + bc.mu.RLock() + hash, err := bc.store.Get(storage.TxIndexKey(txID)) + bc.mu.RUnlock() // Release lock before calling GetBlock to prevent potential deadlocks + + if err != nil { + return nil, err + } + + block, err := bc.GetBlock(hash) + if err != nil { + return nil, err + } + + for _, tx := range block.Transactions { + if bytes.Equal(tx.TxID, txID) { + return tx, nil + } + } + + return nil, fmt.Errorf("blockchain: transaction %x indexed but missing from block %x", txID, hash) +} + +// LastHash returns a defensive copy of the current chain tip's hash. +func (bc *Blockchain) LastHash() []byte { + bc.mu.RLock() + defer bc.mu.RUnlock() + return bytes.Clone(bc.lastHash) +} + +// Height returns the current height of the blockchain. +func (bc *Blockchain) Height() uint64 { + bc.mu.RLock() + defer bc.mu.RUnlock() + return bc.height +} + +// Iterator returns a new iterator starting from the current chain tip. +// It allows for manual traversal using Next(). +func (bc *Blockchain) Iterator() *Iterator { + return &Iterator{ + currentHash: bc.LastHash(), + store: bc.store, + } +} + +// Blocks returns a range-compatible iterator sequence that walks +// the chain backwards from the tip to the Genesis block. +// +// Usage: +// +// for block, err := range bc.Blocks() { +// if err != nil { ... } +// // process block +// } +func (bc *Blockchain) Blocks() iter.Seq2[*Block, error] { + return bc.Iterator().All() +} + +// Close gracefully closes the underlying storage engine. +func (bc *Blockchain) Close() error { + return bc.store.Close() +} diff --git a/internal/blockchain/iterator.go b/internal/blockchain/iterator.go @@ -0,0 +1,79 @@ +// 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 blockchain + +import ( + "bytes" + "iter" + + "certichain/internal/storage" +) + +// Iterator represents a blockchain iterator that walks the chain backwards +// from a specific starting hash. It is not thread-safe. +type Iterator struct { + currentHash []byte + store storage.Store +} + +// Next returns the next block in the iteration (walking backwards). +// It returns (nil, nil) when the beginning of the chain is reached successfully. +func (it *Iterator) Next() (*Block, error) { + if len(it.currentHash) == 0 { + return nil, nil + } + + // Fetch the block data from storage. + data, err := it.store.Get(storage.BlockKey(it.currentHash)) + if err != nil { + return nil, err + } + + block, err := Deserialize(data) + if err != nil { + return nil, err + } + + // Update pointer to the previous block. + if block.Header.Height == 0 { + it.currentHash = nil + } else { + it.currentHash = bytes.Clone(block.Header.PrevHash[:]) + } + + return block, nil +} + +// HasNext returns true if there are more blocks to iterate. +func (it *Iterator) HasNext() bool { + return len(it.currentHash) > 0 +} + +// All returns a range-compatible iterator sequence. +// It yields blocks walking backwards from the starting point. +func (it *Iterator) All() iter.Seq2[*Block, error] { + return func(yield func(*Block, error) bool) { + for it.HasNext() { + block, err := it.Next() + if err != nil { + yield(nil, err) + return + } + if !yield(block, nil) { + return + } + } + } +}