config: rearrange getConfiguration usage

avoid using getConfiguration inside object construction and
replace it with passing suitable param
This commit is contained in:
jangko 2021-09-07 22:00:21 +07:00
parent 9108301eef
commit c9cfebfa97
No known key found for this signature in database
GPG Key ID: 31702AE10541E6B9
17 changed files with 66 additions and 62 deletions

View File

@ -30,7 +30,7 @@ proc processNode(genesisFile, chainFile,
conf.net.networkId
)
initializeEmptyDb(chainDB)
initializeEmptyDb(chainDB, conf.customNetwork)
discard importRlpBlock(chainFile, chainDB)
let head = chainDB.getCanonicalHead()
let blockHash = "0x" & head.blockHash.data.toHex

View File

@ -11,7 +11,7 @@ import
std/[os, parseopt, json],
eth/[p2p, trie/db], ../../../nimbus/db/db_chain,
../../../nimbus/sync/protocol_eth65,
../../../nimbus/[genesis, config, conf_utils],
../../../nimbus/[genesis, config, conf_utils, context],
../../../nimbus/graphql/ethapi, ../../../tests/test_helpers,
graphql, ../sim_utils
@ -74,14 +74,15 @@ proc main() =
quit(QuitFailure)
let
ethCtx = newEthContext()
conf = getConfiguration()
ethNode = setupEthNode(eth)
ethNode = setupEthNode(conf, ethCtx, eth)
chainDB = newBaseChainDB(newMemoryDb(),
pruneTrie = false,
conf.net.networkId
)
initializeEmptyDb(chainDB)
initializeEmptyDb(chainDB, conf.customNetwork)
discard importRlpBlock(blocksFile, chainDB)
let ctx = setupGraphqlContext(chainDB, ethNode)

View File

@ -82,7 +82,7 @@ type
balance*: UInt256
nonce* : AccountNonce
CustomGenesis* = object
CustomNetwork* = object
config* : ChainConfig
genesis*: Genesis
@ -148,7 +148,7 @@ template to(a: string, b: type UInt256): UInt256 =
# json_serialization decode table stuff
UInt256.fromHex(a)
proc loadCustomGenesis*(fileName: string, cg: var CustomGenesis): bool =
proc loadCustomNetwork*(fileName: string, cg: var CustomNetwork): bool =
var cc: CustomChain
try:
cc = Json.loadFile(fileName, CustomChain, allowUnknownFields = true)

View File

@ -9,7 +9,8 @@
import
chronicles, eth/[common, rlp], stew/io2,
./p2p/chain, ./db/[db_chain, select_backend]
./p2p/chain, ./db/[db_chain, select_backend],
config
type
# trick the rlp decoder

View File

@ -124,7 +124,7 @@ type
ws*: RpcConfiguration ## Websocket JSON-RPC configuration
net*: NetConfiguration ## Network configuration
debug*: DebugConfiguration ## Debug configuration
customGenesis*: CustomGenesis ## Custom Genesis Configuration
customNetwork*: CustomNetwork ## Custom Genesis Configuration
importKey*: string
importFile*: string
verifyFromOk*: bool ## activate `verifyFrom` setting
@ -247,8 +247,8 @@ proc chainConfig*(id: NetworkId): ChainConfig =
else:
# everything else will use CustomNet config
let conf = getConfiguration()
trace "Custom genesis block configuration loaded", conf=conf.customGenesis.config
conf.customGenesis.config
trace "Custom genesis block configuration loaded", conf=conf.customNetwork.config
conf.customNetwork.config
proc processList(v: string, o: var seq[string]) =
## Process comma-separated list of strings.
@ -497,7 +497,7 @@ proc processNetArguments(key, value: string): ConfigStatus =
elif skey == "kovan":
config.net.setNetwork(KovanNet)
elif skey == "customnetwork":
if not loadCustomGenesis(value, config.customGenesis):
if not loadCustomNetwork(value, config.customNetwork):
result = Error
if NetworkIdSet notin config.net.flags:
# prevent clash with --networkid if it already set
@ -809,7 +809,7 @@ when declared(os.paramCount): # not available with `--app:lib`
# they usage should not be mixed in other places
# we only set networkId to chainId if networkId not set in cli and
# we are using custom genesis/custom chain config via json file.
config.net.networkId = NetworkId(config.customGenesis.config.chainId)
config.net.networkId = NetworkId(config.customNetwork.config.chainId)
proc processArguments*(msg: var string): ConfigStatus =
var opt = initOptParser()

