Replace root hash by root content id

This commit is contained in:
Mark Spanbroek 2021-01-14 13:41:54 +01:00 committed by markspanbroek
parent 096fe0e40d
commit dd18f50ec6
4 changed files with 23 additions and 21 deletions

View File

@ -1,10 +1,10 @@
import pkg/libp2p/multihash
export multihash
import pkg/libp2p
type
MerkleDag* = object
data*: seq[byte]
proc rootHash*(dag: MerkleDag): MultiHash =
MultiHash.digest("sha2-256", dag.data).get()
proc rootId*(dag: MerkleDag): Cid =
let codec = multiCodec("dag-pb")
let hash = MultiHash.digest("sha2-256", dag.data).get()
Cid.init(CIDv0, codec, hash).get()

View File

@ -1,21 +1,22 @@
import std/tables
import std/hashes
import pkg/libp2p
import ./merkledag
export merkledag
type
Repo* = ref object
storage: Table[MultiHash, MerkleDag]
storage: Table[Cid, MerkleDag]
proc hash(multihash: MultiHash): Hash =
hash($multihash)
proc hash(id: Cid): Hash =
hash($id)
proc store*(repo: Repo, dag: MerkleDag) =
repo.storage[dag.rootHash] = dag
repo.storage[dag.rootId] = dag
proc contains*(repo: Repo, hash: MultiHash): bool =
repo.storage.hasKey(hash)
proc contains*(repo: Repo, id: Cid): bool =
repo.storage.hasKey(id)
proc retrieve*(repo: Repo, hash: MultiHash): MerkleDag =
repo.storage[hash]
proc retrieve*(repo: Repo, id: Cid): MerkleDag =
repo.storage[id]

View File

@ -1,11 +1,12 @@
import std/unittest
import pkg/libp2p
import pkg/dagger/merkledag
suite "Merkle DAG":
test "has a root hash":
test "has a content id":
let dag1 = MerkleDag(data: @[1'u8, 2'u8, 3'u8])
let dag2 = MerkleDag(data: @[4'u8, 5'u8, 6'u8])
let dag3 = MerkleDag(data: @[4'u8, 5'u8, 6'u8])
check dag1.rootHash != dag2.rootHash
check dag2.rootHash == dag3.rootHash
check dag1.rootId != dag2.rootId
check dag2.rootId == dag3.rootId

View File

@ -12,11 +12,11 @@ suite "repo":
test "stores Merkle DAGs":
repo.store(dag)
test "retrieves Merkle DAGs by their root hash":
test "retrieves Merkle DAGs by their root id":
repo.store(dag)
check repo.retrieve(dag.rootHash) == dag
check repo.retrieve(dag.rootId) == dag
test "knows which hashes are stored":
check repo.contains(dag.rootHash) == false
test "knows which ids are stored":
check repo.contains(dag.rootId) == false
repo.store(dag)
check repo.contains(dag.rootHash) == true
check repo.contains(dag.rootId) == true