Skip to content

Commit

Permalink
Merge pull request #1918 from PlatONnetwork/feature/double-chainid-1
Browse files Browse the repository at this point in the history
Feature/double chainid 1
  • Loading branch information
benbaley authored Mar 31, 2022
2 parents 17144b7 + 667787a commit 66ed834
Show file tree
Hide file tree
Showing 36 changed files with 442 additions and 86 deletions.
8 changes: 4 additions & 4 deletions accounts/abi/bind/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ func NewKeyStoreTransactor(keystore *keystore.KeyStore, account accounts.Account
if address != account.Address {
return nil, ErrNotAuthorized
}
signature, err := keystore.SignHash(account, signer.Hash(tx).Bytes())
signature, err := keystore.SignHash(account, signer.Hash(tx, nil).Bytes())
if err != nil {
return nil, err
}
Expand All @@ -89,7 +89,7 @@ func NewKeyedTransactor(key *ecdsa.PrivateKey) *TransactOpts {
if address != keyAddr {
return nil, ErrNotAuthorized
}
signature, err := crypto.Sign(signer.Hash(tx).Bytes(), key)
signature, err := crypto.Sign(signer.Hash(tx, nil).Bytes(), key)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -124,7 +124,7 @@ func NewKeyStoreTransactorWithChainID(keystore *keystore.KeyStore, account accou
if address != account.Address {
return nil, ErrNotAuthorized
}
signature, err := keystore.SignHash(account, signer.Hash(tx).Bytes())
signature, err := keystore.SignHash(account, signer.Hash(tx, nil).Bytes())
if err != nil {
return nil, err
}
Expand All @@ -147,7 +147,7 @@ func NewKeyedTransactorWithChainID(key *ecdsa.PrivateKey, chainID *big.Int) (*Tr
if address != keyAddr {
return nil, ErrNotAuthorized
}
signature, err := crypto.Sign(signer.Hash(tx).Bytes(), key)
signature, err := crypto.Sign(signer.Hash(tx, nil).Bytes(), key)
if err != nil {
return nil, err
}
Expand Down
2 changes: 1 addition & 1 deletion common/vm/inner_contract.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
// You should have received a copy of the GNU Lesser General Public License
// along with the PlatON-Go library. If not, see <http://www.gnu.org/licenses/>.


package vm

import "github.com/PlatONnetwork/PlatON-Go/common"
Expand All @@ -28,6 +27,7 @@ var (
GovContractAddr = common.HexToAddress("0x1000000000000000000000000000000000000005") // The PlatON Precompiled contract addr for governance
DelegateRewardPoolAddr = common.HexToAddress("0x1000000000000000000000000000000000000006") // The PlatON Precompiled contract addr for delegate reward
ValidatorInnerContractAddr = common.HexToAddress("0x2000000000000000000000000000000000000000") // The PlatON Precompiled contract addr for cbft inner
VrfInnerContractAddr = common.HexToAddress("0x3000000000000000000000000000000000000001") // The PlatON Precompiled contract addr for vrf inner
)

type PrecompiledContractCheck interface {
Expand Down
3 changes: 2 additions & 1 deletion core/blockchain_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package core
import (
"errors"
"fmt"
"github.com/PlatONnetwork/PlatON-Go/x/gov"
"sort"
"sync"
"time"
Expand Down Expand Up @@ -284,11 +285,11 @@ func (bcc *BlockChainCache) Execute(block *types.Block, parent *types.Block) err
if executed() {
return nil
}
SenderCacher.RecoverFromBlock(types.NewEIP155Signer(bcc.chainConfig.ChainID), block)

log.Debug("Start execute block", "hash", block.Hash(), "number", block.Number(), "sealHash", block.Header().SealHash())
start := time.Now()
state, err := bcc.MakeStateDB(parent)
SenderCacher.RecoverFromBlock(types.MakeSigner(bcc.chainConfig, gov.Gte120VersionState(state)), block)
elapse := time.Since(start)
if err != nil {
return errors.New("execute block error")
Expand Down
2 changes: 1 addition & 1 deletion core/blockchain_reactor.go
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,7 @@ func (bcr *BlockChainReactor) EndBlocker(header *types.Header, state xcom.StateD

func (bcr *BlockChainReactor) VerifyTx(tx *types.Transaction, to common.Address) error {

if !vm.IsPlatONPrecompiledContract(to) {
if !vm.IsPlatONPrecompiledContract(to, true) {
return nil
}

Expand Down
27 changes: 27 additions & 0 deletions core/evm.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ func NewEVMContext(msg Message, header *types.Header, chain ChainContext) vm.Con
CanTransfer: CanTransfer,
Transfer: Transfer,
GetHash: GetHashFn(header, chain),
GetNonce: GetNonceFn(header, chain),
Origin: msg.From(),
Coinbase: beneficiary,
BlockNumber: new(big.Int).Set(header.Number),
Expand All @@ -60,6 +61,8 @@ func NewEVMContext(msg Message, header *types.Header, chain ChainContext) vm.Con
GasPrice: new(big.Int).Set(msg.GasPrice()),
BlockHash: blockHash,
Difficulty: new(big.Int).SetUint64(0), // This one must not be deleted, otherwise the solidity contract will be failed
Nonce: header.Nonce,
ParentHash: header.ParentHash,
}
}

Expand Down Expand Up @@ -95,6 +98,30 @@ func GetHashFn(ref *types.Header, chain ChainContext) func(n uint64) common.Hash
}
}

func GetNonceFn(ref *types.Header, chain ChainContext) func(n uint64) []byte {
var cache map[uint64][]byte

return func(n uint64) []byte {
// If there's no hash cache yet, make one
if cache == nil {
cache = map[uint64][]byte{
ref.Number.Uint64() - 1: ref.Nonce.Bytes(),
}
}
// Try to fulfill the request from the cache
if nonce, ok := cache[n]; ok {
return nonce
}
for block := chain.Engine().GetBlockByHashAndNum(ref.ParentHash, ref.Number.Uint64()-1); block != nil; block = chain.Engine().GetBlockByHashAndNum(block.Header().ParentHash, block.Header().Number.Uint64()-1) {
cache[block.Header().Number.Uint64()-1] = block.Header().Nonce.Bytes()
if n == block.Header().Number.Uint64()-1 {
return block.Header().Nonce.Bytes()
}
}
return nil
}
}

// CanTransfer checks whether there are enough funds in the address' account to make a transfer.
// This does not take the necessary gas in to account to make the transfer valid.
func CanTransfer(db vm.StateDB, addr common.Address, amount *big.Int) bool {
Expand Down
9 changes: 9 additions & 0 deletions core/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,9 @@ func SetupGenesisBlock(db ethdb.Database, snapshotBaseDB snapshotdb.BaseDB, gene
return newcfg, stored, nil
}
if genesis == nil {
if storedcfg.PIP7ChainID == nil {
storedcfg.PIP7ChainID = params.PrivatePIP7ChainID
}
if err := common.SetAddressHRP(storedcfg.AddressHRP); err != nil {
return newcfg, stored, err
}
Expand Down Expand Up @@ -318,6 +321,12 @@ func (g *Genesis) InitGenesisAndSetEconomicConfig(path string) error {
if g.Config.GenesisVersion == 0 {
return errors.New("genesis version configuration is missed")
}
if g.Config.ChainID == nil {
return errors.New("chainId configuration is missed")
}
if g.Config.PIP7ChainID == nil {
g.Config.PIP7ChainID = params.PrivatePIP7ChainID
}

xcom.ResetEconomicDefaultConfig(g.EconomicModel)
// Uodate the NodeBlockTimeWindow and PerRoundBlocks of EconomicModel config
Expand Down
31 changes: 24 additions & 7 deletions core/parallel_executor.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
package core

import (
"github.com/PlatONnetwork/PlatON-Go/crypto"
"math/big"
"runtime"
"sync"
"time"

"github.com/PlatONnetwork/PlatON-Go/x/gov"

"github.com/PlatONnetwork/PlatON-Go/crypto"

"github.com/panjf2000/ants/v2"

"github.com/PlatONnetwork/PlatON-Go/core/state"
Expand All @@ -24,6 +27,8 @@ const (
var (
executorOnce sync.Once
executor Executor
EIP155Signer types.Signer
PIP7Signer types.Signer
)

type Executor struct {
Expand Down Expand Up @@ -56,7 +61,9 @@ func NewExecutor(chainConfig *params.ChainConfig, chainContext ChainContext, vmC
})
executor.chainConfig = chainConfig
executor.chainContext = chainContext
executor.signer = types.NewEIP155Signer(chainConfig.ChainID)
EIP155Signer = types.NewEIP155Signer(chainConfig.ChainID)
PIP7Signer = types.MakeSigner(chainConfig, true)
executor.signer = EIP155Signer
executor.vmCfg = vmCfg
executor.txpool = txpool
})
Expand All @@ -66,13 +73,23 @@ func GetExecutor() *Executor {
return &executor
}

func (exe *Executor) MakeSigner(stateDB *state.StateDB) types.Signer {
pip7 := gov.Gte120VersionState(stateDB)
if pip7 {
exe.signer = PIP7Signer
} else {
exe.signer = EIP155Signer
}
return exe.signer
}

func (exe *Executor) Signer() types.Signer {
return exe.signer
}

func (exe *Executor) ExecuteTransactions(ctx *ParallelContext) error {
if len(ctx.txList) > 0 {
txDag := NewTxDag(exe.signer)
txDag := NewTxDag(exe.Signer())
start := time.Now()
// load tx fromAddress from txpool by txHash
if err := txDag.MakeDagGraph(ctx, exe); err != nil {
Expand Down Expand Up @@ -100,7 +117,7 @@ func (exe *Executor) ExecuteTransactions(ctx *ParallelContext) error {
break
}

from := tx.FromAddr(exe.signer)
from := tx.FromAddr(exe.Signer())
if _, popped := ctx.poppedAddresses[from]; popped {
log.Debug("Address popped", "from", from.Bech32())
continue
Expand Down Expand Up @@ -155,7 +172,7 @@ func (exe *Executor) executeParallelTx(ctx *ParallelContext, idx int, intrinsicG
}
tx := ctx.GetTx(idx)

msg, err := tx.AsMessage(exe.signer)
msg, err := tx.AsMessage(exe.Signer())
if err != nil {
//gas pool is subbed
ctx.buildTransferFailedResult(idx, err, true)
Expand Down Expand Up @@ -233,13 +250,13 @@ func (exe *Executor) executeContractTransaction(ctx *ParallelContext, idx int) {
func (exe *Executor) isContract(tx *types.Transaction, state *state.StateDB, ctx *ParallelContext) bool {
address := tx.To()
if address == nil { // create contract
contractAddress := crypto.CreateAddress(tx.FromAddr(exe.signer), tx.Nonce())
contractAddress := crypto.CreateAddress(tx.FromAddr(exe.Signer()), tx.Nonce())
ctx.tempContractCache[contractAddress] = struct{}{}
return true
}
if _, ok := ctx.tempContractCache[*address]; ok {
return true
}
isContract := vm.IsPrecompiledContract(*address) || state.GetCodeSize(*address) > 0
isContract := vm.IsPrecompiledContract(*address, gov.Gte120VersionState(state)) || state.GetCodeSize(*address) > 0
return isContract
}
2 changes: 1 addition & 1 deletion core/parallel_state_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func (p *ParallelStateProcessor) Process(block *types.Block, statedb *state.Stat
if len(block.Transactions()) > 0 {
start := time.Now()
tempContractCache := make(map[common.Address]struct{})
ctx := NewParallelContext(statedb, header, block.Hash(), gp, false, GetExecutor().Signer(), tempContractCache)
ctx := NewParallelContext(statedb, header, block.Hash(), gp, false, GetExecutor().MakeSigner(statedb), tempContractCache)
ctx.SetBlockGasUsedHolder(usedGas)
ctx.SetTxList(block.Transactions())

Expand Down
4 changes: 3 additions & 1 deletion core/state_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import (
"bytes"
"strconv"

"github.com/PlatONnetwork/PlatON-Go/x/gov"

"github.com/PlatONnetwork/PlatON-Go/common"
"github.com/PlatONnetwork/PlatON-Go/consensus"
"github.com/PlatONnetwork/PlatON-Go/core/snapshotdb"
Expand Down Expand Up @@ -115,7 +117,7 @@ func ApplyTransaction(config *params.ChainConfig, bc ChainContext, gp *GasPool,
statedb *state.StateDB, header *types.Header, tx *types.Transaction,
usedGas *uint64, cfg vm.Config) (*types.Receipt, uint64, error) {

msg, err := tx.AsMessage(types.NewEIP155Signer(config.ChainID))
msg, err := tx.AsMessage(types.MakeSigner(config, gov.Gte120VersionState(statedb)))

if err != nil {
return nil, 0, err
Expand Down
4 changes: 3 additions & 1 deletion core/state_transition.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import (
"math/big"
"time"

"github.com/PlatONnetwork/PlatON-Go/x/gov"

"github.com/PlatONnetwork/PlatON-Go/common"
"github.com/PlatONnetwork/PlatON-Go/core/vm"
"github.com/PlatONnetwork/PlatON-Go/log"
Expand Down Expand Up @@ -245,7 +247,7 @@ func (st *StateTransition) TransitionDb() (*ExecutionResult, error) {
ctx := context.Background()
var cancelFn context.CancelFunc
if st.evm.GetVMConfig().VmTimeoutDuration > 0 &&
(contractCreation || !vm.IsPrecompiledContract(*(msg.To()))) {
(contractCreation || !vm.IsPrecompiledContract(*(msg.To()), gov.Gte120VersionState(st.state))) {

timeout := time.Duration(st.evm.GetVMConfig().VmTimeoutDuration) * time.Millisecond
ctx, cancelFn = context.WithTimeout(ctx, timeout)
Expand Down
24 changes: 23 additions & 1 deletion core/tx_pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package core
import (
"errors"
"fmt"
"github.com/PlatONnetwork/PlatON-Go/x/gov"
"math"
"math/big"
"sort"
Expand Down Expand Up @@ -320,12 +321,20 @@ func NewTxPool(config TxPoolConfig, chainconfig *params.ChainConfig, chain txPoo
// Sanitize the input to ensure no vulnerable gas prices are set
config = (&config).sanitize()

pip7 := false
if currentBlock := chain.CurrentBlock(); currentBlock != nil {
stateDB, err := chain.GetState(currentBlock.Header())
if err == nil && stateDB != nil {
pip7 = gov.Gte120VersionState(stateDB)
}
}

// Create the transaction pool with its initial settings
pool := &TxPool{
config: config,
chainconfig: chainconfig,
chain: chain,
signer: types.NewEIP155Signer(chainconfig.ChainID),
signer: types.MakeSigner(chainconfig, pip7),
pending: make(map[common.Address]*txList),
queue: make(map[common.Address]*txList),
beats: make(map[common.Address]time.Time),
Expand Down Expand Up @@ -498,6 +507,13 @@ func (pool *TxPool) ForkedReset(newHeader *types.Header, rollback []*types.Block
pool.pendingNonces = newTxNoncer(statedb)
pool.currentMaxGas = newHeader.GasLimit

// reset signer
if gov.Gte120VersionState(statedb) {
pool.signer = types.MakeSigner(pool.chainconfig, true)
pool.locals.signer = pool.signer
pool.cacheAccountNeedPromoted.signer = pool.signer
}

// Inject any transactions discarded due to reorgs
t := time.Now()
SenderCacher.recover(pool.signer, reinject)
Expand Down Expand Up @@ -1401,6 +1417,12 @@ func (pool *TxPool) reset(oldHead, newHead *types.Header) {
pool.currentState = statedb
pool.pendingNonces = newTxNoncer(statedb)
pool.currentMaxGas = newHead.GasLimit
// reset signer
if gov.Gte120VersionState(statedb) {
pool.signer = types.MakeSigner(pool.chainconfig, true)
pool.locals.signer = pool.signer
pool.cacheAccountNeedPromoted.signer = pool.signer
}
// Inject any transactions discarded due to reorgs
t := time.Now()
SenderCacher.recover(pool.signer, reinject)
Expand Down
2 changes: 1 addition & 1 deletion core/types/receipt.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ func (r Receipts) GetRlp(i int) []byte {
// DeriveFields fills the receipts with their computed fields based on consensus
// data and contextual infos like containing block and transactions.
func (r Receipts) DeriveFields(config *params.ChainConfig, hash common.Hash, number uint64, txs Transactions) error {
signer := NewEIP155Signer(config.ChainID)
signer := NewPIP7Signer(config.ChainID, config.PIP7ChainID)

logIndex := uint(0)
if len(txs) != len(r) {
Expand Down
3 changes: 1 addition & 2 deletions core/types/transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ func (tx *Transaction) AsMessage(s Signer) (Message, error) {
// WithSignature returns a new transaction with the given signature.
// This signature needs to be formatted as described in the yellow paper (v+35).
func (tx *Transaction) WithSignature(signer Signer, sig []byte) (*Transaction, error) {
r, s, v, err := signer.SignatureValues(tx, sig)
r, s, v, err := signer.SignatureValues(sig)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -296,7 +296,6 @@ func (tx *Transaction) FromAddr(signer Signer) common.Address {
if err != nil {
return common.Address{}
}
//log.Debug("Sender cache2", "add", addr, "hash", tx.Hash(), "poi", fmt.Sprintf("%p", tx))
tx.from.Store(sigCache{signer: signer, from: addr})
return addr
}
Expand Down
Loading

0 comments on commit 66ed834

Please sign in to comment.