2023-01-19 08:33:11 +00:00
|
|
|
# Nimbus
|
2024-01-12 21:06:19 +00:00
|
|
|
# Copyright (c) 2023-2024 Status Research & Development GmbH
|
2023-01-19 08:33:11 +00:00
|
|
|
# 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.
|
|
|
|
|
2024-03-12 13:06:22 +00:00
|
|
|
## The beacon_lc_bridge is a "standalone" bridge, which means that it requires
|
|
|
|
## only a Portal client to inject content into the Portal network, but retrieves
|
|
|
|
## the content via p2p protocols only (no private / centralized full node access
|
|
|
|
## required).
|
|
|
|
## The bridge allows to follow the head of the beacon chain and inject the latest
|
|
|
|
## execution block headers and bodies into the Portal history network.
|
|
|
|
## It can, optionally, inject the beacon LC content into the Portal beacon network.
|
|
|
|
##
|
|
|
|
## The bridge does consensus light client sync and follows beacon block gossip.
|
|
|
|
## Once it is synced, the execution payload of new beacon blocks will be
|
|
|
|
## extracted and injected in the Portal network as execution headers and blocks.
|
|
|
|
##
|
|
|
|
## The injection into the Portal network is done via the `portal_historyGossip`
|
|
|
|
## JSON-RPC endpoint of a running Fluffy node.
|
|
|
|
##
|
|
|
|
## Actions that this type of bridge (currently?) cannot perform:
|
|
|
|
## 1. Inject block receipts into the portal network
|
|
|
|
## 2. Inject epoch accumulators into the portal network
|
|
|
|
## 3. Backfill headers and blocks
|
|
|
|
## 4. Provide proofs for the headers
|
|
|
|
##
|
|
|
|
## - To provide 1., it would require devp2p/eth access for the bridge to remain
|
|
|
|
## standalone.
|
|
|
|
## - To provide 2., it could use Era1 files.
|
|
|
|
## - To provide 3. and 4, it could use Era1 files pre-merge, and Era files
|
|
|
|
## post-merge. To backfill without Era or Era1 files, it could use libp2p and
|
|
|
|
## devp2p for access to the blocks, however it would not be possible to (easily)
|
|
|
|
## build the proofs for the headers.
|
2023-01-19 08:33:11 +00:00
|
|
|
|
2023-01-31 12:38:08 +00:00
|
|
|
{.push raises: [].}
|
2023-01-19 08:33:11 +00:00
|
|
|
|
|
|
|
import
|
|
|
|
std/[os, strutils, options],
|
2024-02-28 17:31:45 +00:00
|
|
|
chronicles,
|
|
|
|
chronos,
|
|
|
|
confutils,
|
2024-04-25 10:22:21 +00:00
|
|
|
eth/[keys, rlp, trie, trie/db],
|
2023-01-19 08:33:11 +00:00
|
|
|
# Need to rename this because of web3 ethtypes and ambigious indentifier mess
|
|
|
|
# for `BlockHeader`.
|
|
|
|
eth/common/eth_types as etypes,
|
|
|
|
eth/common/eth_types_rlp,
|
2023-06-04 06:00:50 +00:00
|
|
|
beacon_chain/el/el_manager,
|
2023-01-19 08:33:11 +00:00
|
|
|
beacon_chain/gossip_processing/optimistic_processor,
|
|
|
|
beacon_chain/networking/topic_params,
|
|
|
|
beacon_chain/spec/beaconstate,
|
|
|
|
beacon_chain/spec/datatypes/[phase0, altair, bellatrix],
|
2023-01-31 12:38:08 +00:00
|
|
|
beacon_chain/[light_client, nimbus_binary_common],
|
2023-01-19 08:33:11 +00:00
|
|
|
# Weirdness. Need to import this to be able to do errors.ValidationResult as
|
|
|
|
# else we get an ambiguous identifier, ValidationResult from eth & libp2p.
|
|
|
|
libp2p/protocols/pubsub/errors,
|
2024-03-12 13:06:22 +00:00
|
|
|
../../rpc/portal_rpc_client,
|
2023-03-28 13:50:23 +00:00
|
|
|
../../network/history/[history_content, history_network],
|
2023-10-20 10:06:25 +00:00
|
|
|
../../network/beacon/beacon_content,
|
2023-01-19 08:33:11 +00:00
|
|
|
../../common/common_types,
|
2023-07-25 18:53:31 +00:00
|
|
|
./beacon_lc_bridge_conf
|
2023-01-19 08:33:11 +00:00
|
|
|
|
2023-03-28 13:50:23 +00:00
|
|
|
from stew/objects import checkedEnumAssign
|
2023-12-08 09:35:50 +00:00
|
|
|
from web3/primitives as web3types import BlockHash
|
2023-03-28 13:50:23 +00:00
|
|
|
|
2023-01-19 08:33:11 +00:00
|
|
|
from beacon_chain/gossip_processing/block_processor import newExecutionPayload
|
|
|
|
from beacon_chain/gossip_processing/eth2_processor import toValidationResult
|
|
|
|
|
2023-03-09 23:40:55 +00:00
|
|
|
type Hash256 = etypes.Hash256
|
|
|
|
|
2023-10-17 12:19:50 +00:00
|
|
|
template asEthHash(hash: web3types.BlockHash): Hash256 =
|
2023-01-19 08:33:11 +00:00
|
|
|
Hash256(data: distinctBase(hash))
|
|
|
|
|
2023-05-30 04:56:54 +00:00
|
|
|
proc calculateTransactionData(
|
2024-02-28 17:31:45 +00:00
|
|
|
items: openArray[TypedTransaction]
|
|
|
|
): Hash256 {.raises: [].} =
|
2024-04-25 10:22:21 +00:00
|
|
|
var tr = initHexaryTrie(newMemoryDB(), isPruning = false)
|
2023-05-30 04:56:54 +00:00
|
|
|
for i, t in items:
|
|
|
|
try:
|
|
|
|
let tx = distinctBase(t)
|
|
|
|
tr.put(rlp.encode(i), tx)
|
2023-09-19 04:52:28 +00:00
|
|
|
except CatchableError as e:
|
|
|
|
# tr.put interface can raise exception
|
2023-05-30 04:56:54 +00:00
|
|
|
raiseAssert(e.msg)
|
|
|
|
|
|
|
|
return tr.rootHash()
|
|
|
|
|
|
|
|
# TODO: Since Capella we can also access ExecutionPayloadHeader and thus
|
|
|
|
# could get the Roots through there instead.
|
2024-02-28 17:31:45 +00:00
|
|
|
proc calculateWithdrawalsRoot(items: openArray[WithdrawalV1]): Hash256 {.raises: [].} =
|
2024-04-25 10:22:21 +00:00
|
|
|
var tr = initHexaryTrie(newMemoryDB(), isPruning = false)
|
2023-05-30 04:56:54 +00:00
|
|
|
for i, w in items:
|
|
|
|
try:
|
|
|
|
let withdrawal = etypes.Withdrawal(
|
|
|
|
index: distinctBase(w.index),
|
|
|
|
validatorIndex: distinctBase(w.validatorIndex),
|
|
|
|
address: distinctBase(w.address),
|
2024-02-28 17:31:45 +00:00
|
|
|
amount: distinctBase(w.amount),
|
2023-05-30 04:56:54 +00:00
|
|
|
)
|
|
|
|
tr.put(rlp.encode(i), rlp.encode(withdrawal))
|
2023-09-19 04:52:28 +00:00
|
|
|
except CatchableError as e:
|
2023-05-30 04:56:54 +00:00
|
|
|
raiseAssert(e.msg)
|
|
|
|
|
|
|
|
return tr.rootHash()
|
|
|
|
|
|
|
|
proc asPortalBlockData*(
|
2024-02-28 17:31:45 +00:00
|
|
|
payload: ExecutionPayloadV1
|
|
|
|
): (common_types.BlockHash, BlockHeaderWithProof, PortalBlockBodyLegacy) =
|
2023-01-19 08:33:11 +00:00
|
|
|
let
|
|
|
|
txRoot = calculateTransactionData(payload.transactions)
|
|
|
|
|
|
|
|
header = etypes.BlockHeader(
|
|
|
|
parentHash: payload.parentHash.asEthHash,
|
|
|
|
ommersHash: EMPTY_UNCLE_HASH,
|
|
|
|
coinbase: EthAddress payload.feeRecipient,
|
|
|
|
stateRoot: payload.stateRoot.asEthHash,
|
|
|
|
txRoot: txRoot,
|
2024-06-14 07:31:08 +00:00
|
|
|
receiptsRoot: payload.receiptsRoot.asEthHash,
|
|
|
|
logsBloom: distinctBase(payload.logsBloom),
|
2023-01-19 08:33:11 +00:00
|
|
|
difficulty: default(DifficultyInt),
|
2024-06-14 07:31:08 +00:00
|
|
|
number: payload.blockNumber.distinctBase,
|
2024-07-07 06:52:11 +00:00
|
|
|
gasLimit: distinctBase(payload.gasLimit),
|
|
|
|
gasUsed: distinctBase(payload.gasUsed),
|
2023-10-18 02:16:11 +00:00
|
|
|
timestamp: payload.timestamp.EthTime,
|
2023-01-19 08:33:11 +00:00
|
|
|
extraData: bytes payload.extraData,
|
2024-06-14 07:31:08 +00:00
|
|
|
mixHash: payload.prevRandao.asEthHash,
|
2023-01-19 08:33:11 +00:00
|
|
|
nonce: default(BlockNonce),
|
2024-06-14 07:31:08 +00:00
|
|
|
baseFeePerGas: Opt.some(payload.baseFeePerGas),
|
|
|
|
withdrawalsRoot: Opt.none(Hash256),
|
|
|
|
blobGasUsed: Opt.none(uint64),
|
|
|
|
excessBlobGas: Opt.none(uint64),
|
2023-01-19 08:33:11 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
headerWithProof = BlockHeaderWithProof(
|
2024-02-28 17:31:45 +00:00
|
|
|
header: ByteList(rlp.encode(header)), proof: BlockHeaderProof.init()
|
|
|
|
)
|
2023-01-19 08:33:11 +00:00
|
|
|
|
|
|
|
var transactions: Transactions
|
|
|
|
for tx in payload.transactions:
|
|
|
|
discard transactions.add(TransactionByteList(distinctBase(tx)))
|
|
|
|
|
2024-02-28 17:31:45 +00:00
|
|
|
let body =
|
|
|
|
PortalBlockBodyLegacy(transactions: transactions, uncles: Uncles(@[byte 0xc0]))
|
2023-01-19 08:33:11 +00:00
|
|
|
|
|
|
|
let hash = common_types.BlockHash(data: distinctBase(payload.blockHash))
|
|
|
|
|
|
|
|
(hash, headerWithProof, body)
|
|
|
|
|
2023-05-30 04:56:54 +00:00
|
|
|
proc asPortalBlockData*(
|
2024-05-15 03:07:59 +00:00
|
|
|
payload: ExecutionPayloadV2 | ExecutionPayloadV3 | ExecutionPayloadV4
|
2024-02-28 17:31:45 +00:00
|
|
|
): (common_types.BlockHash, BlockHeaderWithProof, PortalBlockBodyShanghai) =
|
2023-05-30 04:56:54 +00:00
|
|
|
let
|
|
|
|
txRoot = calculateTransactionData(payload.transactions)
|
2024-06-14 07:31:08 +00:00
|
|
|
withdrawalsRoot = Opt.some(calculateWithdrawalsRoot(payload.withdrawals))
|
2023-05-30 04:56:54 +00:00
|
|
|
|
2024-02-28 17:31:45 +00:00
|
|
|
# TODO: adjust blobGasUsed & excessBlobGas according to deneb fork!
|
2023-05-30 04:56:54 +00:00
|
|
|
header = etypes.BlockHeader(
|
|
|
|
parentHash: payload.parentHash.asEthHash,
|
|
|
|
ommersHash: EMPTY_UNCLE_HASH,
|
|
|
|
coinbase: EthAddress payload.feeRecipient,
|
|
|
|
stateRoot: payload.stateRoot.asEthHash,
|
|
|
|
txRoot: txRoot,
|
2024-06-14 07:31:08 +00:00
|
|
|
receiptsRoot: payload.receiptsRoot.asEthHash,
|
|
|
|
logsBloom: distinctBase(payload.logsBloom),
|
2023-05-30 04:56:54 +00:00
|
|
|
difficulty: default(DifficultyInt),
|
2024-06-14 07:31:08 +00:00
|
|
|
number: payload.blockNumber.distinctBase,
|
2024-07-07 06:52:11 +00:00
|
|
|
gasLimit: distinctBase(payload.gasLimit),
|
|
|
|
gasUsed: distinctBase(payload.gasUsed),
|
2023-10-18 02:16:11 +00:00
|
|
|
timestamp: payload.timestamp.EthTime,
|
2023-05-30 04:56:54 +00:00
|
|
|
extraData: bytes payload.extraData,
|
2024-06-14 07:31:08 +00:00
|
|
|
mixHash: payload.prevRandao.asEthHash,
|
2023-05-30 04:56:54 +00:00
|
|
|
nonce: default(BlockNonce),
|
2024-06-14 07:31:08 +00:00
|
|
|
baseFeePerGas: Opt.some(payload.baseFeePerGas),
|
2023-05-30 04:56:54 +00:00
|
|
|
withdrawalsRoot: withdrawalsRoot,
|
2024-06-14 07:31:08 +00:00
|
|
|
blobGasUsed: Opt.none(uint64),
|
|
|
|
excessBlobGas: Opt.none(uint64),
|
2023-05-30 04:56:54 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
headerWithProof = BlockHeaderWithProof(
|
2024-02-28 17:31:45 +00:00
|
|
|
header: ByteList(rlp.encode(header)), proof: BlockHeaderProof.init()
|
|
|
|
)
|
2023-05-30 04:56:54 +00:00
|
|
|
|
|
|
|
var transactions: Transactions
|
|
|
|
for tx in payload.transactions:
|
|
|
|
discard transactions.add(TransactionByteList(distinctBase(tx)))
|
|
|
|
|
|
|
|
func toWithdrawal(x: WithdrawalV1): Withdrawal =
|
|
|
|
Withdrawal(
|
|
|
|
index: x.index.uint64,
|
|
|
|
validatorIndex: x.validatorIndex.uint64,
|
|
|
|
address: x.address.EthAddress,
|
2024-02-28 17:31:45 +00:00
|
|
|
amount: x.amount.uint64,
|
2023-05-30 04:56:54 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var withdrawals: Withdrawals
|
|
|
|
for w in payload.withdrawals:
|
|
|
|
discard withdrawals.add(WithdrawalByteList(rlp.encode(toWithdrawal(w))))
|
|
|
|
|
|
|
|
let body = PortalBlockBodyShanghai(
|
2024-02-28 17:31:45 +00:00
|
|
|
transactions: transactions, uncles: Uncles(@[byte 0xc0]), withdrawals: withdrawals
|
|
|
|
)
|
2023-05-30 04:56:54 +00:00
|
|
|
|
|
|
|
let hash = common_types.BlockHash(data: distinctBase(payload.blockHash))
|
|
|
|
|
|
|
|
(hash, headerWithProof, body)
|
|
|
|
|
2023-02-07 16:21:12 +00:00
|
|
|
proc run(config: BeaconBridgeConf) {.raises: [CatchableError].} =
|
2023-01-19 08:33:11 +00:00
|
|
|
# Required as both Eth2Node and LightClient requires correct config type
|
|
|
|
var lcConfig = config.asLightClientConf()
|
|
|
|
|
|
|
|
setupLogging(config.logLevel, config.logStdout, none(OutFile))
|
|
|
|
|
2023-09-15 14:21:00 +00:00
|
|
|
notice "Launching fluffy beacon chain light bridge",
|
2023-01-19 08:33:11 +00:00
|
|
|
cmdParams = commandLineParams(), config
|
|
|
|
|
|
|
|
let metadata = loadEth2Network(config.eth2Network)
|
|
|
|
|
|
|
|
for node in metadata.bootstrapNodes:
|
|
|
|
lcConfig.bootstrapNodes.add node
|
|
|
|
|
2024-02-28 17:31:45 +00:00
|
|
|
template cfg(): auto =
|
|
|
|
metadata.cfg
|
2023-01-19 08:33:11 +00:00
|
|
|
|
|
|
|
let
|
|
|
|
genesisState =
|
|
|
|
try:
|
2024-02-28 17:31:45 +00:00
|
|
|
template genesisData(): auto =
|
|
|
|
metadata.genesis.bakedBytes
|
|
|
|
|
|
|
|
newClone(
|
|
|
|
readSszForkedHashedBeaconState(
|
|
|
|
cfg, genesisData.toOpenArray(genesisData.low, genesisData.high)
|
|
|
|
)
|
|
|
|
)
|
2023-01-19 08:33:11 +00:00
|
|
|
except CatchableError as err:
|
|
|
|
raiseAssert "Invalid baked-in state: " & err.msg
|
|
|
|
|
2024-01-12 21:06:19 +00:00
|
|
|
genesisTime = getStateField(genesisState[], genesis_time)
|
|
|
|
beaconClock = BeaconClock.init(genesisTime).valueOr:
|
|
|
|
error "Invalid genesis time in state", genesisTime
|
|
|
|
quit QuitFailure
|
2023-01-19 08:33:11 +00:00
|
|
|
|
|
|
|
getBeaconTime = beaconClock.getBeaconTimeFn()
|
|
|
|
|
2024-02-28 17:31:45 +00:00
|
|
|
genesis_validators_root = getStateField(genesisState[], genesis_validators_root)
|
2023-01-19 08:33:11 +00:00
|
|
|
forkDigests = newClone ForkDigests.init(cfg, genesis_validators_root)
|
|
|
|
|
|
|
|
genesisBlockRoot = get_initial_beacon_block(genesisState[]).root
|
|
|
|
|
|
|
|
rng = keys.newRng()
|
|
|
|
|
|
|
|
netKeys = getRandomNetKeys(rng[])
|
|
|
|
|
|
|
|
network = createEth2Node(
|
2024-02-28 17:31:45 +00:00
|
|
|
rng, lcConfig, netKeys, cfg, forkDigests, getBeaconTime, genesis_validators_root
|
2023-01-19 08:33:11 +00:00
|
|
|
)
|
|
|
|
|
2023-03-28 13:50:23 +00:00
|
|
|
portalRpcClient = newRpcHttpClient()
|
|
|
|
|
2024-02-28 17:31:45 +00:00
|
|
|
optimisticHandler = proc(
|
2024-06-19 01:57:45 +00:00
|
|
|
signedBlock: ForkedSignedBeaconBlock
|
2024-02-28 17:31:45 +00:00
|
|
|
): Future[void] {.async: (raises: [CancelledError]).} =
|
2023-01-19 08:33:11 +00:00
|
|
|
# TODO: Should not be gossiping optimistic blocks, but instead store them
|
|
|
|
# in a cache and only gossip them after they are confirmed due to an LC
|
|
|
|
# finalized header.
|
|
|
|
notice "New LC optimistic block",
|
2024-02-28 17:31:45 +00:00
|
|
|
opt = signedBlock.toBlockId(), wallSlot = getBeaconTime().slotOrZero
|
2023-01-19 08:33:11 +00:00
|
|
|
|
|
|
|
withBlck(signedBlock):
|
2023-04-13 16:40:01 +00:00
|
|
|
when consensusFork >= ConsensusFork.Bellatrix:
|
2023-10-17 12:19:50 +00:00
|
|
|
if forkyBlck.message.is_execution_block:
|
2024-02-28 17:31:45 +00:00
|
|
|
template payload(): auto =
|
|
|
|
forkyBlck.message.body.execution_payload
|
2023-01-19 08:33:11 +00:00
|
|
|
|
2023-03-28 13:50:23 +00:00
|
|
|
# TODO: Get rid of the asEngineExecutionPayload step?
|
|
|
|
let executionPayload = payload.asEngineExecutionPayload()
|
2024-02-28 17:31:45 +00:00
|
|
|
let (hash, headerWithProof, body) = asPortalBlockData(executionPayload)
|
2023-01-19 08:33:11 +00:00
|
|
|
|
|
|
|
logScope:
|
2024-02-28 17:31:45 +00:00
|
|
|
blockhash = history_content.`$` hash
|
2023-01-19 08:33:11 +00:00
|
|
|
|
|
|
|
block: # gossip header
|
2023-03-23 07:49:16 +00:00
|
|
|
let contentKey = history_content.ContentKey.init(blockHeader, hash)
|
2023-01-19 08:33:11 +00:00
|
|
|
let encodedContentKey = contentKey.encode.asSeq()
|
|
|
|
|
|
|
|
try:
|
2023-03-28 13:50:23 +00:00
|
|
|
let peers = await portalRpcClient.portal_historyGossip(
|
2024-02-28 17:31:45 +00:00
|
|
|
toHex(encodedContentKey), SSZ.encode(headerWithProof).toHex()
|
|
|
|
)
|
|
|
|
info "Block header gossiped",
|
|
|
|
peers, contentKey = encodedContentKey.toHex()
|
2023-01-19 08:33:11 +00:00
|
|
|
except CatchableError as e:
|
|
|
|
error "JSON-RPC error", error = $e.msg
|
2024-01-24 15:28:03 +00:00
|
|
|
# TODO: clean-up when json-rpc gets async raises annotations
|
|
|
|
try:
|
|
|
|
await portalRpcClient.close()
|
|
|
|
except CatchableError:
|
|
|
|
discard
|
2023-01-19 08:33:11 +00:00
|
|
|
|
|
|
|
# For bodies to get verified, the header needs to be available on
|
|
|
|
# the network. Wait a little to get the headers propagated through
|
|
|
|
# the network.
|
2023-03-28 13:50:23 +00:00
|
|
|
await sleepAsync(2.seconds)
|
2023-01-19 08:33:11 +00:00
|
|
|
|
|
|
|
block: # gossip block
|
2023-03-23 07:49:16 +00:00
|
|
|
let contentKey = history_content.ContentKey.init(blockBody, hash)
|
2023-01-19 08:33:11 +00:00
|
|
|
let encodedContentKey = contentKey.encode.asSeq()
|
|
|
|
|
|
|
|
try:
|
2023-03-28 13:50:23 +00:00
|
|
|
let peers = await portalRpcClient.portal_historyGossip(
|
2024-02-28 17:31:45 +00:00
|
|
|
encodedContentKey.toHex(), SSZ.encode(body).toHex()
|
|
|
|
)
|
|
|
|
info "Block body gossiped",
|
|
|
|
peers, contentKey = encodedContentKey.toHex()
|
2023-01-19 08:33:11 +00:00
|
|
|
except CatchableError as e:
|
|
|
|
error "JSON-RPC error", error = $e.msg
|
|
|
|
|
2024-01-24 15:28:03 +00:00
|
|
|
# TODO: clean-up when json-rpc gets async raises annotations
|
|
|
|
try:
|
|
|
|
await portalRpcClient.close()
|
|
|
|
except CatchableError:
|
|
|
|
discard
|
2023-03-28 13:50:23 +00:00
|
|
|
|
2023-01-19 08:33:11 +00:00
|
|
|
return
|
|
|
|
|
2024-02-28 17:31:45 +00:00
|
|
|
optimisticProcessor = initOptimisticProcessor(getBeaconTime, optimisticHandler)
|
2023-01-19 08:33:11 +00:00
|
|
|
|
|
|
|
lightClient = createLightClient(
|
2024-02-28 17:31:45 +00:00
|
|
|
network, rng, lcConfig, cfg, forkDigests, getBeaconTime, genesis_validators_root,
|
|
|
|
LightClientFinalizationMode.Optimistic,
|
|
|
|
)
|
2023-01-19 08:33:11 +00:00
|
|
|
|
2023-03-23 07:49:16 +00:00
|
|
|
### Beacon Light Client content bridging specific callbacks
|
2024-02-28 17:31:45 +00:00
|
|
|
proc onBootstrap(lightClient: LightClient, bootstrap: ForkedLightClientBootstrap) =
|
2023-03-23 07:49:16 +00:00
|
|
|
withForkyObject(bootstrap):
|
|
|
|
when lcDataFork > LightClientDataFork.None:
|
|
|
|
info "New Beacon LC bootstrap",
|
|
|
|
forkyObject, slot = forkyObject.header.beacon.slot
|
|
|
|
|
|
|
|
let
|
|
|
|
root = hash_tree_root(forkyObject.header)
|
|
|
|
contentKey = encode(bootstrapContentKey(root))
|
2024-02-28 17:31:45 +00:00
|
|
|
forkDigest =
|
|
|
|
forkDigestAtEpoch(forkDigests[], epoch(forkyObject.header.beacon.slot), cfg)
|
|
|
|
content = encodeBootstrapForked(forkDigest, bootstrap)
|
2023-03-23 07:49:16 +00:00
|
|
|
|
|
|
|
proc GossipRpcAndClose() {.async.} =
|
|
|
|
try:
|
|
|
|
let
|
|
|
|
contentKeyHex = contentKey.asSeq().toHex()
|
2023-10-20 10:06:25 +00:00
|
|
|
peers = await portalRpcClient.portal_beaconGossip(
|
2024-02-28 17:31:45 +00:00
|
|
|
contentKeyHex, content.toHex()
|
|
|
|
)
|
|
|
|
info "Beacon LC bootstrap gossiped", peers, contentKey = contentKeyHex
|
2023-03-23 07:49:16 +00:00
|
|
|
except CatchableError as e:
|
|
|
|
error "JSON-RPC error", error = $e.msg
|
|
|
|
|
2023-03-28 13:50:23 +00:00
|
|
|
await portalRpcClient.close()
|
2023-03-23 07:49:16 +00:00
|
|
|
|
|
|
|
asyncSpawn(GossipRpcAndClose())
|
|
|
|
|
|
|
|
proc onUpdate(lightClient: LightClient, update: ForkedLightClientUpdate) =
|
|
|
|
withForkyObject(update):
|
|
|
|
when lcDataFork > LightClientDataFork.None:
|
|
|
|
info "New Beacon LC update",
|
|
|
|
update, slot = forkyObject.attested_header.beacon.slot
|
|
|
|
|
|
|
|
let
|
|
|
|
period = forkyObject.attested_header.beacon.slot.sync_committee_period
|
|
|
|
contentKey = encode(updateContentKey(period.uint64, uint64(1)))
|
|
|
|
forkDigest = forkDigestAtEpoch(
|
2024-02-28 17:31:45 +00:00
|
|
|
forkDigests[], epoch(forkyObject.attested_header.beacon.slot), cfg
|
2023-03-23 07:49:16 +00:00
|
|
|
)
|
2024-02-28 17:31:45 +00:00
|
|
|
content = encodeLightClientUpdatesForked(forkDigest, @[update])
|
2023-03-23 07:49:16 +00:00
|
|
|
|
|
|
|
proc GossipRpcAndClose() {.async.} =
|
|
|
|
try:
|
|
|
|
let
|
|
|
|
contentKeyHex = contentKey.asSeq().toHex()
|
2023-10-20 10:06:25 +00:00
|
|
|
peers = await portalRpcClient.portal_beaconGossip(
|
2024-02-28 17:31:45 +00:00
|
|
|
contentKeyHex, content.toHex()
|
|
|
|
)
|
|
|
|
info "Beacon LC bootstrap gossiped", peers, contentKey = contentKeyHex
|
2023-03-23 07:49:16 +00:00
|
|
|
except CatchableError as e:
|
|
|
|
error "JSON-RPC error", error = $e.msg
|
|
|
|
|
2023-03-28 13:50:23 +00:00
|
|
|
await portalRpcClient.close()
|
2023-03-23 07:49:16 +00:00
|
|
|
|
|
|
|
asyncSpawn(GossipRpcAndClose())
|
|
|
|
|
|
|
|
proc onOptimisticUpdate(
|
2024-02-28 17:31:45 +00:00
|
|
|
lightClient: LightClient, update: ForkedLightClientOptimisticUpdate
|
|
|
|
) =
|
2023-03-23 07:49:16 +00:00
|
|
|
withForkyObject(update):
|
|
|
|
when lcDataFork > LightClientDataFork.None:
|
|
|
|
info "New Beacon LC optimistic update",
|
|
|
|
update, slot = forkyObject.attested_header.beacon.slot
|
|
|
|
|
|
|
|
let
|
2023-10-06 15:42:34 +00:00
|
|
|
slot = forkyObject.signature_slot
|
2023-03-23 07:49:16 +00:00
|
|
|
contentKey = encode(optimisticUpdateContentKey(slot.uint64))
|
|
|
|
forkDigest = forkDigestAtEpoch(
|
2024-02-28 17:31:45 +00:00
|
|
|
forkDigests[], epoch(forkyObject.attested_header.beacon.slot), cfg
|
2023-03-23 07:49:16 +00:00
|
|
|
)
|
2024-02-28 17:31:45 +00:00
|
|
|
content = encodeOptimisticUpdateForked(forkDigest, update)
|
2023-03-23 07:49:16 +00:00
|
|
|
|
|
|
|
proc GossipRpcAndClose() {.async.} =
|
|
|
|
try:
|
|
|
|
let
|
|
|
|
contentKeyHex = contentKey.asSeq().toHex()
|
2023-10-20 10:06:25 +00:00
|
|
|
peers = await portalRpcClient.portal_beaconGossip(
|
2024-02-28 17:31:45 +00:00
|
|
|
contentKeyHex, content.toHex()
|
|
|
|
)
|
|
|
|
info "Beacon LC bootstrap gossiped", peers, contentKey = contentKeyHex
|
2023-03-23 07:49:16 +00:00
|
|
|
except CatchableError as e:
|
|
|
|
error "JSON-RPC error", error = $e.msg
|
|
|
|
|
2023-03-28 13:50:23 +00:00
|
|
|
await portalRpcClient.close()
|
2023-03-23 07:49:16 +00:00
|
|
|
|
|
|
|
asyncSpawn(GossipRpcAndClose())
|
|
|
|
|
|
|
|
proc onFinalityUpdate(
|
2024-02-28 17:31:45 +00:00
|
|
|
lightClient: LightClient, update: ForkedLightClientFinalityUpdate
|
|
|
|
) =
|
2023-03-23 07:49:16 +00:00
|
|
|
withForkyObject(update):
|
|
|
|
when lcDataFork > LightClientDataFork.None:
|
|
|
|
info "New Beacon LC finality update",
|
|
|
|
update, slot = forkyObject.attested_header.beacon.slot
|
|
|
|
let
|
|
|
|
finalizedSlot = forkyObject.finalized_header.beacon.slot
|
2023-10-06 13:46:53 +00:00
|
|
|
contentKey = encode(finalityUpdateContentKey(finalizedSlot.uint64))
|
2023-03-23 07:49:16 +00:00
|
|
|
forkDigest = forkDigestAtEpoch(
|
2024-02-28 17:31:45 +00:00
|
|
|
forkDigests[], epoch(forkyObject.attested_header.beacon.slot), cfg
|
2023-03-23 07:49:16 +00:00
|
|
|
)
|
2024-02-28 17:31:45 +00:00
|
|
|
content = encodeFinalityUpdateForked(forkDigest, update)
|
2023-03-23 07:49:16 +00:00
|
|
|
|
|
|
|
proc GossipRpcAndClose() {.async.} =
|
|
|
|
try:
|
|
|
|
let
|
|
|
|
contentKeyHex = contentKey.asSeq().toHex()
|
2023-10-20 10:06:25 +00:00
|
|
|
peers = await portalRpcClient.portal_beaconGossip(
|
2024-02-28 17:31:45 +00:00
|
|
|
contentKeyHex, content.toHex()
|
|
|
|
)
|
|
|
|
info "Beacon LC bootstrap gossiped", peers, contentKey = contentKeyHex
|
2023-03-23 07:49:16 +00:00
|
|
|
except CatchableError as e:
|
|
|
|
error "JSON-RPC error", error = $e.msg
|
|
|
|
|
2023-03-28 13:50:23 +00:00
|
|
|
await portalRpcClient.close()
|
2023-03-23 07:49:16 +00:00
|
|
|
|
|
|
|
asyncSpawn(GossipRpcAndClose())
|
|
|
|
|
|
|
|
###
|
|
|
|
|
2023-03-28 13:50:23 +00:00
|
|
|
waitFor portalRpcClient.connect(config.rpcAddress, Port(config.rpcPort), false)
|
|
|
|
|
2023-01-19 08:33:11 +00:00
|
|
|
info "Listening to incoming network requests"
|
2024-01-13 01:41:57 +00:00
|
|
|
network.registerProtocol(
|
2024-02-28 17:31:45 +00:00
|
|
|
PeerSync,
|
|
|
|
PeerSync.NetworkState.init(cfg, forkDigests, genesisBlockRoot, getBeaconTime),
|
|
|
|
)
|
2023-01-19 08:33:11 +00:00
|
|
|
network.addValidator(
|
|
|
|
getBeaconBlocksTopic(forkDigests.phase0),
|
2024-02-28 17:31:45 +00:00
|
|
|
proc(signedBlock: phase0.SignedBeaconBlock): errors.ValidationResult =
|
|
|
|
toValidationResult(optimisticProcessor.processSignedBeaconBlock(signedBlock))
|
|
|
|
,
|
|
|
|
)
|
2023-01-19 08:33:11 +00:00
|
|
|
network.addValidator(
|
|
|
|
getBeaconBlocksTopic(forkDigests.altair),
|
2024-02-28 17:31:45 +00:00
|
|
|
proc(signedBlock: altair.SignedBeaconBlock): errors.ValidationResult =
|
|
|
|
toValidationResult(optimisticProcessor.processSignedBeaconBlock(signedBlock))
|
|
|
|
,
|
|
|
|
)
|
2023-01-19 08:33:11 +00:00
|
|
|
network.addValidator(
|
|
|
|
getBeaconBlocksTopic(forkDigests.bellatrix),
|
2024-02-28 17:31:45 +00:00
|
|
|
proc(signedBlock: bellatrix.SignedBeaconBlock): errors.ValidationResult =
|
|
|
|
toValidationResult(optimisticProcessor.processSignedBeaconBlock(signedBlock))
|
|
|
|
,
|
|
|
|
)
|
2023-04-13 16:40:01 +00:00
|
|
|
network.addValidator(
|
|
|
|
getBeaconBlocksTopic(forkDigests.capella),
|
2024-02-28 17:31:45 +00:00
|
|
|
proc(signedBlock: capella.SignedBeaconBlock): errors.ValidationResult =
|
|
|
|
toValidationResult(optimisticProcessor.processSignedBeaconBlock(signedBlock))
|
|
|
|
,
|
|
|
|
)
|
2023-04-13 16:40:01 +00:00
|
|
|
network.addValidator(
|
|
|
|
getBeaconBlocksTopic(forkDigests.deneb),
|
2024-02-28 17:31:45 +00:00
|
|
|
proc(signedBlock: deneb.SignedBeaconBlock): errors.ValidationResult =
|
|
|
|
toValidationResult(optimisticProcessor.processSignedBeaconBlock(signedBlock))
|
|
|
|
,
|
|
|
|
)
|
2023-01-19 08:33:11 +00:00
|
|
|
lightClient.installMessageValidators()
|
|
|
|
|
|
|
|
waitFor network.startListening()
|
|
|
|
waitFor network.start()
|
|
|
|
|
|
|
|
proc onFinalizedHeader(
|
2024-02-28 17:31:45 +00:00
|
|
|
lightClient: LightClient, finalizedHeader: ForkedLightClientHeader
|
|
|
|
) =
|
2023-01-27 14:57:48 +00:00
|
|
|
withForkyHeader(finalizedHeader):
|
|
|
|
when lcDataFork > LightClientDataFork.None:
|
2024-02-28 17:31:45 +00:00
|
|
|
info "New LC finalized header", finalized_header = shortLog(forkyHeader)
|
2023-01-19 08:33:11 +00:00
|
|
|
|
|
|
|
proc onOptimisticHeader(
|
2024-02-28 17:31:45 +00:00
|
|
|
lightClient: LightClient, optimisticHeader: ForkedLightClientHeader
|
|
|
|
) =
|
2023-01-27 14:57:48 +00:00
|
|
|
withForkyHeader(optimisticHeader):
|
|
|
|
when lcDataFork > LightClientDataFork.None:
|
2024-02-28 17:31:45 +00:00
|
|
|
info "New LC optimistic header", optimistic_header = shortLog(forkyHeader)
|
2023-01-19 08:33:11 +00:00
|
|
|
|
|
|
|
lightClient.onFinalizedHeader = onFinalizedHeader
|
|
|
|
lightClient.onOptimisticHeader = onOptimisticHeader
|
|
|
|
lightClient.trustedBlockRoot = some config.trustedBlockRoot
|
|
|
|
|
2023-03-23 07:49:16 +00:00
|
|
|
if config.beaconLightClient:
|
|
|
|
lightClient.bootstrapObserver = onBootstrap
|
|
|
|
lightClient.updateObserver = onUpdate
|
|
|
|
lightClient.finalityUpdateObserver = onFinalityUpdate
|
|
|
|
lightClient.optimisticUpdateObserver = onOptimisticUpdate
|
|
|
|
|
2023-01-19 08:33:11 +00:00
|
|
|
func shouldSyncOptimistically(wallSlot: Slot): bool =
|
2023-01-27 14:57:48 +00:00
|
|
|
let optimisticHeader = lightClient.optimisticHeader
|
|
|
|
withForkyHeader(optimisticHeader):
|
|
|
|
when lcDataFork > LightClientDataFork.None:
|
|
|
|
# Check whether light client has synced sufficiently close to wall slot
|
|
|
|
const maxAge = 2 * SLOTS_PER_EPOCH
|
|
|
|
forkyHeader.beacon.slot >= max(wallSlot, maxAge.Slot) - maxAge
|
|
|
|
else:
|
|
|
|
false
|
2023-01-19 08:33:11 +00:00
|
|
|
|
|
|
|
var blocksGossipState: GossipState = {}
|
|
|
|
proc updateBlocksGossipStatus(slot: Slot) =
|
|
|
|
let
|
|
|
|
isBehind = not shouldSyncOptimistically(slot)
|
|
|
|
|
|
|
|
targetGossipState = getTargetGossipState(
|
|
|
|
slot.epoch, cfg.ALTAIR_FORK_EPOCH, cfg.BELLATRIX_FORK_EPOCH,
|
2024-05-26 07:13:59 +00:00
|
|
|
cfg.CAPELLA_FORK_EPOCH, cfg.DENEB_FORK_EPOCH, cfg.ELECTRA_FORK_EPOCH, isBehind,
|
2024-02-28 17:31:45 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
template currentGossipState(): auto =
|
|
|
|
blocksGossipState
|
2023-01-19 08:33:11 +00:00
|
|
|
|
|
|
|
if currentGossipState == targetGossipState:
|
|
|
|
return
|
|
|
|
|
|
|
|
if currentGossipState.card == 0 and targetGossipState.card > 0:
|
2024-02-28 17:31:45 +00:00
|
|
|
debug "Enabling blocks topic subscriptions", wallSlot = slot, targetGossipState
|
2023-01-19 08:33:11 +00:00
|
|
|
elif currentGossipState.card > 0 and targetGossipState.card == 0:
|
2024-02-28 17:31:45 +00:00
|
|
|
debug "Disabling blocks topic subscriptions", wallSlot = slot
|
2023-01-19 08:33:11 +00:00
|
|
|
else:
|
|
|
|
# Individual forks added / removed
|
|
|
|
discard
|
|
|
|
|
|
|
|
let
|
|
|
|
newGossipForks = targetGossipState - currentGossipState
|
|
|
|
oldGossipForks = currentGossipState - targetGossipState
|
|
|
|
|
|
|
|
for gossipFork in oldGossipForks:
|
2023-04-13 16:40:01 +00:00
|
|
|
let forkDigest = forkDigests[].atConsensusFork(gossipFork)
|
2023-01-19 08:33:11 +00:00
|
|
|
network.unsubscribe(getBeaconBlocksTopic(forkDigest))
|
|
|
|
|
|
|
|
for gossipFork in newGossipForks:
|
2023-04-13 16:40:01 +00:00
|
|
|
let forkDigest = forkDigests[].atConsensusFork(gossipFork)
|
2023-01-19 08:33:11 +00:00
|
|
|
network.subscribe(
|
2024-02-28 17:31:45 +00:00
|
|
|
getBeaconBlocksTopic(forkDigest), blocksTopicParams, enableTopicMetrics = true
|
|
|
|
)
|
2023-01-19 08:33:11 +00:00
|
|
|
|
|
|
|
blocksGossipState = targetGossipState
|
|
|
|
|
|
|
|
proc onSecond(time: Moment) =
|
|
|
|
let wallSlot = getBeaconTime().slotOrZero()
|
|
|
|
updateBlocksGossipStatus(wallSlot + 1)
|
|
|
|
lightClient.updateGossipStatus(wallSlot + 1)
|
|
|
|
|
|
|
|
proc runOnSecondLoop() {.async.} =
|
|
|
|
let sleepTime = chronos.seconds(1)
|
|
|
|
while true:
|
|
|
|
let start = chronos.now(chronos.Moment)
|
|
|
|
await chronos.sleepAsync(sleepTime)
|
|
|
|
let afterSleep = chronos.now(chronos.Moment)
|
|
|
|
let sleepTime = afterSleep - start
|
|
|
|
onSecond(start)
|
|
|
|
let finished = chronos.now(chronos.Moment)
|
|
|
|
let processingTime = finished - afterSleep
|
|
|
|
trace "onSecond task completed", sleepTime, processingTime
|
|
|
|
|
|
|
|
onSecond(Moment.now())
|
|
|
|
lightClient.start()
|
|
|
|
|
|
|
|
asyncSpawn runOnSecondLoop()
|
|
|
|
while true:
|
|
|
|
poll()
|
|
|
|
|
|
|
|
when isMainModule:
|
2023-02-07 16:21:12 +00:00
|
|
|
{.pop.}
|
2024-02-28 17:31:45 +00:00
|
|
|
var config = makeBannerAndConfig("Nimbus beacon chain bridge", BeaconBridgeConf)
|
2023-02-07 16:21:12 +00:00
|
|
|
{.push raises: [].}
|
|
|
|
|
|
|
|
run(config)
|