Fix minor exception effect issues (#2448)

Makes code compatible with
https://github.com/status-im/nim-chronos/pull/166 without requiring it.
This commit is contained in:
Jacek Sieka 2021-03-24 17:20:55 +01:00 committed by GitHub
parent a4a2c1c0e1
commit 8b76ceed52
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 73 additions and 53 deletions

View File

@ -59,7 +59,7 @@ type
immutableValidators*: ImmutableValidatorsSeq immutableValidators*: ImmutableValidatorsSeq
immutableValidatorsMem*: seq[ImmutableValidatorData] immutableValidatorsMem*: seq[ImmutableValidatorData]
checkpoint*: proc() {.gcsafe.} checkpoint*: proc() {.gcsafe, raises: [Defect].}
Keyspaces* = enum Keyspaces* = enum
defaultKeyspace = "kvstore" defaultKeyspace = "kvstore"

View File

@ -215,8 +215,7 @@ type
OnBlockAdded* = proc( OnBlockAdded* = proc(
blckRef: BlockRef, blck: TrustedSignedBeaconBlock, blckRef: BlockRef, blck: TrustedSignedBeaconBlock,
epochRef: EpochRef, state: HashedBeaconState) {.raises: [Defect], gcsafe.} epochRef: EpochRef, state: HashedBeaconState) {.gcsafe, raises: [Defect].}
# The `{.gcsafe.}` annotation is needed to shut up the compiler.
template validator_keys*(e: EpochRef): untyped = e.validator_key_store[1][] template validator_keys*(e: EpochRef): untyped = e.validator_key_store[1][]

View File

@ -122,7 +122,7 @@ proc sendEth(web3: Web3, to: Eth1Address, valueEth: int): Future[TxHash] =
web3.send(tr) web3.send(tr)
type type
DelayGenerator* = proc(): chronos.Duration {.closure, gcsafe.} DelayGenerator* = proc(): chronos.Duration {.gcsafe, raises: [Defect].}
proc ethToWei(eth: UInt256): UInt256 = proc ethToWei(eth: UInt256): UInt256 =
eth * 1000000000000000000.u256 eth * 1000000000000000000.u256

View File

@ -112,7 +112,7 @@ type
pubkey: Bytes48, pubkey: Bytes48,
withdrawalCredentials: Bytes32, withdrawalCredentials: Bytes32,
amount: Bytes8, amount: Bytes8,
signature: Bytes96, merkleTreeIndex: Bytes8, j: JsonNode) {.raises: [Defect], gcsafe.} signature: Bytes96, merkleTreeIndex: Bytes8, j: JsonNode) {.gcsafe, raises: [Defect].}
BlockProposalEth1Data* = object BlockProposalEth1Data* = object
vote*: Eth1Data vote*: Eth1Data

View File

@ -157,13 +157,13 @@ type
InvalidRequest InvalidRequest
ServerError ServerError
PeerStateInitializer* = proc(peer: Peer): RootRef {.gcsafe.} PeerStateInitializer* = proc(peer: Peer): RootRef {.gcsafe, raises: [Defect].}
NetworkStateInitializer* = proc(network: EthereumNode): RootRef {.gcsafe.} NetworkStateInitializer* = proc(network: EthereumNode): RootRef {.gcsafe, raises: [Defect].}
OnPeerConnectedHandler* = proc(peer: Peer, incoming: bool): Future[void] {.gcsafe.} OnPeerConnectedHandler* = proc(peer: Peer, incoming: bool): Future[void] {.gcsafe.}
OnPeerDisconnectedHandler* = proc(peer: Peer): Future[void] {.gcsafe.} OnPeerDisconnectedHandler* = proc(peer: Peer): Future[void] {.gcsafe, raises: [Defect].}
ThunkProc* = LPProtoHandler ThunkProc* = LPProtoHandler
MounterProc* = proc(network: Eth2Node) {.gcsafe.} MounterProc* = proc(network: Eth2Node) {.gcsafe.}
MessageContentPrinter* = proc(msg: pointer): string {.gcsafe.} MessageContentPrinter* = proc(msg: pointer): string {.gcsafe, raises: [Defect].}
# https://github.com/ethereum/eth2.0-specs/blob/v1.0.1/specs/phase0/p2p-interface.md#goodbye # https://github.com/ethereum/eth2.0-specs/blob/v1.0.1/specs/phase0/p2p-interface.md#goodbye
DisconnectionReason* = enum DisconnectionReason* = enum
@ -1638,7 +1638,7 @@ proc setValidTopics*(node: Eth2Node, topics: openArray[string]) =
proc addValidator*[MsgType](node: Eth2Node, proc addValidator*[MsgType](node: Eth2Node,
topic: string, topic: string,
msgValidator: proc(msg: MsgType): msgValidator: proc(msg: MsgType):
ValidationResult {.gcsafe.} ) = ValidationResult {.gcsafe, raises: [Defect].} ) =
# Validate messages as soon as subscribed # Validate messages as soon as subscribed
proc execValidator( proc execValidator(
topic: string, message: GossipMsg): Future[ValidationResult] {.async.} = topic: string, message: GossipMsg): Future[ValidationResult] {.async.} =

