From 44c4bb56a27240f9b41e74b74a0fc7dee73b3e50 Mon Sep 17 00:00:00 2001 From: Mark Spanbroek Date: Wed, 30 Jun 2021 11:22:28 +0200 Subject: [PATCH] Add transaction store --- abc/txstore.nim | 30 ++++++++++++++++++++++++++++++ tests/testTxStore.nim | 20 ++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 abc/txstore.nim create mode 100644 tests/testTxStore.nim diff --git a/abc/txstore.nim b/abc/txstore.nim new file mode 100644 index 0000000..36a7d97 --- /dev/null +++ b/abc/txstore.nim @@ -0,0 +1,30 @@ +import std/tables +import std/hashes +import ./transactions + +type + TxStore* = object + genesis: TxHash + transactions: Table[TxHash, Transaction] + +export transactions + +func hash(h: TxHash): Hash = + h.toBytes.hash + +func add*(store: var TxStore, transactions: varargs[Transaction]) = + for transaction in transactions: + store.transactions[transaction.hash] = transaction + +func init*(_: type TxStore, genesis: Transaction): TxStore = + result.genesis = genesis.hash + result.add(genesis) + +func genesis*(store: TxStore): TxHash = + store.genesis + +func hasTx*(store: TxStore, hash: TxHash): bool = + store.transactions.hasKey(hash) + +func `[]`*(store: TxStore, hash: TxHash): Transaction = + store.transactions[hash] diff --git a/tests/testTxStore.nim b/tests/testTxStore.nim new file mode 100644 index 0000000..e003d1d --- /dev/null +++ b/tests/testTxStore.nim @@ -0,0 +1,20 @@ +import abc/txstore +import ./basics +import ./alicebob + +suite "Transaction Store": + + let genesis = Transaction.genesis + let transaction = Transaction.example + + test "is initialized with a genesis transaction": + let store = TxStore.init(genesis) + check store.hasTx(genesis.hash) + check store[genesis.hash] == genesis + + test "stores transactions": + var store = TxStore.init(genesis) + check not store.hasTx(transaction.hash) + store.add(transaction) + check store.hasTx(transaction.hash) + check store[transaction.hash] == transaction