@@ -139,6 +139,18 @@ bool to_integer(Integer& out, double value) NOEXCEPT
139139 return true ;
140140}
141141
142+ // TODO: centralize in server (also used in bitcoind and native interfaces).
143+ template <typename Object, typename ...Args>
144+ std::string to_hex (const Object& object, size_t size, Args&&... args) NOEXCEPT
145+ {
146+ std::string out (two * size, ' \0 ' );
147+ stream::out::fast sink{ out };
148+ write::base16::fast writer{ sink };
149+ object.to_data (writer, std::forward<Args>(args)...);
150+ BC_ASSERT (writer);
151+ return out;
152+ }
153+
142154// Handlers (blockchain).
143155// ----------------------------------------------------------------------------
144156
@@ -179,21 +191,22 @@ void protocol_electrum::handle_blockchain_headers_subscribe(const code& ec,
179191 return ;
180192
181193 const auto & query = archive ();
182- const auto link = query.to_header (query.get_top_confirmed_hash ());
183- const auto height = query.get_height (link);
184- const auto header = query.get_header (link);
185- if (height.is_terminal () || !header)
194+ const auto top = query.get_top_confirmed ();
195+ const auto link = query.to_confirmed (top);
196+
197+ // This is unlikely but possible due to a race condition during reorg.
198+ if (!link.is_terminal ())
186199 {
187200 send_code (error::not_found);
188201 return ;
189202 }
190203
191- // See protocol_native::to_hex().
192- std::string hex (two * chain:: header::serialized_size (), ' \0 ' );
193- stream::out::fast sink{ hex };
194- write::base16::fast writer{ sink } ;
195- header-> to_data (writer) ;
196- BC_ASSERT (writer);
204+ const auto header = query. get_header (link);
205+ if (! header)
206+ {
207+ send_code (error::server_error) ;
208+ return ;
209+ }
197210
198211 // TODO: signal header subscription.
199212
@@ -204,8 +217,8 @@ void protocol_electrum::handle_blockchain_headers_subscribe(const code& ec,
204217 {
205218 object_t
206219 {
207- { " height" , height. value },
208- { " hex" , hex }
220+ { " height" , top },
221+ { " hex" , to_hex (*header, chain::header::serialized_size ()) }
209222 }
210223 }, 256 , BIND (complete, _1));
211224}
0 commit comments