Skip to content

Commit

Permalink
Nimbus light client integration with status-go
Browse files Browse the repository at this point in the history
  • Loading branch information
Vitaliy Vlasov committed Aug 18, 2023
1 parent df9c73c commit e04d676
Show file tree
Hide file tree
Showing 24 changed files with 167 additions and 31 deletions.
2 changes: 1 addition & 1 deletion .gitmodules
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@
branch = master
[submodule "vendor/nim-confutils"]
path = vendor/nim-confutils
url = https://github.com/status-im/nim-confutils.git
url = https://github.com/siphiuel/nim-confutils.git
ignore = dirty
branch = master
[submodule "vendor/nim-blscurve"]
Expand Down
25 changes: 24 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ FLUFFY_TOOLS_CSV := $(subst $(SPACE),$(COMMA),$(FLUFFY_TOOLS))
nimbus \
fluffy \
nimbus_verified_proxy \
libverifproxy \
test \
test-reproducibility \
clean \
Expand Down Expand Up @@ -299,9 +300,31 @@ evmstate_test: | build deps evmstate
txparse: | build deps
$(ENV_SCRIPT) nim c $(NIM_PARAMS) "tools/txparse/$@.nim"

# Shared library for verified proxy
OS = $(shell $(CC) -dumpmachine)
ifneq (, $(findstring darwin, $(OS)))
SHAREDLIBEXT = dylib
else
ifneq (, $(findstring mingw, $(OS))$(findstring cygwin, $(OS))$(findstring msys, $(OS)))
SHAREDLIBEXT = dll
else
SHAREDLIBEXT = so
endif
endif

VERIF_PROXY_OUT_PATH ?= build/libverifproxy/

libverifproxy: | build deps
+ echo -e $(BUILD_MSG) "build/$@" && \
$(ENV_SCRIPT) nim --version && \
$(ENV_SCRIPT) nim c --app:lib -d:"libp2p_pki_schemes=secp256k1" --header:verifproxy.h --noMain:on --threads:on --nimcache:nimcache/libverifproxy -o:$(VERIF_PROXY_OUT_PATH)/$@.$(SHAREDLIBEXT) $(NIM_PARAMS) nimbus_verified_proxy/nimbus_verified_proxy.nim
cp nimcache/libverifproxy/verifproxy.h $(VERIF_PROXY_OUT_PATH)/
cp vendor/nimbus-build-system/vendor/Nim-csources-v1/c_code/nimbase.h $(VERIF_PROXY_OUT_PATH)/
echo -e $(BUILD_END_MSG) "build/$@"

# usual cleaning
clean: | clean-common
rm -rf build/{nimbus,fluffy,nimbus_verified_proxy,$(TOOLS_CSV),$(FLUFFY_TOOLS_CSV),all_tests,test_kvstore_rocksdb,test_rpc,all_fluffy_tests,all_fluffy_portal_spec_tests,test_portal_testnet,portalcli,blockwalk,eth_data_exporter,utp_test_app,utp_test,*.dSYM}
rm -rf build/{nimbus,fluffy,libverifproxy,nimbus_verified_proxy,$(TOOLS_CSV),$(FLUFFY_TOOLS_CSV),all_tests,test_kvstore_rocksdb,test_rpc,all_fluffy_tests,all_fluffy_portal_spec_tests,test_portal_testnet,portalcli,blockwalk,eth_data_exporter,utp_test_app,utp_test,*.dSYM}
rm -rf tools/t8n/{t8n,t8n_test}
rm -rf tools/evmstate/{evmstate,evmstate_test}
ifneq ($(USE_LIBBACKTRACE), 0)
Expand Down
7 changes: 5 additions & 2 deletions config.nims
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,11 @@ if not defined(windows):
--threads:on
--opt:speed
--excessiveStackTrace:on
# enable metric collection
--define:metrics
# enable metric collection
# (commented away for now due nimbus_verified proxy error: "metrics error:
# Adding a new combination of label values from another thread than the one
# in which the collector was created is not allowed")
#--define:metrics
# for heap-usage-by-instance-type metrics and object base-type strings
--define:nimTypeNames

