nimbus-eth1/fluffy/network/history/history_network.nim

68 lines
2.2 KiB
Nim
Raw Normal View History

# Nimbus
# Copyright (c) 2021 Status Research & Development GmbH
# 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.
import
std/[options, sugar],
stew/results, chronos,
eth/p2p/discoveryv5/[protocol, enr],
../../content_db,
../wire/[portal_protocol, portal_stream],
./history_content
const
historyProtocolId* = [byte 0x50, 0x0B]
# TODO: Extract common parts from the different networks
type HistoryNetwork* = ref object
portalProtocol*: PortalProtocol
contentDB*: ContentDB
proc toContentIdHandler(contentKey: ByteList): Option[ContentId] =
some(toContentId(contentKey))
proc getContent*(n: HistoryNetwork, key: ContentKey):
Future[Option[seq[byte]]] {.async.} =
let
keyEncoded = encode(key)
contentId = toContentId(keyEncoded)
contentInRange = n.portalProtocol.inRange(contentId)
# When the content id is in the radius range, try to look it up in the db.
if contentInRange:
let contentFromDB = n.contentDB.get(contentId)
if contentFromDB.isSome():
return contentFromDB
let content = await n.portalProtocol.contentLookup(keyEncoded, contentId)
# When content is found and is in the radius range, store it.
if content.isSome() and contentInRange:
n.contentDB.put(contentId, content.get().asSeq())
# TODO: for now returning bytes, ultimately it would be nice to return proper
# domain types.
return content.map(x => x.asSeq())
proc new*(
T: type HistoryNetwork,
baseProtocol: protocol.Protocol,
contentDB: ContentDB,
portalStream: PortalStream,
dataRadius = UInt256.high(),
bootstrapRecords: openArray[Record] = []): T =
let portalProtocol = PortalProtocol.new(
baseProtocol, historyProtocolId, contentDB, toContentIdHandler,
portalStream, dataRadius, bootstrapRecords)
return HistoryNetwork(portalProtocol: portalProtocol, contentDB: contentDB)
proc start*(p: HistoryNetwork) =
p.portalProtocol.start()
proc stop*(p: HistoryNetwork) =
p.portalProtocol.stop()