chore(rln-relay): address laundry list for tests (#1452)

* chore(rln-relay): s/var/let

* chore(rln-relay): s/var/let

* chore(rln-relay): s/check/require

* chore(rln-relay): s/check/require

* fix(rln-relay): s/check/require
This commit is contained in:
Aaryamann Challani 2022-12-07 22:47:08 +05:30 committed by GitHub
parent ab7ee30e24
commit f08680045e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 74 additions and 67 deletions

View File

@ -34,7 +34,7 @@ procSuite "Waku rln relay":
memListRes.isOk() memListRes.isOk()
let (groupKeys, root) = memListRes.get() let (groupKeys, root) = memListRes.get()
check: require:
groupKeys.len == 100 groupKeys.len == 100
let let
# convert the keys to MembershipKeyPair structs # convert the keys to MembershipKeyPair structs
@ -79,7 +79,7 @@ procSuite "Waku rln relay":
suite "Waku rln relay": suite "Waku rln relay":
test "key_gen Nim Wrappers": test "key_gen Nim Wrappers":
var let
merkleDepth: csize_t = 20 merkleDepth: csize_t = 20
let rlnInstance = createRLNInstance() let rlnInstance = createRLNInstance()
@ -89,18 +89,18 @@ suite "Waku rln relay":
# keysBufferPtr will hold the generated key pairs i.e., secret and public keys # keysBufferPtr will hold the generated key pairs i.e., secret and public keys
var var
keysBuffer: Buffer keysBuffer: Buffer
let
keysBufferPtr = addr(keysBuffer) keysBufferPtr = addr(keysBuffer)
done = key_gen(rlnInstance.get(), keysBufferPtr) done = key_gen(rlnInstance.get(), keysBufferPtr)
check: require:
# check whether the keys are generated successfully # check whether the keys are generated successfully
done == true done
if done: let generatedKeys = cast[ptr array[64, byte]](keysBufferPtr.`ptr`)[]
var generatedKeys = cast[ptr array[64, byte]](keysBufferPtr.`ptr`)[] check:
check: # the public and secret keys together are 64 bytes
# the public and secret keys together are 64 bytes generatedKeys.len == 64
generatedKeys.len == 64 debug "generated keys: ", generatedKeys
debug "generated keys: ", generatedKeys
test "membership Key Generation": test "membership Key Generation":
# create an RLN instance # create an RLN instance
@ -113,7 +113,7 @@ suite "Waku rln relay":
keyPairRes.isOk() keyPairRes.isOk()
let keyPair = keyPairRes.get() let keyPair = keyPairRes.get()
var empty: array[32, byte] let empty = default(array[32, byte])
check: check:
keyPair.idKey.len == 32 keyPair.idKey.len == 32
keyPair.idCommitment.len == 32 keyPair.idCommitment.len == 32
@ -129,27 +129,27 @@ suite "Waku rln relay":
rlnInstance.isOk() rlnInstance.isOk()
# read the Merkle Tree root # read the Merkle Tree root
var let
root1 {.noinit.}: Buffer = Buffer() root1 {.noinit.}: Buffer = Buffer()
rootPtr1 = addr(root1) rootPtr1 = unsafeAddr(root1)
getRootSuccessful1 = getRoot(rlnInstance.get(), rootPtr1) getRootSuccessful1 = getRoot(rlnInstance.get(), rootPtr1)
check: require:
getRootSuccessful1 getRootSuccessful1
root1.len == 32 root1.len == 32
# read the Merkle Tree root # read the Merkle Tree root
var let
root2 {.noinit.}: Buffer = Buffer() root2 {.noinit.}: Buffer = Buffer()
rootPtr2 = addr(root2) rootPtr2 = unsafeAddr(root2)
getRootSuccessful2 = getRoot(rlnInstance.get(), rootPtr2) getRootSuccessful2 = getRoot(rlnInstance.get(), rootPtr2)
check: require:
getRootSuccessful2 getRootSuccessful2
root2.len == 32 root2.len == 32
var rootValue1 = cast[ptr array[32, byte]] (root1.`ptr`) let rootValue1 = cast[ptr array[32, byte]] (root1.`ptr`)
let rootHex1 = rootValue1[].inHex let rootHex1 = rootValue1[].inHex
var rootValue2 = cast[ptr array[32, byte]] (root2.`ptr`) let rootValue2 = cast[ptr array[32, byte]] (root2.`ptr`)
let rootHex2 = rootValue2[].inHex let rootHex2 = rootValue2[].inHex
# the two roots must be identical # the two roots must be identical
@ -163,13 +163,13 @@ suite "Waku rln relay":
let rln = rlnInstance.get() let rln = rlnInstance.get()
# read the Merkle Tree root # read the Merkle Tree root
var root1 = getMerkleRoot(rln) let root1 = getMerkleRoot(rln)
require: require:
root1.isOk() root1.isOk()
let rootHex1 = root1.value().inHex let rootHex1 = root1.value().inHex
# read the Merkle Tree root # read the Merkle Tree root
var root2 = getMerkleRoot(rln) let root2 = getMerkleRoot(rln)
require: require:
root2.isOk() root2.isOk()
let rootHex2 = root2.value().inHex let rootHex2 = root2.value().inHex
@ -190,8 +190,8 @@ suite "Waku rln relay":
keypairRes.isOk() keypairRes.isOk()
let keyPair = keyPairRes.get() let keyPair = keyPairRes.get()
var pkBuffer = toBuffer(keyPair.idCommitment) let pkBuffer = toBuffer(keyPair.idCommitment)
let pkBufferPtr = addr pkBuffer let pkBufferPtr = unsafeAddr(pkBuffer)
# add the member to the tree # add the member to the tree
let memberAdded = updateNextMember(rln, pkBufferPtr) let memberAdded = updateNextMember(rln, pkBufferPtr)
@ -254,9 +254,9 @@ suite "Waku rln relay":
let rln = rlnInstance.get() let rln = rlnInstance.get()
# read the Merkle Tree root # read the Merkle Tree root
var let
root1 {.noinit.}: Buffer = Buffer() root1 {.noinit.}: Buffer = Buffer()
rootPtr1 = addr(root1) rootPtr1 = unsafeAddr(root1)
getRootSuccessful1 = getRoot(rln, rootPtr1) getRootSuccessful1 = getRoot(rln, rootPtr1)
require: require:
getRootSuccessful1 getRootSuccessful1
@ -268,8 +268,8 @@ suite "Waku rln relay":
keypairRes.isOk() keypairRes.isOk()
let keyPair = keyPairRes.get() let keyPair = keyPairRes.get()
var pkBuffer = toBuffer(keyPair.idCommitment) let pkBuffer = toBuffer(keyPair.idCommitment)
let pkBufferPtr = addr pkBuffer let pkBufferPtr = unsafeAddr(pkBuffer)
# add the member to the tree # add the member to the tree
let memberAdded = updateNextMember(rln, pkBufferPtr) let memberAdded = updateNextMember(rln, pkBufferPtr)
@ -277,9 +277,9 @@ suite "Waku rln relay":
memberAdded memberAdded
# read the Merkle Tree root after insertion # read the Merkle Tree root after insertion
var let
root2 {.noinit.}: Buffer = Buffer() root2 {.noinit.}: Buffer = Buffer()
rootPtr2 = addr(root2) rootPtr2 = unsafeAddr(root2)
getRootSuccessful = getRoot(rln, rootPtr2) getRootSuccessful = getRoot(rln, rootPtr2)
require: require:
getRootSuccessful getRootSuccessful
@ -292,9 +292,9 @@ suite "Waku rln relay":
deletionSuccess deletionSuccess
# read the Merkle Tree root after the deletion # read the Merkle Tree root after the deletion
var let
root3 {.noinit.}: Buffer = Buffer() root3 {.noinit.}: Buffer = Buffer()
rootPtr3 = addr(root3) rootPtr3 = unsafeAddr(root3)
getRootSuccessful3 = getRoot(rln, rootPtr3) getRootSuccessful3 = getRoot(rln, rootPtr3)
require: require:
getRootSuccessful3 getRootSuccessful3
@ -383,17 +383,17 @@ suite "Waku rln relay":
rlnInstance.isOk() rlnInstance.isOk()
# prepare the input # prepare the input
var let
msg = "Hello".toBytes() msg = "Hello".toBytes()
hashInput = appendLength(msg) hashInput = appendLength(msg)
hashInputBuffer = toBuffer(hashInput) hashInputBuffer = toBuffer(hashInput)
# prepare other inputs to the hash function # prepare other inputs to the hash function
var outputBuffer: Buffer let outputBuffer = default(Buffer)
let hashSuccess = hash(rlnInstance.get(), addr hashInputBuffer, let hashSuccess = hash(rlnInstance.get(), unsafeAddr hashInputBuffer,
addr outputBuffer) unsafeAddr outputBuffer)
check: require:
hashSuccess hashSuccess
let outputArr = cast[ptr array[32, byte]](outputBuffer.`ptr`)[] let outputArr = cast[ptr array[32, byte]](outputBuffer.`ptr`)[]
@ -401,7 +401,7 @@ suite "Waku rln relay":
"1e32b3ab545c07c8b4a7ab1ca4f46bc31e4fdc29ac3b240ef1d54b4017a26e4c" == "1e32b3ab545c07c8b4a7ab1ca4f46bc31e4fdc29ac3b240ef1d54b4017a26e4c" ==
outputArr.inHex() outputArr.inHex()
var let
hashOutput = cast[ptr array[32, byte]] (outputBuffer.`ptr`)[] hashOutput = cast[ptr array[32, byte]] (outputBuffer.`ptr`)[]
hashOutputHex = hashOutput.toHex() hashOutputHex = hashOutput.toHex()
@ -499,8 +499,9 @@ suite "Waku rln relay":
protobuf = rateLimitProof.encode() protobuf = rateLimitProof.encode()
decodednsp = RateLimitProof.init(protobuf.buffer) decodednsp = RateLimitProof.init(protobuf.buffer)
require:
decodednsp.isOk()
check: check:
decodednsp.isErr() == false
decodednsp.value == rateLimitProof decodednsp.value == rateLimitProof
test "test proofVerify and proofGen for a valid proof": test "test proofVerify and proofGen for a valid proof":
@ -542,7 +543,7 @@ suite "Waku rln relay":
let messageBytes = "Hello".toBytes() let messageBytes = "Hello".toBytes()
# prepare the epoch # prepare the epoch
var epoch: Epoch let epoch = default(Epoch)
debug "epoch", epochHex = epoch.inHex() debug "epoch", epochHex = epoch.inHex()
# generate proof # generate proof
@ -550,7 +551,7 @@ suite "Waku rln relay":
memKeys = memKeys, memKeys = memKeys,
memIndex = MembershipIndex(index), memIndex = MembershipIndex(index),
epoch = epoch) epoch = epoch)
check: require:
proofRes.isOk() proofRes.isOk()
let proof = proofRes.value let proof = proofRes.value
@ -561,8 +562,10 @@ suite "Waku rln relay":
# Ensure the proof verification did not error out # Ensure the proof verification did not error out
check: require:
verified.isOk() verified.isOk()
check:
verified.value() == true verified.value() == true
test "test proofVerify and proofGen for an invalid proof": test "test proofVerify and proofGen for an invalid proof":
@ -602,7 +605,7 @@ suite "Waku rln relay":
let messageBytes = "Hello".toBytes() let messageBytes = "Hello".toBytes()
# prepare the epoch # prepare the epoch
var epoch: Epoch let epoch = default(Epoch)
debug "epoch in bytes", epochHex = epoch.inHex() debug "epoch in bytes", epochHex = epoch.inHex()
@ -612,7 +615,7 @@ suite "Waku rln relay":
memKeys = memKeys, memKeys = memKeys,
memIndex = MembershipIndex(badIndex), memIndex = MembershipIndex(badIndex),
epoch = epoch) epoch = epoch)
check: require:
proofRes.isOk() proofRes.isOk()
let proof = proofRes.value let proof = proofRes.value
@ -676,7 +679,7 @@ suite "Waku rln relay":
let messageBytes = "Hello".toBytes() let messageBytes = "Hello".toBytes()
# prepare the epoch # prepare the epoch
var epoch: Epoch let epoch = default(Epoch)
debug "epoch in bytes", epochHex = epoch.inHex() debug "epoch in bytes", epochHex = epoch.inHex()
# generate proof # generate proof
@ -769,7 +772,7 @@ suite "Waku rln relay":
let messageBytes = "Hello".toBytes() let messageBytes = "Hello".toBytes()
# prepare the epoch # prepare the epoch
var epoch: Epoch let epoch = default(Epoch)
debug "epoch in bytes", epochHex = epoch.inHex() debug "epoch in bytes", epochHex = epoch.inHex()
# generate proof # generate proof
@ -836,7 +839,7 @@ suite "Waku rln relay":
wakurlnrelay = WakuRLNRelay() wakurlnrelay = WakuRLNRelay()
epoch = getCurrentEpoch() epoch = getCurrentEpoch()
# cretae some dummy nullifiers and secret shares # create some dummy nullifiers and secret shares
var nullifier1: Nullifier var nullifier1: Nullifier
for index, x in nullifier1.mpairs: nullifier1[index] = 1 for index, x in nullifier1.mpairs: nullifier1[index] = 1
var shareX1: MerkleNode var shareX1: MerkleNode
@ -892,8 +895,9 @@ suite "Waku rln relay":
# wm3 has the same nullifier as wm1 but different secret shares, it should be detected as duplicate # wm3 has the same nullifier as wm1 but different secret shares, it should be detected as duplicate
let result3 = wakurlnrelay.hasDuplicate(wm3) let result3 = wakurlnrelay.hasDuplicate(wm3)
check: require:
result3.isOk() result3.isOk()
check:
# it is a duplicate # it is a duplicate
result3.value == true result3.value == true
@ -945,17 +949,19 @@ suite "Waku rln relay":
# create some messages from the same peer and append rln proof to them, except wm4 # create some messages from the same peer and append rln proof to them, except wm4
var var
wm1 = WakuMessage(payload: "Valid message".toBytes()) wm1 = WakuMessage(payload: "Valid message".toBytes())
proofAdded1 = wakuRlnRelay.appendRLNProof(wm1, time)
# another message in the same epoch as wm1, it will break the messaging rate limit # another message in the same epoch as wm1, it will break the messaging rate limit
wm2 = WakuMessage(payload: "Spam".toBytes()) wm2 = WakuMessage(payload: "Spam".toBytes())
proofAdded2 = wakuRlnRelay.appendRLNProof(wm2, time)
# wm3 points to the next epoch # wm3 points to the next epoch
wm3 = WakuMessage(payload: "Valid message".toBytes()) wm3 = WakuMessage(payload: "Valid message".toBytes())
proofAdded3 = wakuRlnRelay.appendRLNProof(wm3, time+EpochUnitSeconds)
wm4 = WakuMessage(payload: "Invalid message".toBytes()) wm4 = WakuMessage(payload: "Invalid message".toBytes())
# checks proofs are added let
check: proofAdded1 = wakuRlnRelay.appendRLNProof(wm1, time)
proofAdded2 = wakuRlnRelay.appendRLNProof(wm2, time)
proofAdded3 = wakuRlnRelay.appendRLNProof(wm3, time+EpochUnitSeconds)
# ensure proofs are added
require:
proofAdded1 proofAdded1
proofAdded2 proofAdded2
proofAdded3 proofAdded3
@ -1013,8 +1019,8 @@ suite "Waku rln relay":
keyPairRes.isOk() keyPairRes.isOk()
let keyPair = keyPairRes.get() let keyPair = keyPairRes.get()
var empty: array[32, byte] let empty = default(array[32, byte])
check: require:
keyPair.idKey.len == 32 keyPair.idKey.len == 32
keyPair.idCommitment.len == 32 keyPair.idCommitment.len == 32
keyPair.idKey != empty keyPair.idKey != empty
@ -1037,13 +1043,14 @@ suite "Waku rln relay":
writeRlnCredentials(filepath, rlnMembershipCredentials, password).isOk() writeRlnCredentials(filepath, rlnMembershipCredentials, password).isOk()
let readCredentialsResult = readRlnCredentials(filepath, password) let readCredentialsResult = readRlnCredentials(filepath, password)
check: require:
readCredentialsResult.isOk() readCredentialsResult.isOk()
let credentials = readCredentialsResult.get() let credentials = readCredentialsResult.get()
check: require:
credentials.isSome() credentials.isSome()
check:
credentials.get().membershipKeyPair == keyPair credentials.get().membershipKeyPair == keyPair
credentials.get().rlnIndex == index credentials.get().rlnIndex == index

