adds JSON serialization to BitTorrent manifest

This commit is contained in:
Marcin Czenko 2025-03-12 02:59:02 +01:00
parent f0a9306320
commit fe1cc15fbd
No known key found for this signature in database
GPG Key ID: 33DEA0C8E30937C0
2 changed files with 23 additions and 7 deletions

View File

@ -4,6 +4,7 @@ import pkg/questionable
import pkg/questionable/results
import ../../merkletree/codex/codex
import ../../utils/json
import ../../errors
import ../../codextypes
@ -12,14 +13,14 @@ import ../bencoding
type
BitTorrentPiece* = MultiHash
BitTorrentInfo* = ref object
length*: uint64
pieceLength*: uint32
pieces*: seq[BitTorrentPiece]
name*: ?string
length* {.serialize.}: uint64
pieceLength* {.serialize.}: uint32
pieces* {.serialize.}: seq[BitTorrentPiece]
name* {.serialize.}: ?string
BitTorrentManifest* = ref object
info*: BitTorrentInfo
codexManifestCid*: Cid
info* {.serialize.}: BitTorrentInfo
codexManifestCid* {.serialize.}: Cid
proc `$`*(self: BitTorrentInfo): string =
"BitTorrentInfo(length: " & $self.length & ", pieceLength: " & $self.pieceLength &
@ -29,6 +30,10 @@ proc `$`*(self: BitTorrentManifest): string =
"BitTorrentManifest(info: " & $self.info & ", codexManifestCid: " &
$self.codexManifestCid & ")"
func `==`*(a: BitTorrentInfo, b: BitTorrentInfo): bool =
a.length == b.length and a.pieceLength == b.pieceLength and a.pieces == b.pieces and
a.name == b.name
proc newBitTorrentManifest*(
info: BitTorrentInfo, codexManifestCid: Cid
): BitTorrentManifest =

View File

@ -2,7 +2,8 @@ import std/options
import std/typetraits
from pkg/ethers import Address
from pkg/libp2p import
Cid, PeerId, SignedPeerRecord, MultiAddress, AddressInfo, init, `$`
Cid, PeerId, SignedPeerRecord, MultiAddress, AddressInfo, MultiHash, init, hex, `$`
import pkg/stew/byteutils
import pkg/contractabi
import pkg/codexdht/discv5/node as dn
import pkg/serde/json
@ -35,3 +36,13 @@ func `%`*(obj: MultiAddress): JsonNode =
func `%`*(address: ethers.Address): JsonNode =
% $address
proc fromJson*(_: type MultiHash, json: JsonNode): ?!MultiHash =
expectJsonKind(MultiHash, JString, json)
echo "[MultiHash.fromJson] json.str: ", json.str
without bytes =? json.str.hexToSeqByte.catch, err:
return failure(err.msg)
MultiHash.init(bytes).mapFailure
func `%`*(multiHash: MultiHash): JsonNode =
%multiHash.hex