iterator.go (2041B)
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 "iter" 20 21 "certichain/internal/storage" 22 ) 23 24 // Iterator represents a blockchain iterator that walks the chain backwards 25 // from a specific starting hash. It is not thread-safe. 26 type Iterator struct { 27 currentHash []byte 28 store storage.Store 29 } 30 31 // Next returns the next block in the iteration (walking backwards). 32 // It returns (nil, nil) when the beginning of the chain is reached successfully. 33 func (it *Iterator) Next() (*Block, error) { 34 if len(it.currentHash) == 0 { 35 return nil, nil 36 } 37 38 // Fetch the block data from storage. 39 data, err := it.store.Get(storage.BlockKey(it.currentHash)) 40 if err != nil { 41 return nil, err 42 } 43 44 block, err := Deserialize(data) 45 if err != nil { 46 return nil, err 47 } 48 49 // Update pointer to the previous block. 50 if block.Header.Height == 0 { 51 it.currentHash = nil 52 } else { 53 it.currentHash = bytes.Clone(block.Header.PrevHash[:]) 54 } 55 56 return block, nil 57 } 58 59 // HasNext returns true if there are more blocks to iterate. 60 func (it *Iterator) HasNext() bool { 61 return len(it.currentHash) > 0 62 } 63 64 // All returns a range-compatible iterator sequence. 65 // It yields blocks walking backwards from the starting point. 66 func (it *Iterator) All() iter.Seq2[*Block, error] { 67 return func(yield func(*Block, error) bool) { 68 for it.HasNext() { 69 block, err := it.Next() 70 if err != nil { 71 yield(nil, err) 72 return 73 } 74 if !yield(block, nil) { 75 return 76 } 77 } 78 } 79 }