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
|
|
|
|
2022-03-15 18:47:31 +00:00
|
|
|
const
|
|
|
|
BlockSize* = 4096 # file chunk read size
|
|
|
|
|
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
|
|
|
|
|
2022-03-15 18:47:31 +00:00
|
|
|
# TODO: If the hash is `>=` to the data,
|
|
|
|
# use the Cid as a container!
|
|
|
|
Block(
|
2022-01-11 02:25:13 +00:00
|
|
|
cid: cid,
|
2022-03-15 18:47:31 +00:00
|
|
|
data: @data).success
|
2021-08-30 19:25:20 +00:00
|
|
|
|
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],
|
2022-03-15 18:47:31 +00:00
|
|
|
verify: bool = true): ?!T =
|
2022-01-11 02:25:13 +00:00
|
|
|
|
|
|
|
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
|