2021-06-08 20:50:34 +02:00
|
|
|
const { ethers } = require('hardhat')
|
|
|
|
const { BigNumber } = ethers
|
|
|
|
const { randomBN, poseidonHash } = require('./utils')
|
|
|
|
|
|
|
|
function fromPrivkey(privkey) {
|
|
|
|
return {
|
|
|
|
privkey,
|
|
|
|
pubkey: poseidonHash([privkey]),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class Utxo {
|
2021-06-09 12:56:33 +02:00
|
|
|
constructor({ amount, pubkey, privkey, blinding, index } = {}) {
|
2021-06-08 20:50:34 +02:00
|
|
|
if (!pubkey) {
|
|
|
|
if (privkey) {
|
|
|
|
pubkey = fromPrivkey(privkey).pubkey
|
|
|
|
} else {
|
2021-06-09 12:56:33 +02:00
|
|
|
;({ pubkey, privkey } = fromPrivkey(randomBN()))
|
2021-06-08 20:50:34 +02:00
|
|
|
}
|
|
|
|
}
|
2021-06-09 12:56:33 +02:00
|
|
|
this.amount = BigNumber.from(amount || 0)
|
|
|
|
this.blinding = blinding || randomBN()
|
|
|
|
this.pubkey = pubkey
|
|
|
|
this.privkey = privkey
|
|
|
|
this.index = index
|
2021-06-08 20:50:34 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
getCommitment() {
|
|
|
|
if (!this._commitment) {
|
|
|
|
this._commitment = poseidonHash([this.amount, this.blinding, this.pubkey])
|
|
|
|
}
|
|
|
|
return this._commitment
|
|
|
|
}
|
|
|
|
|
|
|
|
getNullifier() {
|
|
|
|
if (!this._nullifier) {
|
2021-06-09 12:30:08 +02:00
|
|
|
if (this.amount > 0 && (this.index === undefined || !this.privkey === undefined)) {
|
2021-06-08 20:50:34 +02:00
|
|
|
throw new Error('Can not compute nullifier without utxo index or private key')
|
|
|
|
}
|
|
|
|
this._nullifier = poseidonHash([this.getCommitment(), this.index || 0, this.privkey || 0])
|
|
|
|
}
|
|
|
|
return this._nullifier
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = Utxo
|