Merge pull request #380 from nguyenbatam/fix_duplicate_hook_reward

Fix duplicate hook reward & api get reward
This commit is contained in:
Tuna 2019-01-02 15:48:42 +07:00 committed by GitHub
commit 6645f23a80
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 66 additions and 76 deletions

View file

@ -1087,9 +1087,9 @@ func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *eth.Config) {
cfg.EnablePreimageRecording = ctx.GlobalBool(VMEnableDebugFlag.Name)
}
if ctx.GlobalIsSet(StoreRewardFlag.Name) {
cfg.StoreRewardFolder = filepath.Join(stack.DataDir(), "tomo", "rewards")
if _, err := os.Stat(cfg.StoreRewardFolder); os.IsNotExist(err) {
os.Mkdir(cfg.StoreRewardFolder, os.ModePerm)
common.StoreRewardFolder = filepath.Join(stack.DataDir(), "tomo", "rewards")
if _, err := os.Stat(common.StoreRewardFolder); os.IsNotExist(err) {
os.Mkdir(common.StoreRewardFolder, os.ModePerm)
}
}
// Override any default configs for hard coded networks.

View file

@ -18,3 +18,4 @@ const (
)
var IsTestnet bool = false
var StoreRewardFolder string

View file

@ -18,10 +18,13 @@ package posv
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math/big"
"math/rand"
"path/filepath"
"strconv"
"sync"
"time"
@ -215,7 +218,6 @@ type Posv struct {
signatures *lru.ARCCache // Signatures of recent blocks to speed up mining
validatorSignatures *lru.ARCCache // Signatures of recent blocks to speed up mining
verifiedHeaders *lru.ARCCache
rewards *lru.ARCCache
proposals map[common.Address]bool // Current list of proposals we are pushing
signer common.Address // Ethereum address of the signing key
@ -241,7 +243,6 @@ func New(config *params.PosvConfig, db ethdb.Database) *Posv {
signatures, _ := lru.NewARC(inmemorySnapshots)
validatorSignatures, _ := lru.NewARC(inmemorySnapshots)
verifiedHeaders, _ := lru.NewARC(inmemorySnapshots)
rewards, _ := lru.NewARC(inmemorySnapshots)
return &Posv{
config: &conf,
db: db,
@ -249,7 +250,6 @@ func New(config *params.PosvConfig, db ethdb.Database) *Posv {
signatures: signatures,
verifiedHeaders: verifiedHeaders,
validatorSignatures: validatorSignatures,
rewards: rewards,
proposals: make(map[common.Address]bool),
}
}
@ -850,11 +850,19 @@ func (c *Posv) Finalize(chain consensus.ChainReader, header *types.Header, state
rCheckpoint := chain.Config().Posv.RewardCheckpoint
if c.HookReward != nil && number%rCheckpoint == 0 {
err, rewardResults := c.HookReward(chain, state, header)
err, rewards := c.HookReward(chain, state, header)
if err != nil {
return nil, err
}
c.rewards.Add(header.Hash(), rewardResults)
if len(common.StoreRewardFolder) > 0 {
data, err := json.Marshal(rewards)
if err == nil {
err = ioutil.WriteFile(filepath.Join(common.StoreRewardFolder, header.Number.String()+"."+header.Hash().Hex()), data, 0644)
}
if err != nil {
log.Error("Error when save reward info ", "number", header.Number, "hash", header.Hash().Hex(), "err", err)
}
}
}
// the state remains as is and uncles are dropped
@ -1084,15 +1092,3 @@ func Hop(len, pre, cur int) int {
return len - 1
}
}
func (c *Posv) GetRewards(hash common.Hash) map[string]interface{} {
rewards, ok := c.rewards.Get(hash)
if !ok {
return nil
}
return rewards.(map[string]interface{})
}
func (c *Posv) InsertRewards(hash common.Hash, rewards map[string]interface{}) {
c.rewards.Add(hash, rewards)
}

View file

@ -144,7 +144,6 @@ type BlockChain struct {
badBlocks *lru.Cache // Bad block cache
IPCEndpoint string
Client *ethclient.Client // Global ipc client instance.
HookWriteRewards func(header *types.Header)
}
// NewBlockChain returns a fully initialised block chain using information
@ -1222,9 +1221,6 @@ func (bc *BlockChain) insertChain(chain types.Blocks) (int, []interface{}, []*ty
}
}
}
if bc.HookWriteRewards != nil {
bc.HookWriteRewards(block.Header())
}
}
// Append a single chain head event if we've progressed the chain
if lastCanon != nil && bc.CurrentBlock().Hash() == lastCanon.Hash() {
@ -1431,9 +1427,6 @@ func (bc *BlockChain) insertBlock(block *types.Block) ([]interface{}, []*types.L
events = append(events, ChainHeadEvent{block})
log.Debug("New ChainHeadEvent from fetcher ", "number", block.NumberU64(), "hash", block.Hash())
}
if bc.HookWriteRewards != nil {
bc.HookWriteRewards(block.Header())
}
return events, coalescedLogs, nil
}

View file

