rm ncli/ncli_testnet.nim tests/all_tests.nim tests/mocking/mock_deposits.nim tests/test_keymanager_api.nim

This commit is contained in:
Jenkins 2024-03-20 03:06:04 +02:00
parent d1b91a842f
commit c60ee355ec
4 changed files with 0 additions and 346 deletions

View File

@ -1,178 +0,0 @@
{.push raises: [].}
import
std/[json, options],
chronos, bearssl/rand, confutils, json_serialization,
web3, eth/keys, eth/p2p/discoveryv5/random2,
stew/[io2, byteutils],
../beacon_chain/conf,
../beacon_chain/spec/eth2_merkleization,
../beacon_chain/spec/datatypes/base,
../beacon_chain/validators/keystore_management
from std/os import changeFileExt, fileExists
from std/times import toUnix
from ../beacon_chain/spec/beaconstate import initialize_beacon_state_from_eth1
# For nim-confutils, which uses this kind of init(Type, value) pattern
func init(T: type IpAddress, ip: IpAddress): T = ip
const mockEth1BlockHash* =
Eth2Digest.fromHex("0x4242424242424242424242424242424242424242")
type
Eth1Address = web3.Address
StartUpCommand {.pure.} = enum
createTestnet
CliConfig* = object
web3Url* {.
defaultValue: "",
desc: "URL of the Web3 server to observe Eth1"
name: "web3-url" }: string
privateKey* {.
defaultValue: ""
desc: "Private key of the controlling account"
name: "private-key" }: string
eth2Network* {.
desc: "The Eth2 network preset to use"
name: "network" }: Option[string]
case cmd* {.command.}: StartUpCommand
of StartUpCommand.createTestnet:
testnetDepositsFile* {.
desc: "A LaunchPad deposits file for the genesis state validators"
name: "deposits-file" .}: InputFile
totalValidators* {.
desc: "The number of validator deposits in the newly created chain"
name: "total-validators" .}: uint64
dataDir* {.
desc: "Nimbus data directory where the keys of the bootstrap node will be placed"
name: "data-dir" .}: OutDir
genesisTime* {.
desc: "Unix epoch time of the network genesis"
name: "genesis-time" .}: Option[uint64]
executionGenesisBlock* {.
desc: "The execution genesis block in a merged testnet"
name: "execution-genesis-block" .}: Option[InputFile]
outputGenesis* {.
desc: "Output file where to write the initial state snapshot"
name: "output-genesis" .}: OutFile
outputDepositTreeSnapshot* {.
desc: "Output file where to write the initial deposit tree snapshot"
name: "output-deposit-tree-snapshot" .}: OutFile
type
PubKeyBytes = DynamicBytes[48, 48]
WithdrawalCredentialsBytes = DynamicBytes[32, 32]
SignatureBytes = DynamicBytes[96, 96]
contract(DepositContract):
proc deposit(pubkey: PubKeyBytes,
withdrawalCredentials: WithdrawalCredentialsBytes,
signature: SignatureBytes,
deposit_data_root: FixedBytes[32])
from ".."/beacon_chain/spec/datatypes/bellatrix import BloomLogs, ExecutionAddress
template `as`(address: Eth1Address, T: type bellatrix.ExecutionAddress): T =
T(data: distinctBase(address))
func asEth2Digest*(x: BlockHash): Eth2Digest =
Eth2Digest(data: array[32, byte](x))
template asBlockHash*(x: Eth2Digest): BlockHash =
BlockHash(x.data)
template `as`(address: BlockHash, T: type Eth2Digest): T =
asEth2Digest(address)
func getOrDefault[T](x: Option[T]): T =
if x.isSome:
x.get
else:
default T
func `as`(blk: BlockObject, T: type bellatrix.ExecutionPayloadHeader): T =
T(parent_hash: blk.parentHash as Eth2Digest,
fee_recipient: blk.miner as ExecutionAddress,
state_root: blk.stateRoot as Eth2Digest,
receipts_root: blk.receiptsRoot as Eth2Digest,
logs_bloom: BloomLogs(data: distinctBase(blk.logsBloom)),
prev_randao: Eth2Digest(data: blk.difficulty.toByteArrayBE), # Is BE correct here?
block_number: uint64 blk.number,
gas_limit: uint64 blk.gasLimit,
gas_used: uint64 blk.gasUsed,
timestamp: uint64 blk.timestamp,
extra_data: List[byte, MAX_EXTRA_DATA_BYTES].init(blk.extraData.bytes),
base_fee_per_gas: blk.baseFeePerGas.getOrDefault(),
block_hash: blk.hash as Eth2Digest,
transactions_root: blk.transactionsRoot as Eth2Digest)
from ".."/beacon_chain/spec/deposit_snapshots import DepositTreeSnapshot
func createDepositTreeSnapshot(deposits: seq[DepositData],
blockHash: Eth2Digest,
blockHeight: uint64): DepositTreeSnapshot =
var merkleizer = DepositsMerkleizer.init()
for i, deposit in deposits:
let htr = hash_tree_root(deposit)
merkleizer.addChunk(htr.data)
DepositTreeSnapshot(
eth1Block: blockHash,
depositContractState: merkleizer.toDepositContractState,
blockHeight: blockHeight)
import ssz_serialization
import ".."/beacon_chain/spec/ssz_codec
proc doCreateTestnet*(config: CliConfig,
rng: var HmacDrbgContext)
{.raises: [CatchableError].} =
let launchPadDeposits = try:
Json.loadFile(config.testnetDepositsFile.string, seq[LaunchPadDeposit])
except SerializationError as err:
quit 1
var deposits: seq[DepositData]
for i in 0 ..< launchPadDeposits.len:
deposits.add(launchPadDeposits[i] as DepositData)
let
startTime = if config.genesisTime.isSome:
config.genesisTime.get
else:
uint64(times.toUnix(times.getTime()))
outGenesis = config.outputGenesis.string
eth1Hash = mockEth1BlockHash
cfg = getRuntimeConfig(config.eth2Network)
# This is intentionally left default initialized, when the user doesn't
# provide an execution genesis block. The generated genesis state will
# then be considered non-finalized merged state according to the spec.
var genesisBlock = BlockObject()
let genesisExecutionPayloadHeader = genesisBlock as bellatrix.ExecutionPayloadHeader
var initialState = newClone(initialize_beacon_state_from_eth1(
cfg, eth1Hash, startTime, deposits, genesisExecutionPayloadHeader))
initialState.genesis_time = startTime
doAssert initialState.validators.len > 0
let outSszGenesis = outGenesis.changeFileExt "ssz"
SSZ.saveFile(outSszGenesis, initialState[])
SSZ.saveFile(
config.outputDepositTreeSnapshot.string,
createDepositTreeSnapshot(
deposits,
genesisExecutionPayloadHeader.block_hash,
genesisExecutionPayloadHeader.block_number))