View File

@ -6,7 +6,7 @@ import
./genesis_alloc, ./config, ./constants,
./chain_config, ./forks, ./p2p/gaslimit
proc defaultGenesisBlockForNetwork*(id: NetworkId): Genesis =
proc genesisBlockForNetwork*(id: NetworkId, cn: CustomNetwork): Genesis =
result = case id
of MainNet:
Genesis(
@ -44,8 +44,7 @@ proc defaultGenesisBlockForNetwork*(id: NetworkId): Genesis =
)
else:
# everything else will use custom genesis
let customGenesis = getConfiguration().customGenesis
customGenesis.genesis
cn.genesis
proc toBlock*(g: Genesis, db: BaseChainDB = nil): BlockHeader =
let (tdb, pruneTrie) = if db.isNil: (newMemoryDB(), true)
@ -90,7 +89,7 @@ proc commit*(g: Genesis, db: BaseChainDB) =
doAssert(b.blockNumber == 0, "can't commit genesis block with number > 0")
discard db.persistHeaderToDb(b)
proc initializeEmptyDb*(db: BaseChainDB) =
proc initializeEmptyDb*(db: BaseChainDB, cn: CustomNetwork) =
trace "Writing genesis to DB"
let networkId = getConfiguration().net.networkId
defaultGenesisBlockForNetwork(networkId).commit(db)
let genesis = genesisBlockForNetwork(db.networkId, cn)
genesis.commit(db)

View File

@ -28,9 +28,6 @@ import
## * No multiple bind addresses support
## * No database support
const
nimbusClientId = "nimbus 0.1.0"
type
NimbusState = enum
Starting, Running, Stopping
@ -62,7 +59,7 @@ proc start(nimbus: NimbusNode) =
chainDB.populateProgress()
if canonicalHeadHashKey().toOpenArray notin trieDB:
initializeEmptyDb(chainDb)
initializeEmptyDb(chainDb, conf.customNetwork)
doAssert(canonicalHeadHashKey().toOpenArray in trieDB)
if conf.importFile.len > 0:
@ -126,7 +123,7 @@ proc start(nimbus: NimbusNode) =
(address.tcpPort, address.udpPort) = extPorts.get()
nimbus.ethNode = newEthereumNode(keypair, address, conf.net.networkId,
nil, nimbusClientId,
nil, conf.net.ident,
addAllCapabilities = false,
minPeers = conf.net.maxPeers)
# Add protocol capabilities based on protocol flags
@ -137,6 +134,7 @@ proc start(nimbus: NimbusNode) =
# chainRef: some name to avoid module-name/filed/function misunderstandings
let chainRef = newChain(chainDB)
chainRef.setForkId(conf.customNetwork)
nimbus.ethNode.chain = chainRef
if conf.verifyFromOk:
chainRef.extraValidation = 0 < conf.verifyFrom
@ -145,7 +143,7 @@ proc start(nimbus: NimbusNode) =
## Creating RPC Server
if RpcFlags.Enabled in conf.rpc.flags:
nimbus.rpcServer = newRpcHttpServer(conf.rpc.binds)
setupCommonRpc(nimbus.ethNode, nimbus.rpcServer)
setupCommonRpc(nimbus.ethNode, conf, nimbus.rpcServer)
# Enable RPC APIs based on RPC flags and protocol flags
if RpcFlags.Eth in conf.rpc.flags and ProtocolFlags.Eth in conf.net.protocols:
@ -157,7 +155,7 @@ proc start(nimbus: NimbusNode) =
if RpcFlags.Enabled in conf.ws.flags:
doAssert(conf.ws.binds.len > 0)
nimbus.wsRpcServer = newRpcWebSocketServer(conf.ws.binds[0])
setupCommonRpc(nimbus.ethNode, nimbus.wsRpcServer)
setupCommonRpc(nimbus.ethNode, conf, nimbus.wsRpcServer)
# Enable Websocket RPC APIs based on RPC flags and protocol flags
if RpcFlags.Eth in conf.ws.flags and ProtocolFlags.Eth in conf.net.protocols:

View File

@ -13,6 +13,7 @@ import
../../db/db_chain,
../../genesis,
../../utils,
../../chain_config,
../clique,
../validate,
../validate/epoch_hash_cache,
@ -127,10 +128,6 @@ proc initChain(c: Chain; db: BaseChainDB; poa: Clique; extraValidation: bool)
if not db.config.daoForkSupport:
db.config.daoForkBlock = db.config.homesteadBlock
let g = defaultGenesisBlockForNetwork(db.networkId)
c.blockZeroHash = g.toBlock.blockHash
let genesisCRC = crc32(0, c.blockZeroHash.data)
c.forkIds = calculateForkIds(db.config, genesisCRC)
c.extraValidation = extraValidation
# Initalise the PoA state regardless of whether it is needed on the current
@ -240,6 +237,13 @@ proc `verifyFrom=`*(c: Chain; verifyFrom: uint64) {.inline.} =
## `true`.
c.verifyFrom = verifyFrom.u256
proc setForkId*(c: Chain, cn = CustomNetwork())
{. raises: [Defect,CatchableError].} =
let g = genesisBlockForNetwork(c.db.networkId, cn)
c.blockZeroHash = g.toBlock.blockHash
let genesisCRC = crc32(0, c.blockZeroHash.data)
c.forkIds = calculateForkIds(c.db.config, genesisCRC)
# ------------------------------------------------------------------------------
# End
# ------------------------------------------------------------------------------

View File

@ -25,7 +25,7 @@ type
ip : string # address string
ports : NodePorts
proc setupCommonRPC*(node: EthereumNode, server: RpcServer) =
proc setupCommonRPC*(node: EthereumNode, conf: NimbusConfiguration, server: RpcServer) =
server.rpc("web3_clientVersion") do() -> string:
result = NimbusIdent
@ -34,11 +34,9 @@ proc setupCommonRPC*(node: EthereumNode, server: RpcServer) =
result = "0x" & $keccak_256.digest(rawdata)
server.rpc("net_version") do() -> string:
let conf = getConfiguration()
result = $conf.net.networkId
server.rpc("net_listening") do() -> bool:
let conf = getConfiguration()
let numPeers = node.peerPool.connectedNodes.len
result = numPeers < conf.net.maxPeers

View File

@ -9,7 +9,8 @@ import
eth/trie/[hexary, db],
../nimbus/db/[storage_types, db_chain, select_backend],
../nimbus/[genesis],
../nimbus/p2p/chain
../nimbus/p2p/chain,
../nimbus/chain_config
const
manualCommit = nimbus_db_backend == "lmdb"
@ -46,7 +47,7 @@ proc main() {.used.} =
if canonicalHeadHashKey().toOpenArray notin trieDB:
persistToDb(db):
initializeEmptyDb(chainDB)
initializeEmptyDb(chainDB, CustomNetwork())
doAssert(canonicalHeadHashKey().toOpenArray in trieDB)
var head = chainDB.getCanonicalHead()

View File