@ -18,8 +18,10 @@ package eth
import (
"context"
"github.com/ethereum/go-ethereum/consensus/posv"
"encoding/json"
"io/ioutil"
"math/big"
"path/filepath"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common"
@ -236,11 +238,25 @@ func (b *EthApiBackend) GetEngine() consensus.Engine {
}
func (s *EthApiBackend) GetRewardByHash(hash common.Hash) map[string]interface{} {
if c, ok := s.eth.Engine().(*posv.Posv); ok {
rewards := c.GetRewards(hash)
if rewards != nil {
header := s.eth.blockchain.GetHeaderByHash(hash)
if header != nil {
data, err := ioutil.ReadFile(filepath.Join(common.StoreRewardFolder, header.Number.String()+"."+header.Hash().Hex()))
if err == nil {
rewards := make(map[string]interface{})
err = json.Unmarshal(data, &rewards)
if err == nil {
return rewards
}
} else {
data, err = ioutil.ReadFile(filepath.Join(common.StoreRewardFolder, header.Number.String()+"."+header.HashNoValidator().Hex()))
if err == nil {
rewards := make(map[string]interface{})
err = json.Unmarshal(data, &rewards)
if err == nil {
return rewards
}
}
}
}
return make(map[string]interface{})
}

View file

@ -18,12 +18,9 @@
package eth
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math/big"
"path/filepath"
"runtime"
"sync"
"sync/atomic"
@ -369,27 +366,6 @@ func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) {
}
return false
}
eth.blockchain.HookWriteRewards = func(header *types.Header) {
if len(config.StoreRewardFolder) > 0 {
rewards := c.GetRewards(header.Hash())
if rewards == nil {
rewards = c.GetRewards(header.HashNoValidator())
if rewards != nil {
c.InsertRewards(header.Hash(), rewards)
}
}
if rewards == nil {
return
}
data, err := json.Marshal(rewards)
if err == nil {
err = ioutil.WriteFile(filepath.Join(config.StoreRewardFolder, header.Number.String()+"."+header.Hash().Hex()), data, 0644)
}
if err != nil {
log.Error("Error when save reward info ", "number", header.Number, "hash", header.Hash().Hex(), "err", err)
}
}
}
}
return eth, nil
}

View file

@ -114,8 +114,6 @@ type Config struct {
// Miscellaneous options
DocRoot string `toml:"-"`
StoreRewardFolder string
}
type configMarshaling struct {

View file

@ -494,13 +494,7 @@ func (s *PublicBlockChainAPI) BlockNumber() *big.Int {
// BlockNumber returns the block number of the chain head.
func (s *PublicBlockChainAPI) GetRewardByHash(hash common.Hash) map[string]interface{} {
if c, ok := s.b.GetEngine().(*posv.Posv); ok {
rewards := c.GetRewards(hash)
if rewards != nil {
return rewards
}
}
return make(map[string]interface{})
return s.b.GetRewardByHash(hash)
}
// GetBalance returns the amount of wei for the given address in the state of the

View file

@ -18,8 +18,10 @@ package les
import (
"context"
"github.com/ethereum/go-ethereum/consensus/posv"
"encoding/json"
"io/ioutil"
"math/big"
"path/filepath"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common"
@ -202,11 +204,25 @@ func (b *LesApiBackend) GetEngine() consensus.Engine {
return b.eth.engine
}
func (s *LesApiBackend) GetRewardByHash(hash common.Hash) map[string]interface{} {
if c, ok := s.eth.Engine().(*posv.Posv); ok {
rewards := c.GetRewards(hash)
if rewards != nil {
header := s.eth.blockchain.GetHeaderByHash(hash)
if header != nil {
data, err := ioutil.ReadFile(filepath.Join(common.StoreRewardFolder, header.Number.String()+"."+header.Hash().Hex()))
if err == nil {
rewards := make(map[string]interface{})
err = json.Unmarshal(data, &rewards)
if err == nil {
return rewards
}
} else {
data, err = ioutil.ReadFile(filepath.Join(common.StoreRewardFolder, header.Number.String()+"."+header.HashNoValidator().Hex()))
if err == nil {
rewards := make(map[string]interface{})
err = json.Unmarshal(data, &rewards)
if err == nil {
return rewards
}
}
}
}
return make(map[string]interface{})
}

View file

@ -612,12 +612,12 @@ func (self *worker) commitNewWork() {
delete(self.possibleUncles, hash)
}
}
if atomic.LoadInt32(&self.mining) == 1 {
// Create the new block to seal with the consensus engine
if work.Block, err = self.engine.Finalize(self.chain, header, work.state, work.txs, uncles, work.receipts); err != nil {
log.Error("Failed to finalize block for sealing", "err", err)
return
}
if atomic.LoadInt32(&self.mining) == 1 {
log.Info("Committing new block", "number", work.Block.Number(), "txs", work.tcount, "special txs", len(specialTxs), "uncles", len(uncles), "elapsed", common.PrettyDuration(time.Since(tstart)))
self.unconfirmed.Shift(work.Block.NumberU64() - 1)
self.lastParentBlockCommit = parent.Hash().Hex()