Introduce acknowledgements

This commit is contained in:
Mark Spanbroek 2021-06-30 17:18:19 +02:00
parent 1db30e9ee7
commit 9208af338f
4 changed files with 86 additions and 0 deletions

40
abc/acks.nim Normal file
View File

@ -0,0 +1,40 @@
import pkg/questionable
import ./hash
export hash
type
Ack* = object
previous: ?Hash
transactions: seq[Hash]
func init*(_: type Ack, transactions: openArray[Hash]): ?Ack =
if transactions.len == 0:
return none Ack
some Ack(transactions: @transactions)
func init*(_: type Ack,
previous: Hash,
transactions: openArray[Hash]): ?Ack =
without var ack =? Ack.init(transactions):
return none Ack
ack.previous = previous.some
some ack
func previous*(ack: Ack): ?Hash =
ack.previous
func transactions*(ack: Ack): seq[Hash] =
ack.transactions
func toBytes*(ack: Ack): seq[byte] =
let previous = ack.previous |? Hash.default
result.add(previous.toBytes)
result.add(ack.transactions.len.uint8)
for transaction in ack.transactions:
result.add(transaction.toBytes)
func hash*(ack: Ack): Hash =
hash(ack.toBytes)

View File

@ -1,6 +1,7 @@
import std/random
import pkg/questionable
import abc
import abc/acks
import ./alicebob
proc example*(_: type PrivateKey): PrivateKey =
@ -25,3 +26,7 @@ proc example*(_: type Transaction): Transaction =
victor
)
transaction
proc example*(_: type Ack): Ack =
let tx1, tx2 = Transaction.example
!Ack.init([tx1.hash, tx2.hash])

40
tests/abc/testAcks.nim Normal file
View File

@ -0,0 +1,40 @@
import abc/acks
import ./basics
import ./alicebob
suite "Acknowledgements":
let tx1, tx2 = Transaction.example
test "a first acknowledgement can be made":
let ack = Ack.init([tx1.hash, tx2.hash])
check ack.isSome
check ack.?transactions == @[tx1.hash, tx2.hash].some
check ack.?previous == Hash.none
test "an acknowledgement has a hash":
let ack1, ack2 = Ack.example
check ack1.hash == ack1.hash
check ack2.hash == ack2.hash
check ack1.hash != ack2.hash
test "an acknowledgement references a previous acknowledgement":
let previous = Ack.example
let ack = Ack.init(previous.hash, [tx1.hash, tx2.hash])
check ack.isSome
check ack.?transactions == @[tx1.hash, tx2.hash].some
check ack.?previous == previous.hash.some
test "an acknowledgement can be converted to bytes":
let previous = Ack.example
let ack = !Ack.init(previous.hash, [tx1.hash, tx2.hash])
var expected: seq[byte]
expected.add(previous.hash.toBytes)
expected.add(2) # amount of transactions
expected.add(tx1.hash.toBytes)
expected.add(tx2.hash.toBytes)
check ack.toBytes == expected
test "an acknowledgement must contain at least one transaction":
let previous = Ack.example
check Ack.init(previous.hash, []).isNone

View File

@ -1,3 +1,4 @@
import abc/testAcks
import abc/testKeys
import abc/testTransactions
import abc/testTxStore