[blockchain] Create fresh big int, remove more dead code from static … (#2749)

* [blockchain] Create fresh big int, remove more dead code from static analysis

* [measure] Remove IzZero/IsNil checks
pull/2758/head
Edgar Aroutiounian 5 years ago committed by GitHub
parent 191f1d5ee2
commit ba1c0cd0a3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 36
      core/blockchain.go
  2. 40
      core/chain_makers.go
  3. 42
      core/tx_cacher.go
  4. 28
      core/tx_pool_test.go
  5. 5
      staking/availability/measure.go

@ -138,7 +138,6 @@ type BlockChain struct {
pendingCrossLinksMutex sync.RWMutex // pending crosslinks lock
pendingSlashingCandidatesMU sync.RWMutex // pending slashing candidates
checkpoint int // checkpoint counts towards the new checkpoint
currentBlock atomic.Value // Current head of the block chain
currentFastBlock atomic.Value // Current head of the fast-sync chain (may be above the block chain!)
@ -1590,26 +1589,6 @@ func (bc *BlockChain) InsertHeaderChain(chain []*block.Header, checkFreq int) (i
return bc.hc.InsertHeaderChain(chain, whFunc, start)
}
// writeHeader writes a header into the local chain, given that its parent is
// already known. If the total difficulty of the newly inserted header becomes
// greater than the current known TD, the canonical chain is re-routed.
//
// Note: This method is not concurrent-safe with inserting blocks simultaneously
// into the chain, as side effects caused by reorganisations cannot be emulated
// without the real blocks. Hence, writing headers directly should only be done
// in two scenarios: pure-header mode of operation (light clients), or properly
// separated header/block phases (non-archive clients).
func (bc *BlockChain) writeHeader(header *block.Header) error {
bc.wg.Add(1)
defer bc.wg.Done()
bc.mu.Lock()
defer bc.mu.Unlock()
_, err := bc.hc.WriteHeader(header)
return err
}
// CurrentHeader retrieves the current head header of the canonical chain. The
// header is retrieved from the HeaderChain's internal cache.
func (bc *BlockChain) CurrentHeader() *block.Header {
@ -2180,10 +2159,7 @@ func (bc *BlockChain) IsSpent(cxp *types.CXReceiptsProof) bool {
shardID := cxp.MerkleProof.ShardID
blockNum := cxp.MerkleProof.BlockNum.Uint64()
by, _ := rawdb.ReadCXReceiptsProofSpent(bc.db, shardID, blockNum)
if by == rawdb.SpentByte {
return true
}
return false
return by == rawdb.SpentByte
}
// ReadTxLookupEntry returns where the given transaction resides in the chain,
@ -2349,7 +2325,7 @@ func (bc *BlockChain) UpdateValidatorVotingPower(
for i := range value {
earningWrapping[i] = staking.VoteWithCurrentEpochEarning{
Vote: value[i],
Earned: common.Big0,
Earned: big.NewInt(0),
}
}
stats.MetricsPerShard = earningWrapping
@ -2714,7 +2690,7 @@ func (bc *BlockChain) addDelegationIndex(
// If there is an existing delegation, just return
validatorAddressBytes := validatorAddress.Bytes()
for _, delegation := range delegations {
if bytes.Compare(delegation.ValidatorAddress.Bytes(), validatorAddressBytes) == 0 {
if bytes.Equal(delegation.ValidatorAddress[:], validatorAddressBytes[:]) {
return delegations, nil
}
}
@ -2726,7 +2702,9 @@ func (bc *BlockChain) addDelegationIndex(
return delegations, err
}
for i := range wrapper.Delegations {
if bytes.Compare(wrapper.Delegations[i].DelegatorAddress.Bytes(), delegatorAddress.Bytes()) == 0 {
if bytes.Equal(
wrapper.Delegations[i].DelegatorAddress[:], delegatorAddress[:],
) {
// TODO(audit): change the way of indexing if we allow delegation deletion.
delegations = append(delegations, staking.DelegationIndex{
validatorAddress,
@ -2778,7 +2756,7 @@ func (bc *BlockChain) GetECDSAFromCoinbase(header *block.Header) (common.Address
}
for _, member := range committee.Slots {
// After staking the coinbase address will be the address of bls public key
if bytes.Compare(member.EcdsaAddress[:], coinbase[:]) == 0 {
if bytes.Equal(member.EcdsaAddress[:], coinbase[:]) {
return member.EcdsaAddress, nil
}

@ -37,21 +37,18 @@ import (
// BlockGen creates blocks for testing.
// See GenerateChain for a detailed explanation.
type BlockGen struct {
i int
parent *types.Block
chain []*types.Block
factory blockfactory.Factory
header *block.Header
statedb *state.DB
i int
parent *types.Block
chain []*types.Block
factory blockfactory.Factory
header *block.Header
statedb *state.DB
gasPool *GasPool
txs []*types.Transaction
stkTxs staking.StakingTransactions
receipts []*types.Receipt
uncles []*block.Header
config *params.ChainConfig
engine consensus_engine.Engine
config *params.ChainConfig
engine consensus_engine.Engine
}
// SetCoinbase sets the coinbase of the generated block.
@ -248,27 +245,8 @@ func makeHeader(chain consensus_engine.ChainReader, parent *types.Block, state *
Header()
}
// makeHeaderChain creates a deterministic chain of headers rooted at parent.
func makeHeaderChain(parent *block.Header, n int, engine consensus_engine.Engine, db ethdb.Database, seed int) []*block.Header {
blocks := makeBlockChain(types.NewBlockWithHeader(parent), n, engine, db, seed)
headers := make([]*block.Header, len(blocks))
for i, block := range blocks {
headers[i] = block.Header()
}
return headers
}
// makeBlockChain creates a deterministic chain of blocks rooted at parent.
func makeBlockChain(parent *types.Block, n int, engine consensus_engine.Engine, db ethdb.Database, seed int) []*types.Block {
blocks, _ := GenerateChain(params.TestChainConfig, parent, engine, db, n, func(i int, b *BlockGen) {
b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)})
})
return blocks
}
type fakeChainReader struct {
config *params.ChainConfig
genesis *types.Block
config *params.ChainConfig
}
// Config returns the chain configuration.

@ -17,14 +17,9 @@
package core
import (
"runtime"
"github.com/ethereum/go-ethereum/core/types"
)
// senderCacher is a concurrent transaction sender recoverer anc cacher.
var senderCacher = newTxSenderCacher(runtime.NumCPU())
// txSenderCacherRequest is a request for recovering transaction senders with a
// specific signature scheme and caching it into the transactions themselves.
//
@ -66,40 +61,3 @@ func (cacher *txSenderCacher) cache() {
}
}
}
// recover recovers the senders from a batch of transactions and caches them
// back into the same data structures. There is no validation being done, nor
// any reaction to invalid signatures. That is up to calling code later.
func (cacher *txSenderCacher) recover(signer types.Signer, txs []*types.Transaction) {
// If there's nothing to recover, abort
if len(txs) == 0 {
return
}
// Ensure we have meaningful task sizes and schedule the recoveries
tasks := cacher.threads
if len(txs) < tasks*4 {
tasks = (len(txs) + 3) / 4
}
for i := 0; i < tasks; i++ {
cacher.tasks <- &txSenderCacherRequest{
signer: signer,
txs: txs[i:],
inc: tasks,
}
}
}
// recoverFromBlocks recovers the senders from a batch of blocks and caches them
// back into the same data structures. There is no validation being done, nor
// any reaction to invalid signatures. That is up to calling code later.
func (cacher *txSenderCacher) recoverFromBlocks(signer types.Signer, blocks []*types.Block) {
count := 0
for _, block := range blocks {
count += len(block.Transactions())
}
txs := make([]*types.Transaction, 0, count)
for _, block := range blocks {
txs = append(txs, block.Transactions()...)
}
cacher.recover(signer, txs)
}

@ -176,34 +176,6 @@ func validateTxPoolInternals(pool *TxPool) error {
return nil
}
// validateEvents checks that the correct number of transaction addition events
// were fired on the pool's event feed.
func validateEvents(events chan NewTxsEvent, count int) error {
var received []*types.Transaction
for len(received) < count {
select {
case ev := <-events:
received = append(received, ev.Txs...)
case <-time.After(time.Second):
return fmt.Errorf("event #%d not fired", len(received))
}
}
if len(received) > count {
return fmt.Errorf("more than %d events fired: %v", count, received[count:])
}
select {
case ev := <-events:
return fmt.Errorf("more than %d events fired: %v", count, ev.Txs)
case <-time.After(50 * time.Millisecond):
// This branch should be "default", but it's a data race between goroutines,
// reading the event channel and pushing into it, so better wait a bit ensuring
// really nothing gets injected.
}
return nil
}
func deriveSender(tx types.PoolTransaction) (common.Address, error) {
return types.PoolTransactionSender(types.HomesteadSigner{}, tx)
}

@ -185,11 +185,6 @@ func ComputeCurrentSigning(
}
s1, s2 := numeric.NewDecFromBigInt(signed), numeric.NewDecFromBigInt(toSign)
if s2.IsZero() || s2.IsNil() {
utils.Logger().Debug().Interface("s2", s2).
Msg("s2 is 0 or nil")
return computed
}
computed.Percentage = s1.Quo(s2)
computed.IsBelowThreshold = IsBelowSigningThreshold(computed.Percentage)
return computed

Loading…
Cancel
Save