Skip to content

Commit 5da7ec7

Browse files
committed
cmd, eth, rpc: fix some RPC issues with pending blocks
1 parent a8fd0de commit 5da7ec7

5 files changed

Lines changed: 107 additions & 114 deletions

File tree

‎cmd/gethrpctest/main.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,10 @@ var (
5252
func main() {
5353
flag.Parse()
5454

55+
// Enable logging errors, we really do want to see those
56+
glog.SetV(2)
57+
glog.SetToStderr(true)
58+
5559
// Load the test suite to run the RPC against
5660
tests, err := tests.LoadBlockTests(*testFile)
5761
if err != nil {

‎eth/api.go‎

Lines changed: 94 additions & 104 deletions
Original file line numberDiff line numberDiff line change
@@ -53,19 +53,40 @@ const (
5353
defaultGas = uint64(90000)
5454
)
5555

56-
// blockByNumber is a commonly used helper function which retrieves and returns the block for the given block number. It
57-
// returns nil when no block could be found.
56+
// blockByNumber is a commonly used helper function which retrieves and returns
57+
// the block for the given block number, capable of handling two special blocks:
58+
// rpc.LatestBlockNumber adn rpc.PendingBlockNumber. It returns nil when no block
59+
// could be found.
5860
func blockByNumber(m *miner.Miner, bc *core.BlockChain, blockNr rpc.BlockNumber) *types.Block {
61+
// Pending block is only known by the miner
5962
if blockNr == rpc.PendingBlockNumber {
6063
return m.PendingBlock()
6164
}
65+
// Otherwise resolve and return the block
6266
if blockNr == rpc.LatestBlockNumber {
6367
return bc.CurrentBlock()
6468
}
65-
6669
return bc.GetBlockByNumber(uint64(blockNr))
6770
}
6871

72+
// stateAndBlockByNumber is a commonly used helper function which retrieves and
73+
// returns the state and containing block for the given block number, capable of
74+
// handling two special states: rpc.LatestBlockNumber adn rpc.PendingBlockNumber.
75+
// It returns nil when no block or state could be found.
76+
func stateAndBlockByNumber(m *miner.Miner, bc *core.BlockChain, blockNr rpc.BlockNumber, chainDb ethdb.Database) (*state.StateDB, *types.Block, error) {
77+
// Pending state is only known by the miner
78+
if blockNr == rpc.PendingBlockNumber {
79+
return m.PendingState(), m.PendingBlock(), nil
80+
}
81+
// Otherwise resolve the block number and return its state
82+
block := blockByNumber(m, bc, blockNr)
83+
if block == nil {
84+
return nil, nil, nil
85+
}
86+
stateDb, err := state.New(block.Root(), chainDb)
87+
return stateDb, block, err
88+
}
89+
6990
// PublicEthereumAPI provides an API to access Ethereum related information.
7091
// It offers only methods that operate on public data that is freely available to anyone.
7192
type PublicEthereumAPI struct {
@@ -395,16 +416,12 @@ func (s *PublicBlockChainAPI) BlockNumber() *big.Int {
395416
return s.bc.CurrentHeader().Number
396417
}
397418

398-
// GetBalance returns the amount of wei for the given address in the state of the given block number.
399-
// When block number equals rpc.LatestBlockNumber the current block is used.
419+
// GetBalance returns the amount of wei for the given address in the state of the
420+
// given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
421+
// block numbers are also allowed.
400422
func (s *PublicBlockChainAPI) GetBalance(address common.Address, blockNr rpc.BlockNumber) (*big.Int, error) {
401-
block := blockByNumber(s.miner, s.bc, blockNr)
402-
if block == nil {
403-
return nil, nil
404-
}
405-
406-
state, err := state.New(block.Root(), s.chainDb)
407-
if err != nil {
423+
state, _, err := stateAndBlockByNumber(s.miner, s.bc, blockNr, s.chainDb)
424+
if state == nil || err != nil {
408425
return nil, err
409426
}
410427
return state.GetBalance(address), nil
@@ -414,7 +431,14 @@ func (s *PublicBlockChainAPI) GetBalance(address common.Address, blockNr rpc.Blo
414431
// transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
415432
func (s *PublicBlockChainAPI) GetBlockByNumber(blockNr rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
416433
if block := blockByNumber(s.miner, s.bc, blockNr); block != nil {
417-
return s.rpcOutputBlock(block, true, fullTx)
434+
response, err := s.rpcOutputBlock(block, true, fullTx)
435+
if err == nil && blockNr == rpc.PendingBlockNumber {
436+
// Pending blocks need to nil out a few fields
437+
for _, field := range []string{"hash", "nonce", "logsBloom", "miner"} {
438+
response[field] = nil
439+
}
440+
}
441+
return response, err
418442
}
419443
return nil, nil
420444
}
@@ -431,10 +455,6 @@ func (s *PublicBlockChainAPI) GetBlockByHash(blockHash common.Hash, fullTx bool)
431455
// GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true
432456
// all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
433457
func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(blockNr rpc.BlockNumber, index rpc.HexNumber) (map[string]interface{}, error) {
434-
if blockNr == rpc.PendingBlockNumber {
435-
return nil, nil
436-
}
437-
438458
if block := blockByNumber(s.miner, s.bc, blockNr); block != nil {
439459
uncles := block.Uncles()
440460
if index.Int() < 0 || index.Int() >= len(uncles) {
@@ -464,10 +484,6 @@ func (s *PublicBlockChainAPI) GetUncleByBlockHashAndIndex(blockHash common.Hash,
464484

465485
// GetUncleCountByBlockNumber returns number of uncles in the block for the given block number
466486
func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(blockNr rpc.BlockNumber) *rpc.HexNumber {
467-
if blockNr == rpc.PendingBlockNumber {
468-
return rpc.NewHexNumber(0)
469-
}
470-
471487
if block := blockByNumber(s.miner, s.bc, blockNr); block != nil {
472488
return rpc.NewHexNumber(len(block.Uncles()))
473489
}
@@ -508,38 +524,26 @@ func (s *PublicBlockChainAPI) NewBlocks(args NewBlocksArgs) (rpc.Subscription, e
508524

509525
// GetCode returns the code stored at the given address in the state for the given block number.
510526
func (s *PublicBlockChainAPI) GetCode(address common.Address, blockNr rpc.BlockNumber) (string, error) {
511-
return s.GetData(address, blockNr)
512-
}
513-
514-
// GetData returns the data stored at the given address in the state for the given block number.
515-
func (s *PublicBlockChainAPI) GetData(address common.Address, blockNr rpc.BlockNumber) (string, error) {
516-
if block := blockByNumber(s.miner, s.bc, blockNr); block != nil {
517-
state, err := state.New(block.Root(), s.chainDb)
518-
if err != nil {
519-
return "", err
520-
}
521-
res := state.GetCode(address)
522-
if len(res) == 0 { // backwards compatibility
523-
return "0x", nil
524-
}
525-
return common.ToHex(res), nil
527+
state, _, err := stateAndBlockByNumber(s.miner, s.bc, blockNr, s.chainDb)
528+
if state == nil || err != nil {
529+
return "", err
526530
}
527-
528-
return "0x", nil
531+
res := state.GetCode(address)
532+
if len(res) == 0 { // backwards compatibility
533+
return "0x", nil
534+
}
535+
return common.ToHex(res), nil
529536
}
530537

531-
// GetStorageAt returns the storage from the state at the given address, key and block number.
538+
// GetStorageAt returns the storage from the state at the given address, key and
539+
// block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
540+
// numbers are also allowed.
532541
func (s *PublicBlockChainAPI) GetStorageAt(address common.Address, key string, blockNr rpc.BlockNumber) (string, error) {
533-
if block := blockByNumber(s.miner, s.bc, blockNr); block != nil {
534-
state, err := state.New(block.Root(), s.chainDb)
535-
if err != nil {
536-
return "", err
537-
}
538-
539-
return state.GetState(address, common.HexToHash(key)).Hex(), nil
542+
state, _, err := stateAndBlockByNumber(s.miner, s.bc, blockNr, s.chainDb)
543+
if state == nil || err != nil {
544+
return "0x", err
540545
}
541-
542-
return "0x", nil
546+
return state.GetState(address, common.HexToHash(key)).Hex(), nil
543547
}
544548

545549
// callmsg is the message type used for call transations.
@@ -570,55 +574,51 @@ type CallArgs struct {
570574
}
571575

572576
func (s *PublicBlockChainAPI) doCall(args CallArgs, blockNr rpc.BlockNumber) (string, *big.Int, error) {
573-
if block := blockByNumber(s.miner, s.bc, blockNr); block != nil {
574-
stateDb, err := state.New(block.Root(), s.chainDb)
575-
if err != nil {
576-
return "0x", nil, err
577-
}
578-
579-
stateDb = stateDb.Copy()
580-
var from *state.StateObject
581-
if args.From == (common.Address{}) {
582-
accounts, err := s.am.Accounts()
583-
if err != nil || len(accounts) == 0 {
584-
from = stateDb.GetOrNewStateObject(common.Address{})
585-
} else {
586-
from = stateDb.GetOrNewStateObject(accounts[0].Address)
587-
}
577+
// Fetch the state associated with the block number
578+
stateDb, block, err := stateAndBlockByNumber(s.miner, s.bc, blockNr, s.chainDb)
579+
if stateDb == nil || err != nil {
580+
return "0x", nil, err
581+
}
582+
stateDb = stateDb.Copy()
583+
584+
// Retrieve the account state object to interact with
585+
var from *state.StateObject
586+
if args.From == (common.Address{}) {
587+
accounts, err := s.am.Accounts()
588+
if err != nil || len(accounts) == 0 {
589+
from = stateDb.GetOrNewStateObject(common.Address{})
588590
} else {
589-
from = stateDb.GetOrNewStateObject(args.From)
590-
}
591-
592-
from.SetBalance(common.MaxBig)
593-
594-
msg := callmsg{
595-
from: from,
596-
to: &args.To,
597-
gas: args.Gas.BigInt(),
598-
gasPrice: args.GasPrice.BigInt(),
599-
value: args.Value.BigInt(),
600-
data: common.FromHex(args.Data),
601-
}
602-
603-
if msg.gas.Cmp(common.Big0) == 0 {
604-
msg.gas = big.NewInt(50000000)
605-
}
606-
607-
if msg.gasPrice.Cmp(common.Big0) == 0 {
608-
msg.gasPrice = new(big.Int).Mul(big.NewInt(50), common.Shannon)
591+
from = stateDb.GetOrNewStateObject(accounts[0].Address)
609592
}
593+
} else {
594+
from = stateDb.GetOrNewStateObject(args.From)
595+
}
596+
from.SetBalance(common.MaxBig)
610597

611-
header := s.bc.CurrentBlock().Header()
612-
vmenv := core.NewEnv(stateDb, s.bc, msg, header)
613-
gp := new(core.GasPool).AddGas(common.MaxBig)
614-
res, gas, err := core.ApplyMessage(vmenv, msg, gp)
615-
if len(res) == 0 { // backwards compatability
616-
return "0x", gas, err
617-
}
618-
return common.ToHex(res), gas, err
598+
// Assemble the CALL invocation
599+
msg := callmsg{
600+
from: from,
601+
to: &args.To,
602+
gas: args.Gas.BigInt(),
603+
gasPrice: args.GasPrice.BigInt(),
604+
value: args.Value.BigInt(),
605+
data: common.FromHex(args.Data),
619606
}
607+
if msg.gas.Cmp(common.Big0) == 0 {
608+
msg.gas = big.NewInt(50000000)
609+
}
610+
if msg.gasPrice.Cmp(common.Big0) == 0 {
611+
msg.gasPrice = new(big.Int).Mul(big.NewInt(50), common.Shannon)
612+
}
613+
// Execute the call and return
614+
vmenv := core.NewEnv(stateDb, s.bc, msg, block.Header())
615+
gp := new(core.GasPool).AddGas(common.MaxBig)
620616

621-
return "0x", common.Big0, nil
617+
res, gas, err := core.ApplyMessage(vmenv, msg, gp)
618+
if len(res) == 0 { // backwards compatibility
619+
return "0x", gas, err
620+
}
621+
return common.ToHex(res), gas, err
622622
}
623623

624624
// Call executes the given transaction on the state for the given block number.
@@ -802,14 +802,9 @@ func getTransaction(chainDb ethdb.Database, txPool *core.TxPool, txHash common.H
802802

803803
// GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
804804
func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(blockNr rpc.BlockNumber) *rpc.HexNumber {
805-
if blockNr == rpc.PendingBlockNumber {
806-
return rpc.NewHexNumber(0)
807-
}
808-
809805
if block := blockByNumber(s.miner, s.bc, blockNr); block != nil {
810806
return rpc.NewHexNumber(len(block.Transactions()))
811807
}
812-
813808
return nil
814809
}
815810

@@ -839,13 +834,8 @@ func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(blockHash c
839834

840835
// GetTransactionCount returns the number of transactions the given address has sent for the given block number
841836
func (s *PublicTransactionPoolAPI) GetTransactionCount(address common.Address, blockNr rpc.BlockNumber) (*rpc.HexNumber, error) {
842-
block := blockByNumber(s.miner, s.bc, blockNr)
843-
if block == nil {
844-
return nil, nil
845-
}
846-
847-
state, err := state.New(block.Root(), s.chainDb)
848-
if err != nil {
837+
state, _, err := stateAndBlockByNumber(s.miner, s.bc, blockNr, s.chainDb)
838+
if state == nil || err != nil {
849839
return nil, err
850840
}
851841
return rpc.NewHexNumber(state.GetNonce(address)), nil

‎eth/filters/api.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -239,13 +239,13 @@ func (args *NewFilterArgs) UnmarshalJSON(data []byte) error {
239239
return err
240240
}
241241

242-
if raw.From == nil {
242+
if raw.From == nil || raw.From.Int64() < 0 {
243243
args.FromBlock = rpc.LatestBlockNumber
244244
} else {
245245
args.FromBlock = *raw.From
246246
}
247247

248-
if raw.ToBlock == nil {
248+
if raw.ToBlock == nil || raw.ToBlock.Int64() < 0 {
249249
args.ToBlock = rpc.LatestBlockNumber
250250
} else {
251251
args.ToBlock = *raw.ToBlock

‎rpc/server.go‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -332,7 +332,6 @@ func (s *Server) handle(ctx context.Context, codec ServerCodec, req *serverReque
332332
return res
333333
}
334334
}
335-
336335
return codec.CreateResponse(req.id, reply[0].Interface())
337336
}
338337

@@ -344,7 +343,6 @@ func (s *Server) exec(ctx context.Context, codec ServerCodec, req *serverRequest
344343
} else {
345344
response = s.handle(ctx, codec, req)
346345
}
347-
348346
if err := codec.Write(response); err != nil {
349347
glog.V(logger.Error).Infof("%v\n", err)
350348
codec.Close()

‎rpc/types.go‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -174,12 +174,14 @@ type HexNumber big.Int
174174
// NewHexNumber creates a new hex number instance which will serialize the given val with `%#x` on marshal.
175175
func NewHexNumber(val interface{}) *HexNumber {
176176
if val == nil {
177-
return nil
177+
return nil // note, this doesn't catch nil pointers, only passing nil directly!
178178
}
179179

180-
if v, ok := val.(*big.Int); ok && v != nil {
181-
hn := new(big.Int).Set(v)
182-
return (*HexNumber)(hn)
180+
if v, ok := val.(*big.Int); ok {
181+
if v != nil {
182+
return (*HexNumber)(new(big.Int).Set(v))
183+
}
184+
return nil
183185
}
184186

185187
rval := reflect.ValueOf(val)
@@ -303,10 +305,9 @@ const (
303305
)
304306

305307
// UnmarshalJSON parses the given JSON fragement into a BlockNumber. It supports:
306-
// - "latest" or "earliest" as string arguments
308+
// - "latest", "earliest" or "pending" as string arguments
307309
// - the block number
308310
// Returned errors:
309-
// - an unsupported error when "pending" is specified (not yet implemented)
310311
// - an invalid block number error when the given argument isn't a known strings
311312
// - an out of range error when the given block number is either too little or too large
312313
func (bn *BlockNumber) UnmarshalJSON(data []byte) error {

0 commit comments

Comments
 (0)