ethclient, internal/ethapi: add support for EIP-695 (eth_chainId) (#19694)

EIP-695 was written in 2017. Parity and Infura have support for this
method and we should, too.
pull/19697/head
Felix Lange 6 years ago committed by Péter Szilágyi
parent c420dcb39c
commit 2b54666018
  1. 10
      ethclient/ethclient.go
  2. 16
      ethclient/ethclient_test.go
  3. 5
      internal/ethapi/api.go

@ -61,6 +61,16 @@ func (ec *Client) Close() {
// Blockchain Access // Blockchain Access
// ChainId retrieves the current chain ID for transaction replay protection.
func (ec *Client) ChainID(ctx context.Context) (*big.Int, error) {
var result hexutil.Big
err := ec.c.CallContext(ctx, &result, "eth_chainId")
if err != nil {
return nil, err
}
return (*big.Int)(&result), err
}
// BlockByHash returns the given full block. // BlockByHash returns the given full block.
// //
// Note that loading full blocks requires two requests. Use HeaderByHash // Note that loading full blocks requires two requests. Use HeaderByHash

@ -319,3 +319,19 @@ func TestTransactionInBlockInterrupted(t *testing.T) {
t.Fatal("error should not be nil") t.Fatal("error should not be nil")
} }
} }
func TestChainID(t *testing.T) {
backend, _ := newTestBackend(t)
client, _ := backend.Attach()
defer backend.Stop()
defer client.Close()
ec := NewClient(client)
id, err := ec.ChainID(context.Background())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if id == nil || id.Cmp(params.AllEthashProtocolChanges.ChainID) != 0 {
t.Fatalf("ChainID returned wrong number: %+v", id)
}
}

@ -529,6 +529,11 @@ func NewPublicBlockChainAPI(b Backend) *PublicBlockChainAPI {
return &PublicBlockChainAPI{b} return &PublicBlockChainAPI{b}
} }
// ChainId returns the chainID value for transaction replay protection.
func (s *PublicBlockChainAPI) ChainId() *hexutil.Big {
return (*hexutil.Big)(s.b.ChainConfig().ChainID)
}
// BlockNumber returns the block number of the chain head. // BlockNumber returns the block number of the chain head.
func (s *PublicBlockChainAPI) BlockNumber() hexutil.Uint64 { func (s *PublicBlockChainAPI) BlockNumber() hexutil.Uint64 {
header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available

Loading…
Cancel
Save