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-27 17:02:35 +00:00
|
|
|
{.push raises: [Defect].}
|
2021-02-26 00:23:22 +00:00
|
|
|
|
2021-08-27 17:02:35 +00:00
|
|
|
import pkg/libp2p
|
|
|
|
import pkg/questionable
|
|
|
|
import pkg/stew/byteutils
|
2021-02-26 00:23:22 +00:00
|
|
|
|
|
|
|
type
|
|
|
|
CidDontMatchError* = object of CatchableError
|
|
|
|
|
|
|
|
Block* = object of RootObj
|
|
|
|
cid*: Cid
|
|
|
|
data*: seq[byte]
|
|
|
|
|
|
|
|
proc `$`*(b: Block): string =
|
|
|
|
result &= "cid: " & $b.cid
|
|
|
|
result &= "\ndata: " & string.fromBytes(b.data)
|
|
|
|
|
|
|
|
proc new*(
|
|
|
|
T: type Block,
|
|
|
|
cid: Cid,
|
|
|
|
data: openArray[byte] = [],
|
|
|
|
verify: bool = false): T =
|
|
|
|
let b = Block.new(
|
|
|
|
data,
|
|
|
|
cid.cidver,
|
|
|
|
cid.mhash.get().mcodec,
|
|
|
|
cid.mcodec
|
|
|
|
)
|
|
|
|
|
|
|
|
if verify and cid != b.cid:
|
|
|
|
raise newException(CidDontMatchError,
|
|
|
|
"The suplied Cid doesn't match the data!")
|
|
|
|
|
|
|
|
return b
|
|
|
|
|
|
|
|
proc new*(
|
|
|
|
T: type Block,
|
|
|
|
data: openArray[byte] = [],
|
2021-08-27 17:02:35 +00:00
|
|
|
version = CIDv1,
|
2021-02-26 00:23:22 +00:00
|
|
|
hcodec = multiCodec("sha2-256"),
|
2021-08-27 17:02:35 +00:00
|
|
|
codec = multiCodec("raw")): T =
|
2021-02-26 00:23:22 +00:00
|
|
|
let hash = MultiHash.digest($hcodec, data).get()
|
|
|
|
Block(
|
|
|
|
cid: Cid.init(version, codec, hash).get(),
|
|
|
|
data: @data)
|