View File

@ -42,7 +42,7 @@ proc uploadRLNContract*(ethClientAddress: string): Future[Address] {.async.} =
let add = web3.defaultAccount let add = web3.defaultAccount
debug "contract deployer account address ", add debug "contract deployer account address ", add
var balance = await web3.provider.eth_getBalance(web3.defaultAccount, "latest") let balance = await web3.provider.eth_getBalance(web3.defaultAccount, "latest")
debug "Initial account balance: ", balance debug "Initial account balance: ", balance
# deploy the poseidon hash contract and gets its address # deploy the poseidon hash contract and gets its address
@ -69,11 +69,11 @@ proc uploadRLNContract*(ethClientAddress: string): Future[Address] {.async.} =
# deploy membership contract with its constructor inputs # deploy membership contract with its constructor inputs
let receipt = await web3.deployContract(MembershipContractCode, let receipt = await web3.deployContract(MembershipContractCode,
contractInput = contractInput) contractInput = contractInput)
var contractAddress = receipt.contractAddress.get let contractAddress = receipt.contractAddress.get
debug "Address of the deployed membership contract: ", contractAddress debug "Address of the deployed membership contract: ", contractAddress
balance = await web3.provider.eth_getBalance(web3.defaultAccount, "latest") let newBalance = await web3.provider.eth_getBalance(web3.defaultAccount, "latest")
debug "Account balance after the contract deployment: ", balance debug "Account balance after the contract deployment: ", newBalance
await web3.close() await web3.close()
debug "disconnected from ", ethClientAddress debug "disconnected from ", ethClientAddress
@ -92,7 +92,7 @@ proc createEthAccount(): Future[(keys.PrivateKey, Address)] {.async.} =
let pk = keys.PrivateKey.random(theRNG[]) let pk = keys.PrivateKey.random(theRNG[])
let acc = Address(toCanonicalAddress(pk.toPublicKey())) let acc = Address(toCanonicalAddress(pk.toPublicKey()))
var tx: EthSend var tx:EthSend
tx.source = accounts[0] tx.source = accounts[0]
tx.value = some(ethToWei(10.u256)) tx.value = some(ethToWei(10.u256))
tx.to = some(acc) tx.to = some(acc)
@ -100,7 +100,7 @@ proc createEthAccount(): Future[(keys.PrivateKey, Address)] {.async.} =
# Send 10 eth to acc # Send 10 eth to acc
discard await web3.send(tx) discard await web3.send(tx)
var balance = await web3.provider.eth_getBalance(acc, "latest") let balance = await web3.provider.eth_getBalance(acc, "latest")
assert(balance == ethToWei(10.u256)) assert(balance == ethToWei(10.u256))
return (pk, acc) return (pk, acc)
@ -142,7 +142,7 @@ proc runGanache(): Process =
var cmdline: string var cmdline: string
while true: while true:
if runGanache.outputstream.readLine(cmdline): if runGanache.outputstream.readLine(cmdline):
ganacheStartLog.add cmdline ganacheStartLog.add(cmdline)
if cmdline.contains("Listening on 127.0.0.1:8540"): if cmdline.contains("Listening on 127.0.0.1:8540"):
break break
debug "Ganache daemon is running and ready", pid=ganachePID, startLog=ganacheStartLog debug "Ganache daemon is running and ready", pid=ganachePID, startLog=ganacheStartLog
@ -206,13 +206,13 @@ procSuite "Waku-rln-relay":
debug "membership commitment key", pk = pk debug "membership commitment key", pk = pk
# test ------------------------------ # test ------------------------------
var fut = newFuture[void]() let fut = newFuture[void]()
let s = await contractObj.subscribe(MemberRegistered, %*{"fromBlock": "0x0", let s = await contractObj.subscribe(MemberRegistered, %*{"fromBlock": "0x0",
"address": contractAddress}) do( "address": contractAddress}) do(
pubkey: Uint256, index: Uint256){.raises: [Defect], gcsafe.}: pubkey: Uint256, index: Uint256){.raises: [Defect], gcsafe.}:
try: try:
debug "onRegister", pubkey = pubkey, index = index debug "onRegister", pubkey = pubkey, index = index
check: require:
pubkey == pk pubkey == pk
fut.complete() fut.complete()
except Exception as err: except Exception as err:
@ -278,7 +278,7 @@ procSuite "Waku-rln-relay":
let pk2 = keyPair2.idCommitment.toUInt256() let pk2 = keyPair2.idCommitment.toUInt256()
debug "membership commitment key", pk2 = pk2 debug "membership commitment key", pk2 = pk2
var events = [newFuture[void](), newFuture[void]()] let events = [newFuture[void](), newFuture[void]()]
var futIndex = 0 var futIndex = 0
var handler: GroupUpdateHandler var handler: GroupUpdateHandler
handler = proc (blockNumber: BlockNumber, handler = proc (blockNumber: BlockNumber,
@ -336,7 +336,7 @@ procSuite "Waku-rln-relay":
let tx = await sender.register(20.u256).send(value = MembershipFee) # value is the membership fee let tx = await sender.register(20.u256).send(value = MembershipFee) # value is the membership fee
debug "The hash of registration tx: ", tx debug "The hash of registration tx: ", tx
# var members: array[2, uint256] = [20.u256, 21.u256] # let members: array[2, uint256] = [20.u256, 21.u256]
# debug "This is the batch registration result ", await sender.registerBatch(members).send(value = (members.len * MembershipFee)) # value is the membership fee # debug "This is the batch registration result ", await sender.registerBatch(members).send(value = (members.len * MembershipFee)) # value is the membership fee
let balance = await web3.provider.eth_getBalance(web3.defaultAccount, "latest") let balance = await web3.provider.eth_getBalance(web3.defaultAccount, "latest")