Introduce BLS based keys

This commit is contained in:
Mark Spanbroek 2021-06-24 14:43:17 +02:00
parent 0342502830
commit 6c5113e08a
4 changed files with 47 additions and 1 deletions

View File

@ -2,3 +2,6 @@ version = "0.1.0"
author = "ABC Authors" author = "ABC Authors"
description = "Asynchronous Blockchain" description = "Asynchronous Blockchain"
license = "MIT" license = "MIT"
requires "https://github.com/markspanbroek/nim-blscurve#fix-nimble"
requires "nimcrypto"

22
abc/keys.nim Normal file
View File

@ -0,0 +1,22 @@
import pkg/blscurve as bls
import pkg/nimcrypto
type
PrivateKey* = distinct bls.SecretKey
PublicKey* = distinct bls.PublicKey
proc `==`*(a, b: PrivateKey): bool {.borrow.}
proc `==`*(a, b: PublicKey): bool {.borrow.}
proc random*(_: type PrivateKey): PrivateKey =
var seed = newSeq[byte](64)
doAssert randomBytes(seed) == seed.len
doAssert deriveMasterSecretKey(bls.SecretKey(result), seed)
burnArray(seed)
proc erase*(key: var PrivateKey) =
burnMem(key)
proc toPublicKey*(private: PrivateKey): PublicKey =
doAssert publicFromSecret(bls.PublicKey(result), bls.SecretKey(private))

1
tests/nim.cfg Normal file
View File

@ -0,0 +1 @@
--path:".."

20
tests/testKeys.nim Normal file
View File

@ -0,0 +1,20 @@
import std/unittest
import abc/keys
suite "Keys":
test "generates random private keys":
check PrivateKey.random != PrivateKey.random
test "erases memory associated with a private key":
var key = PrivateKey.random
let bytes = cast[ptr[uint64]](addr key)
check bytes[] != 0
erase key
check bytes[] == 0
test "derives public key from private key":
let key1, key2 = PrivateKey.random()
check key1.toPublicKey == key1.toPublicKey
check key2.toPublicKey == key2.toPublicKey
check key1.toPublicKey != key2.toPublicKey