@ -2,7 +2,8 @@ import
json, eth/common, stint, chronicles, eth/rlp,
eth/trie/db, ../nimbus/db/[db_chain, capturedb, select_backend],
../nimbus/[tracer, config],
../nimbus/p2p/chain
../nimbus/p2p/chain,
../nimbus/chain_config
proc dumpTest(chainDB: BaseChainDB, blockNumber: int) =
let

View File

@ -43,7 +43,7 @@ type
## transactions.
prng: Rand
accounts: Table[string,PrivateKey] ## accounts table
boot: CustomGenesis ## imported Genesis configuration
boot: CustomNetwork ## imported Genesis configuration
batch: seq[seq[BlockHeader]] ## collect header chains
chain: Chain
@ -242,8 +242,8 @@ proc sayHeaderChain*(ap: TesterPool; indent = 0): TesterPool {.discardable.} =
proc newVoterPool*(networkId = GoerliNet): TesterPool =
TesterPool(
boot: CustomGenesis(
genesis: defaultGenesisBlockForNetwork(networkId),
boot: CustomNetwork(
genesis: genesisBlockForNetwork(networkId, CustomNetwork()),
config: chainConfig(networkId))).initTesterPool
# ------------------------------------------------------------------------------

View File

@ -89,6 +89,7 @@ template runTest(network: untyped) =
chainDB = newBaseChainDB(memDB, true, network)
chain = newChain(chainDB)
chain.setForkId()
for x in `network IDs`:
let id = chain.getForkId(x.blockNumber.toBlockNumber)
check id.crc == x.id.crc

View File

@ -8,39 +8,39 @@ const dataFolder = "tests" / "customgenesis"
proc genesisTest() =
suite "Genesis":
test "Correct mainnet hash":
let g = defaultGenesisBlockForNetwork(MainNet)
let g = genesisBlockForNetwork(MainNet, CustomNetwork())
let b = g.toBlock
check(b.blockHash == "D4E56740F876AEF8C010B86A40D5F56745A118D0906A34E69AEC8C0DB1CB8FA3".toDigest)
test "Correct ropstennet hash":
let g = defaultGenesisBlockForNetwork(RopstenNet)
let g = genesisBlockForNetwork(RopstenNet, CustomNetwork())
let b = g.toBlock
check(b.blockHash == "41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d".toDigest)
test "Correct rinkebynet hash":
let g = defaultGenesisBlockForNetwork(RinkebyNet)
let g = genesisBlockForNetwork(RinkebyNet, CustomNetwork())
let b = g.toBlock
check(b.blockHash == "6341fd3daf94b748c72ced5a5b26028f2474f5f00d824504e4fa37a75767e177".toDigest)
test "Correct goerlinet hash":
let g = defaultGenesisBlockForNetwork(GoerliNet)
let g = genesisBlockForNetwork(GoerliNet, CustomNetwork())
let b = g.toBlock
check(b.blockHash == "bf7e331f7f7c1dd2e05159666b3bf8bc7a8a3a9eb1d518969eab529dd9b88c1a".toDigest)
proc customGenesisTest() =
suite "Custom Genesis":
test "loadCustomGenesis":
var cga, cgb, cgc: CustomGenesis
check loadCustomGenesis(dataFolder / "berlin2000.json", cga)
check loadCustomGenesis(dataFolder / "chainid7.json", cgb)
check loadCustomGenesis(dataFolder / "noconfig.json", cgc)
var cga, cgb, cgc: CustomNetwork
check loadCustomNetwork(dataFolder / "berlin2000.json", cga)
check loadCustomNetwork(dataFolder / "chainid7.json", cgb)
check loadCustomNetwork(dataFolder / "noconfig.json", cgc)
check cga.config.poaEngine == false
check cgb.config.poaEngine == false
check cgc.config.poaEngine == false
test "calaveras.json":
var cg: CustomGenesis
check loadCustomGenesis(dataFolder / "calaveras.json", cg)
var cg: CustomNetwork
check loadCustomNetwork(dataFolder / "calaveras.json", cg)
let h = toBlock(cg.genesis, nil)
let stateRoot = "664c93de37eb4a72953ea42b8c046cdb64c9f0b0bca5505ade8d970d49ebdb8c".toDigest
let genesisHash = "eb9233d066c275efcdfed8037f4fc082770176aefdbcb7691c71da412a5670f2".toDigest

View File

@ -41,18 +41,18 @@ proc setupChain(chainDB: BaseChainDB) =
let genesis = jn.toBlock("genesisRLP")
let conf = getConfiguration()
conf.customGenesis.genesis.nonce = genesis.header.nonce
conf.customGenesis.genesis.extraData = genesis.header.extraData
conf.customGenesis.genesis.gasLimit = genesis.header.gasLimit
conf.customGenesis.genesis.difficulty = genesis.header.difficulty
conf.customGenesis.genesis.mixHash = genesis.header.mixDigest
conf.customGenesis.genesis.coinBase = genesis.header.coinbase
conf.customGenesis.genesis.timestamp = genesis.header.timestamp
conf.customGenesis.genesis.baseFeePerGas = genesis.header.fee
if not parseGenesisAlloc($(jn["pre"]), conf.customGenesis.genesis.alloc):
conf.customNetwork.genesis.nonce = genesis.header.nonce
conf.customNetwork.genesis.extraData = genesis.header.extraData
conf.customNetwork.genesis.gasLimit = genesis.header.gasLimit
conf.customNetwork.genesis.difficulty = genesis.header.difficulty
conf.customNetwork.genesis.mixHash = genesis.header.mixDigest
conf.customNetwork.genesis.coinBase = genesis.header.coinbase
conf.customNetwork.genesis.timestamp = genesis.header.timestamp
conf.customNetwork.genesis.baseFeePerGas = genesis.header.fee
if not parseGenesisAlloc($(jn["pre"]), conf.customNetwork.genesis.alloc):
quit(QuitFailure)
chainDB.initializeEmptyDb()
chainDB.initializeEmptyDb(conf.customNetwork)
let blocks = jn["blocks"]
var headers: seq[BlockHeader]
@ -72,7 +72,7 @@ proc setupChain(chainDB: BaseChainDB) =
proc graphqlMain*() =
let conf = getConfiguration()
conf.net.networkId = CustomNet
conf.customGenesis.config = ChainConfig(
conf.customNetwork.config = ChainConfig(
chainId : MainNet.ChainId,
byzantiumBlock : 0.toBlockNumber,
constantinopleBlock : 0.toBlockNumber,

View File

@ -9,7 +9,7 @@ import
unittest2, json, os, tables, strutils,
eth/[common, rlp], stew/byteutils, eth/trie/db,
./test_helpers, ../nimbus/db/db_chain,
../nimbus/p2p/chain
../nimbus/p2p/chain, ../nimbus/config
# use tracerTestGen.nim to generate additional test data
proc testFixture(node: JsonNode, testStatusIMPL: var TestStatus) =

View File

@ -145,7 +145,7 @@ proc rpcMain*() =
debugEcho unlock.error
doAssert(unlock.isOk)
defaultGenesisBlockForNetwork(conf.net.networkId).commit(chain)
genesisBlockForNetwork(conf.net.networkId, conf.customNetwork).commit(chain)
doAssert(canonicalHeadHashKey().toOpenArray in chain.db)
let env = setupEnv(chain, signer, ks2, ctx)
@ -154,7 +154,7 @@ proc rpcMain*() =
var
rpcServer = newRpcSocketServer(["localhost:" & $RPC_PORT])
client = newRpcSocketClient()
setupCommonRpc(ethNode, rpcServer)
setupCommonRpc(ethNode, conf, rpcServer)
setupEthRpc(ethNode, ctx, chain, rpcServer)
# Begin tests