2015-08-03 12:03:55 +00:00
|
|
|
var fs = require('fs');
|
|
|
|
var web3 = require('web3');
|
2015-08-03 12:44:16 +00:00
|
|
|
var sha3_256 = require('js-sha3').sha3_256;
|
2015-08-03 12:03:55 +00:00
|
|
|
|
2015-10-09 14:18:18 +00:00
|
|
|
ChainManager = function(_web3) {
|
2015-08-05 12:35:39 +00:00
|
|
|
this.chainManagerConfig = {};
|
2015-08-03 12:44:16 +00:00
|
|
|
this.currentChain = {};
|
2015-08-04 01:54:39 +00:00
|
|
|
this.file = "";
|
2015-10-09 14:18:18 +00:00
|
|
|
this.web3 = _web3;
|
2015-08-03 12:44:16 +00:00
|
|
|
}
|
2015-08-03 12:03:55 +00:00
|
|
|
|
|
|
|
ChainManager.prototype.loadConfigFile = function(filename) {
|
2015-08-05 12:35:39 +00:00
|
|
|
this.file = filename;
|
2015-08-03 12:03:55 +00:00
|
|
|
try {
|
|
|
|
var obj = JSON.parse(fs.readFileSync(filename));
|
|
|
|
this.chainManagerConfig = obj;
|
|
|
|
} catch (e) {
|
2015-08-05 12:35:39 +00:00
|
|
|
console.warn("error reading " + filename + "; defaulting to empty set");
|
2015-08-03 12:03:55 +00:00
|
|
|
}
|
|
|
|
return this;
|
|
|
|
};
|
|
|
|
|
|
|
|
ChainManager.prototype.loadConfig = function(config) {
|
|
|
|
this.chainManagerConfig = config;
|
|
|
|
return this;
|
|
|
|
};
|
|
|
|
|
2015-08-04 01:54:39 +00:00
|
|
|
ChainManager.prototype.init = function(env, config) {
|
2015-10-09 14:18:18 +00:00
|
|
|
if (this.web3 === undefined) {
|
|
|
|
web3.setProvider(new web3.providers.HttpProvider("http://" + config.rpcHost + ":" + config.rpcPort));
|
|
|
|
}
|
2015-08-03 12:03:55 +00:00
|
|
|
|
2015-10-09 14:18:18 +00:00
|
|
|
var block = this.web3.eth.getBlock(0);
|
2015-09-25 07:44:37 +00:00
|
|
|
if(!block){
|
|
|
|
throw new Error("Cannot get the genesis block, is embark blockchain running ?");
|
|
|
|
}
|
2015-09-25 07:55:35 +00:00
|
|
|
var chainId = block.hash;
|
2015-08-03 12:03:55 +00:00
|
|
|
|
|
|
|
if (this.chainManagerConfig[chainId] === undefined) {
|
2015-08-03 12:44:16 +00:00
|
|
|
this.chainManagerConfig[chainId] = {contracts: {}};
|
|
|
|
}
|
|
|
|
|
|
|
|
this.currentChain = this.chainManagerConfig[chainId];
|
2015-10-09 14:18:18 +00:00
|
|
|
//this.web3 = web3;
|
2015-08-03 12:44:16 +00:00
|
|
|
}
|
|
|
|
|
2015-08-06 02:19:21 +00:00
|
|
|
ChainManager.prototype.addContract = function(contractName, code, args, address) {
|
|
|
|
this.currentChain.contracts[sha3_256(code + contractName + args.join(','))] = {
|
2015-08-03 12:44:16 +00:00
|
|
|
name: contractName,
|
|
|
|
address: address
|
2015-08-03 12:03:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-08-06 02:19:21 +00:00
|
|
|
ChainManager.prototype.getContract = function(contractName, code, args) {
|
|
|
|
return this.currentChain.contracts[sha3_256(code + contractName + args.join(','))];
|
2015-08-04 01:01:15 +00:00
|
|
|
}
|
|
|
|
|
2015-08-04 01:54:39 +00:00
|
|
|
ChainManager.prototype.save = function() {
|
|
|
|
fs.writeFileSync(this.file, JSON.stringify(this.chainManagerConfig));
|
|
|
|
}
|
|
|
|
|
2015-08-03 12:03:55 +00:00
|
|
|
module.exports = ChainManager;
|