clear redundant code

This commit is contained in:
Nguyen Sy Thanh Son 2019-01-03 05:04:26 +00:00
parent a210d7ad14
commit 752ac2b426
5 changed files with 7 additions and 338 deletions

View file

@ -42,7 +42,6 @@ import (
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/state" "github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types" "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/ethdb"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
@ -196,22 +195,7 @@ func BuildTxOpeningRandomize(nonce uint64, randomizeAddr common.Address, randomi
} }
// Get signers signed for blockNumber from blockSigner contract. // Get signers signed for blockNumber from blockSigner contract.
func GetSignersFromContract(addrBlockSigner common.Address, client bind.ContractBackend, blockHash common.Hash) ([]common.Address, error) { func GetSignersFromContract(c *posv.Posv, addrBlockSigner common.Address, client bind.ContractBackend, blockHash common.Hash) ([]common.Address, error) {
blockSigner, err := contract.NewBlockSigner(addrBlockSigner, client)
if err != nil {
log.Error("Fail get instance of blockSigner", "error", err)
return nil, err
}
opts := new(bind.CallOpts)
addrs, err := blockSigner.GetSigners(opts, blockHash)
if err != nil {
log.Error("Fail get block signers", "error", err)
return nil, err
}
return addrs, nil
}
func GetSignersFromContract2(c *posv.Posv, addrBlockSigner common.Address, client bind.ContractBackend, blockHash common.Hash) ([]common.Address, error) {
blockSigner, err := contract.NewBlockSigner(addrBlockSigner, client) blockSigner, err := contract.NewBlockSigner(addrBlockSigner, client)
if err != nil { if err != nil {
log.Error("Fail get instance of blockSigner", "error", err) log.Error("Fail get instance of blockSigner", "error", err)
@ -338,7 +322,7 @@ func GetRewardForCheckpoint(c *posv.Posv, chain consensus.ChainReader, blockSign
for i := startBlockNumber; i <= endBlockNumber; i++ { for i := startBlockNumber; i <= endBlockNumber; i++ {
go func(i uint64) { go func(i uint64) {
block := chain.GetHeaderByNumber(i) block := chain.GetHeaderByNumber(i)
addrs, err := GetSignersFromContract2(c, blockSignerAddr, client, block.Hash()) addrs, err := GetSignersFromContract(c, blockSignerAddr, client, block.Hash())
// addrs, err := GetSignersFromContract2(c, blockSignerAddr, client, block.Hash()) // addrs, err := GetSignersFromContract2(c, blockSignerAddr, client, block.Hash())
if err != nil { if err != nil {
log.Crit("Fail to get signers from smartcontract.", "error", err, "blockNumber", i) log.Crit("Fail to get signers from smartcontract.", "error", err, "blockNumber", i)
@ -414,18 +398,6 @@ func CalculateRewardForSigner(chainReward *big.Int, signers map[common.Address]*
return resultSigners, nil return resultSigners, nil
} }
// Get candidate owner by address.
func GetCandidatesOwnerBySigner2(vmenv *vm.EVM, signerAddr common.Address) common.Address {
owner := signerAddr
owner, err := core.GetCandidateOwner(signerAddr, vmenv)
if err != nil {
log.Error("Fail get candidate owner", "error", err)
return owner
}
return owner
}
func GetCandidatesOwnerBySigner(validator *contractValidator.TomoValidator, signerAddr common.Address) common.Address { func GetCandidatesOwnerBySigner(validator *contractValidator.TomoValidator, signerAddr common.Address) common.Address {
owner := signerAddr owner := signerAddr
opts := new(bind.CallOpts) opts := new(bind.CallOpts)
@ -438,81 +410,6 @@ func GetCandidatesOwnerBySigner(validator *contractValidator.TomoValidator, sign
return owner return owner
} }
// Calculate reward for holders.
func CalculateRewardForHolders2(foudationWalletAddr common.Address, vmenv *vm.EVM, state *state.StateDB, signer common.Address, calcReward *big.Int) (error, map[common.Address]*big.Int) {
rewards, err := GetRewardBalancesRate2(foudationWalletAddr, signer, calcReward, vmenv)
if err != nil {
return err, nil
}
if len(rewards) > 0 {
for holder, reward := range rewards {
state.AddBalance(holder, reward)
}
}
return nil, rewards
}
// Get reward balance rates for master node, founder and holders.
func GetRewardBalancesRate2(foudationWalletAddr common.Address, masterAddr common.Address, totalReward *big.Int, vmenv *vm.EVM) (map[common.Address]*big.Int, error) {
owner := GetCandidatesOwnerBySigner2(vmenv, masterAddr)
balances := make(map[common.Address]*big.Int)
rewardMaster := new(big.Int).Mul(totalReward, new(big.Int).SetInt64(common.RewardMasterPercent))
rewardMaster = new(big.Int).Div(rewardMaster, new(big.Int).SetInt64(100))
balances[owner] = rewardMaster
// Get voters for masternode.
voters, err := core.GetVoters(masterAddr, vmenv)
if err != nil {
log.Error("Fail to get voters", "error", err)
return nil, err
}
if len(voters) > 0 {
totalVoterReward := new(big.Int).Mul(totalReward, new(big.Int).SetUint64(common.RewardVoterPercent))
totalVoterReward = new(big.Int).Div(totalVoterReward, new(big.Int).SetUint64(100))
totalCap := new(big.Int)
// Get voters capacities.
voterCaps := make(map[common.Address]*big.Int)
for _, voteAddr := range voters {
voterCap, err := core.GetVoterCap(masterAddr, voteAddr, vmenv)
if err != nil {
log.Error("Fail to get vote capacity", "error", err)
return nil, err
}
totalCap.Add(totalCap, voterCap)
voterCaps[voteAddr] = voterCap
}
if totalCap.Cmp(new(big.Int).SetInt64(0)) > 0 {
for addr, voteCap := range voterCaps {
// Only valid voter has cap > 0.
if voteCap.Cmp(new(big.Int).SetInt64(0)) > 0 {
rcap := new(big.Int).Mul(totalVoterReward, voteCap)
rcap = new(big.Int).Div(rcap, totalCap)
if balances[addr] != nil {
balances[addr].Add(balances[addr], rcap)
} else {
balances[addr] = rcap
}
}
}
}
}
foudationReward := new(big.Int).Mul(totalReward, new(big.Int).SetInt64(common.RewardFoundationPercent))
foudationReward = new(big.Int).Div(foudationReward, new(big.Int).SetInt64(100))
balances[foudationWalletAddr] = foudationReward
jsonHolders, err := json.Marshal(balances)
if err != nil {
log.Error("Fail to parse json holders", "error", err)
return nil, err
}
log.Info("Holders reward", "holders", string(jsonHolders), "master node", masterAddr.String())
fmt.Println("Holders reward", "holders", string(jsonHolders), "master node", masterAddr.String())
return balances, nil
}
// Calculate reward for holders. // Calculate reward for holders.
func CalculateRewardForHolders(foudationWalletAddr common.Address, validator *contractValidator.TomoValidator, state *state.StateDB, signer common.Address, calcReward *big.Int) (error, map[common.Address]*big.Int) { func CalculateRewardForHolders(foudationWalletAddr common.Address, validator *contractValidator.TomoValidator, state *state.StateDB, signer common.Address, calcReward *big.Int) (error, map[common.Address]*big.Int) {
rewards, err := GetRewardBalancesRate(foudationWalletAddr, signer, calcReward, validator) rewards, err := GetRewardBalancesRate(foudationWalletAddr, signer, calcReward, validator)

View file

@ -1,24 +0,0 @@
package core
import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/vm"
)
func NewEnv(cfg *Config) *vm.EVM {
context := vm.Context{
CanTransfer: CanTransfer,
Transfer: Transfer,
GetHash: func(uint64) common.Hash { return common.Hash{} },
Origin: cfg.Origin,
Coinbase: cfg.Coinbase,
BlockNumber: cfg.BlockNumber,
Time: cfg.Time,
Difficulty: cfg.Difficulty,
GasLimit: cfg.GasLimit,
GasPrice: cfg.GasPrice,
}
return vm.NewEVM(context, cfg.State, cfg.ChainConfig, cfg.EVMConfig)
}

View file

@ -1,205 +0,0 @@
package core
import (
"math"
"math/big"
"strings"
"time"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/params"
)
// Config is a basic type specifying certain configuration flags for running
// the EVM.
type Config struct {
ChainConfig *params.ChainConfig
Difficulty *big.Int
Origin common.Address
Coinbase common.Address
BlockNumber *big.Int
Time *big.Int
GasLimit uint64
GasPrice *big.Int
Value *big.Int
Debug bool
EVMConfig vm.Config
State *state.StateDB
GetHashFn func(n uint64) common.Hash
}
var abiValidator = `[{"constant":false,"inputs":[{"name":"_candidate","type":"address"}],"name":"propose","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"_candidate","type":"address"},{"name":"_cap","type":"uint256"}],"name":"unvote","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getCandidates","outputs":[{"name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_blockNumber","type":"uint256"}],"name":"getWithdrawCap","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_candidate","type":"address"}],"name":"getVoters","outputs":[{"name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getWithdrawBlockNumbers","outputs":[{"name":"","type":"uint256[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_candidate","type":"address"},{"name":"_voter","type":"address"}],"name":"getVoterCap","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"candidates","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_blockNumber","type":"uint256"},{"name":"_index","type":"uint256"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_candidate","type":"address"}],"name":"getCandidateCap","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_candidate","type":"address"}],"name":"vote","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[],"name":"candidateCount","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"voterWithdrawDelay","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_candidate","type":"address"}],"name":"resign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_candidate","type":"address"}],"name":"getCandidateOwner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"maxValidatorNumber","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"candidateWithdrawDelay","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_candidate","type":"address"}],"name":"isCandidate","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"minCandidateCap","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"minVoterCap","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"_candidates","type":"address[]"},{"name":"_caps","type":"uint256[]"},{"name":"_firstOwner","type":"address"},{"name":"_minCandidateCap","type":"uint256"},{"name":"_minVoterCap","type":"uint256"},{"name":"_maxValidatorNumber","type":"uint256"},{"name":"_candidateWithdrawDelay","type":"uint256"},{"name":"_voterWithdrawDelay","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_voter","type":"address"},{"indexed":false,"name":"_candidate","type":"address"},{"indexed":false,"name":"_cap","type":"uint256"}],"name":"Vote","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_voter","type":"address"},{"indexed":false,"name":"_candidate","type":"address"},{"indexed":false,"name":"_cap","type":"uint256"}],"name":"Unvote","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_owner","type":"address"},{"indexed":false,"name":"_candidate","type":"address"},{"indexed":false,"name":"_cap","type":"uint256"}],"name":"Propose","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_owner","type":"address"},{"indexed":false,"name":"_candidate","type":"address"}],"name":"Resign","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_owner","type":"address"},{"indexed":false,"name":"_blockNumber","type":"uint256"},{"indexed":false,"name":"_cap","type":"uint256"}],"name":"Withdraw","type":"event"}]`
// sets defaults on the config
func setDefaults(cfg *Config) {
if cfg.ChainConfig == nil {
cfg.ChainConfig = &params.ChainConfig{
ChainId: big.NewInt(1),
HomesteadBlock: new(big.Int),
DAOForkBlock: new(big.Int),
DAOForkSupport: false,
EIP150Block: new(big.Int),
EIP155Block: new(big.Int),
EIP158Block: new(big.Int),
}
}
if cfg.Difficulty == nil {
cfg.Difficulty = new(big.Int)
}
if cfg.Time == nil {
cfg.Time = big.NewInt(time.Now().Unix())
}
if cfg.GasLimit == 0 {
cfg.GasLimit = math.MaxUint64
}
if cfg.GasPrice == nil {
cfg.GasPrice = new(big.Int)
}
if cfg.Value == nil {
cfg.Value = new(big.Int)
}
if cfg.BlockNumber == nil {
cfg.BlockNumber = new(big.Int)
}
if cfg.GetHashFn == nil {
cfg.GetHashFn = func(n uint64) common.Hash {
return common.BytesToHash(crypto.Keccak256([]byte(new(big.Int).SetUint64(n).String())))
}
}
}
// Execute executes the code using the input as call data during the execution.
// It returns the EVM's return value, the new state and an error if it failed.
//
// Executes sets up a in memory, temporarily, environment for the execution of
// the given code. It makes sure that it's restored to it's original state afterwards.
/*
func Execute(code, input []byte, cfg *Config) ([]byte, *state.StateDB, error) {
if cfg == nil {
cfg = new(Config)
}
setDefaults(cfg)
if cfg.State == nil {
db, _ := ethdb.NewMemDatabase()
cfg.State, _ = state.New(common.Hash{}, state.NewDatabase(db))
}
var (
address = common.StringToAddress("contract")
vmenv = NewEnv(cfg)
sender = vm.AccountRef(cfg.Origin)
)
cfg.State.CreateAccount(address)
// set the receiver's (the executing contract) code for execution.
cfg.State.SetCode(address, code)
// Call the code with the given configuration.
ret, _, err := vmenv.Call(
sender,
common.StringToAddress("contract"),
input,
cfg.GasLimit,
cfg.Value,
)
return ret, cfg.State, err
}
*/
func NewRuntimeEVM(chainState *state.StateDB) *vm.EVM {
cfg := new(Config)
setDefaults(cfg)
db, _ := ethdb.NewMemDatabase()
cfg.State, _ = state.New(common.Hash{}, state.NewDatabase(db))
var (
address = common.HexToAddress(common.MasternodeVotingSMC)
vmenv = NewEnv(cfg)
)
cfg.State.CreateAccount(address)
code := chainState.GetCode(common.HexToAddress(common.MasternodeVotingSMC))
cfg.State.SetCode(address, code)
f := func(key, val common.Hash) bool {
cfg.State.SetState(address, key, val)
return true
}
chainState.ForEachStorage(common.HexToAddress(common.MasternodeVotingSMC), f)
return vmenv
}
func GetVoters(candidate common.Address, vmenv *vm.EVM) ([]common.Address, error) {
abi, err := abi.JSON(strings.NewReader(abiValidator))
getVoters, err := abi.Pack("getVoters", candidate)
// Call the code with the given configuration.
voters, _, err := vmenv.Call(
vm.AccountRef(common.HexToAddress(common.MasternodeVotingSMC)),
common.HexToAddress(common.MasternodeVotingSMC),
getVoters,
math.MaxUint64,
new(big.Int),
)
ret := common.ExtractAddressFromBytes(voters)
return ret, err
}
func GetCandidateOwner(candidate common.Address, vmenv *vm.EVM) (common.Address, error) {
abi, err := abi.JSON(strings.NewReader(abiValidator))
getCandidateOwner, err := abi.Pack("getCandidateOwner", candidate)
// Call the code with the given configuration.
ret, _, err := vmenv.Call(
vm.AccountRef(common.HexToAddress(common.MasternodeVotingSMC)),
common.HexToAddress(common.MasternodeVotingSMC),
getCandidateOwner,
math.MaxUint64,
new(big.Int),
)
return common.BytesToAddress(ret), err
}
func GetCandidateCap(candidate common.Address, vmenv *vm.EVM) (*big.Int, error) {
abi, err := abi.JSON(strings.NewReader(abiValidator))
getCandidateCap, err := abi.Pack("getCandidateCap", candidate)
// Call the code with the given configuration.
ret, _, err := vmenv.Call(
vm.AccountRef(common.HexToAddress(common.MasternodeVotingSMC)),
common.HexToAddress(common.MasternodeVotingSMC),
getCandidateCap,
math.MaxUint64,
new(big.Int),
)
return new(big.Int).SetBytes(ret), err
}
func GetVoterCap(candidate common.Address, voter common.Address, vmenv *vm.EVM) (*big.Int, error) {
abi, err := abi.JSON(strings.NewReader(abiValidator))
getVoterCap, err := abi.Pack("getVoterCap", candidate, voter)
// Call the code with the given configuration.
ret, _, err := vmenv.Call(
vm.AccountRef(common.HexToAddress(common.MasternodeVotingSMC)),
common.HexToAddress(common.MasternodeVotingSMC),
getVoterCap,
math.MaxUint64,
new(big.Int),
)
return new(big.Int).SetBytes(ret), err
}

View file

@ -259,7 +259,7 @@ func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) {
for i := prevEpoc; i < blockNumberEpoc; i++ { for i := prevEpoc; i < blockNumberEpoc; i++ {
blockHeader := chain.GetHeaderByNumber(i) blockHeader := chain.GetHeaderByNumber(i)
if len(penSigners) > 0 { if len(penSigners) > 0 {
signedMasternodes, err := contracts.GetSignersFromContract(blockSignerAddr, client, blockHeader.Hash()) signedMasternodes, err := contracts.GetSignersFromContract(c, blockSignerAddr, client, blockHeader.Hash())
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -279,7 +279,8 @@ func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) {
} }
} }
} }
log.Debug("Time Calculated HookPenalty ", "block", blockNumberEpoc, "time", common.PrettyDuration(time.Since(start))) // log.Debug("Time Calculated HookPenalty ", "block", blockNumberEpoc, "time", common.PrettyDuration(time.Since(start)))
fmt.Println("Time Calculated HookPenalty ", "block", blockNumberEpoc, "time", common.PrettyDuration(time.Since(start)))
return penSigners, nil return penSigners, nil
} }
return []common.Address{}, nil return []common.Address{}, nil

View file

@ -865,15 +865,15 @@ func (s *PublicBlockChainAPI) rpcOutputBlock(b *types.Block, inclTx bool, fullTx
var filterSigners []common.Address var filterSigners []common.Address
finality := int32(0) finality := int32(0)
if b.Number().Int64() > 0 { if b.Number().Int64() > 0 {
engine := s.b.GetEngine()
addrBlockSigner := common.HexToAddress(common.BlockSigners) addrBlockSigner := common.HexToAddress(common.BlockSigners)
signers, err = contracts.GetSignersFromContract(addrBlockSigner, client, b.Hash()) signers, err = contracts.GetSignersFromContract(engine.(*posv.Posv), addrBlockSigner, client, b.Hash())
if err != nil { if err != nil {
log.Error("Fail to get signers from block signer SC.", "error", err) log.Error("Fail to get signers from block signer SC.", "error", err)
return nil, err return nil, err
} }
// Get block epoc latest. // Get block epoc latest.
if s.b.ChainConfig().Posv != nil { if s.b.ChainConfig().Posv != nil {
engine := s.b.GetEngine()
lastCheckpointNumber := rpc.BlockNumber(b.Number().Uint64() - (b.Number().Uint64() % s.b.ChainConfig().Posv.Epoch)) lastCheckpointNumber := rpc.BlockNumber(b.Number().Uint64() - (b.Number().Uint64() % s.b.ChainConfig().Posv.Epoch))
prevCheckpointBlock, _ := s.b.BlockByNumber(ctx, lastCheckpointNumber) prevCheckpointBlock, _ := s.b.BlockByNumber(ctx, lastCheckpointNumber)
if prevCheckpointBlock != nil { if prevCheckpointBlock != nil {