embark-area-51/lib/modules/ens/index.js

487 lines
17 KiB
JavaScript
Raw Normal View History

const fs = require('../../core/fs.js');
const utils = require('../../utils/utils.js');
const namehash = require('eth-ens-namehash');
2018-07-26 18:50:38 +00:00
const async = require('async');
2018-08-14 14:09:59 +00:00
const embarkJsUtils = require('embarkjs').Utils;
2018-07-25 20:12:17 +00:00
const reverseAddrSuffix = '.addr.reverse';
2018-10-23 18:20:42 +00:00
const ENSFunctions = require('./ENSFunctions');
2018-07-25 20:12:17 +00:00
2018-09-28 14:06:58 +00:00
const MAINNET_ID = '1';
const ROPSTEN_ID = '3';
const RINKEBY_ID = '4';
2018-10-06 00:05:07 +00:00
// Price of ENS registration contract functions
const ENS_GAS_PRICE = 700000;
2018-09-28 14:06:58 +00:00
const ENS_CONTRACTS_CONFIG = {
2018-09-28 14:06:58 +00:00
[MAINNET_ID]: {
2018-10-03 14:29:36 +00:00
"ENSRegistry": {
"address": "0x314159265dd8dbb310642f98f50c066173c1259b",
"silent": true
},
"Resolver": {
"deploy": false
},
"FIFSRegistrar": {
"deploy": false
}
},
2018-09-28 14:06:58 +00:00
[ROPSTEN_ID]: {
2018-10-03 14:29:36 +00:00
"ENSRegistry": {
"address": "0x112234455c3a32fd11230c42e7bccd4a84e02010",
"silent": true
},
"Resolver": {
"deploy": false
},
"FIFSRegistrar": {
"deploy": false
}
},
2018-09-28 14:06:58 +00:00
[RINKEBY_ID]: {
2018-10-03 14:29:36 +00:00
"ENSRegistry": {
"address": "0xe7410170f87102DF0055eB195163A03B7F2Bff4A",
"silent": true
},
"Resolver": {
"deploy": false
},
"FIFSRegistrar": {
"deploy": false
}
}
};
class ENS {
2018-05-30 16:26:49 +00:00
constructor(embark, _options) {
2018-07-25 20:21:00 +00:00
this.env = embark.env;
this.logger = embark.logger;
this.events = embark.events;
2018-05-30 16:26:49 +00:00
this.namesConfig = embark.config.namesystemConfig;
2018-10-05 09:19:10 +00:00
this.enabled = false;
this.registration = this.namesConfig.register || {};
this.embark = embark;
2018-10-03 13:49:07 +00:00
this.ensConfig = require('./ensContractConfigs');
2018-10-03 13:50:37 +00:00
this.configured = false;
2018-10-05 09:19:10 +00:00
this.events.setCommandHandler("ens:resolve", this.ensResolve.bind(this));
2018-08-03 12:50:42 +00:00
if (this.namesConfig === {} ||
this.namesConfig.enabled !== true ||
2018-08-03 19:15:01 +00:00
this.namesConfig.available_providers.indexOf('ens') < 0) {
2018-08-03 12:50:42 +00:00
return;
}
2018-10-05 09:19:10 +00:00
this.enabled = true;
2018-08-06 12:47:27 +00:00
this.doSetENSProvider = this.namesConfig.provider === 'ens';
2018-08-03 12:50:42 +00:00
this.addENSToEmbarkJS();
this.registerEvents();
2018-09-29 20:39:39 +00:00
this.registerConsoleCommands();
}
2018-10-05 09:19:10 +00:00
reset() {
this.configured = false;
}
2018-09-29 20:39:39 +00:00
registerConsoleCommands() {
this.embark.registerConsoleCommand((cmd, _options) => {
let [cmdName, domain] = cmd.split(' ');
return {
match: () => cmdName === 'resolve',
process: (cb) => global.EmbarkJS.Names.resolve(domain, cb)
};
});
this.embark.registerConsoleCommand((cmd, _options) => {
let [cmdName, address] = cmd.split(' ');
return {
match: () => cmdName === 'lookup',
process: (cb) => global.EmbarkJS.Names.lookup(address, cb)
};
});
this.embark.registerConsoleCommand((cmd, _options) => {
let [cmdName, name, address] = cmd.split(' ');
return {
match: () => cmdName === 'registerSubDomain',
process: (cb) => global.EmbarkJS.Names.registerSubDomain(name, address, cb)
};
});
}
registerEvents() {
2018-10-03 13:50:37 +00:00
this.embark.registerActionForEvent("deploy:beforeAll", this.configureContractsAndRegister.bind(this));
2018-10-23 15:01:07 +00:00
this.events.on('blockchain:reseted', this.reset.bind(this));
2018-07-31 14:33:10 +00:00
this.events.setCommandHandler("storage:ens:associate", this.associateStorageToEns.bind(this));
}
2018-09-17 17:58:13 +00:00
setProviderAndRegisterDomains(cb = (() => {})) {
const self = this;
2018-10-03 13:49:07 +00:00
let config = {
env: self.env,
registration: self.registration,
registryAbi: self.ensConfig.ENSRegistry.abiDefinition,
registryAddress: self.ensConfig.ENSRegistry.deployedAddress,
registrarAbi: self.ensConfig.FIFSRegistrar.abiDefinition,
registrarAddress: self.ensConfig.FIFSRegistrar.deployedAddress,
resolverAbi: self.ensConfig.Resolver.abiDefinition,
resolverAddress: self.ensConfig.Resolver.deployedAddress
};
2018-08-06 12:47:27 +00:00
2018-10-03 13:49:07 +00:00
if (self.doSetENSProvider) {
self.addSetProvider(config);
}
2018-10-03 14:29:36 +00:00
self.events.request('blockchain:networkId', (networkId) => {
const isKnownNetwork = Boolean(ENS_CONTRACTS_CONFIG[networkId]);
const shouldRegisterSubdomain = self.registration && self.registration.subdomains && Object.keys(self.registration.subdomains).length;
if (isKnownNetwork || !shouldRegisterSubdomain) {
return cb();
}
2018-10-03 15:09:12 +00:00
2018-10-03 14:29:36 +00:00
self.registerConfigDomains(config, cb);
});
}
associateStorageToEns(options, cb) {
2018-07-31 14:33:10 +00:00
const self = this;
// Code inspired by https://github.com/monkybrain/ipfs-to-ens
2018-07-30 15:57:00 +00:00
const {name, storageHash} = options;
2018-07-31 14:33:10 +00:00
if (!utils.isValidEthDomain(name)) {
return cb('Invalid domain name ' + name);
}
2018-07-30 15:57:00 +00:00
let hashedName = namehash.hash(name);
let contentHash;
try {
2018-07-31 14:33:10 +00:00
contentHash = utils.hashTo32ByteHexString(storageHash);
} catch (e) {
return cb('Invalid IPFS hash');
}
// Set content
async.waterfall([
function getRegistryABI(next) {
self.events.request('contracts:contract', "ENSRegistry", (contract) => {
next(null, contract);
});
},
function createRegistryContract(contract, next) {
self.events.request("blockchain:contract:create",
{abi: contract.abiDefinition, address: contract.deployedAddress},
(resolver) => {
next(null, resolver);
2018-07-26 18:50:38 +00:00
});
},
function getResolverForName(registry, next) {
2018-07-30 15:57:00 +00:00
registry.methods.resolver(hashedName).call((err, resolverAddress) => {
if (err) {
return cb(err);
}
if (resolverAddress === '0x0000000000000000000000000000000000000000') {
return cb('Name not yet registered');
}
next(null, resolverAddress);
});
},
function getResolverABI(resolverAddress, next) {
self.events.request('contracts:contract', "Resolver", (contract) => {
next(null, resolverAddress, contract);
});
},
function createResolverContract(resolverAddress, contract, next) {
self.events.request("blockchain:contract:create",
{abi: contract.abiDefinition, address: resolverAddress},
(resolver) => {
next(null, resolver);
});
},
function getDefaultAccount(resolver, next) {
self.events.request("blockchain:defaultAccount:get", (defaultAccount) => {
next(null, resolver, defaultAccount);
});
},
function setContent(resolver, defaultAccount, next) {
2018-07-30 17:38:12 +00:00
resolver.methods.setContent(hashedName, contentHash).send({from: defaultAccount}).then((transaction) => {
2018-07-30 15:57:00 +00:00
if (transaction.status !== "0x1" && transaction.status !== "0x01" && transaction.status !== true) {
2018-07-30 19:49:58 +00:00
return next('Association failed. Status: ' + transaction.status);
2018-07-30 15:57:00 +00:00
}
next();
2018-07-30 17:38:12 +00:00
}).catch(next);
}
], cb);
}
registerConfigDomains(config, cb) {
const self = this;
2018-08-14 14:09:59 +00:00
const secureSend = embarkJsUtils.secureSend;
2018-10-05 14:49:46 +00:00
self.events.request("blockchain:defaultAccount:get", (defaultAccount) => {
async.each(Object.keys(self.registration.subdomains), (subDomainName, eachCb) => {
const address = self.registration.subdomains[subDomainName];
const reverseNode = utils.soliditySha3(address.toLowerCase().substr(2) + reverseAddrSuffix);
2018-10-23 18:20:42 +00:00
ENSFunctions.registerSubDomain(self.ensContract, self.registrarContract, self.resolverContract, defaultAccount,
subDomainName, self.registration.rootDomain, reverseNode, address, self.logger, secureSend, eachCb);
2018-10-05 14:49:46 +00:00
}, cb);
});
}
2018-10-23 18:20:42 +00:00
createResolverContract(config, callback) {
this.events.request("blockchain:contract:create", {
abi: config.resolverAbi,
address: config.resolverAddress
}, (resolver) => {
callback(null, resolver);
});
}
registerAPI() {
let self = this;
const createInternalResolverContract = function(resolverAddress, callback) {
self.createResolverContract({resolverAbi: self.ensConfig.Resolver.abiDefinition, resolverAddress}, callback);
};
self.embark.registerAPICall(
'get',
'/embark-api/ens/resolve',
(req, res) => {
async.waterfall([
function(callback) {
ENSFunctions.resolveName(req.query.name, self.ensContract, createInternalResolverContract.bind(self), callback);
}
], function(error, address) {
if (error) {
return res.send({error: error.message});
}
res.send({address});
});
}
);
self.embark.registerAPICall(
'get',
'/embark-api/ens/lookup',
(req, res) => {
async.waterfall([
function(callback) {
ENSFunctions.lookupAddress(req.query.address, self.ensContract, utils, createInternalResolverContract.bind(self), callback);
}
], function(error, name) {
if (error) {
return res.send({error: error || error.message});
}
res.send({name});
});
}
);
self.embark.registerAPICall(
'post',
'/embark-api/ens/register',
(req, res) => {
self.events.request("blockchain:defaultAccount:get", (defaultAccount) => {
const secureSend = embarkJsUtils.secureSend;
const {subdomain, address} = req.body;
const reverseNode = utils.soliditySha3(address.toLowerCase().substr(2) + reverseAddrSuffix);
ENSFunctions.registerSubDomain(self.ensContract, self.registrarContract, self.resolverContract, defaultAccount,
subdomain, self.registration.rootDomain, reverseNode, address, self.logger, secureSend, (error) => {
if (error) {
return res.send({error: error || error.message});
}
res.send({name: `${req.body.subdomain}.${self.registration.rootDomain}`, address: req.body.address});
});
});
}
);
}
addENSToEmbarkJS() {
const self = this;
// get namehash, import it into file
self.events.request("version:get:eth-ens-namehash", function(EnsNamehashVersion) {
let currentEnsNamehashVersion = require('../../../package.json').dependencies["eth-ens-namehash"];
if (EnsNamehashVersion !== currentEnsNamehashVersion) {
self.events.request("version:getPackageLocation", "eth-ens-namehash", EnsNamehashVersion, function(err, location) {
self.embark.registerImportFile("eth-ens-namehash", fs.dappPath(location));
});
}
});
2018-10-23 18:20:42 +00:00
let code = fs.readFileSync(utils.joinPath(__dirname, 'ENSFunctions.js')).toString();
code += "\n" + fs.readFileSync(utils.joinPath(__dirname, 'embarkjs.js')).toString();
code += "\nEmbarkJS.Names.registerProvider('ens', __embarkENS);";
this.embark.addCodeToEmbarkJS(code);
}
2018-10-03 13:50:37 +00:00
configureContractsAndRegister(cb) {
2018-10-23 15:59:43 +00:00
const NO_REGISTRATION = 'NO_REGISTRATION';
2018-10-03 13:49:07 +00:00
const self = this;
2018-10-03 13:50:37 +00:00
if (self.configured) {
return cb();
}
2018-10-03 14:29:36 +00:00
self.events.request('blockchain:networkId', (networkId) => {
if (ENS_CONTRACTS_CONFIG[networkId]) {
self.ensConfig = utils.recursiveMerge(self.ensConfig, ENS_CONTRACTS_CONFIG[networkId]);
}
2018-10-02 18:56:07 +00:00
2018-10-03 14:29:36 +00:00
async.waterfall([
function registry(next) {
self.events.request('deploy:contract', self.ensConfig.ENSRegistry, (err, _receipt) => {
return next(err);
});
2018-10-02 18:56:07 +00:00
},
2018-10-03 14:29:36 +00:00
function resolver(next) {
self.ensConfig.Resolver.args = [self.ensConfig.ENSRegistry.deployedAddress];
self.events.request('deploy:contract', self.ensConfig.Resolver, (err, _receipt) => {
return next(err);
});
2018-10-02 18:56:07 +00:00
},
2018-10-03 14:29:36 +00:00
function registrar(next) {
if (!self.registration || !self.registration.rootDomain) {
2018-10-23 15:59:43 +00:00
return next(NO_REGISTRATION);
2018-10-03 14:29:36 +00:00
}
const registryAddress = self.ensConfig.ENSRegistry.deployedAddress;
const rootNode = namehash.hash(self.registration.rootDomain);
const contract = self.ensConfig.FIFSRegistrar;
contract.args = [registryAddress, rootNode];
2018-10-05 14:49:46 +00:00
2018-10-03 14:29:36 +00:00
self.events.request('deploy:contract', contract, (err, _receipt) => {
return next(err);
});
2018-10-05 14:49:46 +00:00
},
function registerRoot(next) {
let config = {
registryAbi: self.ensConfig.ENSRegistry.abiDefinition,
registryAddress: self.ensConfig.ENSRegistry.deployedAddress,
registrarAbi: self.ensConfig.FIFSRegistrar.abiDefinition,
registrarAddress: self.ensConfig.FIFSRegistrar.deployedAddress,
resolverAbi: self.ensConfig.Resolver.abiDefinition,
resolverAddress: self.ensConfig.Resolver.deployedAddress
};
async.parallel([
function createRegistryContract(paraCb) {
self.events.request("blockchain:contract:create",
{abi: config.registryAbi, address: config.registryAddress},
(registry) => {
paraCb(null, registry);
});
},
function createRegistrarContract(paraCb) {
self.events.request("blockchain:contract:create",
{abi: config.registrarAbi, address: config.registrarAddress},
(registrar) => {
paraCb(null, registrar);
});
},
function createResolverContract(paraCb) {
self.events.request("blockchain:contract:create",
{abi: config.resolverAbi, address: config.resolverAddress},
(resolver) => {
paraCb(null, resolver);
});
},
function getWeb3(paraCb) {
self.events.request("blockchain:get",
(web3) => {
paraCb(null, web3);
});
2018-10-05 14:49:46 +00:00
}
], (err, result) => {
self.ensContract = result[0];
self.registrarContract = result[1];
self.resolverContract = result[2];
const web3 = result[3];
2018-10-05 14:49:46 +00:00
const rootNode = namehash.hash(self.registration.rootDomain);
var reverseNode = web3.utils.soliditySha3(web3.eth.defaultAccount.toLowerCase().substr(2) + reverseAddrSuffix);
2018-10-06 00:05:07 +00:00
self.ensContract.methods.setOwner(rootNode, web3.eth.defaultAccount).send({from: web3.eth.defaultAccount, gas: ENS_GAS_PRICE}).then(() => {
return self.ensContract.methods.setResolver(rootNode, config.resolverAddress).send({from: web3.eth.defaultAccount, gas: ENS_GAS_PRICE});
2018-10-05 14:49:46 +00:00
}).then(() => {
2018-10-06 00:05:07 +00:00
return self.ensContract.methods.setResolver(reverseNode, config.resolverAddress).send({from: web3.eth.defaultAccount, gas: ENS_GAS_PRICE});
2018-10-05 14:49:46 +00:00
}).then(() => {
2018-10-06 00:05:07 +00:00
return self.resolverContract.methods.setAddr(rootNode, web3.eth.defaultAccount).send({from: web3.eth.defaultAccount, gas: ENS_GAS_PRICE});
2018-10-05 14:49:46 +00:00
}).then(() => {
2018-10-06 00:05:07 +00:00
return self.resolverContract.methods.setName(reverseNode, self.registration.rootDomain).send({from: web3.eth.defaultAccount, gas: ENS_GAS_PRICE});
2018-10-05 14:49:46 +00:00
}).then((_result) => {
next();
})
.catch(err => {
self.logger.error('Error while registering the root domain');
if (err.message.indexOf('Transaction has been reverted by the EVM') > -1) {
return next(__('Registration was rejected. Did you change the deployment account? If so, delete chains.json'));
}
2018-10-05 14:49:46 +00:00
next(err);
});
});
2018-10-03 14:29:36 +00:00
}
], (err) => {
self.configured = true;
2018-10-23 15:59:43 +00:00
if (err && err !== NO_REGISTRATION) {
2018-10-03 14:29:36 +00:00
self.logger.error('Error while deploying ENS contracts');
self.logger.error(err.message || err);
2018-10-05 14:49:46 +00:00
return cb(err);
2018-10-03 14:29:36 +00:00
}
2018-10-23 18:20:42 +00:00
self.registerAPI();
2018-10-03 14:29:36 +00:00
self.setProviderAndRegisterDomains(cb);
});
2018-10-03 13:49:07 +00:00
});
}
addSetProvider(config) {
let code = "\nEmbarkJS.Names.setProvider('ens'," + JSON.stringify(config) + ");";
let shouldInit = (namesConfig) => {
return (namesConfig.provider === 'ens' && namesConfig.enabled === true);
};
this.embark.addProviderInit('names', code, shouldInit);
2018-08-28 13:43:52 +00:00
this.embark.addConsoleProviderInit('names', code, shouldInit);
}
2018-10-05 09:19:10 +00:00
ensResolve(name, cb) {
const self = this;
if (!self.enabled) {
return cb('ENS not enabled');
}
if(!self.configured) {
return cb('ENS not configured');
}
const hashedName = namehash.hash(name);
async.waterfall([
function getResolverAddress(next) {
self.ensContract.methods.resolver(hashedName).call((err, resolverAddress) => {
if (err) {
return next(err);
}
if(resolverAddress === '0x0000000000000000000000000000000000000000') {
return next('Name not yet registered');
2018-10-05 09:19:10 +00:00
}
next(null, resolverAddress);
2018-10-05 09:19:10 +00:00
});
},
function createResolverContract(resolverAddress, next) {
self.events.request("blockchain:contract:create",
{abi: self.ensConfig.Resolver.abiDefinition, address: resolverAddress},
(resolver) => {
next(null, resolver);
});
},
function resolveName(resolverContract, next) {
resolverContract.methods.addr(hashedName).call(next);
}
], (err, result) => {
if (err) {
self.logger.error(__('Failed to resolve the ENS name: %s', name));
return cb(err);
}
cb(null, result);
});
2018-10-05 09:19:10 +00:00
}
}
module.exports = ENS;