Files
prysm/beacon-chain/node/node.go
Raul Jordan 75521fffbd Implement ListBeaconCommittees RPC Method (#3977)
* Update seed domains (#3872)

* Remove Transfers (#3870)

* Remove active index roots and compact committee roots (#3869)

* Update inclusion reward (#3886)

* Alter proposer selection logic (#3884)

* Fix early committee bias (#3888)

* Remove shards and committees (#3896)

* Epoch spec tests v0.9 (#3907)

* Block spec test v0.9 (#3905)

* rm'ed in protobuf

* build proto

* build proto

* build proto

* fix core package

* Gazelle

* Fixed all the tests

* Fixed static test

* Comment out spec test for now

* One more skip

* fix-roundRobinSync (#3862)

* Starting but need new seed function

* Revert initial sync

* Updated Proposer Slashing

* Fixed all tests

* Lint

* Update inclusion reward

* Fill randao mixes with eth1 data hash

* Test

* Fixing test part1

* All tests passing

* One last test

* Updated config

* Build proto

* Proper skip message

* Conflict and fmt

* Removed crosslinks and shards. Built

* Format and gazelle

* Fixed all the block package tests

* Fixed all the helper tests

* All epoch package tests pass

* All core package tests pass

* Fixed operation tests

* Started fixing rpc test

* RPC tests passed!

* Fixed all init sync tests

* All tests pass

* Fixed blockchain tests

* Lint

* Lint

* Preston's feedback

* Starting

* Remove container

* Fixed block spec tests

* All passing except for block_processing test

* Failing block processing test

* Starting

* Add AggregateAndProof

* All mainnet test passes

* Update deposit contract (#3906)

* Proto spec tests v0.9 (#3908)

* Starting

* Add AggregateAndProof

* Unskip block util tests (#3910)

* rm'ed in protobuf

* build proto

* build proto

* build proto

* fix core package

* Gazelle

* Fixed all the tests

* Fixed static test

* Comment out spec test for now

* One more skip

* fix-roundRobinSync (#3862)

* Starting but need new seed function

* Revert initial sync

* Updated Proposer Slashing

* Fixed all tests

* Lint

* Update inclusion reward

* Fill randao mixes with eth1 data hash

* Test

* Fixing test part1

* All tests passing

* One last test

* Updated config

* Build proto

* Proper skip message

* Conflict and fmt

* Removed crosslinks and shards. Built

* Format and gazelle

* Fixed all the block package tests

* Fixed all the helper tests

* All epoch package tests pass

* All core package tests pass

* Fixed operation tests

* Started fixing rpc test

* RPC tests passed!

* Fixed all init sync tests

* All tests pass

* Fixed blockchain tests

* Lint

* Lint

* Preston's feedback

* Starting

* Remove container

* Fixed block spec tests

* All passing except for block_processing test

* Failing block processing test

* Starting

* Add AggregateAndProof

* All mainnet test passes

* Unskip block util tests

* Slot processing spec test V0.9 (#3912)

* Starting

* Add AggregateAndProof

* Unskip slot processing mainnet test

* Unskip minimal spec test for finalization (#3920)

* Remove outdated interop tests (#3922)

* Rm outdated interop tests

* Rm test runner

* Gazelle

* Update validator to use proposer slot (#3919)

* Fix committee assignment (#3931)

* Replace shard with committee index (#3930)

* Conflict

* Clean up (#3933)

* Remove shard filter in db (#3936)

* Remove lightouse compatibility test (#3939)

* Update Committee Cache for v0.9 (#3948)

* Updated committee cache

* Removed shuffled indices cache

* Started testing run time

* Lint

* Fixed test

* Safeguard against nil head state

* address edge case

* add test

* Fixed TestRoundRobinSync by doubling the epochs

* Unskip TestProtoCompatability (#3958)

* Unskip TestProtoCompatability

* Update WORKSPACE

* Fix minimal config (#3959)

* fix minimal configs

* fix hardcoded value in test

* Simplify verify att time (#3961)

* update readme for deposit contract, regen bindings for vyper 0.1.0b12 (#3963)

* update readme for deposit contract, regen bindings

* medium

* Check nil base state (#3964)

* Copy Block When Receiving it From Sync (#3966)

* copy block

* clone for other service methods too

* Change logging of Bitfield  (#3956)

* change logging of bits

* preston's review

* Unskip Beacon Server Test (#3962)

* run test till the end

* fix up proto message types

* fmt

* resolve broken tests

* better error handling

* fixing new logic to use archived proposer info

* fix up logic

* clip using the max effective balance

* broken build fix with num arg mismatch

* amend archive

* archival logic changed

* rename test

* archive both proposer and attester seeds

* page size 100

* further experiments

* further experimentation, archivedProposerIndex seems wrong

* test passes

* rem log

* fix broken test

* fix test

* gaz

* fix imports

* ethapis

* setup request/response types for the committees

* list beacon committees impl

* beacon committees fetch from archive

* full list beacon committees implementation

* list beacon committees added more useful fields

* actually paginate

* attester server split into subpackage

* attester impl split up successfully

* validator cleaned up

* all packages isolated

* include proposer

* proper naming

* test fix

* proper viz

* naming

* resolved timeout due to config values

* init use minimal

* added all subfiles

* subfile split and gazelle

* shards

* validator folder

* cleanup val

* shay feedback

* initial pagination tests passing

* paginated tests pass

* fix bug regarding total count

* pagination tests pass

* adding final test, archive

* archive test works

* regen protos for archival

* resolve broken test

* test pass

* broken archive test

* rem helpers

* gaz

* fix kv test

* useful gRPC error code standards

* format

* resolved bad test

* test resolution

* ux improvements and bug fixes

* complete

* comments

* Update beacon-chain/archiver/service.go

* Update beacon-chain/rpc/beacon/committees.go

* elim bad test

* preston feedback
2019-11-12 23:32:42 -06:00

524 lines
15 KiB
Go

// Package node defines the services that a beacon chain node would perform.
package node
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"os"
"os/signal"
"path"
"path/filepath"
"strings"
"sync"
"syscall"
"github.com/ethereum/go-ethereum/common"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/beacon-chain/archiver"
"github.com/prysmaticlabs/prysm/beacon-chain/blockchain"
"github.com/prysmaticlabs/prysm/beacon-chain/cache/depositcache"
"github.com/prysmaticlabs/prysm/beacon-chain/db"
"github.com/prysmaticlabs/prysm/beacon-chain/flags"
"github.com/prysmaticlabs/prysm/beacon-chain/gateway"
interopcoldstart "github.com/prysmaticlabs/prysm/beacon-chain/interop-cold-start"
"github.com/prysmaticlabs/prysm/beacon-chain/operations"
"github.com/prysmaticlabs/prysm/beacon-chain/p2p"
"github.com/prysmaticlabs/prysm/beacon-chain/powchain"
"github.com/prysmaticlabs/prysm/beacon-chain/rpc"
prysmsync "github.com/prysmaticlabs/prysm/beacon-chain/sync"
initialsync "github.com/prysmaticlabs/prysm/beacon-chain/sync/initial-sync"
"github.com/prysmaticlabs/prysm/shared"
"github.com/prysmaticlabs/prysm/shared/cmd"
"github.com/prysmaticlabs/prysm/shared/debug"
"github.com/prysmaticlabs/prysm/shared/featureconfig"
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/prysmaticlabs/prysm/shared/prometheus"
"github.com/prysmaticlabs/prysm/shared/sliceutil"
"github.com/prysmaticlabs/prysm/shared/tracing"
"github.com/prysmaticlabs/prysm/shared/version"
"github.com/sirupsen/logrus"
"github.com/urfave/cli"
)
var log = logrus.WithField("prefix", "node")
const beaconChainDBName = "beaconchaindata"
const testSkipPowFlag = "test-skip-pow"
// BeaconNode defines a struct that handles the services running a random beacon chain
// full PoS node. It handles the lifecycle of the entire system and registers
// services to a service registry.
type BeaconNode struct {
ctx *cli.Context
services *shared.ServiceRegistry
lock sync.RWMutex
stop chan struct{} // Channel to wait for termination notifications.
db db.Database
depositCache *depositcache.DepositCache
}
// NewBeaconNode creates a new node instance, sets up configuration options, and registers
// every required service to the node.
func NewBeaconNode(ctx *cli.Context) (*BeaconNode, error) {
if err := tracing.Setup(
"beacon-chain", // service name
ctx.GlobalString(cmd.TracingProcessNameFlag.Name),
ctx.GlobalString(cmd.TracingEndpointFlag.Name),
ctx.GlobalFloat64(cmd.TraceSampleFractionFlag.Name),
ctx.GlobalBool(cmd.EnableTracingFlag.Name),
); err != nil {
return nil, err
}
featureconfig.ConfigureBeaconChain(ctx)
registry := shared.NewServiceRegistry()
beacon := &BeaconNode{
ctx: ctx,
services: registry,
stop: make(chan struct{}),
}
// Use custom config values if the --no-custom-config flag is set.
if !ctx.GlobalBool(flags.NoCustomConfigFlag.Name) {
if featureconfig.Get().MinimalConfig {
log.WithField(
"config", "minimal-spec",
).Info("Using custom chain parameters")
params.UseMinimalConfig()
} else {
log.WithField(
"config", "demo",
).Info("Using custom chain parameters")
params.UseDemoBeaconConfig()
}
}
if err := beacon.startDB(ctx); err != nil {
return nil, err
}
if err := beacon.registerP2P(ctx); err != nil {
return nil, err
}
if err := beacon.registerPOWChainService(ctx); err != nil {
return nil, err
}
if err := beacon.registerOperationService(ctx); err != nil {
return nil, err
}
if err := beacon.registerInteropServices(ctx); err != nil {
return nil, err
}
if err := beacon.registerBlockchainService(ctx); err != nil {
return nil, err
}
if err := beacon.registerInitialSyncService(ctx); err != nil {
return nil, err
}
if err := beacon.registerSyncService(ctx); err != nil {
return nil, err
}
if err := beacon.registerRPCService(ctx); err != nil {
return nil, err
}
if err := beacon.registerGRPCGateway(ctx); err != nil {
return nil, err
}
if err := beacon.registerArchiverService(ctx); err != nil {
return nil, err
}
if !ctx.GlobalBool(cmd.DisableMonitoringFlag.Name) {
if err := beacon.registerPrometheusService(ctx); err != nil {
return nil, err
}
}
return beacon, nil
}
// Start the BeaconNode and kicks off every registered service.
func (b *BeaconNode) Start() {
b.lock.Lock()
log.WithFields(logrus.Fields{
"version": version.GetVersion(),
}).Info("Starting beacon node")
b.services.StartAll()
stop := b.stop
b.lock.Unlock()
go func() {
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(sigc)
<-sigc
log.Info("Got interrupt, shutting down...")
debug.Exit(b.ctx) // Ensure trace and CPU profile data are flushed.
go b.Close()
for i := 10; i > 0; i-- {
<-sigc
if i > 1 {
log.Info("Already shutting down, interrupt more to panic", "times", i-1)
}
}
panic("Panic closing the beacon node")
}()
// Wait for stop channel to be closed.
<-stop
}
// Close handles graceful shutdown of the system.
func (b *BeaconNode) Close() {
b.lock.Lock()
defer b.lock.Unlock()
log.Info("Stopping beacon node")
b.services.StopAll()
if err := b.db.Close(); err != nil {
log.Errorf("Failed to close database: %v", err)
}
close(b.stop)
}
func (b *BeaconNode) startDB(ctx *cli.Context) error {
baseDir := ctx.GlobalString(cmd.DataDirFlag.Name)
dbPath := path.Join(baseDir, beaconChainDBName)
clearDB := ctx.GlobalBool(cmd.ClearDB.Name)
forceClearDB := ctx.GlobalBool(cmd.ForceClearDB.Name)
d, err := db.NewDB(dbPath)
if err != nil {
return err
}
if clearDB || forceClearDB {
d, err = confirmDelete(d, dbPath, forceClearDB)
if err != nil {
return err
}
}
log.WithField("database-path", dbPath).Info("Checking DB")
b.db = d
b.depositCache = depositcache.NewDepositCache()
return nil
}
func (b *BeaconNode) registerP2P(ctx *cli.Context) error {
// Bootnode ENR may be a filepath to an ENR file.
bootnodeAddrs := strings.Split(ctx.GlobalString(cmd.BootstrapNode.Name), ",")
for i, addr := range bootnodeAddrs {
if filepath.Ext(addr) == ".enr" {
b, err := ioutil.ReadFile(addr)
if err != nil {
return err
}
bootnodeAddrs[i] = string(b)
}
}
svc, err := p2p.NewService(&p2p.Config{
NoDiscovery: ctx.GlobalBool(cmd.NoDiscovery.Name),
StaticPeers: sliceutil.SplitCommaSeparated(ctx.GlobalStringSlice(cmd.StaticPeers.Name)),
BootstrapNodeAddr: bootnodeAddrs,
RelayNodeAddr: ctx.GlobalString(cmd.RelayNode.Name),
DataDir: ctx.GlobalString(cmd.DataDirFlag.Name),
HostAddress: ctx.GlobalString(cmd.P2PHost.Name),
PrivateKey: ctx.GlobalString(cmd.P2PPrivKey.Name),
TCPPort: ctx.GlobalUint(cmd.P2PTCPPort.Name),
UDPPort: ctx.GlobalUint(cmd.P2PUDPPort.Name),
MaxPeers: ctx.GlobalUint(cmd.P2PMaxPeers.Name),
WhitelistCIDR: ctx.GlobalString(cmd.P2PWhitelist.Name),
EnableUPnP: ctx.GlobalBool(cmd.EnableUPnPFlag.Name),
Encoding: ctx.GlobalString(cmd.P2PEncoding.Name),
})
if err != nil {
return err
}
return b.services.RegisterService(svc)
}
func (b *BeaconNode) fetchP2P(ctx *cli.Context) p2p.P2P {
var p *p2p.Service
if err := b.services.FetchService(&p); err != nil {
panic(err)
}
return p
}
func (b *BeaconNode) registerBlockchainService(ctx *cli.Context) error {
var web3Service *powchain.Service
if err := b.services.FetchService(&web3Service); err != nil {
return err
}
var opsService *operations.Service
if err := b.services.FetchService(&opsService); err != nil {
return err
}
maxRoutines := ctx.GlobalInt64(cmd.MaxGoroutines.Name)
blockchainService, err := blockchain.NewService(context.Background(), &blockchain.Config{
BeaconDB: b.db,
DepositCache: b.depositCache,
ChainStartFetcher: web3Service,
OpsPoolService: opsService,
P2p: b.fetchP2P(ctx),
MaxRoutines: maxRoutines,
})
if err != nil {
return errors.Wrap(err, "could not register blockchain service")
}
return b.services.RegisterService(blockchainService)
}
func (b *BeaconNode) registerOperationService(ctx *cli.Context) error {
operationService := operations.NewService(context.Background(), &operations.Config{
BeaconDB: b.db,
})
return b.services.RegisterService(operationService)
}
func (b *BeaconNode) registerPOWChainService(cliCtx *cli.Context) error {
if cliCtx.GlobalBool(testSkipPowFlag) {
return b.services.RegisterService(&powchain.Service{})
}
depAddress := cliCtx.GlobalString(flags.DepositContractFlag.Name)
if depAddress == "" {
var err error
depAddress, err = fetchDepositContract()
if err != nil {
log.WithError(err).Fatal("Cannot fetch deposit contract")
}
}
if !common.IsHexAddress(depAddress) {
log.Fatalf("Invalid deposit contract address given: %s", depAddress)
}
ctx := context.Background()
cfg := &powchain.Web3ServiceConfig{
ETH1Endpoint: cliCtx.GlobalString(flags.Web3ProviderFlag.Name),
HTTPEndPoint: cliCtx.GlobalString(flags.HTTPWeb3ProviderFlag.Name),
DepositContract: common.HexToAddress(depAddress),
BeaconDB: b.db,
DepositCache: b.depositCache,
}
web3Service, err := powchain.NewService(ctx, cfg)
if err != nil {
return errors.Wrap(err, "could not register proof-of-work chain web3Service")
}
knownContract, err := b.db.DepositContractAddress(ctx)
if err != nil {
return err
}
if len(knownContract) > 0 && !bytes.Equal(cfg.DepositContract.Bytes(), knownContract) {
return fmt.Errorf("database contract is %#x but tried to run with %#x", knownContract, cfg.DepositContract.Bytes())
}
return b.services.RegisterService(web3Service)
}
func (b *BeaconNode) registerSyncService(ctx *cli.Context) error {
var operationService *operations.Service
if err := b.services.FetchService(&operationService); err != nil {
return err
}
var web3Service *powchain.Service
if err := b.services.FetchService(&web3Service); err != nil {
return err
}
var chainService *blockchain.Service
if err := b.services.FetchService(&chainService); err != nil {
return err
}
var initSync *initialsync.InitialSync
if err := b.services.FetchService(&initSync); err != nil {
return err
}
rs := prysmsync.NewRegularSync(&prysmsync.Config{
DB: b.db,
P2P: b.fetchP2P(ctx),
Operations: operationService,
Chain: chainService,
InitialSync: initSync,
})
return b.services.RegisterService(rs)
}
func (b *BeaconNode) registerInitialSyncService(ctx *cli.Context) error {
var chainService *blockchain.Service
if err := b.services.FetchService(&chainService); err != nil {
return err
}
is := initialsync.NewInitialSync(&initialsync.Config{
DB: b.db,
Chain: chainService,
P2P: b.fetchP2P(ctx),
})
return b.services.RegisterService(is)
}
func (b *BeaconNode) registerRPCService(ctx *cli.Context) error {
var chainService *blockchain.Service
if err := b.services.FetchService(&chainService); err != nil {
return err
}
var operationService *operations.Service
if err := b.services.FetchService(&operationService); err != nil {
return err
}
var web3Service *powchain.Service
if err := b.services.FetchService(&web3Service); err != nil {
return err
}
var syncService *initialsync.InitialSync
if err := b.services.FetchService(&syncService); err != nil {
return err
}
genesisValidators := ctx.GlobalUint64(flags.InteropNumValidatorsFlag.Name)
genesisStatePath := ctx.GlobalString(flags.InteropGenesisStateFlag.Name)
var depositFetcher depositcache.DepositFetcher
var chainStartFetcher powchain.ChainStartFetcher
if genesisValidators > 0 || genesisStatePath != "" {
var interopService *interopcoldstart.Service
if err := b.services.FetchService(&interopService); err != nil {
return err
}
depositFetcher = interopService
chainStartFetcher = interopService
} else {
depositFetcher = b.depositCache
chainStartFetcher = web3Service
}
port := ctx.GlobalString(flags.RPCPort.Name)
cert := ctx.GlobalString(flags.CertFlag.Name)
key := ctx.GlobalString(flags.KeyFlag.Name)
mockEth1DataVotes := ctx.GlobalBool(flags.InteropMockEth1DataVotesFlag.Name)
rpcService := rpc.NewService(context.Background(), &rpc.Config{
Port: port,
CertFlag: cert,
KeyFlag: key,
BeaconDB: b.db,
Broadcaster: b.fetchP2P(ctx),
HeadFetcher: chainService,
ForkFetcher: chainService,
FinalizationFetcher: chainService,
BlockReceiver: chainService,
AttestationReceiver: chainService,
StateFeedListener: chainService,
GenesisTimeFetcher: chainService,
AttestationsPool: operationService,
OperationsHandler: operationService,
POWChainService: web3Service,
ChainStartFetcher: chainStartFetcher,
MockEth1Votes: mockEth1DataVotes,
SyncService: syncService,
DepositFetcher: depositFetcher,
PendingDepositFetcher: b.depositCache,
})
return b.services.RegisterService(rpcService)
}
func (b *BeaconNode) registerPrometheusService(ctx *cli.Context) error {
var additionalHandlers []prometheus.Handler
var p *p2p.Service
if err := b.services.FetchService(&p); err != nil {
panic(err)
}
additionalHandlers = append(additionalHandlers, prometheus.Handler{Path: "/p2p", Handler: p.InfoHandler})
var c *blockchain.Service
if err := b.services.FetchService(&c); err != nil {
panic(err)
}
additionalHandlers = append(additionalHandlers, prometheus.Handler{Path: "/heads", Handler: c.HeadsHandler})
if featureconfig.Get().EnableBackupWebhook {
additionalHandlers = append(additionalHandlers, prometheus.Handler{Path: "/db/backup", Handler: db.BackupHandler(b.db)})
}
service := prometheus.NewPrometheusService(
fmt.Sprintf(":%d", ctx.GlobalInt64(cmd.MonitoringPortFlag.Name)),
b.services,
additionalHandlers...,
)
hook := prometheus.NewLogrusCollector()
logrus.AddHook(hook)
return b.services.RegisterService(service)
}
func (b *BeaconNode) registerGRPCGateway(ctx *cli.Context) error {
gatewayPort := ctx.GlobalInt(flags.GRPCGatewayPort.Name)
if gatewayPort > 0 {
selfAddress := fmt.Sprintf("127.0.0.1:%d", ctx.GlobalInt(flags.RPCPort.Name))
gatewayAddress := fmt.Sprintf("0.0.0.0:%d", gatewayPort)
return b.services.RegisterService(gateway.New(context.Background(), selfAddress, gatewayAddress, nil /*optional mux*/))
}
return nil
}
func (b *BeaconNode) registerInteropServices(ctx *cli.Context) error {
genesisTime := ctx.GlobalUint64(flags.InteropGenesisTimeFlag.Name)
genesisValidators := ctx.GlobalUint64(flags.InteropNumValidatorsFlag.Name)
genesisStatePath := ctx.GlobalString(flags.InteropGenesisStateFlag.Name)
if genesisValidators > 0 || genesisStatePath != "" {
svc := interopcoldstart.NewColdStartService(context.Background(), &interopcoldstart.Config{
GenesisTime: genesisTime,
NumValidators: genesisValidators,
BeaconDB: b.db,
DepositCache: b.depositCache,
GenesisPath: genesisStatePath,
})
return b.services.RegisterService(svc)
}
return nil
}
func (b *BeaconNode) registerArchiverService(ctx *cli.Context) error {
shouldArchive := ctx.GlobalBool(flags.ArchiveEnableFlag.Name)
if !shouldArchive {
return nil
}
var chainService *blockchain.Service
if err := b.services.FetchService(&chainService); err != nil {
return err
}
svc := archiver.NewArchiverService(context.Background(), &archiver.Config{
BeaconDB: b.db,
HeadFetcher: chainService,
NewHeadNotifier: chainService,
})
return b.services.RegisterService(svc)
}