@@ -2,7 +2,6 @@ package chain
22
33import (
44 "context"
5- "encoding/json"
65 "fmt"
76
87 "github.com/dgraph-io/badger/v4"
@@ -98,15 +97,37 @@ func (c *Chain) AddBlock(data string) {
9897 c .currentHash = newBlock .GetHash ()
9998}
10099
101- // PrettyPrint this formats the chain into a readable json format for easy debugging
102- func (c * Chain ) PrettyPrint () {
103- json , err := json .MarshalIndent (c , "Blockchain " , "" )
104- if err != nil {
105- fmt .Printf ("error marshalling block: %s" , err )
100+ // GetAllBlocks retrieves all blocks from the chain store
101+ //
102+ // Process:
103+ // - It first creates an iterator object for the loop process
104+ // - while there is a block on the chain it gets it and appends it to a slice of blocks
105+ // - Reverse the blocks to get them in chronological order (oldest first)
106+ //
107+ // Returns:
108+ // - `blocks []*block.Block`: a slice of blocks for this chain
109+ // - `err error`: an error object
110+ func (c * Chain ) GetAllBlocks () (blocks []* block.Block , err error ) {
111+ iter := c .iter ()
112+
113+ for iter .HasNext (c .chainCtx ) {
114+ block := iter .Next (c .chainCtx )
115+ if block == nil {
116+ err = fmt .Errorf ("failed to get block %s" , c .currentHash )
117+ return blocks , err
118+ }
119+ blocks = append (blocks , block )
106120 }
107- fmt .Println (string (json ))
121+
122+ // Reverse the blocks to get them in chronological order (oldest first)
123+ for i , j := 0 , len (blocks )- 1 ; i < j ; i , j = i + 1 , j - 1 {
124+ blocks [i ], blocks [j ] = blocks [j ], blocks [i ]
125+ }
126+
127+ return blocks , err
108128}
109129
130+
110131// iter add a block to the chain
111132//
112133// Process:
@@ -121,7 +142,4 @@ func (c *Chain) iter() ChainIterator {
121142 }
122143}
123144
124- // Utility functions
125- func (c * Chain ) FindLast () (block.Block , error ) {
126- return c .store .FindLast (c .chainCtx )
127- }
145+
0 commit comments