2021-02-01 16:40:32 +03:00
|
|
|
const crypto = require('crypto')
|
2021-02-02 14:20:59 +03:00
|
|
|
const ethers = require('ethers')
|
|
|
|
const BigNumber = ethers.BigNumber
|
|
|
|
const { poseidon } = require('circomlib')
|
2021-02-01 16:40:32 +03:00
|
|
|
|
2021-02-02 14:20:59 +03:00
|
|
|
const poseidonHash = (items) => BigNumber.from(poseidon(items).toString())
|
2021-02-01 16:40:32 +03:00
|
|
|
|
|
|
|
const poseidonHash2 = (a, b) => poseidonHash([a, b])
|
|
|
|
|
|
|
|
/** Generate random number of specified byte length */
|
2021-02-02 14:20:59 +03:00
|
|
|
const randomBN = (nbytes = 31) => BigNumber.from(crypto.randomBytes(nbytes))
|
2021-02-01 16:40:32 +03:00
|
|
|
|
|
|
|
/** BigNumber to hex string of specified length */
|
|
|
|
const toFixedHex = (number, length = 32) =>
|
|
|
|
'0x' +
|
2021-02-02 14:27:58 +03:00
|
|
|
(number instanceof Buffer
|
|
|
|
? number.toString('hex')
|
|
|
|
: BigNumber.from(number).toHexString().slice(2)
|
|
|
|
).padStart(length * 2, '0')
|
2021-02-01 16:40:32 +03:00
|
|
|
|
2021-02-02 14:27:58 +03:00
|
|
|
const toBuffer = (value, length) =>
|
|
|
|
Buffer.from(
|
|
|
|
BigNumber.from(value)
|
|
|
|
.toHexString()
|
|
|
|
.slice(2)
|
|
|
|
.padStart(length * 2, '0'),
|
|
|
|
'hex',
|
|
|
|
)
|
2021-02-01 16:40:32 +03:00
|
|
|
|
|
|
|
function bitsToNumber(bits) {
|
|
|
|
let result = 0
|
|
|
|
for (const item of bits.slice().reverse()) {
|
|
|
|
result = (result << 1) + item
|
|
|
|
}
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
randomBN,
|
|
|
|
bitsToNumber,
|
|
|
|
toFixedHex,
|
2021-02-02 14:20:59 +03:00
|
|
|
toBuffer,
|
2021-02-01 16:40:32 +03:00
|
|
|
poseidonHash,
|
|
|
|
poseidonHash2,
|
|
|
|
}
|