2020-10-18 19:44:28 +00:00
package commands
import (
"context"
"fmt"
2021-05-20 18:25:53 +00:00
"github.com/ledgerwatch/erigon/common"
"github.com/ledgerwatch/erigon/core/rawdb"
"github.com/ledgerwatch/erigon/core/types"
"github.com/ledgerwatch/erigon/ethdb"
"github.com/ledgerwatch/erigon/rpc"
2020-10-18 19:44:28 +00:00
)
2020-10-24 17:03:52 +00:00
// GetHeaderByNumber implements tg_getHeaderByNumber. Returns a block's header given a block number ignoring the block's transaction and uncle list (may be faster).
2020-10-20 21:16:28 +00:00
func ( api * TgImpl ) GetHeaderByNumber ( ctx context . Context , blockNumber rpc . BlockNumber ) ( * types . Header , error ) {
2021-03-30 07:09:00 +00:00
// Pending block is only known by the miner
if blockNumber == rpc . PendingBlockNumber {
2021-05-17 12:15:19 +00:00
block := api . pendingBlock ( )
if block == nil {
return nil , nil
}
2021-03-30 07:09:00 +00:00
return block . Header ( ) , nil
}
2021-04-03 06:26:00 +00:00
tx , err := api . db . BeginRo ( ctx )
2020-10-18 19:44:28 +00:00
if err != nil {
return nil , err
}
defer tx . Rollback ( )
2021-03-30 09:53:54 +00:00
header := rawdb . ReadHeaderByNumber ( ethdb . NewRoTxDb ( tx ) , uint64 ( blockNumber . Int64 ( ) ) )
2020-10-18 19:44:28 +00:00
if header == nil {
2020-10-20 21:16:28 +00:00
return nil , fmt . Errorf ( "block header not found: %d" , blockNumber . Int64 ( ) )
2020-10-18 19:44:28 +00:00
}
return header , nil
}
2020-10-24 17:03:52 +00:00
// GetHeaderByHash implements tg_getHeaderByHash. Returns a block's header given a block's hash.
2020-10-18 19:44:28 +00:00
func ( api * TgImpl ) GetHeaderByHash ( ctx context . Context , hash common . Hash ) ( * types . Header , error ) {
2021-04-03 06:26:00 +00:00
tx , err := api . db . BeginRo ( ctx )
2020-10-18 19:44:28 +00:00
if err != nil {
return nil , err
}
defer tx . Rollback ( )
2021-03-30 09:53:54 +00:00
header , err := rawdb . ReadHeaderByHash ( ethdb . NewRoTxDb ( tx ) , hash )
2020-10-24 06:57:09 +00:00
if err != nil {
return nil , err
}
2020-10-18 19:44:28 +00:00
if header == nil {
return nil , fmt . Errorf ( "block header not found: %s" , hash . String ( ) )
}
return header , nil
}