Skip to content

Commit

Permalink
Add missing hashOutputs check to ElGamal and Peillier.
Browse files Browse the repository at this point in the history
  • Loading branch information
msinkec committed Oct 24, 2023
1 parent 10b419c commit f2d1aa6
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 6 deletions.
8 changes: 6 additions & 2 deletions src/contracts/elGamalHE.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { SmartContract, assert, method, prop } from 'scrypt-ts'
import { SmartContract, assert, hash256, method, prop } from 'scrypt-ts'
import { Point, SECP256K1 } from 'scrypt-ts-lib'

export type CT = {
Expand All @@ -19,7 +19,11 @@ export class ElGamalHE extends SmartContract {
public add(toAdd: CT) {
// Add encrypted value to the total sum.
this.salarySum = ElGamalHE.addCT(this.salarySum, toAdd)
assert(true)

const outputs =
this.buildStateOutput(this.ctx.utxo.value) +
this.buildChangeOutput()
assert(hash256(outputs) == this.ctx.hashOutputs, 'hashOutputs mismatch')
}

@method()
Expand Down
14 changes: 11 additions & 3 deletions src/contracts/paillierHE.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { SmartContract, assert, method, prop } from 'scrypt-ts'
import { SmartContract, assert, hash256, method, prop } from 'scrypt-ts'

export class PaillierHE extends SmartContract {
// max # of bits for e = ceil(log2(n))
Expand All @@ -21,13 +21,21 @@ export class PaillierHE extends SmartContract {
@method()
public add(toAdd: bigint) {
this.x = PaillierHE.addCT(this.x, toAdd, this.nSquare)
assert(true)

const outputs =
this.buildStateOutput(this.ctx.utxo.value) +
this.buildChangeOutput()
assert(hash256(outputs) == this.ctx.hashOutputs, 'hashOutputs mismatch')
}

@method()
public mul(factor: bigint) {
this.x = PaillierHE.mulCT(this.x, factor, this.nSquare)
assert(true)

const outputs =
this.buildStateOutput(this.ctx.utxo.value) +
this.buildChangeOutput()
assert(hash256(outputs) == this.ctx.hashOutputs, 'hashOutputs mismatch')
}

@method()
Expand Down
4 changes: 3 additions & 1 deletion tests/paillierHE.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ describe('Heavy: Test SmartContract `PaillierHE`', () => {
let currentInstance = instance

for (let i = 0; i < 5; ++i) {
const nextInstance = currentInstance.next()
let nextInstance = currentInstance.next()

// Add encrypted amount (100) to the contract commulative value.
const toAdd = publicKey.encrypt(100n)
Expand All @@ -49,6 +49,8 @@ describe('Heavy: Test SmartContract `PaillierHE`', () => {

currentInstance = nextInstance

nextInstance = currentInstance.next()

// Multiply encrypted amount.
const k = 5n
nextInstance.x = PaillierHE.mulCT(
Expand Down

0 comments on commit f2d1aa6

Please sign in to comment.