Expand Down
124 changes: 117 additions & 7 deletions nimbus_verified_proxy/nimbus_verified_proxy.nim
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
{.push raises: [].}

import
std/[os, strutils],
std/[atomics, json, os, strutils],
chronicles, chronicles/chronos_tools, chronos, confutils,
eth/keys,
json_rpc/rpcproxy,
Expand Down Expand Up @@ -40,14 +40,32 @@ func getConfiguredChainId(networkMetadata: Eth2NetworkMetadata): Quantity =
else:
return networkMetadata.cfg.DEPOSIT_CHAIN_ID.Quantity

proc run(config: VerifiedProxyConf) {.raises: [CatchableError].} =
type OnHeaderCallback* = proc (s: cstring) {.cdecl, raises: [], gcsafe.}

var optimisticHeaderCallback : OnHeaderCallback = nil
var finalizedHeaderCallback : OnHeaderCallback = nil
proc setOptimisticHeaderCallback*(cb: OnHeaderCallback) {.exportc, dynlib.} =
optimisticHeaderCallback = cb
echo "optimistic header callback set"

proc setFinalizedHeaderCallback*(cb: OnHeaderCallback) {.exportc, dynlib.} =
finalizedHeaderCallback = cb
echo "finalized header callback set"



proc run(config: VerifiedProxyConf) {.raises: [CatchableError], gcsafe.} =
# Required as both Eth2Node and LightClient requires correct config type
var lcConfig = config.asLightClientConf()

setupLogging(config.logLevel, config.logStdout, none(OutFile))
{.gcsafe.}:
setupLogging(config.logLevel, config.logStdout, none(OutFile))

notice "Launching Nimbus verified proxy",
version = fullVersionStr, cmdParams = commandLineParams(), config
try:
notice "Launching Nimbus verified proxy",
version = fullVersionStr, cmdParams = getCLIParams(), config
except Exception:
notice "getCLIParams() exception"

let
metadata = loadEth2Network(config.eth2Network)
Expand Down Expand Up @@ -163,6 +181,13 @@ proc run(config: VerifiedProxyConf) {.raises: [CatchableError].} =
when lcDataFork > LightClientDataFork.None:
info "New LC finalized header",
finalized_header = shortLog(forkyHeader)
if finalizedHeaderCallback != nil:
notice "### Invoking finalizedHeaderCallback"
try:
finalizedHeaderCallback(Json.encode(finalizedHeader))
except SerializationError as e:
notice "finalizedHeaderCallback exception"


proc onOptimisticHeader(
lightClient: LightClient, optimisticHeader: ForkedLightClientHeader) =
Expand All @@ -171,6 +196,13 @@ proc run(config: VerifiedProxyConf) {.raises: [CatchableError].} =
info "New LC optimistic header",
optimistic_header = shortLog(forkyHeader)
optimisticProcessor.setOptimisticHeader(forkyHeader.beacon)
if optimisticHeaderCallback != nil:
try:
notice "### Invoking optimisticHeaderCallback"
optimisticHeaderCallback(Json.encode(optimisticHeader))
except SerializationError as e:
notice "optimisticHeaderCallback exception"


lightClient.onFinalizedHeader = onFinalizedHeader
lightClient.onOptimisticHeader = onOptimisticHeader
Expand Down Expand Up @@ -249,10 +281,88 @@ proc run(config: VerifiedProxyConf) {.raises: [CatchableError].} =
while true:
poll()

when isMainModule:
proc quit*() {.exportc, dynlib.} =
echo "Quitting"

proc NimMain() {.importc.}

var initialized: Atomic[bool]

proc initLib() =
if not initialized.exchange(true):
NimMain() # Every Nim library needs to call `NimMain` once exactly
when declared(setupForeignThreadGc): setupForeignThreadGc()
when declared(nimGC_setStackBottom):
var locals {.volatile, noinit.}: pointer
locals = addr(locals)
nimGC_setStackBottom(locals)


