2018-11-26 13:33:06 +00:00
|
|
|
import
|
2020-10-14 14:04:08 +00:00
|
|
|
std/[deques, tables, hashes, options, strformat, strutils],
|
2020-07-02 15:14:11 +00:00
|
|
|
chronos, web3, web3/ethtypes as web3Types, json, chronicles,
|
|
|
|
eth/common/eth_types, eth/async_utils,
|
2020-10-15 11:49:02 +00:00
|
|
|
spec/[datatypes, digest, crypto, beaconstate, helpers],
|
2020-10-12 01:07:20 +00:00
|
|
|
ssz, beacon_chain_db, network_metadata, merkle_minimal, beacon_node_status
|
2018-11-26 13:33:06 +00:00
|
|
|
|
2020-06-19 17:42:28 +00:00
|
|
|
export
|
2020-07-02 15:14:11 +00:00
|
|
|
web3Types
|
2020-06-19 17:42:28 +00:00
|
|
|
|
2020-03-24 11:13:07 +00:00
|
|
|
contract(DepositContract):
|
|
|
|
proc deposit(pubkey: Bytes48,
|
|
|
|
withdrawalCredentials: Bytes32,
|
|
|
|
signature: Bytes96,
|
|
|
|
deposit_data_root: FixedBytes[32])
|
|
|
|
|
|
|
|
proc get_deposit_root(): FixedBytes[32]
|
|
|
|
proc get_deposit_count(): Bytes8
|
|
|
|
|
|
|
|
proc DepositEvent(pubkey: Bytes48,
|
|
|
|
withdrawalCredentials: Bytes32,
|
|
|
|
amount: Bytes8,
|
|
|
|
signature: Bytes96,
|
|
|
|
index: Bytes8) {.event.}
|
|
|
|
# TODO
|
|
|
|
# The raises list of this module are still not usable due to general
|
|
|
|
# Exceptions being reported from Chronos's asyncfutures2.
|
|
|
|
|
2018-11-26 13:33:06 +00:00
|
|
|
type
|
2020-03-24 11:13:07 +00:00
|
|
|
Eth1BlockNumber* = uint64
|
|
|
|
Eth1BlockTimestamp* = uint64
|
2020-07-02 15:14:11 +00:00
|
|
|
Eth1BlockHeader = web3Types.BlockHeader
|
2020-03-24 11:13:07 +00:00
|
|
|
|
2020-10-12 01:07:20 +00:00
|
|
|
Database* = object
|
|
|
|
|
2020-03-24 11:13:07 +00:00
|
|
|
Eth1Block* = ref object
|
|
|
|
number*: Eth1BlockNumber
|
|
|
|
timestamp*: Eth1BlockTimestamp
|
|
|
|
deposits*: seq[Deposit]
|
|
|
|
voteData*: Eth1Data
|
2020-11-03 01:21:07 +00:00
|
|
|
activeValidatorsCount*: uint64
|
2020-06-25 23:33:06 +00:00
|
|
|
|
2020-03-24 11:13:07 +00:00
|
|
|
Eth1Chain* = object
|
2020-06-27 12:01:19 +00:00
|
|
|
knownStart: Eth1Data
|
2020-03-24 11:13:07 +00:00
|
|
|
blocks: Deque[Eth1Block]
|
|
|
|
blocksByHash: Table[BlockHash, Eth1Block]
|
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
Eth1Monitor* = ref object
|
2020-10-12 01:07:20 +00:00
|
|
|
db: BeaconChainDB
|
2020-07-07 23:02:14 +00:00
|
|
|
preset: RuntimePreset
|
2020-11-12 19:01:26 +00:00
|
|
|
depositContractDeployedAt: BlockHashOrNumber
|
2020-10-14 14:04:08 +00:00
|
|
|
|
|
|
|
dataProvider: Web3DataProviderRef
|
2020-11-03 01:21:07 +00:00
|
|
|
|
|
|
|
latestEth1BlockNumber: Eth1BlockNumber
|
|
|
|
eth1Progress: AsyncEvent
|
|
|
|
|
2020-10-14 14:04:08 +00:00
|
|
|
eth1Chain: Eth1Chain
|
2018-11-26 13:33:06 +00:00
|
|
|
|
2020-04-23 18:58:54 +00:00
|
|
|
genesisState: NilableBeaconStateRef
|
2019-09-09 15:59:02 +00:00
|
|
|
genesisStateFut: Future[void]
|
2018-11-26 13:33:06 +00:00
|
|
|
|
2019-11-22 13:16:07 +00:00
|
|
|
runFut: Future[void]
|
|
|
|
|
2020-10-14 14:04:08 +00:00
|
|
|
Web3DataProvider* = object
|
2020-03-24 11:13:07 +00:00
|
|
|
url: string
|
|
|
|
web3: Web3
|
|
|
|
ns: Sender[DepositContract]
|
2020-06-27 12:01:19 +00:00
|
|
|
blockHeadersSubscription: Subscription
|
2020-03-24 11:13:07 +00:00
|
|
|
|
|
|
|
Web3DataProviderRef* = ref Web3DataProvider
|
|
|
|
|
|
|
|
ReorgDepthLimitExceeded = object of CatchableError
|
|
|
|
CorruptDataProvider = object of CatchableError
|
|
|
|
|
|
|
|
DisconnectHandler* = proc () {.gcsafe, raises: [Defect].}
|
|
|
|
|
|
|
|
DepositEventHandler* = proc (
|
|
|
|
pubkey: Bytes48,
|
|
|
|
withdrawalCredentials: Bytes32,
|
|
|
|
amount: Bytes8,
|
2020-05-08 14:24:47 +00:00
|
|
|
signature: Bytes96, merkleTreeIndex: Bytes8, j: JsonNode) {.raises: [Defect], gcsafe.}
|
2020-03-24 11:13:07 +00:00
|
|
|
|
|
|
|
const
|
2020-06-17 16:39:16 +00:00
|
|
|
web3Timeouts = 5.seconds
|
2020-11-03 01:21:07 +00:00
|
|
|
hasDepositRootChecks = defined(with_deposit_root_checks)
|
2020-07-07 23:02:14 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
template depositContractAddress(m: Eth1Monitor): Eth1Address =
|
2020-10-14 14:04:08 +00:00
|
|
|
m.dataProvider.ns.contractAddress
|
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
template web3Url(m: Eth1Monitor): string =
|
2020-10-14 14:04:08 +00:00
|
|
|
m.dataProvider.url
|
|
|
|
|
2020-11-12 13:49:13 +00:00
|
|
|
proc fixupWeb3Urls*(web3Url: var string) =
|
2020-11-05 23:11:06 +00:00
|
|
|
## Converts HTTP and HTTPS Infura URLs to their WebSocket equivalents
|
|
|
|
## because we are missing a functional HTTPS client.
|
|
|
|
let normalizedUrl = toLowerAscii(web3Url)
|
|
|
|
var pos = 0
|
|
|
|
|
2020-11-12 13:49:13 +00:00
|
|
|
template skip(x: string): bool {.dirty.} =
|
2020-11-05 23:11:06 +00:00
|
|
|
if normalizedUrl.len - pos >= x.len and
|
|
|
|
normalizedUrl.toOpenArray(pos, pos + x.len - 1) == x:
|
|
|
|
pos += x.len
|
|
|
|
true
|
|
|
|
else:
|
|
|
|
false
|
|
|
|
|
|
|
|
if not (skip("https://") or skip("http://")):
|
2020-11-12 13:49:13 +00:00
|
|
|
if not (skip("ws://") or skip("wss://")):
|
|
|
|
web3Url = "ws://" & web3Url
|
|
|
|
warn "The Web3 URL does not specify a protocol. Assuming a WebSocket server", web3Url
|
2020-11-05 23:11:06 +00:00
|
|
|
return
|
|
|
|
|
2020-11-12 13:49:13 +00:00
|
|
|
block infuraRewrite:
|
|
|
|
var pos = pos
|
|
|
|
let network = if skip("mainnet"): mainnet
|
|
|
|
elif skip("goerli"): goerli
|
|
|
|
else: break
|
2020-11-05 23:11:06 +00:00
|
|
|
|
2020-11-12 13:49:13 +00:00
|
|
|
if not skip(".infura.io/v3/"):
|
|
|
|
break
|
2020-11-05 23:11:06 +00:00
|
|
|
|
2020-11-12 13:49:13 +00:00
|
|
|
template infuraKey: string = normalizedUrl.substr(pos)
|
2020-11-05 23:11:06 +00:00
|
|
|
|
2020-11-12 13:49:13 +00:00
|
|
|
web3Url = "wss://" & $network & ".infura.io/ws/v3/" & infuraKey
|
|
|
|
return
|
2020-11-05 23:11:06 +00:00
|
|
|
|
2020-11-12 13:49:13 +00:00
|
|
|
block gethRewrite:
|
|
|
|
web3Url = "ws://" & normalizedUrl.substr(pos)
|
|
|
|
warn "Only WebSocket web3 providers are supported. Rewriting URL", web3Url
|
2020-11-05 23:11:06 +00:00
|
|
|
|
2020-07-07 23:02:14 +00:00
|
|
|
# TODO: Add preset validation
|
|
|
|
# MIN_GENESIS_ACTIVE_VALIDATOR_COUNT should be larger than SLOTS_PER_EPOCH
|
2020-08-06 09:08:54 +00:00
|
|
|
# doAssert SECONDS_PER_ETH1_BLOCK * preset.ETH1_FOLLOW_DISTANCE < GENESIS_DELAY,
|
2020-07-07 23:02:14 +00:00
|
|
|
# "Invalid configuration: GENESIS_DELAY is set too low"
|
2020-03-24 11:13:07 +00:00
|
|
|
|
2020-11-09 14:18:55 +00:00
|
|
|
# https://github.com/ethereum/eth2.0-specs/blob/v1.0.0/specs/phase0/validator.md#get_eth1_data
|
2020-03-24 11:13:07 +00:00
|
|
|
func compute_time_at_slot(state: BeaconState, slot: Slot): uint64 =
|
2020-06-15 09:38:05 +00:00
|
|
|
state.genesis_time + slot * SECONDS_PER_SLOT
|
2020-03-24 11:13:07 +00:00
|
|
|
|
2020-11-09 14:18:55 +00:00
|
|
|
# https://github.com/ethereum/eth2.0-specs/blob/v1.0.0/specs/phase0/validator.md#get_eth1_data
|
2020-03-24 11:13:07 +00:00
|
|
|
func voting_period_start_time*(state: BeaconState): uint64 =
|
2020-06-15 09:38:05 +00:00
|
|
|
let eth1_voting_period_start_slot =
|
|
|
|
state.slot - state.slot mod SLOTS_PER_ETH1_VOTING_PERIOD.uint64
|
|
|
|
compute_time_at_slot(state, eth1_voting_period_start_slot)
|
2020-03-24 11:13:07 +00:00
|
|
|
|
2020-11-09 14:18:55 +00:00
|
|
|
# https://github.com/ethereum/eth2.0-specs/blob/v1.0.0/specs/phase0/validator.md#get_eth1_data
|
2020-08-06 09:08:54 +00:00
|
|
|
func is_candidate_block(preset: RuntimePreset, blk: Eth1Block, period_start: uint64): bool =
|
|
|
|
(blk.timestamp + SECONDS_PER_ETH1_BLOCK.uint64 * preset.ETH1_FOLLOW_DISTANCE <= period_start) and
|
|
|
|
(blk.timestamp + SECONDS_PER_ETH1_BLOCK.uint64 * preset.ETH1_FOLLOW_DISTANCE * 2 >= period_start)
|
2020-03-24 11:13:07 +00:00
|
|
|
|
2020-06-19 17:42:28 +00:00
|
|
|
func asEth2Digest*(x: BlockHash): Eth2Digest =
|
2020-03-24 11:13:07 +00:00
|
|
|
Eth2Digest(data: array[32, byte](x))
|
|
|
|
|
|
|
|
template asBlockHash(x: Eth2Digest): BlockHash =
|
|
|
|
BlockHash(x.data)
|
|
|
|
|
2020-09-06 08:39:25 +00:00
|
|
|
func shortLog*(b: Eth1Block): string =
|
2020-06-27 12:01:19 +00:00
|
|
|
&"{b.number}:{shortLog b.voteData.block_hash}"
|
|
|
|
|
2020-03-24 11:13:07 +00:00
|
|
|
template findBlock*(eth1Chain: Eth1Chain, hash: BlockHash): Eth1Block =
|
|
|
|
eth1Chain.blocksByHash.getOrDefault(hash, nil)
|
|
|
|
|
|
|
|
template findBlock*(eth1Chain: Eth1Chain, eth1Data: Eth1Data): Eth1Block =
|
|
|
|
getOrDefault(eth1Chain.blocksByHash, asBlockHash(eth1Data.block_hash), nil)
|
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
func latestCandidateBlock(eth1Chain: Eth1Chain,
|
|
|
|
preset: RuntimePreset,
|
|
|
|
periodStart: uint64): Eth1Block =
|
2020-03-24 11:13:07 +00:00
|
|
|
for i in countdown(eth1Chain.blocks.len - 1, 0):
|
|
|
|
let blk = eth1Chain.blocks[i]
|
2020-08-06 09:08:54 +00:00
|
|
|
if is_candidate_block(preset, blk, periodStart):
|
2020-03-24 11:13:07 +00:00
|
|
|
return blk
|
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
func popFirst(eth1Chain: var Eth1Chain) =
|
|
|
|
let removed = eth1Chain.blocks.popFirst
|
2020-06-27 12:01:19 +00:00
|
|
|
eth1Chain.blocksByHash.del removed.voteData.block_hash.asBlockHash
|
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
func addBlock(eth1Chain: var Eth1Chain, newBlock: Eth1Block) =
|
2020-10-26 08:55:10 +00:00
|
|
|
eth1Chain.blocks.addLast newBlock
|
|
|
|
eth1Chain.blocksByHash[newBlock.voteData.block_hash.asBlockHash] = newBlock
|
2020-03-24 11:13:07 +00:00
|
|
|
|
|
|
|
template hash*(x: Eth1Block): Hash =
|
|
|
|
hash(x.voteData.block_hash.data)
|
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
proc close*(p: Web3DataProviderRef): Future[void] {.async.} =
|
2020-06-27 12:01:19 +00:00
|
|
|
if p.blockHeadersSubscription != nil:
|
|
|
|
await p.blockHeadersSubscription.unsubscribe()
|
|
|
|
|
|
|
|
await p.web3.close()
|
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
proc getBlockByHash*(p: Web3DataProviderRef, hash: BlockHash):
|
|
|
|
Future[BlockObject] =
|
2020-06-27 12:01:19 +00:00
|
|
|
return p.web3.provider.eth_getBlockByHash(hash, false)
|
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
proc getBlockByNumber*(p: Web3DataProviderRef,
|
|
|
|
number: Eth1BlockNumber): Future[BlockObject] =
|
2020-06-27 12:01:19 +00:00
|
|
|
return p.web3.provider.eth_getBlockByNumber(&"0x{number:X}", false)
|
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
proc getBlockNumber(p: Web3DataProviderRef, hash: BlockHash):
|
|
|
|
Future[Eth1BlockNumber] {.async.} =
|
2020-06-27 12:01:19 +00:00
|
|
|
try:
|
|
|
|
let blk = awaitWithTimeout(p.getBlockByHash(hash), web3Timeouts):
|
|
|
|
return 0
|
|
|
|
return Eth1BlockNumber(blk.number)
|
|
|
|
except CatchableError as exc:
|
2020-10-01 18:56:42 +00:00
|
|
|
debug "Failed to get Eth1 block number from hash",
|
2020-10-12 01:07:20 +00:00
|
|
|
hash = $hash, err = exc.msg
|
2020-08-06 18:47:39 +00:00
|
|
|
raise exc
|
2020-06-27 12:01:19 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
template readJsonField(j: JsonNode, fieldName: string, ValueType: type): untyped =
|
2020-06-27 12:01:19 +00:00
|
|
|
var res: ValueType
|
|
|
|
fromJson(j[fieldName], fieldName, res)
|
|
|
|
res
|
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
proc depositEventsToBlocks(depositsList: JsonNode): seq[Eth1Block] =
|
2020-06-27 12:01:19 +00:00
|
|
|
if depositsList.kind != JArray:
|
|
|
|
raise newException(CatchableError,
|
|
|
|
"Web3 provider didn't return a list of deposit events")
|
|
|
|
|
|
|
|
var lastEth1Block: Eth1Block
|
|
|
|
|
|
|
|
for logEvent in depositsList:
|
|
|
|
let
|
|
|
|
blockNumber = Eth1BlockNumber readJsonField(logEvent, "blockNumber", Quantity)
|
|
|
|
blockHash = readJsonField(logEvent, "blockHash", BlockHash)
|
|
|
|
logData = strip0xPrefix(logEvent["data"].getStr)
|
|
|
|
|
|
|
|
if lastEth1Block == nil or lastEth1Block.number != blockNumber:
|
|
|
|
lastEth1Block = Eth1Block(
|
|
|
|
number: blockNumber,
|
|
|
|
voteData: Eth1Data(block_hash: blockHash.asEth2Digest))
|
|
|
|
|
|
|
|
result.add lastEth1Block
|
|
|
|
|
|
|
|
var
|
|
|
|
pubkey: Bytes48
|
|
|
|
withdrawalCredentials: Bytes32
|
|
|
|
amount: Bytes8
|
|
|
|
signature: Bytes96
|
|
|
|
index: Bytes8
|
|
|
|
|
|
|
|
var offset = 0
|
|
|
|
offset += decode(logData, offset, pubkey)
|
|
|
|
offset += decode(logData, offset, withdrawalCredentials)
|
|
|
|
offset += decode(logData, offset, amount)
|
|
|
|
offset += decode(logData, offset, signature)
|
|
|
|
offset += decode(logData, offset, index)
|
|
|
|
|
|
|
|
lastEth1Block.deposits.add Deposit(
|
|
|
|
data: DepositData(
|
|
|
|
pubkey: ValidatorPubKey.init(array[48, byte](pubkey)),
|
|
|
|
withdrawal_credentials: Eth2Digest(data: array[32, byte](withdrawalCredentials)),
|
2020-07-27 10:59:57 +00:00
|
|
|
amount: bytes_to_uint64(array[8, byte](amount)),
|
2020-06-27 12:01:19 +00:00
|
|
|
signature: ValidatorSig.init(array[96, byte](signature))))
|
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
proc fetchTimestamp(p: Web3DataProviderRef, blk: Eth1Block) {.async.} =
|
|
|
|
let web3block = await p.getBlockByHash(blk.voteData.block_hash.asBlockHash)
|
|
|
|
blk.timestamp = Eth1BlockTimestamp web3block.timestamp
|
|
|
|
|
|
|
|
when hasDepositRootChecks:
|
|
|
|
type
|
|
|
|
DepositContractDataStatus = enum
|
|
|
|
Fetched
|
|
|
|
VerifiedCorrect
|
|
|
|
DepositRootIncorrect
|
|
|
|
DepositRootUnavailable
|
|
|
|
DepositCountIncorrect
|
|
|
|
DepositCountUnavailable
|
|
|
|
|
|
|
|
proc fetchDepositContractData(p: Web3DataProviderRef, blk: Eth1Block):
|
|
|
|
Future[DepositContractDataStatus] {.async.} =
|
|
|
|
let
|
|
|
|
depositRoot = p.ns.get_deposit_root.call(blockNumber = blk.number)
|
|
|
|
rawCount = p.ns.get_deposit_count.call(blockNumber = blk.number)
|
2020-10-21 13:25:53 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
try:
|
|
|
|
let fetchedRoot = asEth2Digest(await depositRoot)
|
|
|
|
if blk.voteData.deposit_root == default(Eth2Digest):
|
|
|
|
blk.voteData.deposit_root = fetchedRoot
|
|
|
|
result = Fetched
|
|
|
|
elif blk.voteData.deposit_root == fetchedRoot:
|
|
|
|
result = VerifiedCorrect
|
|
|
|
else:
|
|
|
|
result = DepositRootIncorrect
|
|
|
|
except CatchableError as err:
|
|
|
|
debug "Failed to fetch deposits root",
|
|
|
|
blockNumber = blk.number,
|
|
|
|
err = err.msg
|
|
|
|
result = DepositRootUnavailable
|
2020-10-21 13:25:53 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
try:
|
|
|
|
let fetchedCount = bytes_to_uint64(array[8, byte](await rawCount))
|
|
|
|
if blk.voteData.deposit_count == 0:
|
|
|
|
blk.voteData.deposit_count = fetchedCount
|
|
|
|
elif blk.voteData.deposit_count != fetchedCount:
|
|
|
|
result = DepositCountIncorrect
|
|
|
|
except CatchableError as err:
|
|
|
|
debug "Failed to fetch deposits count",
|
|
|
|
blockNumber = blk.number,
|
|
|
|
err = err.msg
|
|
|
|
result = DepositCountUnavailable
|
2020-06-27 12:01:19 +00:00
|
|
|
|
2020-10-14 14:04:08 +00:00
|
|
|
proc onBlockHeaders*(p: Web3DataProviderRef,
|
|
|
|
blockHeaderHandler: BlockHeaderHandler,
|
2020-11-03 01:21:07 +00:00
|
|
|
errorHandler: SubscriptionErrorHandler) {.async.} =
|
2020-06-27 12:01:19 +00:00
|
|
|
if p.blockHeadersSubscription != nil:
|
|
|
|
await p.blockHeadersSubscription.unsubscribe()
|
|
|
|
|
2020-10-12 01:07:20 +00:00
|
|
|
info "Waiting for new Eth1 block headers"
|
2020-06-27 12:01:19 +00:00
|
|
|
|
|
|
|
p.blockHeadersSubscription = await p.web3.subscribeForBlockHeaders(
|
2020-09-24 13:07:48 +00:00
|
|
|
blockHeaderHandler, errorHandler)
|
2020-06-27 12:01:19 +00:00
|
|
|
|
2020-11-04 09:06:58 +00:00
|
|
|
func getDepositsRoot(m: DepositsMerkleizer): Eth2Digest =
|
|
|
|
mixInLength(m.getFinalHash, int m.totalChunks)
|
|
|
|
|
2020-11-09 14:18:55 +00:00
|
|
|
# https://github.com/ethereum/eth2.0-specs/blob/v1.0.0/specs/phase0/validator.md#get_eth1_data
|
2020-11-03 01:21:07 +00:00
|
|
|
proc getBlockProposalData*(m: Eth1Monitor,
|
2020-10-26 08:55:10 +00:00
|
|
|
state: BeaconState,
|
|
|
|
finalizedEth1Data: Eth1Data): (Eth1Data, seq[Deposit]) =
|
2020-11-04 09:06:58 +00:00
|
|
|
var pendingDepositsCount = state.eth1_data.deposit_count -
|
|
|
|
state.eth1_deposit_index
|
|
|
|
|
2020-11-10 18:41:04 +00:00
|
|
|
# TODO(zah)
|
|
|
|
# To make block proposal cheaper, we can perform this action more regularly
|
2020-10-26 08:55:10 +00:00
|
|
|
# (e.g. in BeaconNode.onSlot). But keep in mind that this action needs to be
|
|
|
|
# performed only when there are validators attached to the node.
|
2020-11-04 09:06:58 +00:00
|
|
|
let ourDepositsCount = m.db.deposits.len
|
|
|
|
let targetDepositsCount = finalizedEth1Data.deposit_count
|
|
|
|
let hasLatestDeposits = if ourDepositsCount >= targetDepositsCount:
|
|
|
|
m.db.finalizedEth2DepositsMerkleizer.advanceTo(m.db, targetDepositsCount)
|
|
|
|
let ourDepositsRoot = m.db.finalizedEth2DepositsMerkleizer.getDepositsRoot
|
|
|
|
|
|
|
|
if (ourDepositsRoot != finalizedEth1Data.deposit_root):
|
|
|
|
error "Corrupted deposits history. Producing block without deposits",
|
|
|
|
ourDepositsRoot,
|
|
|
|
targetDepositsRoot = finalizedEth1Data.deposit_root,
|
|
|
|
depositsCount = ourDepositsCount
|
|
|
|
false
|
|
|
|
else:
|
|
|
|
true
|
|
|
|
else:
|
|
|
|
warn "ETH1 deposits not fully synced. Producing block without deposits",
|
|
|
|
targetDepositsCount, ourDepositsCount
|
|
|
|
false
|
2020-10-26 08:55:10 +00:00
|
|
|
|
2020-03-24 11:13:07 +00:00
|
|
|
let periodStart = voting_period_start_time(state)
|
|
|
|
|
|
|
|
var otherVotesCountTable = initCountTable[Eth1Block]()
|
|
|
|
for vote in state.eth1_data_votes:
|
2020-10-12 01:07:20 +00:00
|
|
|
let eth1Block = m.eth1Chain.findBlock(vote)
|
2020-10-15 17:30:33 +00:00
|
|
|
if eth1Block != nil and
|
|
|
|
is_candidate_block(m.preset, eth1Block, periodStart) and
|
|
|
|
eth1Block.voteData.deposit_count > state.eth1_data.deposit_count:
|
2020-03-24 11:13:07 +00:00
|
|
|
otherVotesCountTable.inc eth1Block
|
|
|
|
|
|
|
|
if otherVotesCountTable.len > 0:
|
2020-10-12 01:07:20 +00:00
|
|
|
let (winningBlock, votes) = otherVotesCountTable.largest
|
|
|
|
result[0] = winningBlock.voteData
|
|
|
|
if uint64((votes + 1) * 2) > SLOTS_PER_ETH1_VOTING_PERIOD:
|
2020-11-04 09:06:58 +00:00
|
|
|
pendingDepositsCount = winningBlock.voteData.deposit_count -
|
|
|
|
state.eth1_deposit_index
|
2020-03-24 11:13:07 +00:00
|
|
|
else:
|
2020-10-12 01:07:20 +00:00
|
|
|
let latestBlock = m.eth1Chain.latestCandidateBlock(m.preset, periodStart)
|
|
|
|
if latestBlock == nil:
|
2020-10-15 17:30:33 +00:00
|
|
|
result[0] = state.eth1_data
|
2020-10-12 01:07:20 +00:00
|
|
|
else:
|
|
|
|
result[0] = latestBlock.voteData
|
2020-10-15 17:30:33 +00:00
|
|
|
|
2020-11-04 09:06:58 +00:00
|
|
|
if pendingDepositsCount > 0 and hasLatestDeposits:
|
|
|
|
let totalDepositsInNewBlock = min(MAX_DEPOSITS, pendingDepositsCount)
|
2020-10-15 17:30:33 +00:00
|
|
|
|
2020-10-26 08:55:10 +00:00
|
|
|
var
|
2020-11-04 09:06:58 +00:00
|
|
|
deposits = newSeq[Deposit](pendingDepositsCount)
|
|
|
|
depositRoots = newSeq[Eth2Digest](pendingDepositsCount)
|
2020-10-26 08:55:10 +00:00
|
|
|
depositsMerkleizerClone = clone m.db.finalizedEth2DepositsMerkleizer
|
2020-10-15 17:30:33 +00:00
|
|
|
|
2020-10-26 08:55:10 +00:00
|
|
|
depositsMerkleizerClone.advanceTo(m.db, state.eth1_deposit_index)
|
|
|
|
|
|
|
|
for i in 0 ..< totalDepositsInNewBlock:
|
|
|
|
deposits[i].data = m.db.deposits.get(state.eth1_deposit_index + i)
|
|
|
|
depositRoots[i] = hash_tree_root(deposits[i].data)
|
|
|
|
|
|
|
|
let proofs = depositsMerkleizerClone.addChunksAndGenMerkleProofs(depositRoots)
|
2020-10-15 17:30:33 +00:00
|
|
|
|
2020-10-26 08:55:10 +00:00
|
|
|
for i in 0 ..< totalDepositsInNewBlock:
|
|
|
|
deposits[i].proof[0..31] = proofs.getProof(i.int)
|
|
|
|
deposits[i].proof[32].data[0..7] =
|
|
|
|
toBytesLE uint64(state.eth1_deposit_index + i + 1)
|
|
|
|
|
|
|
|
swap(result[1], deposits)
|
2020-03-24 11:13:07 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
proc init*(T: type Eth1Monitor,
|
2020-10-12 01:07:20 +00:00
|
|
|
db: BeaconChainDB,
|
2020-07-07 23:02:14 +00:00
|
|
|
preset: RuntimePreset,
|
2020-10-14 14:04:08 +00:00
|
|
|
web3Url: string,
|
2020-07-02 15:14:11 +00:00
|
|
|
depositContractAddress: Eth1Address,
|
2020-11-12 19:01:26 +00:00
|
|
|
depositContractDeployedAt: BlockHashOrNumber,
|
2020-11-06 21:45:56 +00:00
|
|
|
eth1Network: Option[Eth1Network]): Future[Result[T, string]] {.async.} =
|
2020-11-05 23:11:06 +00:00
|
|
|
var web3Url = web3Url
|
2020-11-12 13:49:13 +00:00
|
|
|
fixupWeb3Urls web3Url
|
2020-11-05 23:11:06 +00:00
|
|
|
|
2020-11-12 16:21:04 +00:00
|
|
|
let web3Fut = newWeb3(web3Url)
|
|
|
|
yield web3Fut or sleepAsync(chronos.seconds(5))
|
|
|
|
if (not web3Fut.finished) or web3Fut.failed:
|
|
|
|
web3Fut.cancel()
|
|
|
|
return err "Failed to setup web3 connection"
|
|
|
|
|
2020-10-14 14:04:08 +00:00
|
|
|
let
|
2020-11-12 16:21:04 +00:00
|
|
|
web3 = web3Fut.read
|
2020-10-14 14:04:08 +00:00
|
|
|
ns = web3.contractSender(DepositContract, depositContractAddress)
|
|
|
|
dataProvider = Web3DataProviderRef(url: web3Url, web3: web3, ns: ns)
|
|
|
|
|
2020-11-06 21:45:56 +00:00
|
|
|
if eth1Network.isSome:
|
|
|
|
let
|
|
|
|
providerNetwork = await web3.provider.net_version()
|
|
|
|
expectedNetwork = case eth1Network.get
|
|
|
|
of mainnet: "1"
|
|
|
|
of rinkeby: "4"
|
|
|
|
of goerli: "5"
|
|
|
|
if expectedNetwork != providerNetwork:
|
2020-11-12 16:21:04 +00:00
|
|
|
return err("The specified web3 provider is not attached to the " &
|
2020-11-06 21:45:56 +00:00
|
|
|
$eth1Network.get & " network")
|
|
|
|
|
2020-10-14 14:04:08 +00:00
|
|
|
return ok T(
|
|
|
|
db: db,
|
2020-10-12 01:07:20 +00:00
|
|
|
preset: preset,
|
2020-11-12 19:01:26 +00:00
|
|
|
depositContractDeployedAt: depositContractDeployedAt,
|
2020-10-14 14:04:08 +00:00
|
|
|
dataProvider: dataProvider,
|
2020-11-12 19:01:26 +00:00
|
|
|
eth1Progress: newAsyncEvent())
|
2019-09-09 15:59:02 +00:00
|
|
|
|
2020-11-14 21:43:27 +00:00
|
|
|
proc allDepositsUpTo(m: Eth1Monitor, totalDeposits: uint64): seq[DepositData] =
|
2020-11-03 01:21:07 +00:00
|
|
|
for i in 0'u64 ..< totalDeposits:
|
2020-11-14 21:43:27 +00:00
|
|
|
result.add m.db.deposits.get(i)
|
2020-10-12 01:07:20 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
proc createGenesisState(m: Eth1Monitor, eth1Block: Eth1Block): BeaconStateRef =
|
2020-10-12 01:07:20 +00:00
|
|
|
notice "Generating genesis state",
|
|
|
|
blockNum = eth1Block.number,
|
|
|
|
blockHash = eth1Block.voteData.block_hash,
|
2020-11-03 01:21:07 +00:00
|
|
|
blockTimestamp = eth1Block.timestamp,
|
2020-10-12 01:07:20 +00:00
|
|
|
totalDeposits = eth1Block.voteData.deposit_count,
|
2020-11-03 01:21:07 +00:00
|
|
|
activeValidators = eth1Block.activeValidatorsCount
|
2020-10-12 01:07:20 +00:00
|
|
|
|
|
|
|
var deposits = m.allDepositsUpTo(eth1Block.voteData.deposit_count)
|
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
result = initialize_beacon_state_from_eth1(
|
|
|
|
m.preset,
|
|
|
|
eth1Block.voteData.block_hash,
|
|
|
|
eth1Block.timestamp.uint64,
|
|
|
|
deposits, {})
|
2020-06-28 20:17:47 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
doAssert result.validators.lenu64 == eth1Block.activeValidatorsCount
|
|
|
|
|
|
|
|
proc signalGenesis(m: Eth1Monitor, genesisState: BeaconStateRef) =
|
2020-06-28 20:17:47 +00:00
|
|
|
m.genesisState = genesisState
|
|
|
|
|
|
|
|
if not m.genesisStateFut.isNil:
|
|
|
|
m.genesisStateFut.complete()
|
|
|
|
m.genesisStateFut = nil
|
2020-06-27 12:01:19 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
template hasEnoughValidators(m: Eth1Monitor, blk: Eth1Block): bool =
|
|
|
|
blk.activeValidatorsCount >= m.preset.MIN_GENESIS_ACTIVE_VALIDATOR_COUNT
|
|
|
|
|
2020-11-14 20:51:50 +00:00
|
|
|
func chainHasEnoughValidators(m: Eth1Monitor): bool =
|
|
|
|
if m.eth1Chain.blocks.len > 0:
|
|
|
|
m.hasEnoughValidators(m.eth1Chain.blocks[^1])
|
|
|
|
else:
|
|
|
|
m.eth1Chain.knownStart.deposit_count >=
|
|
|
|
m.preset.MIN_GENESIS_ACTIVE_VALIDATOR_COUNT
|
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
func isAfterMinGenesisTime(m: Eth1Monitor, blk: Eth1Block): bool =
|
|
|
|
doAssert blk.timestamp != 0
|
|
|
|
let t = genesis_time_from_eth1_timestamp(m.preset, uint64 blk.timestamp)
|
|
|
|
t >= m.preset.MIN_GENESIS_TIME
|
|
|
|
|
|
|
|
func isGenesisCandidate(m: Eth1Monitor, blk: Eth1Block): bool =
|
|
|
|
m.hasEnoughValidators(blk) and m.isAfterMinGenesisTime(blk)
|
|
|
|
|
|
|
|
proc findGenesisBlockInRange(m: Eth1Monitor, startBlock, endBlock: Eth1Block):
|
|
|
|
Future[Eth1Block] {.async.} =
|
|
|
|
doAssert startBlock.timestamp != 0 and not m.isAfterMinGenesisTime(startBlock)
|
|
|
|
doAssert endBlock.timestamp != 0 and m.isAfterMinGenesisTime(endBlock)
|
|
|
|
doAssert m.hasEnoughValidators(startBlock)
|
|
|
|
doAssert m.hasEnoughValidators(endBlock)
|
|
|
|
|
2020-06-28 20:17:47 +00:00
|
|
|
var
|
|
|
|
startBlock = startBlock
|
|
|
|
endBlock = endBlock
|
|
|
|
depositData = startBlock.voteData
|
2020-11-03 01:21:07 +00:00
|
|
|
activeValidatorsCountDuringRange = startBlock.activeValidatorsCount
|
2020-06-28 20:17:47 +00:00
|
|
|
|
|
|
|
while startBlock.number + 1 < endBlock.number:
|
|
|
|
let
|
2020-07-07 23:02:14 +00:00
|
|
|
MIN_GENESIS_TIME = m.preset.MIN_GENESIS_TIME
|
|
|
|
startBlockTime = genesis_time_from_eth1_timestamp(m.preset, startBlock.timestamp)
|
2020-06-28 20:17:47 +00:00
|
|
|
secondsPerBlock = float(endBlock.timestamp - startBlock.timestamp) /
|
|
|
|
float(endBlock.number - startBlock.number)
|
|
|
|
blocksToJump = max(float(MIN_GENESIS_TIME - startBlockTime) / secondsPerBlock, 1.0)
|
2020-11-03 01:21:07 +00:00
|
|
|
candidateNumber = min(endBlock.number - 1, startBlock.number + blocksToJump.uint64)
|
2020-10-14 14:04:08 +00:00
|
|
|
candidateBlock = await m.dataProvider.getBlockByNumber(candidateNumber)
|
2020-06-28 20:17:47 +00:00
|
|
|
|
|
|
|
var candidateAsEth1Block = Eth1Block(number: candidateBlock.number.uint64,
|
|
|
|
timestamp: candidateBlock.timestamp.uint64,
|
|
|
|
voteData: depositData)
|
|
|
|
candidateAsEth1Block.voteData.block_hash = candidateBlock.hash.asEth2Digest
|
|
|
|
|
2020-07-07 23:02:14 +00:00
|
|
|
let candidateGenesisTime = genesis_time_from_eth1_timestamp(
|
|
|
|
m.preset, candidateBlock.timestamp.uint64)
|
|
|
|
|
2020-10-01 18:56:42 +00:00
|
|
|
notice "Probing possible genesis block",
|
2020-06-28 20:17:47 +00:00
|
|
|
`block` = candidateBlock.number.uint64,
|
2020-07-07 23:02:14 +00:00
|
|
|
candidateGenesisTime
|
2020-06-28 20:17:47 +00:00
|
|
|
|
2020-07-07 23:02:14 +00:00
|
|
|
if candidateGenesisTime < MIN_GENESIS_TIME:
|
2020-06-28 20:17:47 +00:00
|
|
|
startBlock = candidateAsEth1Block
|
|
|
|
else:
|
|
|
|
endBlock = candidateAsEth1Block
|
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
if endBlock.activeValidatorsCount == 0:
|
|
|
|
endBlock.activeValidatorsCount = activeValidatorsCountDuringRange
|
|
|
|
|
2020-06-28 20:17:47 +00:00
|
|
|
return endBlock
|
2020-06-27 12:01:19 +00:00
|
|
|
|
2020-09-28 15:19:57 +00:00
|
|
|
proc safeCancel(fut: var Future[void]) =
|
|
|
|
if not fut.isNil and not fut.finished:
|
|
|
|
fut.cancel()
|
2020-11-03 01:21:07 +00:00
|
|
|
fut = nil
|
2020-09-28 15:19:57 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
proc stop*(m: Eth1Monitor) =
|
2020-09-28 15:19:57 +00:00
|
|
|
safeCancel m.runFut
|
2019-09-09 15:59:02 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
proc syncBlockRange(m: Eth1Monitor, fromBlock, toBlock: Eth1BlockNumber) {.async.} =
|
|
|
|
var currentBlock = fromBlock
|
|
|
|
while currentBlock <= toBlock:
|
2020-11-14 20:51:50 +00:00
|
|
|
var
|
|
|
|
depositLogs: JsonNode = nil
|
|
|
|
blocksPerRequest = 5000'u64 # This is roughly a day of Eth1 blocks
|
|
|
|
maxBlockNumberRequested: Eth1BlockNumber
|
2020-03-24 11:13:07 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
while true:
|
2020-11-14 20:51:50 +00:00
|
|
|
maxBlockNumberRequested = min(toBlock, currentBlock + blocksPerRequest - 1)
|
2020-06-25 23:33:06 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
debug "Obtaining deposit log events",
|
|
|
|
fromBlock = currentBlock,
|
2020-11-14 20:51:50 +00:00
|
|
|
toBlock = maxBlockNumberRequested
|
2020-11-03 01:21:07 +00:00
|
|
|
try:
|
|
|
|
depositLogs = await m.dataProvider.ns.getJsonLogs(
|
|
|
|
DepositEvent,
|
|
|
|
fromBlock = some blockId(currentBlock),
|
2020-11-14 20:51:50 +00:00
|
|
|
toBlock = some blockId(maxBlockNumberRequested))
|
|
|
|
currentBlock = maxBlockNumberRequested + 1
|
2020-11-03 01:21:07 +00:00
|
|
|
break
|
|
|
|
except CatchableError as err:
|
|
|
|
blocksPerRequest = blocksPerRequest div 2
|
|
|
|
if blocksPerRequest == 0:
|
|
|
|
raise err
|
2020-03-24 11:13:07 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
let eth1Blocks = depositEventsToBlocks(depositLogs)
|
2020-02-07 07:13:38 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
for i in 0 ..< eth1Blocks.len:
|
2020-11-10 18:41:04 +00:00
|
|
|
# TODO(zah): The DB operations should be executed as a transaction here
|
2020-11-03 01:21:07 +00:00
|
|
|
let blk = eth1Blocks[i]
|
|
|
|
|
|
|
|
for deposit in blk.deposits:
|
|
|
|
m.db.processDeposit(deposit.data)
|
|
|
|
|
|
|
|
blk.voteData.deposit_count =
|
|
|
|
m.db.finalizedEth1DepositsMerkleizer.totalChunks
|
|
|
|
|
2020-11-04 09:06:58 +00:00
|
|
|
blk.voteData.deposit_root =
|
|
|
|
m.db.finalizedEth1DepositsMerkleizer.getDepositsRoot
|
2020-11-03 01:21:07 +00:00
|
|
|
|
|
|
|
blk.activeValidatorsCount = m.db.immutableValidatorData.lenu64
|
2020-03-24 11:13:07 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
m.eth1Chain.addBlock blk
|
|
|
|
|
|
|
|
if eth1Blocks.len > 0:
|
2020-11-14 20:51:50 +00:00
|
|
|
let lastIdx = eth1Blocks.len - 1
|
|
|
|
template lastBlock: auto = eth1Blocks[lastIdx]
|
2020-11-03 01:21:07 +00:00
|
|
|
|
|
|
|
when hasDepositRootChecks:
|
|
|
|
let status = await m.dataProvider.fetchDepositContractData(lastBlock)
|
|
|
|
debug "Deposit root checks", status,
|
|
|
|
ourCount = lastBlock.voteData.deposit_count,
|
|
|
|
ourRoot = lastBlock.voteData.deposit_root
|
|
|
|
|
|
|
|
m.db.putEth1PersistedTo lastBlock.voteData
|
|
|
|
|
|
|
|
notice "Eth1 sync progress",
|
|
|
|
blockNumber = lastBlock.number,
|
|
|
|
depositsProcessed = lastBlock.voteData.deposit_count
|
2020-11-14 20:51:50 +00:00
|
|
|
|
|
|
|
if m.genesisStateFut != nil and m.chainHasEnoughValidators:
|
|
|
|
let lastIdx = m.eth1Chain.blocks.len - 1
|
|
|
|
template lastBlock: auto = m.eth1Chain.blocks[lastIdx]
|
|
|
|
|
|
|
|
if maxBlockNumberRequested == toBlock and
|
|
|
|
(m.eth1Chain.blocks.len == 0 or lastBlock.number != toBlock):
|
|
|
|
let web3Block = await m.dataProvider.getBlockByNumber(toBlock)
|
|
|
|
|
|
|
|
debug "Latest block doesn't hold deposits. Obtaining it",
|
|
|
|
ts = web3Block.timestamp.uint64,
|
|
|
|
number = web3Block.number.uint64
|
|
|
|
|
|
|
|
m.eth1Chain.addBlock Eth1Block(
|
|
|
|
number: Eth1BlockNumber web3Block.number,
|
|
|
|
timestamp: Eth1BlockTimestamp web3Block.timestamp,
|
|
|
|
voteData: Eth1Data(
|
|
|
|
block_hash: web3Block.hash.asEth2Digest,
|
|
|
|
deposit_count: lastBlock.voteData.deposit_count,
|
|
|
|
deposit_root: lastBlock.voteData.deposit_root),
|
|
|
|
activeValidatorsCount: lastBlock.activeValidatorsCount)
|
|
|
|
else:
|
2020-11-03 01:21:07 +00:00
|
|
|
await m.dataProvider.fetchTimestamp(lastBlock)
|
2020-11-14 20:51:50 +00:00
|
|
|
|
|
|
|
var genesisBlockIdx = m.eth1Chain.blocks.len - 1
|
|
|
|
if m.isAfterMinGenesisTime(m.eth1Chain.blocks[genesisBlockIdx]):
|
|
|
|
for i in 1 ..< eth1Blocks.len:
|
|
|
|
let idx = (m.eth1Chain.blocks.len - 1) - i
|
|
|
|
let blk = m.eth1Chain.blocks[idx]
|
|
|
|
await m.dataProvider.fetchTimestamp(blk)
|
|
|
|
if m.isGenesisCandidate(blk):
|
|
|
|
genesisBlockIdx = idx
|
|
|
|
else:
|
|
|
|
break
|
|
|
|
# We have a candidate state on our hands, but our current Eth1Chain
|
|
|
|
# may consist only of blocks that have deposits attached to them
|
|
|
|
# while the real genesis may have happened in a block without any
|
|
|
|
# deposits (triggered by MIN_GENESIS_TIME).
|
|
|
|
#
|
|
|
|
# This can happen when the beacon node is launched after the genesis
|
|
|
|
# event. We take a short cut when constructing the initial Eth1Chain
|
|
|
|
# by downloading only deposit log entries. Thus, we'll see all the
|
|
|
|
# blocks with deposits, but not the regular blocks in between.
|
|
|
|
#
|
|
|
|
# We'll handle this special case below by examing whether we are in
|
|
|
|
# this potential scenario and we'll use a fast guessing algorith to
|
|
|
|
# discover the ETh1 block with minimal valid genesis time.
|
|
|
|
var genesisBlock = m.eth1Chain.blocks[genesisBlockIdx]
|
|
|
|
if genesisBlockIdx > 0:
|
|
|
|
let genesisParent = m.eth1Chain.blocks[genesisBlockIdx - 1]
|
|
|
|
if genesisParent.timestamp == 0:
|
|
|
|
await m.dataProvider.fetchTimestamp(genesisParent)
|
|
|
|
if m.hasEnoughValidators(genesisParent) and
|
|
|
|
genesisBlock.number - genesisParent.number > 1:
|
|
|
|
genesisBlock = await m.findGenesisBlockInRange(genesisParent,
|
|
|
|
genesisBlock)
|
|
|
|
m.signalGenesis m.createGenesisState(genesisBlock)
|
2020-11-03 01:21:07 +00:00
|
|
|
|
|
|
|
proc handleEth1Progress(m: Eth1Monitor) {.async.} =
|
2020-06-27 12:01:19 +00:00
|
|
|
# ATTENTION!
|
2020-11-03 01:21:07 +00:00
|
|
|
# Please note that this code is using an async event in order
|
|
|
|
# to guarantee the strict serial order of processing of deposits.
|
|
|
|
# If we had the same code embedded in the new block headers event,
|
2020-10-12 01:07:20 +00:00
|
|
|
# it could easily re-order the steps due to the interruptible
|
2020-06-27 12:01:19 +00:00
|
|
|
# interleaved execution of async code.
|
2020-11-12 19:01:26 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
var eth1SyncedTo = await m.dataProvider.getBlockNumber(
|
|
|
|
m.eth1Chain.knownStart.block_hash.asBlockHash)
|
2020-09-28 15:19:57 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
while true:
|
|
|
|
if bnStatus == BeaconNodeStatus.Stopping:
|
|
|
|
if not m.genesisStateFut.isNil:
|
|
|
|
m.genesisStateFut.complete()
|
|
|
|
m.genesisStateFut = nil
|
|
|
|
m.stop()
|
|
|
|
return
|
2020-10-14 14:04:08 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
await m.eth1Progress.wait()
|
|
|
|
m.eth1Progress.clear()
|
2020-03-24 11:13:07 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
if m.latestEth1BlockNumber <= m.preset.ETH1_FOLLOW_DISTANCE:
|
|
|
|
continue
|
2020-06-27 12:01:19 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
let targetBlock = m.latestEth1BlockNumber - m.preset.ETH1_FOLLOW_DISTANCE
|
|
|
|
if targetBlock <= eth1SyncedTo:
|
|
|
|
continue
|
2020-03-24 11:13:07 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
await m.syncBlockRange(eth1SyncedTo + 1, targetBlock)
|
|
|
|
eth1SyncedTo = targetBlock
|
2019-11-22 13:16:07 +00:00
|
|
|
|
2020-11-14 20:51:50 +00:00
|
|
|
while m.eth1Chain.blocks.len > 1:
|
2020-11-03 01:21:07 +00:00
|
|
|
# We'll clean old blocks that can no longer be voting candidates.
|
|
|
|
# Technically, we should check that the block is outside of the current
|
|
|
|
# voting period as determined by its timestamp, but we'll approximate
|
|
|
|
# this by requiring a much larger difference in block numbers.
|
|
|
|
# (i.e. twice the follow distance).
|
|
|
|
let earliestBlock = m.eth1Chain.blocks.peekFirst
|
|
|
|
if earliestBlock.number < targetBlock and
|
|
|
|
targetBlock - earliestBlock.number < m.preset.ETH1_FOLLOW_DISTANCE * 2:
|
|
|
|
break
|
|
|
|
m.eth1Chain.popFirst()
|
2020-06-24 13:48:57 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
proc run(m: Eth1Monitor, delayBeforeStart: Duration) {.async.} =
|
2019-11-22 13:16:07 +00:00
|
|
|
if delayBeforeStart != ZeroDuration:
|
|
|
|
await sleepAsync(delayBeforeStart)
|
|
|
|
|
2020-10-14 14:04:08 +00:00
|
|
|
info "Starting Eth1 deposit contract monitoring",
|
|
|
|
contract = $m.depositContractAddress, url = m.web3Url
|
2019-11-22 13:16:07 +00:00
|
|
|
|
2020-11-12 19:01:26 +00:00
|
|
|
let previouslyPersistedTo = m.db.getEth1PersistedTo()
|
|
|
|
m.eth1Chain.knownStart = previouslyPersistedTo.get:
|
|
|
|
# `previouslyPersistedTo` wall null, we start from scratch
|
|
|
|
let deployedAtHash = if m.depositContractDeployedAt.isHash:
|
|
|
|
m.depositContractDeployedAt.hash
|
|
|
|
else:
|
|
|
|
var blk: BlockObject
|
|
|
|
while true:
|
|
|
|
try:
|
|
|
|
blk = await m.dataProvider.getBlockByNumber(m.depositContractDeployedAt.number)
|
|
|
|
break
|
|
|
|
except CatchableError as err:
|
|
|
|
error "Failed to obtain details for the starting block of the deposit contract sync. " &
|
|
|
|
"The Web3 provider may still be not fully synced", error = err.msg
|
|
|
|
await sleepAsync(chronos.seconds(10))
|
|
|
|
blk.hash.asEth2Digest
|
|
|
|
Eth1Data(block_hash: deployedAtHash, deposit_count: 0)
|
|
|
|
|
2020-10-14 14:04:08 +00:00
|
|
|
await m.dataProvider.onBlockHeaders do (blk: Eth1BlockHeader)
|
2020-08-02 21:19:25 +00:00
|
|
|
{.raises: [Defect], gcsafe.}:
|
2020-10-14 14:04:08 +00:00
|
|
|
try:
|
2020-11-03 01:21:07 +00:00
|
|
|
if blk.number.uint64 > m.latestEth1BlockNumber:
|
|
|
|
m.latestEth1BlockNumber = blk.number.uint64
|
|
|
|
m.eth1Progress.fire()
|
2020-10-14 14:04:08 +00:00
|
|
|
except Exception:
|
|
|
|
# TODO Investigate why this exception is being raised
|
2020-11-03 01:21:07 +00:00
|
|
|
raiseAssert "AsyncEvent.fire should not raise exceptions"
|
2020-10-14 14:04:08 +00:00
|
|
|
do (err: CatchableError):
|
|
|
|
debug "Error while processing Eth1 block headers subscription", err = err.msg
|
2020-06-19 17:42:28 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
await m.handleEth1Progress()
|
2019-09-09 15:59:02 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
proc start(m: Eth1Monitor, delayBeforeStart: Duration) =
|
2019-11-22 13:16:07 +00:00
|
|
|
if m.runFut.isNil:
|
|
|
|
let runFut = m.run(delayBeforeStart)
|
|
|
|
m.runFut = runFut
|
2020-03-24 11:13:07 +00:00
|
|
|
runFut.addCallback do (p: pointer):
|
|
|
|
if runFut.failed:
|
|
|
|
if runFut.error[] of CatchableError:
|
|
|
|
if runFut == m.runFut:
|
2020-11-02 20:16:24 +00:00
|
|
|
error "Eth1 chain monitoring failure, restarting", err = runFut.error.msg
|
2020-06-27 12:01:19 +00:00
|
|
|
m.stop()
|
2020-03-24 11:13:07 +00:00
|
|
|
m.start(5.seconds)
|
|
|
|
else:
|
|
|
|
fatal "Fatal exception reached", err = runFut.error.msg
|
|
|
|
quit 1
|
2019-11-22 13:16:07 +00:00
|
|
|
|
2020-11-03 01:21:07 +00:00
|
|
|
proc start*(m: Eth1Monitor) {.inline.} =
|
2019-11-22 13:16:07 +00:00
|
|
|
m.start(0.seconds)
|
|
|
|
|
2020-11-12 16:21:04 +00:00
|
|
|
proc waitGenesis*(m: Eth1Monitor): Future[BeaconStateRef] {.async.} =
|
|
|
|
if m.genesisState.isNil:
|
|
|
|
m.start()
|
|
|
|
|
|
|
|
if m.genesisStateFut.isNil:
|
|
|
|
m.genesisStateFut = newFuture[void]("waitGenesis")
|
|
|
|
|
|
|
|
info "Awaiting genesis event"
|
|
|
|
await m.genesisStateFut
|
|
|
|
m.genesisStateFut = nil
|
|
|
|
|
|
|
|
if m.genesisState != nil:
|
|
|
|
return m.genesisState
|
|
|
|
else:
|
|
|
|
doAssert bnStatus == BeaconNodeStatus.Stopping
|
|
|
|
return new BeaconStateRef # cannot return nil...
|
|
|
|
|
2020-07-28 13:36:11 +00:00
|
|
|
proc getEth1BlockHash*(url: string, blockId: RtBlockIdentifier): Future[BlockHash] {.async.} =
|
2019-10-25 14:53:31 +00:00
|
|
|
let web3 = await newWeb3(url)
|
2020-04-22 23:35:55 +00:00
|
|
|
try:
|
2020-07-28 13:36:11 +00:00
|
|
|
let blk = await web3.provider.eth_getBlockByNumber(blockId, false)
|
|
|
|
return blk.hash
|
2020-04-22 23:35:55 +00:00
|
|
|
finally:
|
|
|
|
await web3.close()
|
|
|
|
|