indexer icon indicating copy to clipboard operation
indexer copied to clipboard

computing block hash

Open guplersaxanoid opened this issue 3 years ago • 2 comments

I'm trying to compute block hash from the block data obtained from the Indexer.

I use this function to serialize the block data after omitting all the empty values and transactions: https://github.com/algorand/js-algorand-sdk/blob/1fed2b7dda980362a7f57c27405ec26270661da0/src/encoding/encoding.ts#L42

Then I compute the block hash with this function:

export function blockHash(header: Record<string,any>) {
  const encodedObj = msgPackEncode(header);
  const prefix = Uint8Array.from('BH'.split('').map((x) => x.charCodeAt(0)));
  const toHash = new Uint8Array([...prefix, ...encodedObj]);
  return sha512_256(toHash);
}

The hash obtained is not the same as the one in previous_block_hash of next block

are there any missing values in the block data returned by the indexer that are required to compute the hash?

guplersaxanoid avatar Oct 17 '22 09:10 guplersaxanoid

related issue: https://github.com/subquery/subql-algorand/issues/14#issuecomment-1280065017

guplersaxanoid avatar Oct 17 '22 09:10 guplersaxanoid

The block data returned by indexer is not in the canonical block format, so you cannot use it to compute the block hash.

To get a block hash you have several options:

  1. look at the next block, which has a previous hash field.
  2. algod API: there is a new /v2/blocks/{round}/hash endpoint
  3. algod API: fetch the raw block (using format=msgpack) and compute the hash. For reference, you can see how it is done here.

winder avatar Oct 18 '22 13:10 winder