computing block hash
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?
related issue: https://github.com/subquery/subql-algorand/issues/14#issuecomment-1280065017
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:
- look at the next block, which has a previous hash field.
- algod API: there is a new
/v2/blocks/{round}/hashendpoint - algod API: fetch the raw block (using
format=msgpack) and compute the hash. For reference, you can see how it is done here.