View File

@ -1 +0,0 @@
import ./test_keymanager_api

View File

@ -1,136 +0,0 @@
# beacon_chain
# Copyright (c) 2018-2024 Status Research & Development GmbH
# Licensed and distributed under either of
# * MIT license (license terms in the root directory or at https://opensource.org/licenses/MIT).
# * Apache v2 license (license terms in the root directory or at https://www.apache.org/licenses/LICENSE-2.0).
# at your option. This file may not be copied, modified, or distributed except according to those terms.
# Mocking deposits and genesis deposits
# ---------------------------------------------------------------
import
# Standard library
std/math,
# Specs
../../beacon_chain/spec/[eth2_merkleization, keystore, forks, signatures],
../../beacon_chain/spec/datatypes/base,
# Internals
../../beacon_chain/extras,
../../beacon_chain/el/merkle_minimal,
# Test utilities
../testblockutil
func mockDepositData(
pubkey: ValidatorPubKey,
amount: uint64,
): DepositData =
# Insecurely use pubkey as withdrawal key
DepositData(
pubkey: pubkey,
withdrawal_credentials: makeWithdrawalCredentials(pubkey),
amount: amount,
)
func mockDepositData(
pubkey: ValidatorPubKey,
privkey: ValidatorPrivKey,
amount: uint64,
# withdrawal_credentials: Eth2Digest,
flags: UpdateFlags = {}
): DepositData =
var ret = mockDepositData(pubkey, amount)
if skipBlsValidation notin flags:
ret.signature = defaultRuntimeConfig.get_deposit_signature(ret, privkey).toValidatorSig()
ret
template mockGenesisDepositsImpl(
result: seq[DepositData],
validatorCount: uint64,
amount: untyped,
flags: UpdateFlags = {},
updateAmount: untyped,
) =
# Genesis deposits with varying amounts
# NOTE: prefer to er on the side of caution and generate a valid Deposit
# (it can still be skipped later).
if skipBlsValidation in flags:
# 1st loop - build deposit data
for valIdx in 0 ..< validatorCount:
# Directly build the Deposit in-place for speed
result.setLen(valIdx + 1)
updateAmount
# DepositData
result[valIdx] =
mockDepositData(MockPubKeys[valIdx.ValidatorIndex], amount)
else: # With signing
var depositsDataHash: seq[Eth2Digest]
var depositsData: seq[DepositData]
# 1st loop - build deposit data
for valIdx in 0 ..< validatorCount:
# Directly build the Deposit in-place for speed
result.setLen(valIdx + 1)
updateAmount
# DepositData
result[valIdx] =
mockDepositData(
MockPubKeys[valIdx.ValidatorIndex],
MockPrivKeys[valIdx.ValidatorIndex],
amount, flags)
depositsData.add result[valIdx]
depositsDataHash.add hash_tree_root(result[valIdx])
proc mockGenesisBalancedDeposits*(
validatorCount: uint64,
amountInEth: Positive,
flags: UpdateFlags = {}
): seq[DepositData] =
## The amount should be strictly positive
## - 1 is the minimum deposit amount (MIN_DEPOSIT_AMOUNT)
## - 16 is the ejection balance (EJECTION_BALANCE)
## - 32 is the max effective balance (MAX_EFFECTIVE_BALANCE)
## ETH beyond do not contribute more for staking.
##
## Only validators with 32 ETH will be active at genesis
let amount = amountInEth.uint64 * 10'u64^9
mockGenesisDepositsImpl(result, validatorCount,amount,flags):
discard
proc mockUpdateStateForNewDeposit*(
state: var ForkyBeaconState,
validator_index: uint64,
amount: uint64,
# withdrawal_credentials: Eth2Digest
flags: UpdateFlags
): Deposit =
# TODO withdrawal credentials
result.data = mockDepositData(
MockPubKeys[validator_index.ValidatorIndex],
MockPrivKeys[validator_index.ValidatorIndex],
amount,
# withdrawal_credentials: Eth2Digest
flags
)
var result_seq = @[result]
let deposit_root = attachMerkleProofs(result_seq)
result.proof = result_seq[0].proof
# TODO: this logic from the consensus-specs test suite seems strange
# but confirmed by running it
state.eth1_deposit_index = 0
state.eth1_data.deposit_root = deposit_root
state.eth1_data.deposit_count = 1

View File

@ -1,31 +0,0 @@
import
std/os,
confutils,
chronos,
../beacon_chain/[
conf,
filepath,
beacon_node,
nimbus_beacon_node,
]
const
dataDir = "./test_keymanager_api"
nodeDataDir = dataDir / "node-0"
nodeValidatorsDir = nodeDataDir / "validators"
nodeSecretsDir = nodeDataDir / "secrets"
proc startBeaconNode() {.raises: [CatchableError].} =
let runNodeConf = try: BeaconNodeConf.load(cmdLine = @[
"--network=" & dataDir,
"--data-dir=" & nodeDataDir])
except Exception as exc: # TODO fix confutils exceptions
raiseAssert exc.msg
let
metadata = loadEth2NetworkMetadata(dataDir).expect("Metadata is compatible")
node = waitFor BeaconNode.init(runNodeConf, metadata)
node.start()
startBeaconNode()