使用truffle生成circom mimc合约

目录

      • 初始化
      • 添加合约
      • 添加迁移脚本
      • remix测试

circom是一种用于编写零知识证明的算术电路的语言。 circomlib中给出了mimc的电路,但是没有直接给出mimc合约,需要通过 mimc_gencontract.js来编译,下面记录一下编译步骤。

初始化

truffle init
使用ganache,所以truffle-config.js中端口号设为7545

module.exports = {
  networks: {
     development: {
      host: "127.0.0.1",   
      port: 7545,          
      network_id: "*",   
     }
  }
};

添加合约

Hasher.sol

pragma solidity ^0.5.16;

library  IMimc { // Mimc hash函数
  function MiMCpe7(uint256 in_x,uint256 in_k) public pure returns(uint256 out_x);
}

contract Hasher {
    function getHash(uint256 _x, uint256 _k)public pure returns(uint256){
        return IMimc.MiMCpe7(_x, _k);
    }
}

添加迁移脚本

需要用到的包用npm提前安装好
从github上将circomlib下载下来放到truffle项目文件夹的平行目录下

2_deploy_mimc.js

const fs = require("fs");
const path = require('path');

const mimcGenContract = require('circomlib/src/mimc_gencontract.js');
const Artifactor = require('truffle-artifactor');

const SEED = 'mimc';
const NROUNDS = 91;

module.exports = function(deployer) {
  return deployer.then(async () => {
    const contractsDir = path.join(__dirname, '..', 'build/contracts');
    let artifactor = new Artifactor(contractsDir);
    let mimcContractName = 'IMimc';
    await artifactor
      .save({
        contractName: mimcContractName,
        abi: mimcGenContract.abi,
        unlinked_binary: mimcGenContract.createCode(SEED, NROUNDS)
      })
      .then(async () => {
        const MiMC = artifacts.require(mimcContractName);
        const m = await deployer.deploy(MiMC);
		
		//将mimc部署的地址保存到文件中
	    const data = JSON.stringify({
		  IMimcAddress: m.address
	    });
	    const buildDir = path.resolve(__dirname, "../build");
	    if (!fs.existsSync(buildDir)) {
		  fs.mkdirSync(buildDir);
	    }
	    fs.writeFileSync(path.resolve(buildDir, "MIMCAddresses.json"), data);
        });
  });
};

3_deploy_Hasher.js

const fs = require("fs");
const path = require("path");
const MiMC = artifacts.require('IMimc');
const hasher= artifacts.require('Hasher');

module.exports = async deployer => {
  await deployer.link(MiMC, hasher); //将IMimc链接到Hasher上
  const MT = await deployer.deploy(hasher);//部署Hasher合约并传入构造函数参数

  //保存Hasher合约部署地址
  const data = JSON.stringify({
    HasherAddress: MT.address
  });
  const buildDir = path.resolve(__dirname, "../build");
  if (!fs.existsSync(buildDir)) {
    fs.mkdirSync(buildDir);
  }
  fs.writeFileSync(path.resolve(buildDir, "HasherAddress.json"), data);
};

编译truffle compile
部署前先打开ganache,truffle migrate

remix测试

选择Web3 Provider连接ganache
直接用Hasher合约地址部署
使用truffle生成circom mimc合约_第1张图片
调用getHash方法
使用truffle生成circom mimc合约_第2张图片
成功获得返回值

你可能感兴趣的:(以太坊,nodejs,区块链)