diff --git a/backend/src/repositories/BlocksRepository.ts b/backend/src/repositories/BlocksRepository.ts index 3a34e3a20..bb0e4f6c5 100644 --- a/backend/src/repositories/BlocksRepository.ts +++ b/backend/src/repositories/BlocksRepository.ts @@ -575,6 +575,31 @@ class BlocksRepository { } } + /** + * Get the canonical block hash at a given height + * @asyncSafe + */ + public async $getCanonicalBlockHashByHeight(height: number): Promise { + try { + const [rows]: any[] = await DB.query(` + SELECT hash + FROM blocks + WHERE height = ? AND stale = 0 + LIMIT 1`, + [height] + ); + + if (rows.length <= 0) { + return null; + } + + return rows[0].hash; + } catch (e) { + logger.err(`Cannot get canonical block hash at height ${height}. Reason: ` + (e instanceof Error ? e.message : e)); + throw e; + } + } + /** * Get one block by hash * @asyncSafe @@ -1258,6 +1283,9 @@ class BlocksRepository { blk.mediantime = dbBlk.mediantime; blk.indexVersion = dbBlk.index_version; blk.stale = dbBlk.stale; + if (dbBlk.stale) { + blk.canonical = await this.$getCanonicalBlockHashByHeight(dbBlk.height) || undefined; + } // BlockExtension extras.totalFees = dbBlk.totalFees; extras.medianFee = dbBlk.medianFee;