Skip to content

Commit

Permalink
Remove Deprecated Spec Logic (#1138)
Browse files Browse the repository at this point in the history
* no more deprecated stuff

* remove incentive functions

* rem deprecated

* remove funcs
  • Loading branch information
rauljordan authored Dec 20, 2018
1 parent 6eb2d81 commit 6125c30
Show file tree
Hide file tree
Showing 18 changed files with 217 additions and 1,779 deletions.
4 changes: 1 addition & 3 deletions beacon-chain/blockchain/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,11 @@ go_library(
importpath = "github.com/prysmaticlabs/prysm/beacon-chain/blockchain",
visibility = ["//beacon-chain:__subpackages__"],
deps = [
"//beacon-chain/core/blocks:go_default_library",
"//beacon-chain/core/state:go_default_library",
"//beacon-chain/core/types:go_default_library",
"//beacon-chain/core/validators:go_default_library",
"//beacon-chain/db:go_default_library",
"//beacon-chain/powchain:go_default_library",
"//beacon-chain/utils:go_default_library",
"//shared/bitutil:go_default_library",
"//shared/event:go_default_library",
"//shared/params:go_default_library",
"@com_github_ethereum_go_ethereum//common:go_default_library",
Expand Down
173 changes: 3 additions & 170 deletions beacon-chain/blockchain/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,19 @@
package blockchain

import (
"bytes"
"context"
"errors"
"fmt"
"time"

"github.com/ethereum/go-ethereum/common"
gethTypes "github.com/ethereum/go-ethereum/core/types"
b "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
"github.com/prysmaticlabs/prysm/beacon-chain/core/state"

"github.com/prysmaticlabs/prysm/beacon-chain/core/types"
v "github.com/prysmaticlabs/prysm/beacon-chain/core/validators"
"github.com/prysmaticlabs/prysm/beacon-chain/db"
"github.com/prysmaticlabs/prysm/beacon-chain/powchain"
"github.com/prysmaticlabs/prysm/beacon-chain/utils"
"github.com/prysmaticlabs/prysm/shared/bitutil"
"github.com/prysmaticlabs/prysm/shared/event"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/sirupsen/logrus"
Expand Down Expand Up @@ -363,7 +361,7 @@ func (c *ChainService) isBlockReadyForProcessing(block *types.Block) bool {
powBlockFetcher = c.web3Service.Client().BlockByHash
}

if err := state.IsValidBlock(c.ctx, beaconState, block, c.enablePOWChain,
if err := b.IsValidBlock(c.ctx, beaconState, block, c.enablePOWChain,
c.beaconDB.HasBlock, powBlockFetcher, c.genesisTime); err != nil {
log.Debugf("block does not fulfill pre-processing conditions %v", err)
return false
Expand All @@ -381,168 +379,3 @@ func (c *ChainService) sendAndDeleteCachedBlocks(currentSlot uint64) {
delete(c.unProcessedBlocks, currentSlot)
}
}

// DEPRECATED: Will be replaced by new block processing method
func (c *ChainService) processBlockOld(block *types.Block) error {
blockHash, err := block.Hash()
if err != nil {
return fmt.Errorf("failed to get hash of block: %v", err)
}

parent, err := c.beaconDB.GetBlock(block.ParentHash())
if err != nil {
return fmt.Errorf("could not get parent block: %v", err)
}
if parent == nil {
return fmt.Errorf("block points to nil parent: %#x", block.ParentHash())
}

beaconState, err := c.beaconDB.GetState()
if err != nil {
return fmt.Errorf("failed to get beacon state: %v", err)
}

if c.enablePOWChain && !c.doesPoWBlockExist(beaconState.ProcessedPowReceiptRootHash32()) {
return errors.New("proof-of-Work chain reference in block does not exist")
}

// Verifies the block against the validity conditions specifies as part of the
// Ethereum 2.0 specification.
if err := state.IsValidBlockOld(
block,
beaconState,
parent.SlotNumber(),
c.genesisTime,
c.beaconDB.HasBlock,
); err != nil {
return fmt.Errorf("block failed validity conditions: %v", err)
}

if err := c.calculateNewBlockVotes(block, beaconState); err != nil {
return fmt.Errorf("failed to calculate block vote cache: %v", err)
}

// First, include new attestations to the active state
// so that they're accounted for during cycle transitions.
beaconState.SetPendingAttestations(block.Attestations())

// If the block is valid, we compute its associated state tuple (active, crystallized)
beaconState, err = c.executeStateTransitionOld(beaconState, block, parent.SlotNumber())
if err != nil {
return fmt.Errorf("initialize new cycle transition failed: %v", err)
}

if err := c.beaconDB.SaveBlock(block); err != nil {
return fmt.Errorf("failed to save block: %v", err)
}
if err := c.beaconDB.SaveUnfinalizedBlockState(beaconState); err != nil {
return fmt.Errorf("error persisting unfinalized block's state: %v", err)
}

log.WithField("hash", fmt.Sprintf("%#x", blockHash)).Info("Processed beacon block")

// We keep a map of unfinalized blocks in memory along with their state
// pair to apply the fork choice rule.
c.unfinalizedBlocks[blockHash] = beaconState

return nil
}

// DEPRECATED: Will be removed soon
func (c *ChainService) executeStateTransitionOld(
beaconState *types.BeaconState,
block *types.Block,
parentSlot uint64,
) (*types.BeaconState, error) {
log.WithField("slotNumber", block.SlotNumber()).Info("Executing state transition")
blockVoteCache, err := c.beaconDB.ReadBlockVoteCache(beaconState.LatestBlockRootHashes32())
if err != nil {
return nil, err
}
newState, err := state.NewStateTransition(beaconState, block, parentSlot, blockVoteCache)
if err != nil {
return nil, err
}
if newState.IsValidatorSetChange(block.SlotNumber()) {
log.WithField("slotNumber", block.SlotNumber()).Info("Validator set rotation occurred")
}
return newState, nil
}

func (c *ChainService) calculateNewBlockVotes(block *types.Block, beaconState *types.BeaconState) error {
for _, attestation := range block.Attestations() {
parentHashes, err := beaconState.SignedParentHashes(block, attestation)
if err != nil {
return err
}
shardCommittees, err := v.GetShardAndCommitteesForSlot(
beaconState.ShardAndCommitteesForSlots(),
beaconState.LastStateRecalculationSlot(),
attestation.GetSlot(),
)
if err != nil {
return fmt.Errorf("unable to fetch ShardAndCommittees for slot %d: %v", attestation.Slot, err)
}
attesterIndices, err := v.AttesterIndices(shardCommittees, attestation)
if err != nil {
return err
}

// Read block vote cache from DB.
var blockVoteCache utils.BlockVoteCache
if blockVoteCache, err = c.beaconDB.ReadBlockVoteCache(parentHashes); err != nil {
return err
}

// Update block vote cache.
for _, h := range parentHashes {
// Skip calculating for this hash if the hash is part of oblique parent hashes.
var skip bool
for _, oblique := range attestation.ObliqueParentHashes {
if bytes.Equal(h[:], oblique) {
skip = true
break
}
}
if skip {
continue
}

// Initialize vote cache of a given block hash if it doesn't exist already.
if !blockVoteCache.IsVoteCacheExist(h) {
blockVoteCache[h] = utils.NewBlockVote()
}

// Loop through attester indices, if the attester has voted but was not accounted for
// in the cache, then we add attester's index and balance to the block cache.
for i, attesterIndex := range attesterIndices {
var attesterExists bool
isBitSet, err := bitutil.CheckBit(attestation.AttesterBitfield, i)
if err != nil {
log.Errorf("Bitfield check for cache adding failed at index: %d with: %v", i, err)
}

if !isBitSet {
continue
}
for _, indexInCache := range blockVoteCache[h].VoterIndices {
if attesterIndex == indexInCache {
attesterExists = true
break
}
}
if !attesterExists {
blockVoteCache[h].VoterIndices = append(blockVoteCache[h].VoterIndices, attesterIndex)
blockVoteCache[h].VoteTotalDeposit += beaconState.ValidatorRegistry()[attesterIndex].Balance
}
}
}

// Write updated block vote cache back to DB.
if err = c.beaconDB.WriteBlockVoteCache(blockVoteCache); err != nil {
return err
}
}

return nil
}
44 changes: 0 additions & 44 deletions beacon-chain/blockchain/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -446,47 +446,3 @@ func TestIsBlockReadyForProcessing(t *testing.T) {
}

}

func TestUpdateBlockVoteCache(t *testing.T) {
db := internal.SetupDB(t)
defer internal.TeardownDB(t, db)
chainService := setupBeaconChain(t, true, db)

beaconState, err := types.NewGenesisBeaconState(nil)
if err != nil {
t.Fatalf("failed to initialize genesis state: %v", err)
}
block := types.NewBlock(&pb.BeaconBlock{
Slot: 1,
ParentRootHash32: []byte{},
Attestations: []*pb.AggregatedAttestation{
{
Slot: 0,
Shard: 1,
AttesterBitfield: []byte{'F', 'F'},
},
},
})

err = chainService.calculateNewBlockVotes(block, beaconState)
if err != nil {
t.Errorf("failed to update the block vote cache: %v", err)
}
}

func TestUpdateBlockVoteCacheNoAttestations(t *testing.T) {
db := internal.SetupDB(t)
defer internal.TeardownDB(t, db)
chainService := setupBeaconChain(t, true, db)

beaconState, err := types.NewGenesisBeaconState(nil)
if err != nil {
t.Fatalf("failed to initialize genesis state: %v", err)
}
block := types.NewBlock(nil)

err = chainService.calculateNewBlockVotes(block, beaconState)
if err != nil {
t.Errorf("failed to update the block vote cache: %v", err)
}
}
16 changes: 14 additions & 2 deletions beacon-chain/core/blocks/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")

go_library(
name = "go_default_library",
srcs = ["block_operations.go"],
srcs = [
"block_operations.go",
"validity_conditions.go",
],
importpath = "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks",
visibility = ["//beacon-chain:__subpackages__"],
deps = [
Expand All @@ -11,16 +14,25 @@ go_library(
"//proto/beacon/p2p/v1:go_default_library",
"//shared/params:go_default_library",
"//shared/slices:go_default_library",
"@com_github_ethereum_go_ethereum//common:go_default_library",
"@com_github_ethereum_go_ethereum//core/types:go_default_library",
],
)

go_test(
name = "go_default_test",
srcs = ["block_operations_test.go"],
srcs = [
"block_operations_test.go",
"validity_conditions_test.go",
],
embed = [":go_default_library"],
deps = [
"//beacon-chain/core/types:go_default_library",
"//beacon-chain/utils:go_default_library",
"//proto/beacon/p2p/v1:go_default_library",
"//shared/params:go_default_library",
"@com_github_ethereum_go_ethereum//common:go_default_library",
"@com_github_ethereum_go_ethereum//core/types:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library",
],
)
66 changes: 66 additions & 0 deletions beacon-chain/core/blocks/validity_conditions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package blocks

import (
"context"
"fmt"
"time"

"github.com/ethereum/go-ethereum/common"
gethTypes "github.com/ethereum/go-ethereum/core/types"
"github.com/prysmaticlabs/prysm/beacon-chain/core/types"
)

// IsValidBlock ensures that the block is compliant with the block processing validity conditions.
// Spec:
// For a beacon chain block, block, to be processed by a node, the following conditions must be met:
// The parent block with root block.parent_root has been processed and accepted.
// The node has processed its state up to slot, block.slot - 1.
// The Ethereum 1.0 block pointed to by the state.processed_pow_receipt_root has been processed and accepted.
// The node's local clock time is greater than or equal to state.genesis_time + block.slot * SLOT_DURATION.
func IsValidBlock(
ctx context.Context,
state *types.BeaconState,
block *types.Block,
enablePOWChain bool,
HasBlock func(hash [32]byte) bool,
GetPOWBlock func(ctx context.Context, hash common.Hash) (*gethTypes.Block, error),
genesisTime time.Time) error {

// Pre-Processing Condition 1:
// Check that the parent Block has been processed and saved.
parentBlock := HasBlock(block.ParentHash())
if !parentBlock {
return fmt.Errorf("unprocessed parent block as it is not saved in the db: %#x", block.ParentHash())
}

// Pre-Processing Condition 2:
// The state is updated up to block.slot -1.

if state.Slot() != block.SlotNumber()-1 {
return fmt.Errorf(
"block slot is not valid %d as it is supposed to be %d", block.SlotNumber(), state.Slot()+1)
}

if enablePOWChain {
powBlock, err := GetPOWBlock(ctx, state.ProcessedPowReceiptRootHash32())
if err != nil {
return fmt.Errorf("unable to retrieve POW chain reference block %v", err)
}

// Pre-Processing Condition 3:
// The block pointed to by the state in state.processed_pow_receipt_root has
// been processed in the ETH 1.0 chain.
if powBlock == nil {
return fmt.Errorf("proof-of-Work chain reference in state does not exist %#x", state.ProcessedPowReceiptRootHash32())
}
}

// Pre-Processing Condition 4:
// The node's local time is greater than or equal to
// state.genesis_time + block.slot * SLOT_DURATION.
if !block.IsSlotValid(genesisTime) {
return fmt.Errorf("slot of block is too high: %d", block.SlotNumber())
}

return nil
}
Loading

0 comments on commit 6125c30

Please sign in to comment.