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
选择Web3 Provider连接ganache
直接用Hasher合约地址部署
调用getHash方法
成功获得返回值