This repository was archived by the owner on Aug 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 182
Add BlockchainContractCaller #1828
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
1aadbe7
Add BlockchainContractCaller
blukat29 d0179fa
Replace governance.contractCaller by BlockchainContractCaller
blukat29 08b2df9
Remove governance.contractCaller
blukat29 15fb12b
Replace Kip103ContractCaller by BlockchainContractCaller
blukat29 0cca6e2
Add StateAt() in ChainReader
2dvorak 0825c69
Replace reward.addressBookConnector by BlockchainContractCaller
2dvorak 4b99a04
Remove reward.addressBookConnector
2dvorak 1b59a93
Update outdated comment
2dvorak 8bdf56c
Add tests for nonzero block numbers
2dvorak b4e1167
Update test code to be more specific
2dvorak 8e1bf34
Make blockChainForCaller interface public
2dvorak File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,140 @@ | ||
// Copyright 2023 The klaytn Authors | ||
// This file is part of the klaytn library. | ||
// | ||
// The klaytn 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 klaytn 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 klaytn library. If not, see <http://www.gnu.org/licenses/>. | ||
|
||
package backends | ||
|
||
import ( | ||
"context" | ||
"math/big" | ||
|
||
"github.com/klaytn/klaytn" | ||
"github.com/klaytn/klaytn/accounts/abi/bind" | ||
"github.com/klaytn/klaytn/blockchain" | ||
"github.com/klaytn/klaytn/blockchain/state" | ||
"github.com/klaytn/klaytn/blockchain/types" | ||
"github.com/klaytn/klaytn/blockchain/vm" | ||
"github.com/klaytn/klaytn/common" | ||
"github.com/klaytn/klaytn/params" | ||
) | ||
|
||
// Maintain separate minimal interfaces of blockchain.BlockChain because ContractBackend are used | ||
// in various situations. BlockChain instances are often passed down as different interfaces such as | ||
// consensus.ChainReader, governance.blockChain, work.BlockChain. | ||
type BlockChainForCaller interface { | ||
// Required by NewEVMContext | ||
blockchain.ChainContext | ||
|
||
// Below is a subset of consensus.ChainReader | ||
// Only using the vocabulary of consensus.ChainReader for potential | ||
// usability within consensus package. | ||
Config() *params.ChainConfig | ||
CurrentHeader() *types.Header | ||
GetHeaderByNumber(number uint64) *types.Header | ||
GetBlock(hash common.Hash, number uint64) *types.Block | ||
State() (*state.StateDB, error) | ||
StateAt(root common.Hash) (*state.StateDB, error) | ||
} | ||
|
||
// BlockchainContractCaller implements bind.ContractCaller, based on | ||
// a user-supplied blockchain.BlockChain instance. | ||
// Its intended purpose is reading system contracts during block processing. | ||
// | ||
// Note that SimulatedBackend creates a new temporary BlockChain for testing, | ||
// whereas BlockchainContractCaller uses an existing BlockChain with existing database. | ||
type BlockchainContractCaller struct { | ||
bc BlockChainForCaller | ||
} | ||
|
||
// This nil assignment ensures at compile time that BlockchainContractCaller implements bind.ContractCaller. | ||
var _ bind.ContractCaller = (*BlockchainContractCaller)(nil) | ||
|
||
func NewBlockchainContractCaller(bc BlockChainForCaller) *BlockchainContractCaller { | ||
return &BlockchainContractCaller{ | ||
bc: bc, | ||
} | ||
} | ||
|
||
func (b *BlockchainContractCaller) CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) ([]byte, error) { | ||
if _, state, err := b.getBlockAndState(blockNumber); err != nil { | ||
return nil, err | ||
} else { | ||
return state.GetCode(account), nil | ||
} | ||
} | ||
|
||
// Executes a read-only function call with respect to the specified block's state, or latest state if not specified. | ||
// | ||
// Returns call result in []byte. | ||
// Returns error when: | ||
// - cannot find the corresponding block or stateDB | ||
// - VM revert error | ||
// - VM other errors (e.g. NotProgramAccount, OutOfGas) | ||
// - Error outside VM | ||
func (b *BlockchainContractCaller) CallContract(ctx context.Context, call klaytn.CallMsg, blockNumber *big.Int) ([]byte, error) { | ||
block, state, err := b.getBlockAndState(blockNumber) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
res, err := b.callContract(call, block, state) | ||
if err != nil { | ||
return nil, err | ||
} | ||
if len(res.Revert()) > 0 { | ||
return nil, newRevertError(res) | ||
} | ||
return res.Return(), res.Unwrap() | ||
} | ||
|
||
func (b *BlockchainContractCaller) callContract(call klaytn.CallMsg, block *types.Block, state *state.StateDB) (*blockchain.ExecutionResult, error) { | ||
if call.Gas == 0 { | ||
call.Gas = uint64(3e8) // enough gas for ordinary contract calls | ||
} | ||
|
||
intrinsicGas, err := types.IntrinsicGas(call.Data, nil, call.To == nil, b.bc.Config().Rules(block.Number())) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
msg := types.NewMessage(call.From, call.To, 0, call.Value, call.Gas, call.GasPrice, call.Data, | ||
false, intrinsicGas) | ||
|
||
evmContext := blockchain.NewEVMContext(msg, block.Header(), b.bc, nil) | ||
// EVM demands the sender to have enough KLAY balance (gasPrice * gasLimit) in buyGas() | ||
// After KIP-71, gasPrice is nonzero baseFee, regardless of the msg.gasPrice (usually 0) | ||
// But our sender (usually 0x0) won't have enough balance. Instead we override gasPrice = 0 here | ||
evmContext.GasPrice = big.NewInt(0) | ||
evm := vm.NewEVM(evmContext, state, b.bc.Config(), &vm.Config{}) | ||
|
||
return blockchain.ApplyMessage(evm, msg) | ||
} | ||
|
||
func (b *BlockchainContractCaller) getBlockAndState(num *big.Int) (*types.Block, *state.StateDB, error) { | ||
var header *types.Header | ||
if num == nil { | ||
header = b.bc.CurrentHeader() | ||
} else { | ||
header = b.bc.GetHeaderByNumber(num.Uint64()) | ||
} | ||
aidan-kwon marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
if header == nil { | ||
return nil, nil, errBlockDoesNotExist | ||
} | ||
|
||
block := b.bc.GetBlock(header.Hash(), header.Number.Uint64()) | ||
state, err := b.bc.StateAt(block.Root()) | ||
return block, state, err | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,149 @@ | ||
// Copyright 2023 The klaytn Authors | ||
// This file is part of the klaytn library. | ||
// | ||
// The klaytn 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 klaytn 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 klaytn library. If not, see <http://www.gnu.org/licenses/>. | ||
|
||
package backends | ||
|
||
import ( | ||
"context" | ||
"errors" | ||
"math/big" | ||
"strings" | ||
"testing" | ||
|
||
"github.com/klaytn/klaytn" | ||
"github.com/klaytn/klaytn/accounts/abi" | ||
"github.com/klaytn/klaytn/blockchain" | ||
"github.com/klaytn/klaytn/blockchain/vm" | ||
"github.com/klaytn/klaytn/common" | ||
"github.com/klaytn/klaytn/consensus/gxhash" | ||
"github.com/klaytn/klaytn/crypto" | ||
"github.com/klaytn/klaytn/params" | ||
"github.com/klaytn/klaytn/storage/database" | ||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
var ( | ||
testAddr = crypto.PubkeyToAddress(testKey.PublicKey) | ||
code1Addr = common.HexToAddress("0x1111111111111111111111111111111111111111") | ||
code2Addr = common.HexToAddress("0x2222222222222222222222222222222222222222") | ||
|
||
parsedAbi1, _ = abi.JSON(strings.NewReader(abiJSON)) | ||
parsedAbi2, _ = abi.JSON(strings.NewReader(reverterABI)) | ||
code1Bytes = common.FromHex(deployedCode) | ||
code2Bytes = common.FromHex(reverterDeployedBin) | ||
) | ||
|
||
func newTestBlockchain() *blockchain.BlockChain { | ||
config := params.TestChainConfig.Copy() | ||
alloc := blockchain.GenesisAlloc{ | ||
testAddr: {Balance: big.NewInt(10000000000)}, | ||
code1Addr: {Balance: big.NewInt(0), Code: code1Bytes}, | ||
code2Addr: {Balance: big.NewInt(0), Code: code2Bytes}, | ||
} | ||
|
||
db := database.NewMemoryDBManager() | ||
genesis := blockchain.Genesis{Config: config, Alloc: alloc} | ||
genesis.MustCommit(db) | ||
|
||
bc, _ := blockchain.NewBlockChain(db, nil, genesis.Config, gxhash.NewFaker(), vm.Config{}) | ||
blukat29 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
// Append 10 blocks to test with block numbers other than 0 | ||
block := bc.CurrentBlock() | ||
blocks, _ := blockchain.GenerateChain(config, block, gxhash.NewFaker(), db, 10, func(i int, b *blockchain.BlockGen) {}) | ||
bc.InsertChain(blocks) | ||
|
||
return bc | ||
} | ||
|
||
func TestBlockchainCodeAt(t *testing.T) { | ||
bc := newTestBlockchain() | ||
c := NewBlockchainContractCaller(bc) | ||
|
||
// Normal cases | ||
code, err := c.CodeAt(context.Background(), code1Addr, nil) | ||
assert.Nil(t, err) | ||
assert.Equal(t, code1Bytes, code) | ||
|
||
code, err = c.CodeAt(context.Background(), code2Addr, nil) | ||
assert.Nil(t, err) | ||
assert.Equal(t, code2Bytes, code) | ||
|
||
code, err = c.CodeAt(context.Background(), code1Addr, common.Big0) | ||
assert.Nil(t, err) | ||
assert.Equal(t, code1Bytes, code) | ||
|
||
code, err = c.CodeAt(context.Background(), code1Addr, common.Big1) | ||
assert.Nil(t, err) | ||
assert.Equal(t, code1Bytes, code) | ||
|
||
code, err = c.CodeAt(context.Background(), code1Addr, big.NewInt(10)) | ||
assert.Nil(t, err) | ||
assert.Equal(t, code1Bytes, code) | ||
|
||
// Non-code address | ||
code, err = c.CodeAt(context.Background(), testAddr, nil) | ||
assert.True(t, code == nil && err == nil) | ||
|
||
// Invalid block number | ||
code, err = c.CodeAt(context.Background(), code1Addr, big.NewInt(11)) | ||
assert.True(t, code == nil && err == errBlockDoesNotExist) | ||
} | ||
|
||
func TestBlockchainCallContract(t *testing.T) { | ||
bc := newTestBlockchain() | ||
c := NewBlockchainContractCaller(bc) | ||
|
||
data_receive, _ := parsedAbi1.Pack("receive", []byte("X")) | ||
data_revertString, _ := parsedAbi2.Pack("revertString") | ||
data_revertNoString, _ := parsedAbi2.Pack("revertNoString") | ||
|
||
// Normal case | ||
ret, err := c.CallContract(context.Background(), klaytn.CallMsg{ | ||
From: testAddr, | ||
To: &code1Addr, | ||
Gas: 1000000, | ||
Data: data_receive, | ||
}, nil) | ||
assert.Nil(t, err) | ||
assert.Equal(t, expectedReturn, ret) | ||
|
||
// Error outside VM - Intrinsic Gas | ||
ret, err = c.CallContract(context.Background(), klaytn.CallMsg{ | ||
From: testAddr, | ||
To: &code1Addr, | ||
Gas: 20000, | ||
Data: data_receive, | ||
}, nil) | ||
assert.True(t, errors.Is(err, blockchain.ErrIntrinsicGas)) | ||
|
||
// VM revert error - empty reason | ||
ret, err = c.CallContract(context.Background(), klaytn.CallMsg{ | ||
From: testAddr, | ||
To: &code2Addr, | ||
Gas: 100000, | ||
Data: data_revertNoString, | ||
}, nil) | ||
assert.Equal(t, "execution reverted: ", err.Error()) | ||
|
||
// VM revert error - string reason | ||
ret, err = c.CallContract(context.Background(), klaytn.CallMsg{ | ||
From: testAddr, | ||
To: &code2Addr, | ||
Gas: 100000, | ||
Data: data_revertString, | ||
}, nil) | ||
assert.Equal(t, "execution reverted: some error", err.Error()) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.