@@ -70,6 +70,38 @@ public function getChainState(): ChainStateReader
7070 return new ChainStateReader ($ this ->chainStateDir );
7171 }
7272
73+ /**
74+ * @param BlockInfo $blockInfo
75+ * @return Block
76+ * @throws Exception
77+ */
78+ public function getBlockByInfo (BlockInfo $ blockInfo ): Block
79+ {
80+ $ blockFile = $ this ->blocksDir . DIRECTORY_SEPARATOR . $ blockInfo ->getFileName ();
81+
82+ return (new BlockFileReader ())->readBlock ($ blockFile , $ blockInfo ->dataPos );
83+ }
84+
85+ /**
86+ * @param string $hash
87+ * @return Block
88+ * @throws Exception
89+ */
90+ public function getBlockByHash (string $ hash ): Block
91+ {
92+ return $ this ->getBlockByInfo ($ this ->getIndex ()->getBlockInfoByHash ($ hash ));
93+ }
94+
95+ /**
96+ * @param int $height
97+ * @return Block
98+ * @throws Exception
99+ */
100+ public function getBlockByHeight (int $ height ): Block
101+ {
102+ return $ this ->getBlockByInfo ($ this ->getIndex ()->getBlockInfoByHeight ($ height ));
103+ }
104+
73105 /**
74106 * @param int|null $minHeight
75107 * @param int|null $maxHeight
@@ -79,11 +111,9 @@ public function getChainState(): ChainStateReader
79111 public function readBlocks (int $ minHeight = null , int $ maxHeight = null ): \Generator
80112 {
81113 $ index = $ this ->getIndex ();
114+
82115 $ minHeight = $ minHeight ?? $ index ->getMinHeight ();
83116 $ maxHeight = $ maxHeight ?? $ index ->getMaxHeight ();
84- $ reader = new BlockFileReader ();
85-
86- $ handles = [];
87117
88118 for ($ i = $ minHeight ; $ i <= $ maxHeight ; $ i ++) {
89119 $ blockInfo = $ index ->getBlockInfoByHeight ($ i );
@@ -92,27 +122,7 @@ public function readBlocks(int $minHeight = null, int $maxHeight = null): \Gener
92122 continue ;
93123 }
94124
95- $ file = $ blockInfo ->getFileName ();
96-
97- if (isset ($ handles [$ file ])) {
98- $ fp = $ handles [$ file ];
99- } else {
100- $ path = $ this ->blocksDir . DIRECTORY_SEPARATOR . $ file ;
101-
102- if (!is_readable ($ path )) {
103- throw new Exception ("Block file ' $ file' not found. " );
104- }
105-
106- $ fp = $ handles [$ file ] = fopen ($ path , 'r ' );
107- }
108-
109- fseek ($ fp , $ blockInfo ->dataPos - 4 );
110-
111- yield $ i => $ reader ->readBlock ($ fp );
112- }
113-
114- foreach ($ handles as $ file => $ fp ) {
115- fclose ($ fp );
125+ yield $ i => $ this ->getBlockByInfo ($ blockInfo );
116126 }
117127 }
118128
0 commit comments