2021-02-26 00:23:22 +00:00
|
|
|
## Nim-Dagger
|
|
|
|
## Copyright (c) 2021 Status Research & Development GmbH
|
|
|
|
## 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.
|
|
|
|
|
2021-08-30 19:25:20 +00:00
|
|
|
{.push raises: [Defect].}
|
2021-02-26 00:23:22 +00:00
|
|
|
|
2021-08-30 19:25:20 +00:00
|
|
|
import pkg/libp2p
|
|
|
|
import pkg/stew/byteutils
|
2022-01-11 02:25:13 +00:00
|
|
|
import pkg/questionable
|
|
|
|
import pkg/questionable/results
|
|
|
|
|
|
|
|
import ./errors
|
2021-02-26 00:23:22 +00:00
|
|
|
|
|
|
|
type
|
|
|
|
Block* = object of RootObj
|
|
|
|
cid*: Cid
|
|
|
|
data*: seq[byte]
|
|
|
|
|
|
|
|
proc `$`*(b: Block): string =
|
|
|
|
result &= "cid: " & $b.cid
|
|
|
|
result &= "\ndata: " & string.fromBytes(b.data)
|
|
|
|
|
2022-01-10 15:32:56 +00:00
|
|
|
func init*(
|
2021-08-30 19:25:20 +00:00
|
|
|
T: type Block,
|
|
|
|
data: openArray[byte] = [],
|
|
|
|
version = CIDv1,
|
2022-01-11 02:25:13 +00:00
|
|
|
mcodec = multiCodec("sha2-256"),
|
|
|
|
codec = multiCodec("raw")): ?!T =
|
|
|
|
|
|
|
|
let
|
|
|
|
hash = ? MultiHash.digest($mcodec, data).mapFailure
|
|
|
|
cid = ? Cid.init(version, codec, hash).mapFailure
|
|
|
|
|
|
|
|
success Block(
|
|
|
|
cid: cid,
|
2021-08-30 19:25:20 +00:00
|
|
|
data: @data)
|
|
|
|
|
2022-01-10 15:32:56 +00:00
|
|
|
func init*(
|
2021-02-26 00:23:22 +00:00
|
|
|
T: type Block,
|
|
|
|
cid: Cid,
|
2022-01-11 02:25:13 +00:00
|
|
|
data: openArray[byte],
|
|
|
|
verify: bool = false): ?!T =
|
|
|
|
|
|
|
|
let
|
|
|
|
mhash = ? cid.mhash.mapFailure
|
|
|
|
b = ? Block.init(
|
|
|
|
data = @data,
|
|
|
|
version = cid.cidver,
|
|
|
|
codec = cid.mcodec,
|
|
|
|
mcodec = mhash.mcodec)
|
|
|
|
|
|
|
|
if verify and cid != b.cid:
|
|
|
|
return failure "Cid's don't match!"
|
|
|
|
|
|
|
|
success b
|