proc parseConfigAndRun*(configJson: cstring) {.gcsafe.} =
let str = $configJson
try:
let jsonNode = parseJson(str)

let rpcAddr = jsonNode["RpcAddress"].getStr()
let myConfig = VerifiedProxyConf(
rpcAddress: ValidIpAddress.init(rpcAddr),
listenAddress: defaultListenAddress,
eth2Network: some(jsonNode["Eth2Network"].getStr()),
trustedBlockRoot: Eth2Digest.fromHex(jsonNode["TrustedBlockRoot"].getStr()),
web3Url: parseCmdArg(Web3Url, jsonNode["Web3Url"].getStr()),
rpcPort: Port(jsonNode["RpcPort"].getInt()),
logLevel: jsonNode["LogLevel"].getStr(),
maxPeers: 160,
nat: NatConfig(hasExtIp: false, nat: NatAny),
logStdout: StdoutLogKind.Auto,
dataDir: OutDir(defaultVerifiedProxyDataDir()),
tcpPort: Port(defaultEth2TcpPort),
udpPort: Port(defaultEth2TcpPort),
agentString: "nimbus",
discv5Enabled: true,
)

run(myConfig)
except Exception as err:
echo "Exception when running ", getCurrentExceptionMsg(), err.getStackTrace()

type Context = object
thread: Thread[ptr Context]
configJson: cstring
stop: bool
onOptimisticHeader: OnHeaderCallback
onFinalizedHeader: OnHeaderCallback

proc runContext(ctx: ptr Context) {.thread.} =
parseConfigAndRun(ctx.configJson)

#[let node = parseConfigAndRun(ctx.configJson)
while not ctx[].stop: # and node.running:
let timeout = sleepAsync(100.millis)
waitFor timeout
# do cleanup
node.stop()]#

proc startLightClientProxy*(configJson: cstring, onOptimisticHeader: OnHeaderCallback, onFinalizedHeader: OnHeaderCallback): ptr Context {.exportc, dynlib.} =
initLib()

let ctx = createShared(Context, 1)
ctx.configJson = cast[cstring](allocShared0(len(configJson) + 1))
ctx.onOptimisticHeader = onOptimisticHeader
ctx.onFinalizedHeader = onFinalizedHeader
copyMem(ctx.configJson, configJson, len(configJson))

try:
createThread(ctx.thread, runContext, ctx)
except Exception as err:
echo "Exception when attempting to invoke createThread ", getCurrentExceptionMsg(), err.getStackTrace()
return ctx

when isMainModule and appType != "lib":
{.pop.}
var config = makeBannerAndConfig(
"Nimbus verified proxy " & fullVersionStr, VerifiedProxyConf)
{.push raises: [].}