View File

@ -28,13 +28,13 @@ type
PeerIndex = object PeerIndex = object
data: int data: int
cmp: proc(a, b: PeerIndex): bool {.closure, gcsafe.} cmp: proc(a, b: PeerIndex): bool {.gcsafe, raises: [Defect].}
PeerScoreCheckCallback*[T] = proc(peer: T): bool {.gcsafe, raises: [Defect].} PeerScoreCheckCallback*[T] = proc(peer: T): bool {.gcsafe, raises: [Defect].}
PeerCounterCallback* = proc() {.gcsafe, raises: [Defect].} PeerCounterCallback* = proc() {.gcsafe, raises: [Defect].}
PeerOnDeleteCallback*[T] = proc(peer: T) {.gcsafe.} PeerOnDeleteCallback*[T] = proc(peer: T) {.gcsafe, raises: [Defect].}
PeerPool*[A, B] = ref object PeerPool*[A, B] = ref object
incNotEmptyEvent*: AsyncEvent incNotEmptyEvent*: AsyncEvent
@ -45,7 +45,7 @@ type
outQueue: HeapQueue[PeerIndex] outQueue: HeapQueue[PeerIndex]
registry: Table[B, PeerIndex] registry: Table[B, PeerIndex]
storage: seq[PeerItem[A]] storage: seq[PeerItem[A]]
cmp: proc(a, b: PeerIndex): bool {.closure, gcsafe.} cmp: proc(a, b: PeerIndex): bool {.gcsafe, raises: [Defect].}
scoreCheck: PeerScoreCheckCallback[A] scoreCheck: PeerScoreCheckCallback[A]
onDeletePeer: PeerOnDeleteCallback[A] onDeletePeer: PeerOnDeleteCallback[A]
peerCounter: PeerCounterCallback peerCounter: PeerCounterCallback
@ -288,7 +288,8 @@ proc deletePeer*[A, B](pool: PeerPool[A, B], peer: A, force = false): bool =
mixin getKey mixin getKey
let key = getKey(peer) let key = getKey(peer)
if pool.registry.hasKey(key): if pool.registry.hasKey(key):
let pindex = pool.registry[key].data let pindex = try: pool.registry[key].data
except KeyError: raiseAssert "checked with hasKey"
var item = addr(pool.storage[pindex]) var item = addr(pool.storage[pindex])
if (PeerFlags.Acquired in item[].flags): if (PeerFlags.Acquired in item[].flags):
if not(force): if not(force):
@ -339,7 +340,7 @@ proc deletePeer*[A, B](pool: PeerPool[A, B], peer: A, force = false): bool =
proc addPeerImpl[A, B](pool: PeerPool[A, B], peer: A, peerKey: B, proc addPeerImpl[A, B](pool: PeerPool[A, B], peer: A, peerKey: B,
peerType: PeerType) = peerType: PeerType) =
proc onPeerClosed(udata: pointer) {.gcsafe.} = proc onPeerClosed(udata: pointer) {.gcsafe, raises: [Defect].} =
discard pool.deletePeer(peer) discard pool.deletePeer(peer)
let item = PeerItem[A](data: peer, peerType: peerType, let item = PeerItem[A](data: peer, peerType: peerType,

View File

@ -1120,12 +1120,14 @@ proc startSyncManager(node: BeaconNode) =
debug "Peer was removed from PeerPool due to low score", peer = peer, debug "Peer was removed from PeerPool due to low score", peer = peer,
peer_score = peer.score, score_low_limit = PeerScoreLowLimit, peer_score = peer.score, score_low_limit = PeerScoreLowLimit,
score_high_limit = PeerScoreHighLimit score_high_limit = PeerScoreHighLimit
asyncSpawn peer.disconnect(PeerScoreLow) asyncSpawn(try: peer.disconnect(PeerScoreLow)
except Exception as exc: raiseAssert exc.msg) # Shouldn't actually happen!
else: else:
debug "Peer was removed from PeerPool", peer = peer, debug "Peer was removed from PeerPool", peer = peer,
peer_score = peer.score, score_low_limit = PeerScoreLowLimit, peer_score = peer.score, score_low_limit = PeerScoreLowLimit,
score_high_limit = PeerScoreHighLimit score_high_limit = PeerScoreHighLimit
asyncSpawn peer.disconnect(FaultOrError) asyncSpawn(try: peer.disconnect(FaultOrError)
except Exception as exc: raiseAssert exc.msg) # Shouldn't actually happen!
node.network.peerPool.setScoreCheck(scoreCheck) node.network.peerPool.setScoreCheck(scoreCheck)
node.network.peerPool.setOnDeletePeer(onDeletePeer) node.network.peerPool.setOnDeletePeer(onDeletePeer)
@ -1319,7 +1321,7 @@ proc initStatusBar(node: BeaconNode) =
enableTrueColors() enableTrueColors()
proc dataResolver(expr: string): string = proc dataResolver(expr: string): string {.raises: [Defect].} =
template justified: untyped = node.chainDag.head.atEpochStart( template justified: untyped = node.chainDag.head.atEpochStart(
node.chainDag.headState.data.data.current_justified_checkpoint.epoch) node.chainDag.headState.data.data.current_justified_checkpoint.epoch)
# TODO: # TODO:

View File

@ -91,7 +91,7 @@ proc noRollback*(state: var BeaconState) =
trace "Skipping rollback of broken state" trace "Skipping rollback of broken state"
type type
RollbackHashedProc* = proc(state: var HashedBeaconState) {.gcsafe.} RollbackHashedProc* = proc(state: var HashedBeaconState) {.gcsafe, raises: [Defect].}
# Hashed-state transition functions # Hashed-state transition functions
# --------------------------------------------------------------- # ---------------------------------------------------------------

View File

@ -1,5 +1,7 @@
{.push raises: [Defect].}
import import
tables, strutils, parseutils, sequtils, terminal, colors std/[strutils, parseutils, sequtils, terminal, colors]
type type
ContentFragments = seq[tuple[kind: InterpolatedKind, value: string]] ContentFragments = seq[tuple[kind: InterpolatedKind, value: string]]
@ -12,7 +14,8 @@ type
cellsLeft: seq[StatusBarCell] cellsLeft: seq[StatusBarCell]
cellsRight: seq[StatusBarCell] cellsRight: seq[StatusBarCell]
DataItemResolver* = proc (dataItem: string): string DataItemResolver* = proc (dataItem: string): string {.
gcsafe, raises: [Defect].}
StatusBarView* = object StatusBarView* = object
model: DataItemResolver model: DataItemResolver
@ -29,10 +32,12 @@ const
backgroundColor = rgb(36, 36, 36) backgroundColor = rgb(36, 36, 36)
foregroundColor = colWhiteSmoke foregroundColor = colWhiteSmoke
func loadFragmentsLayout(contentLayout: string): ContentFragments = func loadFragmentsLayout(contentLayout: string): ContentFragments {.
raises: [Defect, ValueError].} =
result = toSeq(interpolatedFragments(strip contentLayout)) result = toSeq(interpolatedFragments(strip contentLayout))
func loadCellsLayout(cellsLayout: string): seq[StatusBarCell] = func loadCellsLayout(cellsLayout: string): seq[StatusBarCell] {.
raises: [Defect, ValueError].} =
var cells = cellsLayout.split(';') var cells = cellsLayout.split(';')
for cell in cells: for cell in cells:
var columns = cell.split(':', maxSplit = 1) var columns = cell.split(':', maxSplit = 1)
@ -49,7 +54,7 @@ func loadLayout(layout: string): Layout {.raises: [Defect, ValueError].} =
result.cellsLeft = loadCellsLayout(sections[0]) result.cellsLeft = loadCellsLayout(sections[0])
if sections.len == 2: result.cellsRight = loadCellsLayout(sections[1]) if sections.len == 2: result.cellsRight = loadCellsLayout(sections[1])
func updateContent(cell: var StatusBarCell, model: DataItemResolver) = proc updateContent(cell: var StatusBarCell, model: DataItemResolver) =
cell.content.setLen 0 cell.content.setLen 0
for fragment in cell.contentFragments: for fragment in cell.contentFragments:
case fragment[0] case fragment[0]
@ -58,11 +63,11 @@ func updateContent(cell: var StatusBarCell, model: DataItemResolver) =
of ikExpr, ikVar: of ikExpr, ikVar:
cell.content.add model(fragment[1]) cell.content.add model(fragment[1])
func updateCells(cells: var seq[StatusBarCell], model: DataItemResolver) = proc updateCells(cells: var seq[StatusBarCell], model: DataItemResolver) =
for cell in mitems(cells): for cell in mitems(cells):
cell.updateContent(model) cell.updateContent(model)
func update*(s: var StatusBarView) = proc update*(s: var StatusBarView) =
updateCells s.layout.cellsLeft, s.model updateCells s.layout.cellsLeft, s.model
updateCells s.layout.cellsRight, s.model updateCells s.layout.cellsRight, s.model
@ -73,18 +78,29 @@ func width(cells: seq[StatusBarCell]): int =
result = max(0, cells.len - 1) # the number of separators result = max(0, cells.len - 1) # the number of separators
for cell in cells: result += cell.width for cell in cells: result += cell.width
var complained = false
template ignoreException(body: untyped) =
try:
body
except Exception as exc:
if not complained:
# TODO terminal.nim exception leak
echo "Unable to update status bar: ", exc.msg
complained = true
proc renderCells(cells: seq[StatusBarCell], sep: string) = proc renderCells(cells: seq[StatusBarCell], sep: string) =
for i, cell in cells: for i, cell in cells:
stdout.setBackgroundColor backgroundColor ignoreException:
stdout.setForegroundColor foregroundColor stdout.setBackgroundColor backgroundColor
stdout.setStyle {styleDim} stdout.setForegroundColor foregroundColor
if i > 0: stdout.write sep stdout.setStyle {styleDim}
stdout.write " ", cell.label, ": " if i > 0: stdout.write sep
stdout.setStyle {styleBright} stdout.write " ", cell.label, ": "
stdout.write cell.content, " " stdout.setStyle {styleBright}
stdout.resetAttributes() stdout.write cell.content, " "
stdout.resetAttributes()
proc render*(s: var StatusBarView) = proc render*(s: var StatusBarView) {.raises: [Defect, ValueError].} =
doAssert s.consumedLines == 0 doAssert s.consumedLines == 0
let let
@ -92,21 +108,23 @@ proc render*(s: var StatusBarView) =
allCellsWidth = s.layout.cellsLeft.width + s.layout.cellsRight.width allCellsWidth = s.layout.cellsLeft.width + s.layout.cellsRight.width
if allCellsWidth > 0: if allCellsWidth > 0:
renderCells(s.layout.cellsLeft, sepLeft) ignoreException:
stdout.setBackgroundColor backgroundColor renderCells(s.layout.cellsLeft, sepLeft)
if termWidth > allCellsWidth: stdout.setBackgroundColor backgroundColor
stdout.write spaces(termWidth - allCellsWidth) if termWidth > allCellsWidth:
s.consumedLines = 1 stdout.write spaces(termWidth - allCellsWidth)
else: s.consumedLines = 1
stdout.write spaces(max(0, termWidth - s.layout.cellsLeft.width)), "\p" else:
s.consumedLines = 2 stdout.write spaces(max(0, termWidth - s.layout.cellsLeft.width)), "\p"
renderCells(s.layout.cellsRight, sepRight) s.consumedLines = 2
stdout.flushFile renderCells(s.layout.cellsRight, sepRight)
stdout.flushFile
proc erase*(s: var StatusBarView) = proc erase*(s: var StatusBarView) =
for i in 1 ..< s.consumedLines: cursorUp() ignoreException:
for i in 0 ..< s.consumedLines: eraseLine() for i in 1 ..< s.consumedLines: cursorUp()
s.consumedLines = 0 for i in 0 ..< s.consumedLines: eraseLine()
s.consumedLines = 0
func init*(T: type StatusBarView, func init*(T: type StatusBarView,
layout: string, layout: string,

View File

@ -35,7 +35,7 @@ type
else: else:
index: uint32 index: uint32
BeaconBlockCallback* = proc(signedBlock: SignedBeaconBlock) {.gcsafe.} BeaconBlockCallback* = proc(signedBlock: SignedBeaconBlock) {.gcsafe, raises: [Defect].}
BeaconSyncNetworkState* = ref object BeaconSyncNetworkState* = ref object
chainDag*: ChainDAGRef chainDag*: ChainDAGRef

View File

@ -193,7 +193,7 @@ proc keyboardCreatePassword(prompt: string,
return ok(password) return ok(password)
proc keyboardGetPassword[T](prompt: string, attempts: int, proc keyboardGetPassword[T](prompt: string, attempts: int,
pred: proc(p: string): KsResult[T] {.closure.}): KsResult[T] = pred: proc(p: string): KsResult[T] {.gcsafe, raises: [Defect].}): KsResult[T] =
var var
remainingAttempts = attempts remainingAttempts = attempts
counter = 1 counter = 1

2
vendor/nim-chronos vendored

@ -1 +1 @@
Subproject commit c8eefb9382a786993fc703386b0bd446ecf9c037 Subproject commit 4abd7a56450db8eb6578a151af0a5b7ba61bd2bf

2
vendor/nim-eth vendored

@ -1 +1 @@
Subproject commit be5e088b21e06a85cac4826454412db8459ed4f1 Subproject commit 16802c0e5218cce405cd623a554ce95549dd5181

2
vendor/nim-libp2p vendored

@ -1 +1 @@
Subproject commit a54e1cc699f036f3a8eeff33c3d9f893b8a284e9 Subproject commit 54031c9e9bc9882a2e8c2d5937031731ed63ab5e