mirror of
https://github.com/ethereum/go-ethereum.git
synced 2026-04-28 04:22:26 +00:00
In this commit, the RPC API is adapted to run on top of the new Go API.
This required lots of changes to many packages, but has a few side
benefits:
- Ethereum and LightEthereum can now be used as a contract backend.
- Some duplicated code could be removed (there is added duplication in
other places though)
- It is now much easier to see which operations are unsupported with the
light client. Package les previously relied on the full node RPC API
backend, which masked several issues because the RPC API performed
direct access to the chain database.
Changes to packages in detail:
accounts/abi/bind:
- Contract call boilerplate has moved to package core.
cmd/utils:
- les now inherits the event.TypeMux from the Node instance
contracts/release:
- The ReleaseService now uses Ethereum and LightEthereum as backend.
core:
- MissingNumber is exposed so it can be used in package eth.
- GetTransaction now returns the index as an int, for convenience
reasons.
- ApplyCallMessage has been added as the new one and only
implementation of read-only contract calls.
- TxPool exposes NonceAt instead of the more general accessor for the
ManagedState.
core/types:
- Signer.SignECDSA is gone (it was basically unused).
- WithSignature doesn't return an error anymore (all implementations panic for
invalid length). I made this change to avoid code duplication in the API.
eth:
- EthApiBackend is gone. In its place, Ethereum gains many new methods
which implement a large portion of the new Go API. It does not
yet support event subscriptions and log filtering.
- Some accessors for internal objects are gone.
- ethapi.PrivateDebugAPI and ethapi.TxPoolDebugAPI are now created in
package eth for dependency reasons.
eth/downloader:
- Progress returns a pointer to simplify callers.
eth/filters:
- The Backend interface is simpler and uses the stable Go API where
possible. The new BlockReceipts method saves one DB read because
BlockReceipts also takes a block number argument.
- ChainDB is no longer passed via the Backend interface.
- EventSystem now relies on HeaderByHash for reorgs in light client mode
instead of reading from the chain database.
eth/gasprice:
- The LightPriceOracle now uses ethereum.ChainReader instead of
ethapi.Backend.
ethclient:
- TransactionByHash is adapted for the last-minute API change which
adds the isPending return value.
internal/ethapi:
- PublicTxPoolAPI is now called TxPoolDebugAPI, moved to its own file
and talks to the transaction pool instead of using the main Backend.
- The API no longer accesses the chain database directly. All access
is mediated through Backend methods.
- The backend is now split into three interfaces.
Implementing Backend is mandatory but does not require the pending
state. The other two (PendingState, TransactionInclusionBlock) are
optional and discovered at runtime.
les:
- LesApiBackend is gone, LightEthereum gets all the methods.
- Weird accessors copied from package eth are now gone as well.
light:
- TxPool.Stats now returns a queued count of zero. It implements the
ethapi.TxPool interface and can be used with TxPoolDebugAPI.
242 lines
9 KiB
Go
242 lines
9 KiB
Go
// Copyright 2015 The go-ethereum Authors
|
|
// This file is part of the go-ethereum library.
|
|
//
|
|
// The go-ethereum library is free software: you can redistribute it and/or modify
|
|
// it under the terms of the GNU Lesser General Public License as published by
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
// (at your option) any later version.
|
|
//
|
|
// The go-ethereum library is distributed in the hope that it will be useful,
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
// GNU Lesser General Public License for more details.
|
|
//
|
|
// You should have received a copy of the GNU Lesser General Public License
|
|
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
package backends
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"math/big"
|
|
"sync"
|
|
|
|
"github.com/ethereum/go-ethereum"
|
|
"github.com/ethereum/go-ethereum/accounts/abi/bind"
|
|
"github.com/ethereum/go-ethereum/common"
|
|
"github.com/ethereum/go-ethereum/core"
|
|
"github.com/ethereum/go-ethereum/core/state"
|
|
"github.com/ethereum/go-ethereum/core/types"
|
|
"github.com/ethereum/go-ethereum/core/vm"
|
|
"github.com/ethereum/go-ethereum/ethdb"
|
|
"github.com/ethereum/go-ethereum/event"
|
|
"github.com/ethereum/go-ethereum/params"
|
|
"golang.org/x/net/context"
|
|
)
|
|
|
|
// Default chain configuration which sets homestead phase at block 0 (i.e. no frontier)
|
|
var chainConfig = ¶ms.ChainConfig{HomesteadBlock: big.NewInt(0), EIP150Block: new(big.Int), EIP158Block: new(big.Int)}
|
|
|
|
// This nil assignment ensures compile time that SimulatedBackend implements bind.ContractBackend.
|
|
var _ bind.ContractBackend = (*SimulatedBackend)(nil)
|
|
|
|
var errBlockNumberUnsupported = errors.New("SimulatedBackend cannot access blocks other than the latest block")
|
|
|
|
// SimulatedBackend implements bind.ContractBackend, simulating a blockchain in
|
|
// the background. Its main purpose is to allow easily testing contract bindings.
|
|
type SimulatedBackend struct {
|
|
database ethdb.Database // In memory database to store our testing data
|
|
blockchain *core.BlockChain // Ethereum blockchain to handle the consensus
|
|
|
|
mu sync.Mutex
|
|
pendingBlock *types.Block // Currently pending block that will be imported on request
|
|
pendingState *state.StateDB // Currently pending state that will be the active on on request
|
|
|
|
config *params.ChainConfig
|
|
}
|
|
|
|
// NewSimulatedBackend creates a new binding backend using a simulated blockchain
|
|
// for testing purposes.
|
|
func NewSimulatedBackend(accounts ...core.GenesisAccount) *SimulatedBackend {
|
|
database, _ := ethdb.NewMemDatabase()
|
|
core.WriteGenesisBlockForTesting(database, accounts...)
|
|
blockchain, _ := core.NewBlockChain(database, chainConfig, new(core.FakePow), new(event.TypeMux))
|
|
backend := &SimulatedBackend{database: database, blockchain: blockchain}
|
|
backend.rollback()
|
|
return backend
|
|
}
|
|
|
|
// Commit imports all the pending transactions as a single block and starts a
|
|
// fresh new state.
|
|
func (b *SimulatedBackend) Commit() {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
|
|
if _, err := b.blockchain.InsertChain([]*types.Block{b.pendingBlock}); err != nil {
|
|
panic(err) // This cannot happen unless the simulator is wrong, fail in that case
|
|
}
|
|
b.rollback()
|
|
}
|
|
|
|
// Rollback aborts all pending transactions, reverting to the last committed state.
|
|
func (b *SimulatedBackend) Rollback() {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
|
|
b.rollback()
|
|
}
|
|
|
|
func (b *SimulatedBackend) rollback() {
|
|
blocks, _ := core.GenerateChain(chainConfig, b.blockchain.CurrentBlock(), b.database, 1, func(int, *core.BlockGen) {})
|
|
b.pendingBlock = blocks[0]
|
|
b.pendingState, _ = state.New(b.pendingBlock.Root(), b.database)
|
|
}
|
|
|
|
// CodeAt returns the code associated with a certain account in the blockchain.
|
|
func (b *SimulatedBackend) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
|
|
if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
|
|
return nil, errBlockNumberUnsupported
|
|
}
|
|
statedb, _ := b.blockchain.State()
|
|
return statedb.GetCode(contract), nil
|
|
}
|
|
|
|
// BalanceAt returns the wei balance of a certain account in the blockchain.
|
|
func (b *SimulatedBackend) BalanceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (*big.Int, error) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
|
|
if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
|
|
return nil, errBlockNumberUnsupported
|
|
}
|
|
statedb, _ := b.blockchain.State()
|
|
return statedb.GetBalance(contract), nil
|
|
}
|
|
|
|
// NonceAt returns the nonce of a certain account in the blockchain.
|
|
func (b *SimulatedBackend) NonceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (uint64, error) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
|
|
if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
|
|
return 0, errBlockNumberUnsupported
|
|
}
|
|
statedb, _ := b.blockchain.State()
|
|
return statedb.GetNonce(contract), nil
|
|
}
|
|
|
|
// StorageAt returns the value of key in the storage of an account in the blockchain.
|
|
func (b *SimulatedBackend) StorageAt(ctx context.Context, contract common.Address, key common.Hash, blockNumber *big.Int) ([]byte, error) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
|
|
if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
|
|
return nil, errBlockNumberUnsupported
|
|
}
|
|
statedb, _ := b.blockchain.State()
|
|
val := statedb.GetState(contract, key)
|
|
return val[:], nil
|
|
}
|
|
|
|
// TransactionReceipt returns the receipt of a transaction.
|
|
func (b *SimulatedBackend) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) {
|
|
return core.GetReceipt(b.database, txHash), nil
|
|
}
|
|
|
|
// PendingCodeAt returns the code associated with an account in the pending state.
|
|
func (b *SimulatedBackend) PendingCodeAt(ctx context.Context, contract common.Address) ([]byte, error) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
|
|
return b.pendingState.GetCode(contract), nil
|
|
}
|
|
|
|
// CallContract executes a contract call.
|
|
func (b *SimulatedBackend) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
|
|
if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
|
|
return nil, errBlockNumberUnsupported
|
|
}
|
|
state, err := b.blockchain.State()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
rval, _, err := b.callContract(call, b.blockchain.CurrentBlock(), state)
|
|
return rval, err
|
|
}
|
|
|
|
// PendingCallContract executes a contract call on the pending state.
|
|
func (b *SimulatedBackend) PendingCallContract(ctx context.Context, call ethereum.CallMsg) ([]byte, error) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
defer b.pendingState.RevertToSnapshot(b.pendingState.Snapshot())
|
|
|
|
rval, _, err := b.callContract(call, b.pendingBlock, b.pendingState)
|
|
return rval, err
|
|
}
|
|
|
|
// PendingNonceAt implements PendingStateReader.PendingNonceAt, retrieving
|
|
// the nonce currently pending for the account.
|
|
func (b *SimulatedBackend) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
|
|
return b.pendingState.GetOrNewStateObject(account).Nonce(), nil
|
|
}
|
|
|
|
// SuggestGasPrice implements ContractTransactor.SuggestGasPrice. Since the simulated
|
|
// chain doens't have miners, we just return a gas price of 1 for any call.
|
|
func (b *SimulatedBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
|
|
return big.NewInt(1), nil
|
|
}
|
|
|
|
// EstimateGas executes the requested code against the currently pending block/state and
|
|
// returns the used amount of gas.
|
|
func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMsg) (*big.Int, error) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
defer b.pendingState.RevertToSnapshot(b.pendingState.Snapshot())
|
|
|
|
_, gas, err := b.callContract(call, b.pendingBlock, b.pendingState)
|
|
return gas, err
|
|
}
|
|
|
|
// callContract implemens common code between normal and pending contract calls.
|
|
// state is modified during execution, make sure to copy it if necessary.
|
|
func (b *SimulatedBackend) callContract(call ethereum.CallMsg, block *types.Block, state *state.StateDB) ([]byte, *big.Int, error) {
|
|
return core.ApplyCallMessage(call, func(msg core.Message) vm.Environment {
|
|
return core.NewEnv(state, chainConfig, b.blockchain, msg, block.Header(), vm.Config{})
|
|
})
|
|
}
|
|
|
|
// SendTransaction updates the pending block to include the given transaction.
|
|
// It panics if the transaction is invalid.
|
|
func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
|
|
sender, err := types.Sender(types.HomesteadSigner{}, tx)
|
|
if err != nil {
|
|
panic(fmt.Errorf("invalid transaction: %v", err))
|
|
}
|
|
nonce := b.pendingState.GetNonce(sender)
|
|
if tx.Nonce() != nonce {
|
|
panic(fmt.Errorf("invalid transaction nonce: got %d, want %d", tx.Nonce(), nonce))
|
|
}
|
|
|
|
blocks, _ := core.GenerateChain(chainConfig, b.blockchain.CurrentBlock(), b.database, 1, func(number int, block *core.BlockGen) {
|
|
for _, tx := range b.pendingBlock.Transactions() {
|
|
block.AddTx(tx)
|
|
}
|
|
block.AddTx(tx)
|
|
})
|
|
b.pendingBlock = blocks[0]
|
|
b.pendingState, _ = state.New(b.pendingBlock.Root(), b.database)
|
|
return nil
|
|
}
|