blockchain.go (10280B)
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 "bytes" 19 "crypto/ed25519" 20 "errors" 21 "fmt" 22 "iter" 23 "sync" 24 "time" 25 26 "certichain/internal/crypto" 27 "certichain/internal/storage" 28 "certichain/internal/transaction" 29 ) 30 31 // Custom Errors 32 var ( 33 ErrNilTransactions = errors.New("blockchain: transaction slice cannot be nil") // for Tx Slice 34 ErrNilTransactionEntry = errors.New("blockchain: cannot add nil transaction") // for single Tx 35 ErrEmptyBlock = errors.New("blockchain: cannot add block with zero transaction") 36 ErrInvalidHash = errors.New("blockchain: invalid hash length") 37 ErrUnsignedTx = errors.New("blockchain: cannot add block with unsigned transaction") 38 ErrInvalidTxID = errors.New("blockchain: transaction has invalid TxID") 39 ErrInvalidSignature = errors.New("blockchain: invalid transaction signature") 40 ) 41 42 type KeyResolver interface { 43 // Get retrives the ed25519 public key for the DID. 44 Get(did string) (ed25519.PublicKey, error) 45 } 46 47 // Blockchain manages the chain of blocks and provides a high-level API for 48 // storage and retrieval. 49 type Blockchain struct { 50 mu sync.RWMutex 51 store storage.Store 52 lastHash []byte 53 height uint64 54 resolver KeyResolver 55 } 56 57 // Option defines a function signature for configuring the Blockchain. 58 type Option func(*config) 59 60 type config struct { 61 genesisTime int64 62 keyResolver KeyResolver 63 } 64 65 // WithGenesisTime sets a custom timestamp for the Genesis block. 66 // This is useful for maintaining a consistent Genesis hash across different networks. 67 func WithGenesisTime(t int64) Option { 68 return func(c *config) { 69 c.genesisTime = t 70 } 71 } 72 73 // WithKeyResolver configures a resolver used to verify transaction signature during AddBlock. 74 func WithKeyResolver(r KeyResolver) Option { 75 return func(c *config) { 76 c.keyResolver = r 77 } 78 } 79 80 // New initializes a new Blockchain instance. 81 // If the store is empty, it creates and persists the Genesis block. 82 func New(store storage.Store, opts ...Option) (*Blockchain, error) { 83 cfg := &config{ 84 // Default Genesis time: 2014-02-26 00:00:00 UTC 85 genesisTime: time.Date(2014, 2, 26, 0, 0, 0, 0, time.UTC).Unix(), 86 } 87 for _, opt := range opts { 88 opt(cfg) 89 } 90 91 lastHash, err := store.Get(storage.LastHash()) 92 93 // Database is empty, create and persist Genesis 94 if errors.Is(err, storage.ErrNotFound) { 95 genesis, err := createGenesisBlock(cfg.genesisTime) 96 if err != nil { 97 return nil, fmt.Errorf("blockchain: failed to create genesis block: %w", err) 98 } 99 100 data, err := genesis.Serialize() 101 if err != nil { 102 return nil, err 103 } 104 105 batch, err := store.NewBatch() 106 if err != nil { 107 return nil, err 108 } 109 defer batch.Discard() 110 111 // Persist Genesis block and its indexes 112 if err := batch.Set(storage.BlockKey(genesis.Hash[:]), data); err != nil { 113 return nil, fmt.Errorf("blockchain: failed to persist genesis block: %w", err) 114 } 115 if err := batch.Set(storage.HeightKey(0), genesis.Hash[:]); err != nil { 116 return nil, fmt.Errorf("blockchain: failed to persist genesis block: %w", err) 117 } 118 if err := batch.Set(storage.LastHash(), genesis.Hash[:]); err != nil { 119 return nil, fmt.Errorf("blockchain: failed to persist genesis block: %w", err) 120 } 121 122 // Commit the batch 123 if err := batch.Commit(); err != nil { 124 return nil, fmt.Errorf("blockchain: failed to commit genesis: %w", err) 125 } 126 127 return &Blockchain{ 128 store: store, 129 lastHash: bytes.Clone(genesis.Hash[:]), 130 height: 0, 131 resolver: cfg.keyResolver, 132 }, nil 133 } 134 135 if err != nil { 136 return nil, fmt.Errorf("blockchain: failed to load tip: %w", err) 137 } 138 139 // Fetch the last block 140 data, err := store.Get(storage.BlockKey(lastHash)) 141 if err != nil { 142 return nil, fmt.Errorf("blockchain: failed to load last block: %w", err) 143 } 144 lastBlock, err := Deserialize(data) 145 if err != nil { 146 return nil, err 147 } 148 149 return &Blockchain{ 150 store: store, 151 lastHash: bytes.Clone(lastHash), 152 height: lastBlock.Header.Height, 153 resolver: cfg.keyResolver, 154 }, nil 155 } 156 157 // createGenesisBlock creates a deterministic first block for the chain. 158 func createGenesisBlock(timestamp int64) (*Block, error) { 159 block := &Block{ 160 Header: &BlockHeader{ 161 Height: 0, 162 PrevHash: crypto.Hash{}, 163 TimeStamp: timestamp, 164 }, 165 Transactions: []*transaction.Transaction{}, 166 } 167 168 // Compute the Merkle root of the transactions 169 root, err := block.hashTransactions() 170 if err != nil { 171 return nil, err 172 } 173 block.Header.MerkleRoot = crypto.Hash(root) 174 175 // Compute the block hash 176 hash, err := block.Header.computeHash() 177 if err != nil { 178 return nil, err 179 } 180 block.Hash = hash 181 182 return block, nil 183 } 184 185 // AddBlock validates transactions and appends a new block to the chain. 186 // Returns ErrEmptyBlock for empty transaction, to reduce bloat in the blockchain. 187 func (bc *Blockchain) AddBlock(txs []*transaction.Transaction) (*Block, error) { 188 if txs == nil { 189 return nil, ErrNilTransactions 190 } 191 if len(txs) == 0 { 192 return nil, ErrEmptyBlock 193 } 194 195 for _, tx := range txs { 196 if tx == nil { 197 return nil, ErrNilTransactionEntry 198 } 199 if !tx.IsSigned() { 200 return nil, ErrUnsignedTx 201 } 202 if len(tx.TxID) != crypto.HashSize { 203 return nil, ErrInvalidTxID 204 } 205 206 if bc.resolver != nil { 207 pubKey, err := bc.resolver.Get(tx.IssuerDID) 208 if err != nil { 209 return nil, fmt.Errorf("blockchain: failed to resolve issuer key for did %s: %w", 210 tx.IssuerDID, err) 211 } 212 valid, err := tx.Verify(pubKey) 213 if err != nil { 214 return nil, fmt.Errorf("blockchain: failed to verify singnature: %w", err) 215 } 216 if !valid { 217 return nil, ErrInvalidSignature 218 } 219 } 220 } 221 222 bc.mu.Lock() 223 defer bc.mu.Unlock() 224 225 nextHeight := bc.height + 1 226 now := time.Now().Unix() 227 block, err := newBlock(bc.lastHash, nextHeight, txs, now) 228 if err != nil { 229 return nil, fmt.Errorf("blockchain: failed to create block: %w", err) 230 } 231 232 data, err := block.Serialize() 233 if err != nil { 234 return nil, err 235 } 236 237 // Persist the changes atomically 238 batch, err := bc.store.NewBatch() 239 if err != nil { 240 return nil, err 241 } 242 defer batch.Discard() 243 244 // Persist the block data 245 if err := batch.Set(storage.BlockKey(block.Hash[:]), data); err != nil { 246 return nil, err 247 } 248 // Index by height for O(1) retrieval 249 if err := batch.Set(storage.HeightKey(nextHeight), block.Hash[:]); err != nil { 250 return nil, err 251 } 252 253 // Index individual transactions 254 for _, tx := range txs { 255 if err := batch.Set(storage.TxIndexKey(tx.TxID), block.Hash[:]); err != nil { 256 return nil, err 257 } 258 } 259 260 // Update the chain tip 261 if err := batch.Set(storage.LastHash(), block.Hash[:]); err != nil { 262 return nil, err 263 } 264 265 // Commit the batch 266 if err := batch.Commit(); err != nil { 267 return nil, fmt.Errorf("blockchain: failed to commit block: %w", err) 268 } 269 270 // Update the in-memory cache 271 bc.lastHash = bytes.Clone(block.Hash[:]) 272 bc.height = nextHeight 273 274 return block, nil 275 } 276 277 // GetBlock retrieves a block by its hash from storage. 278 func (bc *Blockchain) GetBlock(hash []byte) (*Block, error) { 279 if len(hash) != crypto.HashSize { 280 return nil, ErrInvalidHash 281 } 282 283 bc.mu.RLock() 284 defer bc.mu.RUnlock() 285 286 data, err := bc.store.Get(storage.BlockKey(hash)) 287 if err != nil { 288 return nil, err 289 } 290 291 return Deserialize(data) 292 } 293 294 // GetBlockByHeight retrieves a block by its height using the height index. 295 func (bc *Blockchain) GetBlockByHeight(height uint64) (*Block, error) { 296 bc.mu.RLock() 297 hash, err := bc.store.Get(storage.HeightKey(height)) 298 bc.mu.RUnlock() // Release lock before calling GetBlock to prevent potential deadlocks 299 300 if err != nil { 301 return nil, err 302 } 303 304 return bc.GetBlock(hash) 305 } 306 307 // GetBlockByTxID returns the block with the given transaction ID. 308 func (bc *Blockchain) GetBlockByTxID(txID []byte) (*Block, error) { 309 if len(txID) != crypto.HashSize { 310 return nil, ErrInvalidTxID 311 } 312 313 bc.mu.RLock() 314 hash, err := bc.store.Get(storage.TxIndexKey(txID)) 315 bc.mu.RUnlock() // Release lock before calling GetBlock to prevent potential deadlocks 316 317 if err != nil { 318 return nil, err 319 } 320 321 return bc.GetBlock(hash) 322 } 323 324 // GetTransaction locates a transaction by its ID across the entire blockchain. 325 func (bc *Blockchain) GetTransaction(txID []byte) (*transaction.Transaction, error) { 326 if len(txID) != crypto.HashSize { 327 return nil, ErrInvalidTxID 328 } 329 330 bc.mu.RLock() 331 hash, err := bc.store.Get(storage.TxIndexKey(txID)) 332 bc.mu.RUnlock() // Release lock before calling GetBlock to prevent potential deadlocks 333 334 if err != nil { 335 return nil, err 336 } 337 338 block, err := bc.GetBlock(hash) 339 if err != nil { 340 return nil, err 341 } 342 343 for _, tx := range block.Transactions { 344 if bytes.Equal(tx.TxID, txID) { 345 return tx, nil 346 } 347 } 348 349 return nil, fmt.Errorf("blockchain: transaction %x indexed but missing from block %x", txID, hash) 350 } 351 352 // LastHash returns a defensive copy of the current chain tip's hash. 353 func (bc *Blockchain) LastHash() []byte { 354 bc.mu.RLock() 355 defer bc.mu.RUnlock() 356 return bytes.Clone(bc.lastHash) 357 } 358 359 // Height returns the current height of the blockchain. 360 func (bc *Blockchain) Height() uint64 { 361 bc.mu.RLock() 362 defer bc.mu.RUnlock() 363 return bc.height 364 } 365 366 // Iterator returns a new iterator starting from the current chain tip. 367 // It allows for manual traversal using Next(). 368 func (bc *Blockchain) Iterator() *Iterator { 369 return &Iterator{ 370 currentHash: bc.LastHash(), 371 store: bc.store, 372 } 373 } 374 375 // Blocks returns a range-compatible iterator sequence that walks 376 // the chain backwards from the tip to the Genesis block. 377 // 378 // Usage: 379 // 380 // for block, err := range bc.Blocks() { 381 // if err != nil { ... } 382 // // process block 383 // } 384 func (bc *Blockchain) Blocks() iter.Seq2[*Block, error] { 385 return bc.Iterator().All() 386 } 387 388 // Close gracefully closes the underlying storage engine. 389 func (bc *Blockchain) Close() error { 390 return bc.store.Close() 391 }