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.
|
|
|
|
|
2022-03-18 22:17:51 +00:00
|
|
|
import pkg/upraises
|
|
|
|
|
|
|
|
push: {.upraises: [].}
|
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
|
2022-03-30 02:43:35 +00:00
|
|
|
BlockSize* = 31 * 64 * 4 # file chunk read size
|
2022-03-15 18:47:31 +00:00
|
|
|
|
2021-02-26 00:23:22 +00:00
|
|
|
type
|
2022-03-18 19:50:53 +00:00
|
|
|
Block* = ref object of RootObj
|
2021-02-26 00:23:22 +00:00
|
|
|
cid*: Cid
|
|
|
|
data*: seq[byte]
|
|
|
|
|
|
|
|
proc `$`*(b: Block): string =
|
|
|
|
result &= "cid: " & $b.cid
|
|
|
|
result &= "\ndata: " & string.fromBytes(b.data)
|
|
|
|
|
2022-03-18 19:50:53 +00:00
|
|
|
func new*(
|
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-03-18 19:50:53 +00:00
|
|
|
func new*(
|
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
|
2022-03-18 19:50:53 +00:00
|
|
|
b = ? Block.new(
|
2022-01-11 02:25:13 +00:00
|
|
|
data = @data,
|
|
|
|
version = cid.cidver,
|
|
|
|
codec = cid.mcodec,
|
|
|
|
mcodec = mhash.mcodec)
|
|
|
|
|
|
|
|
if verify and cid != b.cid:
|
2022-03-18 19:50:53 +00:00
|
|
|
return "Cid's don't match!".failure
|
2022-01-11 02:25:13 +00:00
|
|
|
|
|
|
|
success b
|