prysm-pulse/testing/endtoend/components/eth1/miner.go
Nishant Das 927e338f9e
Enable Bellatrix E2E (#10437)
* Fix finding terminal block hash calculation

* Update mainnet_config.go

* Update beacon_block.pb.go

* Various fixes to pass all spec tests for Merge (#9777)

* Proper upgrade altair to merge state

* Use uint64 for ttd

* Correctly upgrade to merge state + object mapping fixes

* Use proper receive block path for initial syncing

* Disable contract lookback

* Disable deposit contract lookback

* Go fmt

* Merge: switch from go bindings to raw rpc calls (#9803)

* Disable genesis ETH1.0 chain header logging

* Update htrutils.go

* all gossip tests passing

* Remove gas validations

* Update penalty params for Merge

* Fix gossip and tx size limits for the merge part 1

* Remove extraneous p2p condition

* Add and use

* Add and use TBH_ACTIVATION_EPOCH

* Update WORKSPACE

* Update Kintsugi engine API (#9865)

* Kintsugi ssz (#9867)

* All spec tests pass

* Update spec test shas

* Update Kintsugi consensus implementations (#9872)

* Remove secp256k1

* Remove unused merge genesis state gen tool

* Manually override nil transaction field. M2 works

* Fix bad hex conversion

* Change Gossip message size and Chunk SIze from 1 MB t0 10MB (#9860)

* change gossip size and chunk size after merge

* change ssz to accomodate both changes

* gofmt config file

* add testcase for merge MsgId

* Update beacon-chain/p2p/message_id.go

Change MB to Mib in comment

Co-authored-by: terence tsao <terence@prysmaticlabs.com>

* change function name from altairMsgID to postAltairMsgID

Co-authored-by: terence tsao <terence@prysmaticlabs.com>

* Sync with develop

* Merge branch 'develop' of github.com:prysmaticlabs/prysm into kintsugi

* Update state_trie.go

* Clean up conflicts

* Fix build

* Update config to devnet1

* Fix state merge

* Handle merge test case for update balance

* Fix build

* State pkg cleanup

* Fix a bug with loading mainnet state

* Fix transactions root

* Add v2 endpoint for merge blocks (#9802)

* Add V2 blocks endpoint for merge blocks

* Update beacon-chain/rpc/apimiddleware/structs.go

Co-authored-by: Radosław Kapka <rkapka@wp.pl>

* go mod

* fix transactions

* Terence's comments

* add missing file

Co-authored-by: Radosław Kapka <rkapka@wp.pl>

* Sync

* Go mod tidy

* change EP field names

* latest kintusgi execution api

* fix conflicts

* converting base fee to big endian format (#10018)

* ReverseByteOrder function does not mess the input

* sync with develop

* use merge gossip sizes

* correct gossip sizes this time

* visibility

* clean ups

* Sync with develop, fix payload nil check bug

* Speed up syncing, hide cosmetic errors

* Sync with develop

* Clean up after sync

* Update generate_keys.go

* sync with develop

* Update mainnet_config.go

* Clean ups

* Sync optimistically candidate blocks (#10193)

* Revert "Sync optimistically candidate blocks (#10193)"

This reverts commit f99a0419ef1efc4bda0be77f22165b8fe4377c0d.

* Sync optimistically candidate blocks (#10193)

* allow optimistic sync

* Fix merge transition block validation

* Update proposer.go

* Sync with develop

* delete deprecated client, update testnet flag

* Change optimistic logic (#10194)

* Logs and err handling

* Fix build

* Clean ups

* Add back get payload

* c

* Done

* Rm uncommented

* Optimistic sync: prysm validator rpcs (#10200)

* Logs to reproduce

* Use pointers

* Use pointers

* Use pointers

* Update json_marshal_unmarshal.go

* Fix marshal

* Update json_marshal_unmarshal.go

* Log

* string total diff

* str

* marshal un

* set string

* json

* gaz

* Comment out optimistic status

* remove kiln flag here (#10269)

* Sync with devleop

* Sync with develop

* clean ups

* refactor engine calls

* Update process_block.go

* Fix deadlock, uncomment duty opt sync

* Update proposer_execution_payload.go

* Sync with develop

* Rm post state check

* Bypass eth1 data checks

* Update proposer_execution_payload.go

* Return early if ttd is not reached

* Sync with devleop

* Update process_block.go

* Update receive_block.go

* Update bzl

* Revert "Update receive_block.go"

This reverts commit 5b4a87c512325d9f26de4db7f941dcd7303cd0d8.

* Fix run time

* add in all the fixes

* fix evaluator bugs

* latest fixes

* sum

* fix to be configurable

* Update go.mod

* Fix AltairCompatible to account for future state version

* Update proposer_execution_payload.go

* fix broken conditional checks

* fix all issues

* Handle pre state Altair with valid payload

* Handle pre state Altair with valid payload

* Log bellatrix fields

* Update log.go

* Revert "fix broken conditional checks"

This reverts commit e118db6c20172783a3bb573d2f78670f0207ec1e.

* LH multiclient working

* Friendly fee recipient log

* Remove extra SetOptimisticToValid

* fix race

* fix test

* Fix base fee per gas

* Fix notifypayload headroot

* tx fuzzer

* clean up with develop branch

* save progress

* 200tx/block

* add LH flags

* Sync with devleop

* cleanup

* cleanup

* hash

* fix build

* fix test

* fix go check

* fmt

* gosec

* add deps

* cleanup

* fix up

* change gas price

* remove flag

* last fix

* use new LH version

* fix up

* fix finalized block panic

Co-authored-by: terence tsao <terence@prysmaticlabs.com>
Co-authored-by: Zahoor Mohamed <zahoor@zahoor.in>
Co-authored-by: kasey <489222+kasey@users.noreply.github.com>
Co-authored-by: Potuz <potuz@prysmaticlabs.com>
Co-authored-by: Radosław Kapka <rkapka@wp.pl>
Co-authored-by: Zahoor Mohamed <zahoor@prysmaticlabs.com>
Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2022-04-05 14:02:46 +00:00

258 lines
7.5 KiB
Go

package eth1
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"math/big"
"os"
"os/exec"
"path"
"strings"
"time"
"github.com/bazelbuild/rules_go/go/tools/bazel"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/rpc"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/config/params"
contracts "github.com/prysmaticlabs/prysm/contracts/deposit/mock"
io "github.com/prysmaticlabs/prysm/io/file"
"github.com/prysmaticlabs/prysm/testing/endtoend/helpers"
e2e "github.com/prysmaticlabs/prysm/testing/endtoend/params"
e2etypes "github.com/prysmaticlabs/prysm/testing/endtoend/types"
log "github.com/sirupsen/logrus"
)
// Miner represents an ETH1 node which mines blocks.
type Miner struct {
e2etypes.ComponentRunner
started chan struct{}
bootstrapEnr string
enr string
keystorePath string
}
// NewMiner creates and returns an ETH1 node miner.
func NewMiner() *Miner {
return &Miner{
started: make(chan struct{}, 1),
}
}
// KeystorePath returns the path of the keystore file.
func (m *Miner) KeystorePath() string {
return m.keystorePath
}
// ENR returns the miner's enode.
func (m *Miner) ENR() string {
return m.enr
}
// SetBootstrapENR sets the bootstrap record.
func (m *Miner) SetBootstrapENR(bootstrapEnr string) {
m.bootstrapEnr = bootstrapEnr
}
// Start runs a mining ETH1 node.
// The miner is responsible for moving the ETH1 chain forward and for deploying the deposit contract.
func (m *Miner) Start(ctx context.Context) error {
binaryPath, found := bazel.FindBinary("cmd/geth", "geth")
if !found {
return errors.New("go-ethereum binary not found")
}
eth1Path := path.Join(e2e.TestParams.TestPath, "eth1data/miner/")
// Clear out potentially existing dir to prevent issues.
if _, err := os.Stat(eth1Path); !os.IsNotExist(err) {
if err = os.RemoveAll(eth1Path); err != nil {
return err
}
}
genesisSrcPath, err := bazel.Runfile(path.Join(staticFilesPath, "genesis.json"))
if err != nil {
return err
}
genesisDstPath := binaryPath[:strings.LastIndex(binaryPath, "/")]
cpCmd := exec.CommandContext(ctx, "cp", genesisSrcPath, genesisDstPath) // #nosec G204 -- Safe
if err = cpCmd.Start(); err != nil {
return err
}
if err = cpCmd.Wait(); err != nil {
return err
}
initCmd := exec.CommandContext(
ctx,
binaryPath,
"init",
genesisDstPath+"/genesis.json",
fmt.Sprintf("--datadir=%s", eth1Path)) // #nosec G204 -- Safe
initFile, err := helpers.DeleteAndCreateFile(e2e.TestParams.LogPath, "eth1-init_miner.log")
if err != nil {
return err
}
initCmd.Stderr = initFile
if err = initCmd.Start(); err != nil {
return err
}
if err = initCmd.Wait(); err != nil {
return err
}
args := []string{
fmt.Sprintf("--datadir=%s", eth1Path),
fmt.Sprintf("--http.port=%d", e2e.TestParams.Ports.Eth1RPCPort),
fmt.Sprintf("--ws.port=%d", e2e.TestParams.Ports.Eth1WSPort),
fmt.Sprintf("--authrpc.port=%d", e2e.TestParams.Ports.Eth1AuthRPCPort),
fmt.Sprintf("--bootnodes=%s", m.bootstrapEnr),
fmt.Sprintf("--port=%d", e2e.TestParams.Ports.Eth1Port),
fmt.Sprintf("--networkid=%d", NetworkId),
"--http",
"--http.api=engine,net,eth",
"--http.addr=127.0.0.1",
"--http.corsdomain=\"*\"",
"--http.vhosts=\"*\"",
"--rpc.allow-unprotected-txs",
"--ws",
"--ws.api=net,eth,engine",
"--ws.addr=127.0.0.1",
"--ws.origins=\"*\"",
"--ipcdisable",
"--verbosity=4",
"--mine",
"--unlock=0x878705ba3f8bc32fcf7f4caa1a35e72af65cf766",
"--allow-insecure-unlock",
fmt.Sprintf("--password=%s", eth1Path+"/keystore/"+minerPasswordFile),
}
keystorePath, err := bazel.Runfile(path.Join(staticFilesPath, minerFile))
if err != nil {
return err
}
jsonBytes, err := ioutil.ReadFile(keystorePath) // #nosec G304 -- ReadFile is safe
if err != nil {
return err
}
err = io.WriteFile(eth1Path+"/keystore/"+minerFile, jsonBytes)
if err != nil {
return err
}
err = io.WriteFile(eth1Path+"/keystore/"+minerPasswordFile, []byte(KeystorePassword))
if err != nil {
return err
}
runCmd := exec.CommandContext(ctx, binaryPath, args...) // #nosec G204 -- Safe
file, err := helpers.DeleteAndCreateFile(e2e.TestParams.LogPath, "eth1_miner.log")
if err != nil {
return err
}
runCmd.Stdout = file
runCmd.Stderr = file
log.Infof("Starting eth1 miner with flags: %s", strings.Join(args[2:], " "))
if err = runCmd.Start(); err != nil {
return fmt.Errorf("failed to start eth1 chain: %w", err)
}
if err = helpers.WaitForTextInFile(file, "Commit new sealing work"); err != nil {
return fmt.Errorf("mining log not found, this means the eth1 chain had issues starting: %w", err)
}
if err = helpers.WaitForTextInFile(file, "Started P2P networking"); err != nil {
return fmt.Errorf("P2P log not found, this means the eth1 chain had issues starting: %w", err)
}
enode, err := enodeFromLogFile(file.Name())
if err != nil {
return err
}
enode = "enode://" + enode + "@127.0.0.1:" + fmt.Sprintf("%d", e2e.TestParams.Ports.Eth1Port)
m.enr = enode
log.Infof("Communicated enode. Enode is %s", enode)
// Connect to the started geth dev chain.
client, err := rpc.DialHTTP(fmt.Sprintf("http://127.0.0.1:%d", e2e.TestParams.Ports.Eth1RPCPort))
if err != nil {
return fmt.Errorf("failed to connect to ipc: %w", err)
}
web3 := ethclient.NewClient(client)
// Deploy the contract.
store, err := keystore.DecryptKey(jsonBytes, KeystorePassword)
if err != nil {
return err
}
// Advancing the blocks eth1follow distance to prevent issues reading the chain.
if err = WaitForBlocks(web3, store, params.BeaconConfig().Eth1FollowDistance); err != nil {
return fmt.Errorf("unable to advance chain: %w", err)
}
txOpts, err := bind.NewTransactorWithChainID(bytes.NewReader(jsonBytes), KeystorePassword, big.NewInt(NetworkId))
if err != nil {
return err
}
nonce, err := web3.PendingNonceAt(ctx, store.Address)
if err != nil {
return err
}
txOpts.Nonce = big.NewInt(0).SetUint64(nonce)
txOpts.Context = ctx
contractAddr, tx, _, err := contracts.DeployDepositContract(txOpts, web3)
if err != nil {
return fmt.Errorf("failed to deploy deposit contract: %w", err)
}
e2e.TestParams.ContractAddress = contractAddr
// Wait for contract to mine.
for pending := true; pending; _, pending, err = web3.TransactionByHash(ctx, tx.Hash()) {
if err != nil {
return err
}
time.Sleep(timeGapPerTX)
}
// Advancing the blocks another eth1follow distance to prevent issues reading the chain.
if err = WaitForBlocks(web3, store, params.BeaconConfig().Eth1FollowDistance); err != nil {
return fmt.Errorf("unable to advance chain: %w", err)
}
// Save keystore path (used for saving and mining deposits).
m.keystorePath = keystorePath
// Mark node as ready.
close(m.started)
return runCmd.Wait()
}
// Started checks whether ETH1 node is started and ready to be queried.
func (m *Miner) Started() <-chan struct{} {
return m.started
}
func enodeFromLogFile(name string) (string, error) {
byteContent, err := ioutil.ReadFile(name) // #nosec G304
if err != nil {
return "", err
}
contents := string(byteContent)
searchText := "self=enode://"
startIdx := strings.Index(contents, searchText)
if startIdx == -1 {
return "", fmt.Errorf("did not find ENR text in %s", contents)
}
startIdx += len(searchText)
endIdx := strings.Index(contents[startIdx:], "@")
if endIdx == -1 {
return "", fmt.Errorf("did not find ENR text in %s", contents)
}
enode := contents[startIdx : startIdx+endIdx]
return strings.TrimPrefix(enode, "-"), nil
}