4

As following answer for How can I find out what the highest block is? guided: we can get the latest mined block's number and its hash inside geth as follows.

> eth.syncing.currentBlock
569367
> eth.getBlock(eth.syncing.currentBlock).hash
"0xac51e27c3fe38af1a0aeb2867a741ba6aa16780e435a586d934ccea3a71874b1"

[Q] Inside a smart contract, is it possible to get the latest mined block's number and its hash? or should I keep an array inside my contract and when new block is mined, externally (my_contract.addNewHash(<some_hash>)) should I put its hash into my array for my contract to read from?

I have tried following keywords from Solidity's website: https://github.com/iurimatias/embark-framework/wiki/Solidity on Solidity Browser and Populus, for example: block.number, block.blockhash, but I do face with following error:

Untitled:6:17: Error: Expected identifier, got 'Semicolon'
    block.number;

Thank you for your valuable time and help.

7

Transactions are always executed in the block being mined. So, at any time, block.number will return the block height in which the transaction is being mined.

However, the hash of the block is not known until it is mined, and the output of transactions is part of the hash calculation, so the transaction has no access to the hash of the block being mined.

If this is any consolation, you can get the hash of the latest mined block, i.e. the one right before this block being mined with block.blockhash(block.number - 1).

Try this:

contract Test {
    uint public blockNumber;
    bytes32 public blockHashNow;
    bytes32 public blockHashPrevious;

    function setValues() {
        blockNumber = block.number;
        blockHashNow = block.blockhash(blockNumber);
        blockHashPrevious = block.blockhash(blockNumber - 1);
    }    
}

Make a transaction to setValues() then you will see that:

  • blockNumber is set at that number it was mined in
  • blockHashNow is set at 0x
  • blockHashPrevious is set at the previous block hash indeed
  • I don't know why but when I tried in Solidity Browser, function does not see the public variables. Error: Undeclared identifier. blockHashPrevious. But I understand the idea. – alper Jan 17 '17 at 11:55
  • Sorry, typo fixed. – Xavier Leprêtre B9lab Jan 17 '17 at 11:59
  • why is the current block hash zero? – Jonathan Lindgren Oct 16 '17 at 5:31
  • Not sure where you got that info. – Xavier Leprêtre B9lab Oct 16 '17 at 20:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.