2021-08-24 07:34:58 +00:00
|
|
|
# Nimbus
|
|
|
|
# Copyright (c) 2021 Status Research & Development GmbH
|
|
|
|
# Licensed under either of
|
|
|
|
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0)
|
|
|
|
# * MIT license ([LICENSE-MIT](LICENSE-MIT) or
|
|
|
|
# http://opensource.org/licenses/MIT)
|
|
|
|
# at your option. This file may not be copied, modified, or distributed except
|
|
|
|
# according to those terms.
|
|
|
|
|
|
|
|
import
|
2021-10-05 23:31:35 +00:00
|
|
|
std/[times, tables, typetraits],
|
|
|
|
pkg/[chronos, stew/results, chronicles, eth/common, eth/keys],
|
2021-08-24 07:34:58 +00:00
|
|
|
"."/[config, db/db_chain, p2p/chain, constants, utils/header],
|
|
|
|
"."/p2p/clique/[clique_defs,
|
|
|
|
clique_desc,
|
|
|
|
clique_cfg,
|
2021-09-11 14:58:01 +00:00
|
|
|
clique_sealer],
|
2022-01-24 13:08:33 +00:00
|
|
|
./p2p/[gaslimit, validate],
|
2022-01-23 11:39:43 +00:00
|
|
|
"."/[chain_config, utils, context],
|
|
|
|
"."/utils/tx_pool
|
2021-08-24 07:34:58 +00:00
|
|
|
|
2021-10-05 23:31:35 +00:00
|
|
|
from web3/ethtypes as web3types import nil
|
2022-01-24 13:08:33 +00:00
|
|
|
from web3/engine_api_types import ExecutionPayloadV1, PayloadAttributesV1
|
2021-10-05 23:31:35 +00:00
|
|
|
|
2021-08-24 07:34:58 +00:00
|
|
|
type
|
2021-10-05 23:31:35 +00:00
|
|
|
EngineState* = enum
|
|
|
|
EngineStopped,
|
|
|
|
EngineRunning,
|
|
|
|
EnginePostMerge
|
|
|
|
|
|
|
|
Web3BlockHash = web3types.BlockHash
|
|
|
|
Web3Address = web3types.Address
|
|
|
|
Web3Bloom = web3types.FixedBytes[256]
|
|
|
|
Web3Quantity = web3types.Quantity
|
2021-08-24 07:34:58 +00:00
|
|
|
|
|
|
|
SealingEngineRef* = ref SealingEngineObj
|
|
|
|
SealingEngineObj = object of RootObj
|
|
|
|
state: EngineState
|
|
|
|
engineLoop: Future[void]
|
2021-10-05 23:31:35 +00:00
|
|
|
chain*: Chain
|
2021-09-07 13:45:01 +00:00
|
|
|
ctx: EthContext
|
|
|
|
signer: EthAddress
|
2022-01-23 11:39:43 +00:00
|
|
|
txPool: TxPoolRef
|
2021-08-24 07:34:58 +00:00
|
|
|
|
2021-10-05 23:31:35 +00:00
|
|
|
template asEthHash*(hash: Web3BlockHash): Hash256 =
|
|
|
|
Hash256(data: distinctBase(hash))
|
|
|
|
|
2021-09-11 14:58:01 +00:00
|
|
|
proc validateSealer*(conf: NimbusConf, ctx: EthContext, chain: Chain): Result[void, string] =
|
2021-08-24 07:34:58 +00:00
|
|
|
if conf.engineSigner == ZERO_ADDRESS:
|
|
|
|
return err("signer address should not zero, use --engine-signer to set signer address")
|
|
|
|
|
2021-09-07 13:45:01 +00:00
|
|
|
let res = ctx.am.getAccount(conf.engineSigner)
|
|
|
|
if res.isErr:
|
2021-08-24 07:34:58 +00:00
|
|
|
return err("signer address not in registered accounts, use --import-key/account to register the account")
|
|
|
|
|
2021-09-07 13:45:01 +00:00
|
|
|
let acc = res.get()
|
2021-08-24 07:34:58 +00:00
|
|
|
if not acc.unlocked:
|
|
|
|
return err("signer account not unlocked, please unlock it first via rpc/password file")
|
|
|
|
|
|
|
|
let chainConf = chain.db.config
|
|
|
|
if not chainConf.poaEngine:
|
|
|
|
return err("currently only PoA engine is supported")
|
|
|
|
|
|
|
|
ok()
|
|
|
|
|
|
|
|
proc isLondon(c: ChainConfig, number: BlockNumber): bool {.inline.} =
|
|
|
|
number >= c.londonBlock
|
|
|
|
|
2021-10-05 23:31:35 +00:00
|
|
|
proc prepareHeader(engine: SealingEngineRef,
|
|
|
|
coinbase: EthAddress,
|
|
|
|
parent: BlockHeader,
|
|
|
|
time: Time): Result[BlockHeader, string] =
|
2021-08-24 07:34:58 +00:00
|
|
|
let timestamp = if parent.timestamp >= time:
|
|
|
|
parent.timestamp + 1.seconds
|
|
|
|
else:
|
|
|
|
time
|
|
|
|
|
|
|
|
var header = BlockHeader(
|
|
|
|
parentHash : parent.blockHash,
|
|
|
|
blockNumber: parent.blockNumber + 1.toBlockNumber,
|
|
|
|
# TODO: gasFloor and gasCeil can be configured by user
|
|
|
|
gasLimit : computeGasLimit(
|
|
|
|
parent.gasUsed,
|
|
|
|
parent.gasLimit,
|
|
|
|
gasFloor = DEFAULT_GAS_LIMIT,
|
|
|
|
gasCeil = DEFAULT_GAS_LIMIT),
|
2022-01-24 13:08:33 +00:00
|
|
|
extraData : daoForkBlockExtraData,
|
2021-10-05 23:31:35 +00:00
|
|
|
coinbase : coinbase,
|
2021-08-24 07:34:58 +00:00
|
|
|
timestamp : timestamp,
|
|
|
|
ommersHash : EMPTY_UNCLE_HASH,
|
|
|
|
stateRoot : parent.stateRoot,
|
|
|
|
txRoot : BLANK_ROOT_HASH,
|
|
|
|
receiptRoot: BLANK_ROOT_HASH
|
|
|
|
)
|
|
|
|
|
|
|
|
# Set baseFee and GasLimit if we are on an EIP-1559 chain
|
|
|
|
let conf = engine.chain.db.config
|
|
|
|
if isLondon(conf, header.blockNumber):
|
|
|
|
header.baseFee = calcEip1599BaseFee(conf, parent)
|
|
|
|
var parentGasLimit = parent.gasLimit
|
|
|
|
if not isLondon(conf, parent.blockNumber):
|
|
|
|
# Bump by 2x
|
|
|
|
parentGasLimit = parent.gasLimit * EIP1559_ELASTICITY_MULTIPLIER
|
|
|
|
# TODO: desiredLimit can be configured by user, gasCeil
|
|
|
|
header.gasLimit = calcGasLimit1559(parentGasLimit, desiredLimit = DEFAULT_GAS_LIMIT)
|
|
|
|
|
2022-01-24 13:08:33 +00:00
|
|
|
if engine.chain.isBlockAfterTtd(header):
|
2021-10-05 23:31:35 +00:00
|
|
|
header.difficulty = DifficultyInt.zero
|
2022-01-24 13:08:33 +00:00
|
|
|
header.mixDigest = default(Hash256)
|
|
|
|
header.nonce = default(BlockNonce)
|
|
|
|
else:
|
|
|
|
let res = engine.chain.clique.prepare(parent, header)
|
|
|
|
if res.isErr:
|
|
|
|
return err($res.error)
|
2021-10-05 23:31:35 +00:00
|
|
|
|
2021-08-24 07:34:58 +00:00
|
|
|
ok(header)
|
|
|
|
|
2021-10-05 23:31:35 +00:00
|
|
|
proc generateBlock(engine: SealingEngineRef,
|
|
|
|
coinbase: EthAddress,
|
|
|
|
parentBlockHeader: BlockHeader,
|
2022-01-24 13:08:33 +00:00
|
|
|
outBlock: var EthBlock,
|
|
|
|
timestamp = getTime()): Result[void, string] =
|
2021-08-24 07:34:58 +00:00
|
|
|
# deviation from standard block generator
|
|
|
|
# - no local and remote transactions inclusion(need tx pool)
|
|
|
|
# - no receipts from tx
|
|
|
|
# - no DAO hard fork
|
|
|
|
# - no local and remote uncles inclusion
|
|
|
|
|
2022-01-24 13:08:33 +00:00
|
|
|
let res = prepareHeader(engine, coinbase, parentBlockHeader, timestamp)
|
2021-08-24 07:34:58 +00:00
|
|
|
if res.isErr:
|
|
|
|
return err("error prepare header")
|
|
|
|
|
2021-10-05 23:31:35 +00:00
|
|
|
outBlock = EthBlock(
|
2021-08-24 07:34:58 +00:00
|
|
|
header: res.get()
|
|
|
|
)
|
|
|
|
|
2022-01-24 13:08:33 +00:00
|
|
|
if not engine.chain.isBlockAfterTtd(outBlock.header):
|
|
|
|
# TODO Post merge, Clique should not be executing
|
|
|
|
let sealRes = engine.chain.clique.seal(outBlock)
|
|
|
|
if sealRes.isErr:
|
|
|
|
return err("error sealing block header: " & $sealRes.error)
|
2021-08-24 07:34:58 +00:00
|
|
|
|
2021-10-05 23:31:35 +00:00
|
|
|
debug "generated block",
|
|
|
|
blockNumber = outBlock.header.blockNumber,
|
|
|
|
blockHash = blockHash(outBlock.header)
|
|
|
|
|
2021-08-24 07:34:58 +00:00
|
|
|
ok()
|
|
|
|
|
2021-10-05 23:31:35 +00:00
|
|
|
proc generateBlock(engine: SealingEngineRef,
|
|
|
|
coinbase: EthAddress,
|
|
|
|
parentHash: Hash256,
|
2022-01-24 13:08:33 +00:00
|
|
|
outBlock: var EthBlock,
|
|
|
|
timestamp = getTime()): Result[void, string] =
|
2021-10-05 23:31:35 +00:00
|
|
|
var parentBlockHeader: BlockHeader
|
|
|
|
if engine.chain.db.getBlockHeader(parentHash, parentBlockHeader):
|
2022-01-24 13:08:33 +00:00
|
|
|
generateBlock(engine, coinbase, parentBlockHeader, outBlock, timestamp)
|
2021-10-05 23:31:35 +00:00
|
|
|
else:
|
|
|
|
# TODO:
|
|
|
|
# This hack shouldn't be necessary if the database can find
|
|
|
|
# the genesis block hash in `getBlockHeader`.
|
|
|
|
let maybeGenesisBlock = engine.chain.currentBlock()
|
|
|
|
if parentHash == maybeGenesisBlock.blockHash:
|
|
|
|
generateBlock(engine, coinbase, maybeGenesisBlock, outBlock)
|
|
|
|
else:
|
|
|
|
return err "parent block not found"
|
|
|
|
|
|
|
|
proc generateBlock(engine: SealingEngineRef,
|
|
|
|
coinbase: EthAddress,
|
2022-01-24 13:08:33 +00:00
|
|
|
outBlock: var EthBlock,
|
|
|
|
timestamp = getTime()): Result[void, string] =
|
|
|
|
generateBlock(engine, coinbase, engine.chain.currentBlock(),
|
|
|
|
outBlock, timestamp)
|
2021-10-05 23:31:35 +00:00
|
|
|
|
2021-08-24 07:34:58 +00:00
|
|
|
proc sealingLoop(engine: SealingEngineRef): Future[void] {.async.} =
|
|
|
|
let clique = engine.chain.clique
|
|
|
|
|
2021-09-07 13:45:01 +00:00
|
|
|
proc signerFunc(signer: EthAddress, message: openArray[byte]):
|
|
|
|
Result[RawSignature, cstring] {.gcsafe.} =
|
|
|
|
let
|
|
|
|
hashData = keccakHash(message)
|
|
|
|
ctx = engine.ctx
|
|
|
|
acc = ctx.am.getAccount(signer).tryGet()
|
|
|
|
rawSign = sign(acc.privateKey, SkMessage(hashData.data)).toRaw
|
|
|
|
|
|
|
|
ok(rawSign)
|
|
|
|
|
|
|
|
clique.authorize(engine.signer, signerFunc)
|
2021-08-24 07:34:58 +00:00
|
|
|
|
2021-10-05 23:31:35 +00:00
|
|
|
# TODO: This should be configurable
|
|
|
|
var coinbase: EthAddress
|
|
|
|
|
2021-08-24 07:34:58 +00:00
|
|
|
# convert times.Duration to chronos.Duration
|
|
|
|
let period = chronos.seconds(clique.cfg.period.inSeconds)
|
|
|
|
|
|
|
|
while engine.state == EngineRunning:
|
|
|
|
# the sealing engine will tick every `cliquePeriod` seconds
|
|
|
|
await sleepAsync(period)
|
|
|
|
|
|
|
|
if engine.state != EngineRunning:
|
|
|
|
break
|
|
|
|
|
|
|
|
# deviation from 'correct' sealing engine:
|
|
|
|
# - no queue for chain reorgs
|
|
|
|
# - no async lock/guard against race with sync algo
|
|
|
|
var blk: EthBlock
|
2021-10-05 23:31:35 +00:00
|
|
|
let blkRes = engine.generateBlock(coinbase, blk)
|
2021-08-24 07:34:58 +00:00
|
|
|
if blkRes.isErr:
|
|
|
|
error "sealing engine generateBlock error", msg=blkRes.error
|
|
|
|
break
|
|
|
|
|
|
|
|
let res = engine.chain.persistBlocks([blk.header], [
|
|
|
|
BlockBody(transactions: blk.txs, uncles: blk.uncles)
|
|
|
|
])
|
|
|
|
|
|
|
|
if res == ValidationResult.Error:
|
|
|
|
error "sealing engine: persistBlocks error"
|
|
|
|
break
|
|
|
|
|
|
|
|
info "block generated", number=blk.header.blockNumber
|
|
|
|
|
2022-01-24 13:08:33 +00:00
|
|
|
template unsafeQuantityToInt64(q: web3types.Quantity): int64 =
|
|
|
|
int64 q
|
|
|
|
|
2021-10-05 23:31:35 +00:00
|
|
|
proc generateExecutionPayload*(engine: SealingEngineRef,
|
2022-01-24 13:08:33 +00:00
|
|
|
payloadAttrs: PayloadAttributesV1,
|
|
|
|
payloadRes: var ExecutionPayloadV1): Result[void, string] =
|
|
|
|
let headBlock = try: engine.chain.db.getCanonicalHead()
|
|
|
|
except CatchableError: return err "No head block in database"
|
|
|
|
|
2021-10-05 23:31:35 +00:00
|
|
|
var blk: EthBlock
|
2022-01-24 13:08:33 +00:00
|
|
|
let blkRes = engine.generateBlock(
|
|
|
|
EthAddress payloadAttrs.suggestedFeeRecipient,
|
|
|
|
headBlock,
|
|
|
|
blk,
|
|
|
|
fromUnix(payloadAttrs.timestamp.unsafeQuantityToInt64))
|
|
|
|
|
2021-10-05 23:31:35 +00:00
|
|
|
if blkRes.isErr:
|
|
|
|
error "sealing engine generateBlock error", msg = blkRes.error
|
|
|
|
return blkRes
|
|
|
|
|
|
|
|
let res = engine.chain.persistBlocks([blk.header], [
|
|
|
|
BlockBody(transactions: blk.txs, uncles: blk.uncles)
|
|
|
|
])
|
|
|
|
|
|
|
|
payloadRes.parentHash = Web3BlockHash blk.header.parentHash.data
|
2022-01-24 13:08:33 +00:00
|
|
|
payloadRes.feeRecipient = Web3Address blk.header.coinbase
|
2021-10-05 23:31:35 +00:00
|
|
|
payloadRes.stateRoot = Web3BlockHash blk.header.stateRoot.data
|
2022-01-24 13:08:33 +00:00
|
|
|
payloadRes.receiptsRoot = Web3BlockHash blk.header.receiptRoot.data
|
2021-10-05 23:31:35 +00:00
|
|
|
payloadRes.logsBloom = Web3Bloom blk.header.bloom
|
2022-01-24 13:08:33 +00:00
|
|
|
# TODO Check the extra data length here
|
|
|
|
# payloadres.extraData = web3types.DynamicBytes[256] blk.header.extraData
|
2021-10-05 23:31:35 +00:00
|
|
|
payloadRes.random = web3types.FixedBytes[32](payloadAttrs.random)
|
|
|
|
payloadRes.blockNumber = Web3Quantity blk.header.blockNumber.truncate(uint64)
|
|
|
|
payloadRes.gasLimit = Web3Quantity blk.header.gasLimit
|
|
|
|
payloadRes.gasUsed = Web3Quantity blk.header.gasUsed
|
|
|
|
payloadRes.timestamp = payloadAttrs.timestamp
|
|
|
|
# TODO
|
|
|
|
# res.extraData
|
|
|
|
payloadRes.baseFeePerGas = blk.header.fee.get(UInt256.zero)
|
|
|
|
payloadRes.blockHash = Web3BlockHash rlpHash(blk.header).data
|
|
|
|
# TODO
|
|
|
|
# res.transactions*: seq[TypedTransaction]
|
|
|
|
|
|
|
|
return ok()
|
|
|
|
|
2021-09-07 13:45:01 +00:00
|
|
|
proc new*(_: type SealingEngineRef,
|
|
|
|
chain: Chain,
|
|
|
|
ctx: EthContext,
|
2021-10-05 23:31:35 +00:00
|
|
|
signer: EthAddress,
|
2022-01-23 11:39:43 +00:00
|
|
|
txPool: TxPoolRef,
|
2021-10-05 23:31:35 +00:00
|
|
|
initialState: EngineState): SealingEngineRef =
|
2021-08-24 07:34:58 +00:00
|
|
|
SealingEngineRef(
|
2021-09-07 13:45:01 +00:00
|
|
|
chain: chain,
|
|
|
|
ctx: ctx,
|
2021-10-05 23:31:35 +00:00
|
|
|
signer: signer,
|
2022-01-23 11:39:43 +00:00
|
|
|
txPool: txPool,
|
2021-10-05 23:31:35 +00:00
|
|
|
state: initialState
|
2021-08-24 07:34:58 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
proc start*(engine: SealingEngineRef) =
|
|
|
|
## Starts sealing engine.
|
|
|
|
if engine.state == EngineStopped:
|
|
|
|
engine.state = EngineRunning
|
|
|
|
engine.engineLoop = sealingLoop(engine)
|
|
|
|
info "sealing engine started"
|
|
|
|
|
|
|
|
proc stop*(engine: SealingEngineRef) {.async.} =
|
|
|
|
## Stop sealing engine from producing more blocks.
|
|
|
|
if engine.state == EngineRunning:
|
|
|
|
engine.state = EngineStopped
|
|
|
|
await engine.engineLoop.cancelAndWait()
|
|
|
|
info "sealing engine stopped"
|