run(config)
2 changes: 1 addition & 1 deletion nimbus_verified_proxy/nimbus_verified_proxy_conf.nim
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ func asLightClientConf*(pc: VerifiedProxyConf): LightClientConf =
discv5Enabled: pc.discv5Enabled,
directPeers: pc.directPeers,
trustedBlockRoot: pc.trustedBlockRoot,
web3Urls: @[],
web3Urls: @[EngineApiUrlConfigValue(url: pc.web3url.web3Url)],
jwtSecret: none(InputFile),
stopAtEpoch: 0
)
Expand Down
2 changes: 1 addition & 1 deletion tests/fixtures/eth_tests
Submodule eth_tests updated 725 files
2 changes: 1 addition & 1 deletion vendor/ethash
2 changes: 1 addition & 1 deletion vendor/nim-chronicles
2 changes: 1 addition & 1 deletion vendor/nim-chronos
Submodule nim-chronos updated 60 files
+2 −2 .github/workflows/ci.yml
+0 −1 .gitignore
+8 −21 chronos.nimble
+71 −6 chronos/apps/http/httpbodyrw.nim
+162 −207 chronos/apps/http/httpclient.nim
+4 −14 chronos/apps/http/httpcommon.nim
+0 −120 chronos/apps/http/httpdebug.nim
+230 −412 chronos/apps/http/httpserver.nim
+4 −1 chronos/apps/http/httptable.nim
+15 −15 chronos/apps/http/multipart.nim
+4 −28 chronos/apps/http/shttpserver.nim
+320 −261 chronos/asyncfutures2.nim
+144 −505 chronos/asyncloop.nim
+159 −163 chronos/asyncmacro2.nim
+0 −1,347 chronos/asyncproc.nim
+31 −31 chronos/asyncsync.nim
+4 −71 chronos/config.nim
+8 −5 chronos/debugutils.nim
+0 −221 chronos/futures.nim
+7 −7 chronos/handles.nim
+25 −23 chronos/ioselects/ioselectors_epoll.nim
+26 −33 chronos/ioselects/ioselectors_kqueue.nim
+22 −19 chronos/ioselects/ioselectors_poll.nim
+204 −407 chronos/osdefs.nim
+0 −1,348 chronos/oserrno.nim
+10 −122 chronos/osutils.nim
+13 −17 chronos/ratelimit.nim
+27 −9 chronos/selectors2.nim
+12 −14 chronos/sendfile.nim
+4 −3 chronos/srcloc.nim
+105 −25 chronos/streams/asyncstream.nim
+14 −19 chronos/streams/tlsstream.nim
+0 −416 chronos/threadsync.nim
+22 −1 chronos/timer.nim
+51 −103 chronos/transports/common.nim
+76 −56 chronos/transports/datagram.nim
+9 −6 chronos/transports/ipnet.nim
+21 −20 chronos/transports/osnet.nim
+280 −286 chronos/transports/stream.nim
+0 −12 chronos/unittest2/asynctests.nim
+6 −18 tests/testall.nim
+157 −150 tests/testasyncstream.nim
+4 −4 tests/testbugs.nim
+4 −4 tests/testdatagram.nim
+4 −4 tests/testfut.nim
+0 −26 tests/testfutures.nim
+134 −386 tests/testhttpclient.nim
+76 −259 tests/testhttpserver.nim
+1 −94 tests/testmacro.nim
+1 −1 tests/testnet.nim
+0 −42 tests/testproc.bat
+0 −468 tests/testproc.nim
+0 −28 tests/testproc.sh
+31 −31 tests/testratelimit.nim
+5 −8 tests/testshttpserver.nim
+38 −57 tests/testsignal.nim
+2 −2 tests/testsoon.nim
+36 −36 tests/teststream.nim
+0 −369 tests/testthreadsync.nim
+2 −2 tests/testutils.nim
2 changes: 1 addition & 1 deletion vendor/nim-confutils
2 changes: 1 addition & 1 deletion vendor/nim-eth
Submodule nim-eth updated 90 files
+82 −0 .appveyor.yml
+5 −5 .github/workflows/ci.yml
+49 −0 .travis.yml
+0 −19 doc/rlp.md
+10 −4 eth.nimble
+5 −2 eth/common/eth_hash.nim
+14 −42 eth/common/eth_types.nim
+1 −7 eth/common/eth_types_json_serialization.nim
+96 −97 eth/common/eth_types_rlp.nim
+3 −22 eth/common/transaction.nim
+2 −2 eth/common/utils.nim
+7 −3 eth/db/kvstore.nim
+55 −63 eth/db/kvstore_sqlite3.nim
+2 −3 eth/keyfile/keyfile.nim
+1 −1 eth/keyfile/uuid.nim
+15 −59 eth/keys.nim
+9 −7 eth/net/nat.nim
+2 −2 eth/net/utils.nim
+5 −5 eth/p2p.nim
+7 −7 eth/p2p/auth.nim
+14 −14 eth/p2p/discovery.nim
+4 −4 eth/p2p/discoveryv5/encoding.nim
+5 −5 eth/p2p/discoveryv5/enr.nim
+1 −12 eth/p2p/discoveryv5/hkdf.nim
+2 −2 eth/p2p/discoveryv5/ip_vote.nim
+2 −10 eth/p2p/discoveryv5/lru.nim
+2 −2 eth/p2p/discoveryv5/messages.nim
+5 −5 eth/p2p/discoveryv5/messages_encoding.nim
+2 −2 eth/p2p/discoveryv5/node.nim
+1 −1 eth/p2p/discoveryv5/nodes_verification.nim
+17 −17 eth/p2p/discoveryv5/protocol.nim
+0 −10 eth/p2p/discoveryv5/random2.nim
+34 −38 eth/p2p/discoveryv5/routing_table.nim
+2 −2 eth/p2p/discoveryv5/sessions.nim
+7 −7 eth/p2p/ecies.nim
+2 −2 eth/p2p/enode.nim
+15 −14 eth/p2p/kademlia.nim
+2 −2 eth/p2p/p2p_backends_helpers.nim
+1 −1 eth/p2p/p2p_protocol_dsl.nim
+2 −2 eth/p2p/peer_pool.nim
+11 −23 eth/p2p/private/p2p_types.nim
+9 −9 eth/p2p/rlpx.nim
+2 −2 eth/p2p/rlpxcrypt.nim
+7 −35 eth/rlp.nim
+6 −9 eth/rlp/object_serialization.nim
+5 −122 eth/rlp/writer.nim
+1 −1 eth/trie/binaries.nim
+5 −13 eth/trie/db.nim
+120 −177 eth/trie/hexary.nim
+2 −2 eth/trie/hexary_proof_verification.nim
+1 −1 eth/trie/nibbles.nim
+2 −2 eth/utp/clock_drift_calculator.nim
+2 −2 eth/utp/delay_histogram.nim
+12 −17 eth/utp/growable_buffer.nim
+2 −2 eth/utp/ledbat_congestion_control.nim
+1 −1 eth/utp/packets.nim
+5 −8 eth/utp/utp.nim
+13 −20 eth/utp/utp_discv5_protocol.nim
+5 −9 eth/utp/utp_protocol.nim
+19 −6 eth/utp/utp_router.nim
+176 −241 eth/utp/utp_socket.nim
+2 −2 eth/utp/utp_utils.nim
+0 −14 tests/common/all_tests.nim
+0 −236 tests/common/test_eip4844.nim
+0 −2 tests/common/test_eth_types.nim
+5 −5 tests/keys/test_keys.nim
+0 −2 tests/nim.cfg
+4 −4 tests/p2p/test_discoveryv5.nim
+1 −1 tests/p2p/test_discoveryv5_encoding.nim
+1 −2 tests/rlp/all_tests.nim
+ tests/rlp/rlps/blocks_1024_td_135112316.rlp
+ tests/rlp/rlps/blocks_10_td_1971072_1.rlp
+ tests/rlp/rlps/blocks_10_td_1971072_2.rlp
+ tests/rlp/rlps/blocks_10_td_1971072_3.rlp
+ tests/rlp/rlps/blocks_10_td_1971072_4.rlp
+ tests/rlp/rlps/blocks_10_td_1971072_5.rlp
+ tests/rlp/rlps/blocks_1_td_196416.rlp
+ tests/rlp/rlps/blocks_1_td_196608.rlp
+ tests/rlp/rlps/blocks_1_td_196704.rlp
+ tests/rlp/rlps/blocks_2_td_393120.rlp
+ tests/rlp/rlps/blocks_2_td_393504.rlp
+4 −0 tests/rlp/test_api_usage.nim
+1 −2 tests/rlp/test_common.nim
+0 −232 tests/rlp/test_rlp_codec.nim
+1 −1 tests/trie/test_branches_utils.nim
+2 −2 tests/trie/test_hexary_proof.nim
+5 −5 tests/utp/test_buffer.nim
+1 −1 tests/utp/test_utils.nim
+30 −31 tests/utp/test_utp_socket.nim
+10 −22 tools/dcli.nim
2 changes: 1 addition & 1 deletion vendor/nim-evmc
2 changes: 1 addition & 1 deletion vendor/nim-presto
2 changes: 1 addition & 1 deletion vendor/nimbus-eth2
Submodule nimbus-eth2 updated 380 files

0 comments on commit e04d676

Please sign in to comment.