nim-secp256k1/tests/test_secp256k1.nim

75 lines
2.0 KiB
Nim
Raw Normal View History

2020-04-17 05:43:30 +00:00
import ../secp256k1, unittest
{.used.}
const
msg0 = SkMessage([
0'u8, 0, 0, 0, 0, 0, 0, 0,
0'u8, 0, 0, 0, 0, 0, 0, 0,
0'u8, 0, 0, 0, 0, 0, 0, 0,
0'u8, 0, 0, 0, 0, 0, 0, 0,
])
msg1 = SkMessage([
2020-04-17 05:43:30 +00:00
1'u8, 0, 0, 0, 0, 0, 0, 0,
1'u8, 0, 0, 0, 0, 0, 0, 0,
1'u8, 0, 0, 0, 0, 0, 0, 0,
1'u8, 0, 0, 0, 0, 0, 0, 0,
])
msg2 = array[40, byte]([
1'u8, 0, 0, 0, 0, 0, 0, 0,
1'u8, 0, 0, 0, 0, 0, 0, 0,
1'u8, 0, 0, 0, 0, 0, 0, 0,
1'u8, 0, 0, 0, 0, 0, 0, 0,
1'u8, 0, 0, 0, 0, 0, 0, 0,
])
2020-04-17 05:43:30 +00:00
proc workingRng(data: var openArray[byte]): bool =
data[0] += 1
true
proc brokenRng(data: var openArray[byte]): bool = false
2020-04-17 05:43:30 +00:00
suite "secp256k1":
test "Key ops":
let
sk = SkSecretKey.random(workingRng).expect("should get a key")
pk = sk.toPublicKey()
2020-04-17 05:43:30 +00:00
check:
SkSecretKey.fromRaw(sk.toRaw())[].toHex() == sk.toHex()
SkSecretKey.fromHex(sk.toHex())[].toHex() == sk.toHex()
SkPublicKey.fromRaw(pk.toRaw())[].toHex() == pk.toHex()
SkPublicKey.fromRaw(pk.toRawCompressed())[].toHex() == pk.toHex()
SkPublicKey.fromHex(pk.toHex())[].toHex() == pk.toHex()
SkSecretKey.random(brokenRng).isErr
2020-04-17 05:43:30 +00:00
2023-04-04 02:43:37 +00:00
test "Keypairs":
check:
SkKeyPair.random(workingRng).isOk()
2020-04-17 05:43:30 +00:00
test "Signatures":
let
sk = SkSecretKey.random(workingRng)[]
pk = sk.toPublicKey()
otherPk = SkSecretKey.random(workingRng)[].toPublicKey()
sig = sign(sk, msg0)
sig2 = signRecoverable(sk, msg0)
sig3 = signSchnorr(sk, msg0)
sig4 = signSchnorr(sk, msg2)
2020-04-17 05:43:30 +00:00
check:
verify(sig, msg0, pk)
not verify(sig, msg0, otherPk)
2020-04-17 05:43:30 +00:00
not verify(sig, msg1, pk)
recover(sig2, msg0)[] == pk
recover(sig2, msg1)[] != pk
SkSignature.fromDer(sig.toDer())[].toHex() == sig.toHex()
verify(sig3, msg0, pk)
verify(sig4, msg2, pk)
2020-04-17 05:43:30 +00:00
test "Message":
check:
SkMessage.fromBytes([]).isErr()
SkMessage.fromBytes([0'u8]).isErr()
SkMessage.fromBytes(array[32, byte](msg0)).isOk()