From 390ac62ed83700597864511e92cceb88e2842141 Mon Sep 17 00:00:00 2001 From: Ivan Martinez Date: Thu, 9 Aug 2018 14:25:48 -0400 Subject: [PATCH] Update docs client/beacon-chain wide (#386) --- beacon-chain/README.md | 7 +++-- beacon-chain/blockchain/core.go | 31 +++++++++++---------- beacon-chain/blockchain/core_test.go | 38 +++++++++++++------------- beacon-chain/blockchain/service.go | 26 ++++++++++-------- beacon-chain/main.go | 3 +- beacon-chain/node/node.go | 5 ++-- beacon-chain/node/node_test.go | 2 +- beacon-chain/params/config.go | 1 + beacon-chain/powchain/service.go | 14 ++++++---- beacon-chain/rpc/service.go | 9 +++++- beacon-chain/simulator/service.go | 3 +- beacon-chain/sync/service.go | 9 ++++-- beacon-chain/sync/service_test.go | 6 ++-- beacon-chain/types/block.go | 8 ++++-- beacon-chain/types/interfaces.go | 2 +- beacon-chain/types/state.go | 41 ++++++++++++++-------------- beacon-chain/utils/shuffle.go | 3 +- client/attester/attester.go | 1 - client/internal/client_helper.go | 1 + client/main.go | 3 +- client/mainchain/interfaces.go | 1 + client/mainchain/utils.go | 3 +- client/node/node.go | 11 ++++++-- client/node/node_test.go | 2 +- client/rpcclient/service.go | 1 + client/syncer/service.go | 1 + client/types/shard.go | 1 + contracts/validator_registration.go | 1 - shared/cmd/flags.go | 1 + shared/p2p/peer.go | 2 +- shared/p2p/service.go | 2 +- shared/testutil/log.go | 1 + 32 files changed, 139 insertions(+), 101 deletions(-) diff --git a/beacon-chain/README.md b/beacon-chain/README.md index b2e205ba89..d08341f03d 100644 --- a/beacon-chain/README.md +++ b/beacon-chain/README.md @@ -1,9 +1,10 @@ # Prysmatic Labs Beacon Chain Implementation -This is the main project folder for the beacon chain implementation of Ethereum 2.0 in Golang by [Prysmatic Labs](https://prysmaticlabs.com). Before you begin, check out our [Contribution Guidelines](#contribution-guidelines) and join our active chat room on Gitter below: +This is the main project folder for the beacon chain implementation of Ethereum 2.0 in Golang by [Prysmatic Labs](https://prysmaticlabs.com). Before you begin, check out our [Contribution Guidelines](#contribution-guidelines) and join our active chat room on Discord or Gitter below: +[![Discord](https://user-images.githubusercontent.com/7288322/34471967-1df7808a-efbb-11e7-9088-ed0b04151291.png)](https://discord.gg/KSA7rPr) [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/prysmaticlabs/prysm?badge&utm_medium=badge&utm_campaign=pr-badge) -Also, read the latest sharding + casper [design spec](https://ethresear.ch/t/convenience-link-to-full-casper-chain-v2-spec/2332), this design spec serves as a source of truth for the beacon chain implementation we follow at prysmatic labs. +Also, read the latest sharding + casper [design spec](https://notes.ethereum.org/SCIg8AH5SA-O4C1G1LYZHQ), this design spec serves as a source of truth for the beacon chain implementation we follow at prysmatic labs. Refer this page on [why](http://email.mg2.substack.com/c/eJwlj9GOhCAMRb9G3jRQQPGBh5mM8xsbhKrsDGIAM9m_X9xN2qZtbpt7rCm4xvSjj5gLOTOmL-809CMbKXFaOKakIl4DZYr2AGyQIGjHOnWH22OiYnoIxmDijaBhhS6fcy7GvjobA9m0mSXOcnZq5GBqLkilXBZhBsus5ZK89VbKkRt-a-BZI6DzZ7iur1lQ953KJ9bemnxgahuQU9XJu6pFPdu8meT8vragzEjpMCwMGLlgLo6h5z1JumQTu4IJd4v15xqMf_8ZLP_Y1bSLdbnrD-LL71i2Kj7DLxaWWF4) -we are comibing sharding and casper together. +we are combining sharding and casper together. diff --git a/beacon-chain/blockchain/core.go b/beacon-chain/blockchain/core.go index bdf5c47531..d816e6fecc 100644 --- a/beacon-chain/blockchain/core.go +++ b/beacon-chain/blockchain/core.go @@ -34,7 +34,7 @@ type beaconState struct { CrystallizedState *types.CrystallizedState } -// NewBeaconChain initializes an instance using genesis state parameters if +// NewBeaconChain initializes a beacon chain using genesis state parameters if // none provided. func NewBeaconChain(db ethdb.Database) (*BeaconChain, error) { beaconChain := &BeaconChain{ @@ -88,33 +88,33 @@ func (b *BeaconChain) GenesisBlock() (*types.Block, error) { return types.NewGenesisBlock() } -// ActiveState exposes a getter to external services. +// ActiveState contains the current state of attestations and changes every block. func (b *BeaconChain) ActiveState() *types.ActiveState { return b.state.ActiveState } -// CrystallizedState exposes a getter to external services. +// CrystallizedState contains epoch dependent validator information, changes every epoch. func (b *BeaconChain) CrystallizedState() *types.CrystallizedState { return b.state.CrystallizedState } -// MutateActiveState allows external services to modify the active state. -func (b *BeaconChain) MutateActiveState(activeState *types.ActiveState) error { +// SetActiveState is a convenience method which sets and persists the active state on the beacon chain. +func (b *BeaconChain) SetActiveState(activeState *types.ActiveState) error { b.lock.Lock() defer b.lock.Unlock() b.state.ActiveState = activeState return b.PersistActiveState() } -// MutateCrystallizedState allows external services to modify the crystallized state. -func (b *BeaconChain) MutateCrystallizedState(crystallizedState *types.CrystallizedState) error { +// SetCrystallizedState is a convenience method which sets and persists the crystallized state on the beacon chain. +func (b *BeaconChain) SetCrystallizedState(crystallizedState *types.CrystallizedState) error { b.lock.Lock() defer b.lock.Unlock() b.state.CrystallizedState = crystallizedState return b.PersistCrystallizedState() } -// PersistActiveState stores proto encoding of the latest beacon chain active state into the db. +// PersistActiveState stores proto encoding of the current beacon chain active state into the db. func (b *BeaconChain) PersistActiveState() error { encodedState, err := b.ActiveState().Marshal() if err != nil { @@ -123,7 +123,7 @@ func (b *BeaconChain) PersistActiveState() error { return b.db.Put([]byte(activeStateLookupKey), encodedState) } -// PersistCrystallizedState stores proto encoding of the latest beacon chain crystallized state into the db. +// PersistCrystallizedState stores proto encoding of the current beacon chain crystallized state into the db. func (b *BeaconChain) PersistCrystallizedState() error { encodedState, err := b.CrystallizedState().Marshal() if err != nil { @@ -132,8 +132,8 @@ func (b *BeaconChain) PersistCrystallizedState() error { return b.db.Put([]byte(crystallizedStateLookupKey), encodedState) } -// IsEpochTransition checks if the current slotNumber divided by the epoch length(64 slots) -// is greater than the current epoch. +// IsEpochTransition checks if the current slotNumber divided +// by the epoch length (64 slots) is greater than the current epoch. func (b *BeaconChain) IsEpochTransition(slotNumber uint64) bool { currentEpoch := b.state.CrystallizedState.CurrentEpoch() isTransition := (slotNumber / params.EpochLength) > currentEpoch @@ -288,7 +288,7 @@ func (b *BeaconChain) calculateRewardsFFG() error { log.Info("Applying rewards and penalties for the validators from last epoch") for i := range activeValidators { - voted, err := b.voted(i) + voted, err := b.hasAttesterAtIndexVoted(i) if err != nil { return fmt.Errorf("exiting calculate rewards FFG due to %v", err) } @@ -305,7 +305,7 @@ func (b *BeaconChain) calculateRewardsFFG() error { log.Info("Resetting total attester deposit to zero") b.ActiveState().SetTotalAttesterDeposits(0) - b.CrystallizedState().UpdateActiveValidators(activeValidators) + b.CrystallizedState().SetActiveValidators(activeValidators) err := b.PersistActiveState() if err != nil { return err @@ -318,8 +318,8 @@ func (b *BeaconChain) calculateRewardsFFG() error { return nil } -// voted checks if a validator has voted by comparing its bit field. -func (b *BeaconChain) voted(index int) (bool, error) { +// hasAttesterAtIndexVoted checks if the attester at the passed index has voted by comparing its bit field. +func (b *BeaconChain) hasAttesterAtIndexVoted(index int) (bool, error) { bitfield := b.state.ActiveState.AttesterBitfield() attesterBlock := (index + 1) / 8 attesterFieldIndex := (index + 1) % 8 @@ -347,6 +347,7 @@ func (b *BeaconChain) resetAttesterBitfield() { b.state.ActiveState.SetAttesterBitfield(newbitfields) } +// saveBlock puts the passed block into the beacon chain db. func (b *BeaconChain) saveBlock(block *types.Block) error { encodedState, err := block.Marshal() if err != nil { diff --git a/beacon-chain/blockchain/core_test.go b/beacon-chain/blockchain/core_test.go index a4d081b8b5..82dd9ec8ed 100644 --- a/beacon-chain/blockchain/core_test.go +++ b/beacon-chain/blockchain/core_test.go @@ -66,7 +66,7 @@ func TestNewBeaconChain(t *testing.T) { } } -func TestMutateActiveState(t *testing.T) { +func TestSetActiveState(t *testing.T) { beaconChain, db := startInMemoryBeaconChain(t) defer db.Close() @@ -76,7 +76,7 @@ func TestMutateActiveState(t *testing.T) { } active := types.NewActiveState(data) - if err := beaconChain.MutateActiveState(active); err != nil { + if err := beaconChain.SetActiveState(active); err != nil { t.Fatalf("unable to mutate active state: %v", err) } if !reflect.DeepEqual(beaconChain.state.ActiveState, active) { @@ -98,7 +98,7 @@ func TestMutateActiveState(t *testing.T) { } } -func TestMutateCrystallizedState(t *testing.T) { +func TestSetCrystallizedState(t *testing.T) { beaconChain, db := startInMemoryBeaconChain(t) defer db.Close() @@ -108,7 +108,7 @@ func TestMutateCrystallizedState(t *testing.T) { } crystallized := types.NewCrystallizedState(data) - if err := beaconChain.MutateCrystallizedState(crystallized); err != nil { + if err := beaconChain.SetCrystallizedState(crystallized); err != nil { t.Fatalf("unable to mutate crystallized state: %v", err) } if !reflect.DeepEqual(beaconChain.state.CrystallizedState, crystallized) { @@ -142,8 +142,8 @@ func TestGetAttestersProposer(t *testing.T) { } _, crystallized := types.NewGenesisStates() - crystallized.UpdateActiveValidators(validators) - beaconChain.MutateCrystallizedState(crystallized) + crystallized.SetActiveValidators(validators) + beaconChain.SetCrystallizedState(crystallized) attesters, proposer, err := beaconChain.getAttestersProposer(common.Hash{'A'}) if err != nil { @@ -391,9 +391,9 @@ func TestRotateValidatorSet(t *testing.T) { {Balance: 99999, WithdrawalAddress: []byte{'O'}}, } - beaconChain.CrystallizedState().UpdateActiveValidators(activeValidators) - beaconChain.CrystallizedState().UpdateQueuedValidators(queuedValidators) - beaconChain.CrystallizedState().UpdateExitedValidators(exitedValidators) + beaconChain.CrystallizedState().SetActiveValidators(activeValidators) + beaconChain.CrystallizedState().SetQueuedValidators(queuedValidators) + beaconChain.CrystallizedState().SetExitedValidators(exitedValidators) if beaconChain.CrystallizedState().ActiveValidatorsLength() != 5 { t.Errorf("Get active validator count failed, wanted 5, got %v", beaconChain.CrystallizedState().ActiveValidatorsLength()) @@ -422,7 +422,7 @@ func TestIsEpochTransition(t *testing.T) { beaconChain, db := startInMemoryBeaconChain(t) defer db.Close() - if err := beaconChain.MutateCrystallizedState(types.NewCrystallizedState(&pb.CrystallizedState{CurrentEpoch: 1})); err != nil { + if err := beaconChain.SetCrystallizedState(types.NewCrystallizedState(&pb.CrystallizedState{CurrentEpoch: 1})); err != nil { t.Fatalf("unable to mutate crystallizedstate: %v", err) } if !beaconChain.IsEpochTransition(128) { @@ -441,7 +441,7 @@ func TestHasVoted(t *testing.T) { beaconChain.ActiveState().SetAttesterBitfield([]byte{255}) for i := 0; i < len(beaconChain.ActiveState().AttesterBitfield()); i++ { - voted, err := beaconChain.voted(i) + voted, err := beaconChain.hasAttesterAtIndexVoted(i) if err != nil { t.Errorf("checking bitfield for vote failed: %v", err) } @@ -454,7 +454,7 @@ func TestHasVoted(t *testing.T) { beaconChain.ActiveState().SetAttesterBitfield([]byte{85}) for i := 0; i < len(beaconChain.ActiveState().AttesterBitfield()); i++ { - voted, err := beaconChain.voted(i) + voted, err := beaconChain.hasAttesterAtIndexVoted(i) if err != nil { t.Errorf("checking bitfield for vote failed: %v", err) } @@ -480,10 +480,10 @@ func TestResetAttesterBitfields(t *testing.T) { validators = append(validators, validator) } - beaconChain.CrystallizedState().UpdateActiveValidators(validators) + beaconChain.CrystallizedState().SetActiveValidators(validators) testAttesterBitfield := []byte{2, 4, 6, 9} - if err := beaconChain.MutateActiveState(types.NewActiveState(&pb.ActiveState{AttesterBitfield: testAttesterBitfield})); err != nil { + if err := beaconChain.SetActiveState(types.NewActiveState(&pb.ActiveState{AttesterBitfield: testAttesterBitfield})); err != nil { t.Fatal("unable to mutate active state") } @@ -506,7 +506,7 @@ func TestResetTotalAttesterDeposit(t *testing.T) { defer db.Close() active := types.NewActiveState(&pb.ActiveState{TotalAttesterDeposits: 10000}) - if err := beaconChain.MutateActiveState(active); err != nil { + if err := beaconChain.SetActiveState(active); err != nil { t.Fatalf("unable to Mutate Active state: %v", err) } if beaconChain.state.ActiveState.TotalAttesterDeposits() != uint64(10000) { @@ -523,7 +523,7 @@ func TestUpdateJustifiedEpoch(t *testing.T) { defer db.Close() data := &pb.CrystallizedState{CurrentEpoch: 5, LastJustifiedEpoch: 4, LastFinalizedEpoch: 3} - beaconChain.MutateCrystallizedState(types.NewCrystallizedState(data)) + beaconChain.SetCrystallizedState(types.NewCrystallizedState(data)) if beaconChain.state.CrystallizedState.LastFinalizedEpoch() != uint64(3) || beaconChain.state.CrystallizedState.LastJustifiedEpoch() != uint64(4) || @@ -541,7 +541,7 @@ func TestUpdateJustifiedEpoch(t *testing.T) { } data = &pb.CrystallizedState{CurrentEpoch: 8, LastJustifiedEpoch: 4, LastFinalizedEpoch: 3} - beaconChain.MutateCrystallizedState(types.NewCrystallizedState(data)) + beaconChain.SetCrystallizedState(types.NewCrystallizedState(data)) if beaconChain.state.CrystallizedState.LastFinalizedEpoch() != uint64(3) || beaconChain.state.CrystallizedState.LastJustifiedEpoch() != uint64(4) || @@ -577,7 +577,7 @@ func TestComputeValidatorRewardsAndPenalties(t *testing.T) { LastJustifiedEpoch: 4, LastFinalizedEpoch: 3, } - if err := beaconChain.MutateCrystallizedState(types.NewCrystallizedState(data)); err != nil { + if err := beaconChain.SetCrystallizedState(types.NewCrystallizedState(data)); err != nil { t.Fatalf("unable to mutate crystallizedstate: %v", err) } @@ -585,7 +585,7 @@ func TestComputeValidatorRewardsAndPenalties(t *testing.T) { testAttesterBitfield := []byte{200, 148, 146, 179, 49} types.NewActiveState(&pb.ActiveState{AttesterBitfield: testAttesterBitfield}) ActiveState := types.NewActiveState(&pb.ActiveState{TotalAttesterDeposits: 40000, AttesterBitfield: testAttesterBitfield}) - if err := beaconChain.MutateActiveState(ActiveState); err != nil { + if err := beaconChain.SetActiveState(ActiveState); err != nil { t.Fatalf("unable to Mutate Active state: %v", err) } if err := beaconChain.calculateRewardsFFG(); err != nil { diff --git a/beacon-chain/blockchain/service.go b/beacon-chain/blockchain/service.go index e0fe4e4e57..6647b71b27 100644 --- a/beacon-chain/blockchain/service.go +++ b/beacon-chain/blockchain/service.go @@ -1,3 +1,4 @@ +// Package blockchain defines the life-cycle and status of the beacon chain. package blockchain import ( @@ -87,17 +88,17 @@ func (c *ChainService) HasStoredState() (bool, error) { return true, nil } -// ProcessedBlockHashes by the chain service. +// ProcessedBlockHashes exposes a getter for the processed block hashes of the chain. func (c *ChainService) ProcessedBlockHashes() [][32]byte { return c.processedBlockHashes } -// ProcessedCrystallizedStateHashes by the chain service. +// ProcessedCrystallizedStateHashes exposes a getter for the processed crystallized state hashes of the chain. func (c *ChainService) ProcessedCrystallizedStateHashes() [][32]byte { return c.processedCrystallizedStateHashes } -// ProcessedActiveStateHashes by the chain service. +// ProcessedActiveStateHashes exposes a getter for the processed active state hashes of the chain. func (c *ChainService) ProcessedActiveStateHashes() [][32]byte { return c.processedActiveStateHashes } @@ -126,6 +127,7 @@ func (c *ChainService) SaveBlock(block *types.Block) error { } // ProcessCrystallizedState accepts a new crystallized state object for inclusion in the chain. +// TODO: Implement crystallized state verifier function and apply fork choice rules func (c *ChainService) ProcessCrystallizedState(state *types.CrystallizedState) error { h, err := state.Hash() if err != nil { @@ -133,12 +135,11 @@ func (c *ChainService) ProcessCrystallizedState(state *types.CrystallizedState) } log.WithField("stateHash", fmt.Sprintf("0x%x", h)).Info("Received crystallized state, processing validity conditions") - // TODO: Implement crystallized state verifier function and apply fork choice rules - return nil } // ProcessActiveState accepts a new active state object for inclusion in the chain. +// TODO: Implement active state verifier function and apply fork choice rules func (c *ChainService) ProcessActiveState(state *types.ActiveState) error { h, err := state.Hash() if err != nil { @@ -146,27 +147,28 @@ func (c *ChainService) ProcessActiveState(state *types.ActiveState) error { } log.WithField("stateHash", fmt.Sprintf("0x%x", h)).Info("Received active state, processing validity conditions") - // TODO: Implement active state verifier function and apply fork choice rules - return nil } // ContainsBlock checks if a block for the hash exists in the chain. // This method must be safe to call from a goroutine +// +// TODO: implement function func (c *ChainService) ContainsBlock(h [32]byte) bool { - // TODO return false } // ContainsCrystallizedState checks if a crystallized state for the hash exists in the chain. +// +// TODO: implement function func (c *ChainService) ContainsCrystallizedState(h [32]byte) bool { - // TODO return false } // ContainsActiveState checks if a active state for the hash exists in the chain. +// +// TODO: implement function func (c *ChainService) ContainsActiveState(h [32]byte) bool { - // TODO return false } @@ -180,6 +182,8 @@ func (c *ChainService) CurrentActiveState() *types.ActiveState { return c.chain.ActiveState() } +// run processes the changes needed every beacon chain block, +// including epoch transition if needed. func (c *ChainService) run(done <-chan struct{}) { for { select { @@ -190,7 +194,7 @@ func (c *ChainService) run(done <-chan struct{}) { log.Errorf("Compute active state failed: %v", err) } - err = c.chain.MutateActiveState(activeState) + err = c.chain.SetActiveState(activeState) if err != nil { log.Errorf("Write active state to disk failed: %v", err) } diff --git a/beacon-chain/main.go b/beacon-chain/main.go index f2b4961b05..07cddf4d21 100644 --- a/beacon-chain/main.go +++ b/beacon-chain/main.go @@ -1,3 +1,4 @@ +// Package beacon-chain defines all the utlities needed for a beacon chain node. package main import ( @@ -21,7 +22,7 @@ func startNode(ctx *cli.Context) error { } logrus.SetLevel(level) - beacon, err := node.New(ctx) + beacon, err := node.NewBeaconNode(ctx) if err != nil { return err } diff --git a/beacon-chain/node/node.go b/beacon-chain/node/node.go index 2953f9cfce..9ee425388f 100644 --- a/beacon-chain/node/node.go +++ b/beacon-chain/node/node.go @@ -1,3 +1,4 @@ +// Package node defines the services that a beacon chain node would perform. package node import ( @@ -38,9 +39,9 @@ type BeaconNode struct { db *database.DB } -// New creates a new node instance, sets up configuration options, and registers +// NewBeaconNode creates a new node instance, sets up configuration options, and registers // every required service to the node. -func New(ctx *cli.Context) (*BeaconNode, error) { +func NewBeaconNode(ctx *cli.Context) (*BeaconNode, error) { registry := shared.NewServiceRegistry() beacon := &BeaconNode{ diff --git a/beacon-chain/node/node_test.go b/beacon-chain/node/node_test.go index 9560c60ab8..4728d0d0af 100644 --- a/beacon-chain/node/node_test.go +++ b/beacon-chain/node/node_test.go @@ -19,7 +19,7 @@ func TestNode_Builds(t *testing.T) { context := cli.NewContext(app, set, nil) - _, err := New(context) + _, err := NewBeaconNode(context) if err != nil { t.Fatalf("Failed to create BeaconNode: %v", err) } diff --git a/beacon-chain/params/config.go b/beacon-chain/params/config.go index 0dcaa09311..160dd92faa 100644 --- a/beacon-chain/params/config.go +++ b/beacon-chain/params/config.go @@ -1,3 +1,4 @@ +// Package params defines important constants that are essential to the beacon chain. package params const ( diff --git a/beacon-chain/powchain/service.go b/beacon-chain/powchain/service.go index 5194191d75..7e44bfb9d5 100644 --- a/beacon-chain/powchain/service.go +++ b/beacon-chain/powchain/service.go @@ -1,3 +1,4 @@ +// Package powchain defines the services that interact with the PoWChain of Ethereum. package powchain import ( @@ -47,7 +48,7 @@ type Web3ServiceConfig struct { } // NewWeb3Service sets up a new instance with an ethclient when -// given a web3 endpoint as a string. +// given a web3 endpoint as a string in the config. func NewWeb3Service(ctx context.Context, config *Web3ServiceConfig) (*Web3Service, error) { if !strings.HasPrefix(config.Endpoint, "ws") && !strings.HasPrefix(config.Endpoint, "ipc") { return nil, fmt.Errorf("web3service requires either an IPC or WebSocket endpoint, provided %s", config.Endpoint) @@ -90,6 +91,7 @@ func (w *Web3Service) Stop() error { return nil } +// run subscribes to all the services for the powchain. func (w *Web3Service) run(done <-chan struct{}) { headSub, err := w.reader.SubscribeNewHead(w.ctx, w.headerChan) if err != nil { @@ -141,22 +143,22 @@ func (w *Web3Service) run(done <-chan struct{}) { } } -// LatestBlockNumber is a getter for blockNumber to make it read-only. +// LatestBlockNumber in the PoWChain. func (w *Web3Service) LatestBlockNumber() *big.Int { return w.blockNumber } -// LatestBlockHash is a getter for blockHash to make it read-only. +// LatestBlockHash in the PoWChain. func (w *Web3Service) LatestBlockHash() common.Hash { return w.blockHash } -// ValidatorRegistered is a getter for validatorRegistered to make it read-only. -func (w *Web3Service) ValidatorRegistered() bool { +// IsValidatorRegistered in the PoWChain. +func (w *Web3Service) IsValidatorRegistered() bool { return w.validatorRegistered } -// Client returns the underlying web3 client. +// Client for interacting with the PoWChain. func (w *Web3Service) Client() types.POWChainClient { return w.client } diff --git a/beacon-chain/rpc/service.go b/beacon-chain/rpc/service.go index 9a1f01ead4..25ec29a93e 100644 --- a/beacon-chain/rpc/service.go +++ b/beacon-chain/rpc/service.go @@ -1,3 +1,4 @@ +// Package rpc defines the services that the beacon-chain uses to communicate via gRPC. package rpc import ( @@ -85,18 +86,24 @@ func (s *Service) Stop() error { } // ShuffleValidators shuffles the validators into attesters/proposers. +// +// TODO: needs to properly shuffle. func (s *Service) ShuffleValidators(req *pb.ShuffleRequest, stream pb.BeaconService_ShuffleValidatorsServer) error { return stream.Send(&pb.ShuffleResponse{IsProposer: true, IsAttester: false}) } // ProposeBlock is called by a proposer in a sharding client and a full beacon node -// the request into a beacon block that can then be included in a canonical chain. +// sends the request into a beacon block that can then be included in a canonical chain. +// +// TODO: needs implementation. func (s *Service) ProposeBlock(ctx context.Context, req *pb.ProposeRequest) (*pb.ProposeResponse, error) { return nil, nil } // SignBlock is a function called by an attester in a sharding client to sign off // on a block. +// +// TODO: needs implementation. func (s *Service) SignBlock(ctx context.Context, req *pb.SignRequest) (*pb.SignResponse, error) { return nil, nil } diff --git a/beacon-chain/simulator/service.go b/beacon-chain/simulator/service.go index 56eb620ba8..b5d0b9cd8d 100644 --- a/beacon-chain/simulator/service.go +++ b/beacon-chain/simulator/service.go @@ -1,3 +1,4 @@ +// Package simulator defines the simulation utility to test the beacon-chain. package simulator import ( @@ -104,7 +105,7 @@ func (sim *Simulator) run(delayChan <-chan time.Time, done <-chan struct{}) { validators = append(validators, validator) } - crystallizedState.UpdateActiveValidators(validators) + crystallizedState.SetActiveValidators(validators) crystallizedStateHash, err := crystallizedState.Hash() if err != nil { diff --git a/beacon-chain/sync/service.go b/beacon-chain/sync/service.go index 1975a4e8f3..da0534a99c 100644 --- a/beacon-chain/sync/service.go +++ b/beacon-chain/sync/service.go @@ -1,3 +1,4 @@ +// Package sync defines the utilities for the beacon-chain to sync with the network. package sync import ( @@ -120,7 +121,7 @@ func (ss *Service) Start() { switch ss.syncMode { case 0: log.Info("Starting initial sync") - go ss.initialSync(time.NewTicker(ss.syncPollingInterval).C, ss.ctx.Done()) + go ss.runInitialSync(time.NewTicker(ss.syncPollingInterval).C, ss.ctx.Done()) default: go ss.run(ss.ctx.Done()) @@ -208,6 +209,8 @@ func (ss *Service) ReceiveCrystallizedState(data *pb.CrystallizedState) error { // ReceiveActiveStateHash accepts a active state hash. // New hashes are forwarded to other peers in the network (unimplemented), and // the contents of the active hash are requested if the local chain doesn't have the hash. +// +// TODO: implement hash forwarding func (ss *Service) ReceiveActiveStateHash(data *pb.ActiveStateHashAnnounce, peer p2p.Peer) { var h [32]byte copy(h[:], data.Hash[:32]) @@ -222,6 +225,8 @@ func (ss *Service) ReceiveActiveStateHash(data *pb.ActiveStateHashAnnounce, peer // ReceiveActiveState accepts a active state object to potentially be included in the local chain. // The service will filter active state objects that have not been requested (unimplemented). +// +// TODO: implement filter for non requested state objects. func (ss *Service) ReceiveActiveState(data *pb.ActiveState) error { state := types.NewActiveState(data) @@ -311,7 +316,7 @@ func (ss *Service) writeBlockToDB(block *types.Block) error { return ss.chainService.SaveBlock(block) } -func (ss *Service) initialSync(delaychan <-chan time.Time, done <-chan struct{}) { +func (ss *Service) runInitialSync(delaychan <-chan time.Time, done <-chan struct{}) { blockSub := ss.p2p.Subscribe(pb.BeaconBlockResponse{}, ss.blockBuf) crystallizedStateSub := ss.p2p.Subscribe(pb.CrystallizedStateResponse{}, ss.crystallizedStateBuf) diff --git a/beacon-chain/sync/service_test.go b/beacon-chain/sync/service_test.go index 9964db5386..d0d45e150b 100644 --- a/beacon-chain/sync/service_test.go +++ b/beacon-chain/sync/service_test.go @@ -708,7 +708,7 @@ func TestSetBlockForInitialSync(t *testing.T) { delayChan := make(chan time.Time) go func() { - ss.initialSync(delayChan, ss.ctx.Done()) + ss.runInitialSync(delayChan, ss.ctx.Done()) exitRoutine <- true }() @@ -756,7 +756,7 @@ func TestSavingBlocksInSync(t *testing.T) { delayChan := make(chan time.Time) go func() { - ss.initialSync(delayChan, ss.ctx.Done()) + ss.runInitialSync(delayChan, ss.ctx.Done()) exitRoutine <- true }() @@ -853,7 +853,7 @@ func TestDelayChan(t *testing.T) { delayChan := make(chan time.Time) go func() { - ss.initialSync(delayChan, ss.ctx.Done()) + ss.runInitialSync(delayChan, ss.ctx.Done()) exitRoutine <- true }() diff --git a/beacon-chain/types/block.go b/beacon-chain/types/block.go index a776fcd209..4b3d801e94 100644 --- a/beacon-chain/types/block.go +++ b/beacon-chain/types/block.go @@ -1,3 +1,4 @@ +// Package types defines the essential types used throughout the beacon-chain. package types import ( @@ -35,13 +36,14 @@ func NewBlock(data *pb.BeaconBlock) (*Block, error) { } // NewGenesisBlock returns the canonical, genesis block for the beacon chain protocol. +// +// TODO: Add more default fields. func NewGenesisBlock() (*Block, error) { genesisTime := time.Date(2018, time.July, 21, 12, 0, 0, 0, time.UTC) protoGenesis, err := ptypes.TimestampProto(genesisTime) if err != nil { return nil, err } - // TODO: Add more default fields. return &Block{data: &pb.BeaconBlock{Timestamp: protoGenesis}}, nil } @@ -88,14 +90,14 @@ func (b *Block) RandaoReveal() [32]byte { return h } -// ActiveStateHash blake2b value. +// ActiveStateHash returns the active state hash. func (b *Block) ActiveStateHash() [32]byte { var h [32]byte copy(h[:], b.data.ActiveStateHash[:32]) return h } -// CrystallizedStateHash blake2b value. +// CrystallizedStateHash returns the crystallized state hash. func (b *Block) CrystallizedStateHash() [32]byte { var h [32]byte copy(h[:], b.data.CrystallizedStateHash[:32]) diff --git a/beacon-chain/types/interfaces.go b/beacon-chain/types/interfaces.go index 72b36d4154..760eb2cd22 100644 --- a/beacon-chain/types/interfaces.go +++ b/beacon-chain/types/interfaces.go @@ -68,7 +68,7 @@ type POWBlockFetcher interface { BlockByHash(ctx context.Context, hash common.Hash) (*gethTypes.Block, error) } -// Logger subscribe filtered log on the PoW chain +// Logger defines a struct that subscribes to filtered logs on the PoW chain. type Logger interface { SubscribeFilterLogs(ctx context.Context, q ethereum.FilterQuery, ch chan<- gethTypes.Log) (ethereum.Subscription, error) } diff --git a/beacon-chain/types/state.go b/beacon-chain/types/state.go index 24c9c76fd4..d08ee86399 100644 --- a/beacon-chain/types/state.go +++ b/beacon-chain/types/state.go @@ -9,7 +9,6 @@ import ( // ActiveState contains fields of current state of beacon chain, // it changes every block. -// TODO: Change ActiveState to use proto type ActiveState struct { data *pb.ActiveState } @@ -116,7 +115,7 @@ func (c *CrystallizedState) Hash() ([32]byte, error) { return blake2b.Sum256(data), nil } -// ActiveValidators returns list of validator that are active. +// ActiveValidators returns the list of active validators. func (c *CrystallizedState) ActiveValidators() []*pb.ValidatorRecord { return c.data.ActiveValidators } @@ -126,12 +125,12 @@ func (c *CrystallizedState) ActiveValidatorsLength() int { return len(c.data.ActiveValidators) } -// UpdateActiveValidators updates active validator set. -func (c *CrystallizedState) UpdateActiveValidators(validators []*pb.ValidatorRecord) { +// SetActiveValidators sets the active validator set. +func (c *CrystallizedState) SetActiveValidators(validators []*pb.ValidatorRecord) { c.data.ActiveValidators = validators } -// QueuedValidators returns list of validator that are queued. +// QueuedValidators returns the list of validators that are queued. func (c *CrystallizedState) QueuedValidators() []*pb.ValidatorRecord { return c.data.QueuedValidators } @@ -141,12 +140,12 @@ func (c *CrystallizedState) QueuedValidatorsLength() int { return len(c.data.QueuedValidators) } -// UpdateQueuedValidators updates queued validator set. -func (c *CrystallizedState) UpdateQueuedValidators(validators []*pb.ValidatorRecord) { +// SetQueuedValidators sets the queued validator set. +func (c *CrystallizedState) SetQueuedValidators(validators []*pb.ValidatorRecord) { c.data.QueuedValidators = validators } -// ExitedValidators returns list of validator that have exited. +// ExitedValidators returns the list of validators that have exited. func (c *CrystallizedState) ExitedValidators() []*pb.ValidatorRecord { return c.data.ExitedValidators } @@ -156,8 +155,8 @@ func (c *CrystallizedState) ExitedValidatorsLength() int { return len(c.data.ExitedValidators) } -// UpdateExitedValidators updates active validator set. -func (c *CrystallizedState) UpdateExitedValidators(validators []*pb.ValidatorRecord) { +// SetExitedValidators sets the exited validator set.. +func (c *CrystallizedState) SetExitedValidators(validators []*pb.ValidatorRecord) { c.data.ExitedValidators = validators } @@ -167,27 +166,27 @@ func (c *CrystallizedState) CurrentEpochShuffling() []uint64 { return c.data.CurrentEpochShuffling } -// CurrentEpoch of the beacon chain. +// CurrentEpoch returns the current epoch of the beacon chain. func (c *CrystallizedState) CurrentEpoch() uint64 { return c.data.CurrentEpoch } -// IncrementEpoch increments epoch by one. +// IncrementEpoch increments the epoch by one. func (c *CrystallizedState) IncrementEpoch() { c.data.CurrentEpoch++ } -// LastJustifiedEpoch of the beacon chain. +// LastJustifiedEpoch return the last justified epoch of the beacon chain. func (c *CrystallizedState) LastJustifiedEpoch() uint64 { return c.data.LastJustifiedEpoch } -// SetLastJustifiedEpoch sets last justified epoch of the beacon chain. +// SetLastJustifiedEpoch sets the last justified epoch of the beacon chain. func (c *CrystallizedState) SetLastJustifiedEpoch(epoch uint64) { c.data.LastJustifiedEpoch = epoch } -// LastFinalizedEpoch of the beacon chain. +// LastFinalizedEpoch returns the last finalized epoch of the beacon chain. func (c *CrystallizedState) LastFinalizedEpoch() uint64 { return c.data.LastFinalizedEpoch } @@ -197,32 +196,32 @@ func (c *CrystallizedState) SetLastFinalizedEpoch(epoch uint64) { c.data.LastFinalizedEpoch = epoch } -// CurrentDynasty of the beacon chain. +// CurrentDynasty returns the current dynasty of the beacon chain. func (c *CrystallizedState) CurrentDynasty() uint64 { return c.data.CurrentDynasty } -// NextShard crosslink assignment will be coming from. +// NextShard returns where the crosslink assignment will be coming from. func (c *CrystallizedState) NextShard() uint64 { return c.data.NextShard } -// CurrentCheckPoint for the FFG state. +// CurrentCheckPoint returns the current checkpoint for the FFG state. func (c *CrystallizedState) CurrentCheckPoint() common.Hash { return common.BytesToHash(c.data.CurrentCheckPoint) } -// TotalDeposits is combined deposits of all the validators. +// TotalDeposits returns the combined deposits of all the validators. func (c *CrystallizedState) TotalDeposits() uint64 { return c.data.TotalDeposits } -// DynastySeed is used to select the committee for each shard. +// DynastySeed returns the seed used to select the committee for each shard. func (c *CrystallizedState) DynastySeed() common.Hash { return common.BytesToHash(c.data.DynastySeed) } -// DynastySeedLastReset is the last epoch the crosslink seed was reset. +// DynastySeedLastReset is the last finalized epoch that the crosslink seed was reset. func (c *CrystallizedState) DynastySeedLastReset() uint64 { return c.data.DynastySeedLastReset } diff --git a/beacon-chain/utils/shuffle.go b/beacon-chain/utils/shuffle.go index 750fa51636..ac69b84794 100644 --- a/beacon-chain/utils/shuffle.go +++ b/beacon-chain/utils/shuffle.go @@ -1,3 +1,4 @@ +// Package utils defines utility functions for the beacon-chain. package utils import ( @@ -39,7 +40,7 @@ func ShuffleIndices(seed common.Hash, validatorCount int) ([]int, error) { // GetCutoffs is used to split up validators into groups at the start // of every epoch. It determines at what height validators can make -// attestations and crosslinks. It returns lists of cutoff indices. +// attestations and crosslinks. It returns a list of cutoff indices. func GetCutoffs(validatorCount int) []int { var heightCutoff = []int{0} var heights []int diff --git a/client/attester/attester.go b/client/attester/attester.go index 09e3c51548..e7188648ab 100644 --- a/client/attester/attester.go +++ b/client/attester/attester.go @@ -36,7 +36,6 @@ func checkSMCForAttester(caller mainchain.ContractCaller, account *accounts.Acco if addr == account.Address { log.Infof("Selected as attester on shard: %d", s) } - } return nil diff --git a/client/internal/client_helper.go b/client/internal/client_helper.go index 3d04ec6b74..e0601c9d6c 100644 --- a/client/internal/client_helper.go +++ b/client/internal/client_helper.go @@ -1,3 +1,4 @@ +// Package internal provides a MockClient for testing. package internal import ( diff --git a/client/main.go b/client/main.go index 2cf69cb7af..bcd5d1e207 100644 --- a/client/main.go +++ b/client/main.go @@ -1,3 +1,4 @@ +// Package client defines the required functionalities for the sharding client. package main import ( @@ -14,7 +15,7 @@ import ( ) func startNode(ctx *cli.Context) error { - shardingNode, err := node.New(ctx) + shardingNode, err := node.NewShardInstance(ctx) if err != nil { return err } diff --git a/client/mainchain/interfaces.go b/client/mainchain/interfaces.go index 30299cacaf..7b3c97fbf8 100644 --- a/client/mainchain/interfaces.go +++ b/client/mainchain/interfaces.go @@ -1,3 +1,4 @@ +// Package mainchain defines the interactions between the Ethereum mainchain and the client. package mainchain import ( diff --git a/client/mainchain/utils.go b/client/mainchain/utils.go index 2c1528525f..6ce73d16b7 100644 --- a/client/mainchain/utils.go +++ b/client/mainchain/utils.go @@ -12,7 +12,7 @@ import ( "github.com/prysmaticlabs/prysm/client/params" ) -// dialRPC endpoint to node. +// dialRPC dials the endpoint from the node. func dialRPC(endpoint string) (*rpc.Client, error) { if endpoint == "" { endpoint = node.DefaultIPCEndpoint(ClientIdentifier) @@ -30,6 +30,7 @@ func initSMC(s *SMCClient) (*contracts.SMC, error) { } // Deploy SMC for development only. + // // TODO: Separate contract deployment from the sharding node. It would only need to be deployed // once on the mainnet, so this code would not need to ship with the node. if len(b) == 0 { diff --git a/client/node/node.go b/client/node/node.go index ee3a4e3fd5..0205cf165c 100644 --- a/client/node/node.go +++ b/client/node/node.go @@ -48,9 +48,9 @@ type ShardEthereum struct { db *database.DB } -// New creates a new sharding-enabled Ethereum instance. This is called in the main +// NewShardInstance creates a new sharding-enabled Ethereum instance. This is called in the main // geth sharding entrypoint. -func New(ctx *cli.Context) (*ShardEthereum, error) { +func NewShardInstance(ctx *cli.Context) (*ShardEthereum, error) { registry := shared.NewServiceRegistry() shardEthereum := &ShardEthereum{ services: registry, @@ -159,6 +159,7 @@ func (s *ShardEthereum) registerP2P() error { return s.services.RegisterService(shardp2p) } +// registerMainchainClient registers the mainchain client to the shard services. func (s *ShardEthereum) registerMainchainClient(ctx *cli.Context) error { path := node.DefaultDataDir() if ctx.GlobalIsSet(cmd.DataDirFlag.Name) { @@ -204,7 +205,7 @@ func (s *ShardEthereum) registerTXPool(actor string) error { return s.services.RegisterService(pool) } -// Registers the actor according to CLI flags. Either attester/proposer/observer. +// registerActorService registers the actor according to CLI flags. Either attester/proposer/observer. func (s *ShardEthereum) registerActorService(config *params.Config, actor string, shardID int) error { var shardp2p *p2p.Server if err := s.services.FetchService(&shardp2p); err != nil { @@ -247,6 +248,9 @@ func (s *ShardEthereum) registerActorService(config *params.Config, actor string return s.services.RegisterService(obs) } } + +// registerSyncerService adds the p2p and mainchain services to the syncer and +// registers the syncer to the shard. func (s *ShardEthereum) registerSyncerService(config *params.Config, shardID int) error { var shardp2p *p2p.Server if err := s.services.FetchService(&shardp2p); err != nil { @@ -264,6 +268,7 @@ func (s *ShardEthereum) registerSyncerService(config *params.Config, shardID int return s.services.RegisterService(sync) } +// registersBeaconRPCService registers a new RPC client for the shard. func (s *ShardEthereum) registerBeaconRPCService(ctx *cli.Context) error { endpoint := ctx.GlobalString(types.BeaconRPCProviderFlag.Name) rpcService := rpcclient.NewRPCClient(context.TODO(), &rpcclient.Config{ diff --git a/client/node/node_test.go b/client/node/node_test.go index 3aca943e53..c91203c21a 100644 --- a/client/node/node_test.go +++ b/client/node/node_test.go @@ -14,7 +14,7 @@ func TestNode_Builds(t *testing.T) { set.String("datadir", "/tmp/datadir", "the node data directory") context := cli.NewContext(app, set, nil) - _, err := New(context) + _, err := NewShardInstance(context) if err != nil { t.Fatalf("Failed to create ShardEthereum: %v", err) } diff --git a/client/rpcclient/service.go b/client/rpcclient/service.go index b4ae06ea67..7f10212f75 100644 --- a/client/rpcclient/service.go +++ b/client/rpcclient/service.go @@ -1,3 +1,4 @@ +// Package rpcclient defines the services for the RPC connections of the client. package rpcclient import ( diff --git a/client/syncer/service.go b/client/syncer/service.go index 3abd3af843..055eb44b8c 100644 --- a/client/syncer/service.go +++ b/client/syncer/service.go @@ -1,3 +1,4 @@ +// Package syncer defines a service that handles the requests/responses between nodes. package syncer import ( diff --git a/client/types/shard.go b/client/types/shard.go index 16fc5cd70c..69c51cbc27 100644 --- a/client/types/shard.go +++ b/client/types/shard.go @@ -1,3 +1,4 @@ +// Package types defines the types used throughout the client. package types import ( diff --git a/contracts/validator_registration.go b/contracts/validator_registration.go index 10abc32fd9..a935577605 100644 --- a/contracts/validator_registration.go +++ b/contracts/validator_registration.go @@ -1,6 +1,5 @@ // Code generated - DO NOT EDIT. // This file is a generated binding and any manual changes will be lost. - package contracts import ( diff --git a/shared/cmd/flags.go b/shared/cmd/flags.go index d4a155bda7..ab037b3769 100644 --- a/shared/cmd/flags.go +++ b/shared/cmd/flags.go @@ -1,3 +1,4 @@ +// Package cmd defines the command line flags for the shared utlities. package cmd import ( diff --git a/shared/p2p/peer.go b/shared/p2p/peer.go index 61d1670a75..d38778a23e 100644 --- a/shared/p2p/peer.go +++ b/shared/p2p/peer.go @@ -1,6 +1,6 @@ package p2p -// Peer TODO - Design and implement. +// Peer TODO: - Design and implement. // See design doc: https://docs.google.com/document/d/1cthKuGPreOSQH96Ujt7sArcT-IRICk6b-QcdD0EnLsI/edit // https://github.com/prysmaticlabs/prysm/issues/175 type Peer struct{} diff --git a/shared/p2p/service.go b/shared/p2p/service.go index 21155e5118..ffca9f30cb 100644 --- a/shared/p2p/service.go +++ b/shared/p2p/service.go @@ -111,7 +111,7 @@ func (s *Server) Send(msg interface{}, peer Peer) { // Broadcast a message to the world. func (s *Server) Broadcast(msg interface{}) { - // TODO https://github.com/prysmaticlabs/prysm/issues/176 + // TODO: https://github.com/prysmaticlabs/prysm/issues/176 topic := topic(msg) log.WithFields(logrus.Fields{ "topic": topic, diff --git a/shared/testutil/log.go b/shared/testutil/log.go index 9cf1041b50..8b2054bfbb 100644 --- a/shared/testutil/log.go +++ b/shared/testutil/log.go @@ -1,3 +1,4 @@ +// Package testutil defines the testing utils such as asserting logs. package testutil import (