2022-01-10 15:32:56 +00:00
|
|
|
## Nim-Dagger
|
2022-01-13 01:55:51 +00:00
|
|
|
## Copyright (c) 2022 Status Research & Development GmbH
|
2022-01-10 15:32:56 +00:00
|
|
|
## Licensed under either of
|
|
|
|
## * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
|
|
|
|
## * MIT license ([LICENSE-MIT](LICENSE-MIT))
|
|
|
|
## at your option.
|
|
|
|
## This file may not be copied, modified, or distributed except according to
|
|
|
|
## those terms.
|
|
|
|
|
|
|
|
import pkg/libp2p/protobuf/minprotobuf
|
2022-01-13 01:55:51 +00:00
|
|
|
import pkg/libp2p
|
2022-01-10 15:32:56 +00:00
|
|
|
import pkg/questionable
|
|
|
|
import pkg/questionable/results
|
|
|
|
|
|
|
|
import ./errors
|
|
|
|
|
|
|
|
type
|
2022-01-13 01:55:51 +00:00
|
|
|
Manifest* = object
|
|
|
|
cid*: ?Cid
|
|
|
|
blocks*: seq[Cid]
|
2022-01-10 15:32:56 +00:00
|
|
|
|
2022-01-13 01:55:51 +00:00
|
|
|
proc encode*(b: var Manifest): ?!seq[byte] =
|
2022-01-10 15:32:56 +00:00
|
|
|
## Encode the manifest into a ``ManifestCodec``
|
|
|
|
## multicodec container (Dag-pb) for now
|
2022-01-13 01:55:51 +00:00
|
|
|
##
|
|
|
|
|
2022-01-10 15:32:56 +00:00
|
|
|
var pbNode = initProtoBuffer()
|
|
|
|
|
|
|
|
for c in b.blocks:
|
|
|
|
var pbLink = initProtoBuffer()
|
|
|
|
pbLink.write(1, c.data.buffer) # write Cid links
|
|
|
|
pbLink.finish()
|
|
|
|
pbNode.write(2, pbLink)
|
|
|
|
|
2022-01-13 01:55:51 +00:00
|
|
|
let cid = !b.cid
|
2022-01-10 15:32:56 +00:00
|
|
|
pbNode.write(1, cid.data.buffer) # set the treeHash Cid as the data field
|
|
|
|
pbNode.finish()
|
|
|
|
|
|
|
|
return pbNode.buffer.success
|
|
|
|
|
2022-01-13 01:55:51 +00:00
|
|
|
proc decode*(_: type Manifest, data: openArray[byte]): ?!Manifest =
|
|
|
|
## Decode a manifest from a data blob
|
2022-01-10 15:32:56 +00:00
|
|
|
##
|
2022-01-13 01:55:51 +00:00
|
|
|
|
2022-01-10 15:32:56 +00:00
|
|
|
var
|
|
|
|
pbNode = initProtoBuffer(data)
|
|
|
|
cidBuf: seq[byte]
|
|
|
|
blocks: seq[Cid]
|
|
|
|
|
2022-01-13 01:55:51 +00:00
|
|
|
if pbNode.getField(1, cidBuf).isErr:
|
|
|
|
return failure("Unable to decode Cid from manifest!")
|
2022-01-10 15:32:56 +00:00
|
|
|
|
2022-01-13 01:55:51 +00:00
|
|
|
let cid = ? Cid.init(cidBuf).mapFailure
|
|
|
|
var linksBuf: seq[seq[byte]]
|
|
|
|
if pbNode.getRepeatedField(2, linksBuf).isOk:
|
|
|
|
for pbLinkBuf in linksBuf:
|
|
|
|
var
|
|
|
|
blocksBuf: seq[seq[byte]]
|
|
|
|
blockBuf: seq[byte]
|
|
|
|
pbLink = initProtoBuffer(pbLinkBuf)
|
2022-01-10 15:32:56 +00:00
|
|
|
|
2022-01-13 01:55:51 +00:00
|
|
|
if pbLink.getField(1, blockBuf).isOk:
|
|
|
|
blocks.add(? Cid.init(blockBuf).mapFailure)
|
2022-01-10 15:32:56 +00:00
|
|
|
|
2022-01-13 01:55:51 +00:00
|
|
|
Manifest(cid: cid.some, blocks: blocks).success
|