Fabcoin Core  0.16.2
P2P Digital Currency
ChainParams.cpp
Go to the documentation of this file.
1 /*
2  This file is part of cpp-ethereum.
3 
4  cpp-ethereum is free software: you can redistribute it and/or modify
5  it under the terms of the GNU General Public License as published by
6  the Free Software Foundation, either version 3 of the License, or
7  (at your option) any later version.
8 
9  cpp-ethereum is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  GNU General Public License for more details.
13 
14  You should have received a copy of the GNU General Public License
15  along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
16 */
22 #include "ChainParams.h"
24 #include <libdevcore/Log.h>
25 #include <libdevcore/TrieDB.h>
26 #include <libethcore/SealEngine.h>
27 #include <libethcore/BlockHeader.h>
28 #include <libethcore/Precompiled.h>
29 #include "GenesisInfo.h"
30 #include "State.h"
31 #include "Account.h"
32 using namespace std;
33 using namespace dev;
34 using namespace eth;
35 namespace js = json_spirit;
36 
37 
38 ChainParams::ChainParams()
39 {
40  for (unsigned i = 1; i <= 4; ++i)
41  genesisState[Address(i)] = Account(0, 1);
42  // Setup default precompiled contracts as equal to genesis of Frontier.
43  precompiled.insert(make_pair(Address(1), PrecompiledContract(3000, 0, PrecompiledRegistrar::executor("ecrecover"))));
44  precompiled.insert(make_pair(Address(2), PrecompiledContract(60, 12, PrecompiledRegistrar::executor("sha256"))));
45  precompiled.insert(make_pair(Address(3), PrecompiledContract(600, 120, PrecompiledRegistrar::executor("ripemd160"))));
46  precompiled.insert(make_pair(Address(4), PrecompiledContract(15, 3, PrecompiledRegistrar::executor("identity"))));
47 }
48 
49 ChainParams::ChainParams(string const& _json, h256 const& _stateRoot)
50 {
51  *this = loadConfig(_json, _stateRoot);
52 }
53 
54 ChainParams ChainParams::loadConfig(string const& _json, h256 const& _stateRoot) const
55 {
56  ChainParams cp(*this);
57  js::mValue val;
58  json_spirit::read_string(_json, val);
59  js::mObject obj = val.get_obj();
60 
61  cp.sealEngineName = obj["sealEngine"].get_str();
62  // params
63  js::mObject params = obj["params"].get_obj();
64  cp.accountStartNonce = u256(fromBigEndian<u256>(fromHex(params["accountStartNonce"].get_str())));
65  cp.maximumExtraDataSize = u256(fromBigEndian<u256>(fromHex(params["maximumExtraDataSize"].get_str())));
66  cp.tieBreakingGas = params.count("tieBreakingGas") ? params["tieBreakingGas"].get_bool() : true;
67  cp.blockReward = u256(fromBigEndian<u256>(fromHex(params["blockReward"].get_str())));
68  for (auto i: params)
69  if (i.first != "accountStartNonce" && i.first != "maximumExtraDataSize" && i.first != "blockReward" && i.first != "tieBreakingGas")
70  cp.otherParams[i.first] = i.second.get_str();
71  // genesis
72  string genesisStr = json_spirit::write_string(obj["genesis"], false);
73  cp = cp.loadGenesis(genesisStr, _stateRoot);
74  // genesis state
75  string genesisStateStr = json_spirit::write_string(obj["accounts"], false);
76  cp = cp.loadGenesisState(genesisStateStr, _stateRoot);
77  return cp;
78 }
79 
80 ChainParams ChainParams::loadGenesisState(string const& _json, h256 const& _stateRoot) const
81 {
82  ChainParams cp(*this);
83  cp.genesisState = jsonToAccountMap(_json, cp.accountStartNonce, nullptr, &cp.precompiled);
84  cp.stateRoot = _stateRoot ? _stateRoot : cp.calculateStateRoot(true);
85  return cp;
86 }
87 
88 ChainParams ChainParams::loadGenesis(string const& _json, h256 const& _stateRoot) const
89 {
90  ChainParams cp(*this);
91 
92  js::mValue val;
93  json_spirit::read_string(_json, val);
94  js::mObject genesis = val.get_obj();
95 
96  cp.parentHash = h256(genesis["parentHash"].get_str());
97  cp.author = genesis.count("coinbase") ? h160(genesis["coinbase"].get_str()) : h160(genesis["author"].get_str());
98  cp.difficulty = genesis.count("difficulty") ? u256(fromBigEndian<u256>(fromHex(genesis["difficulty"].get_str()))) : 0;
99  cp.gasLimit = u256(fromBigEndian<u256>(fromHex(genesis["gasLimit"].get_str())));
100  cp.gasUsed = genesis.count("gasUsed") ? u256(fromBigEndian<u256>(fromHex(genesis["gasUsed"].get_str()))) : 0;
101  cp.timestamp = u256(fromBigEndian<u256>(fromHex(genesis["timestamp"].get_str())));
102  cp.extraData = bytes(fromHex(genesis["extraData"].get_str()));
103 
104  // magic code for handling ethash stuff:
105  if ((genesis.count("mixhash") || genesis.count("mixHash")) && genesis.count("nonce"))
106  {
107  h256 mixHash(genesis[genesis.count("mixhash") ? "mixhash" : "mixHash"].get_str());
108  h64 nonce(genesis["nonce"].get_str());
109  cp.sealFields = 2;
110  cp.sealRLP = rlp(mixHash) + rlp(nonce);
111  }
112  cp.stateRoot = _stateRoot ? _stateRoot : cp.calculateStateRoot();
113  return cp;
114 }
115 
116 SealEngineFace* ChainParams::createSealEngine()
117 {
118  SealEngineFace* ret = SealEngineRegistrar::create(sealEngineName);
119  assert(ret && "Seal engine not found");
120  if (!ret)
121  return nullptr;
122  ret->setChainParams(*this);
123  if (sealRLP.empty())
124  {
125  sealFields = ret->sealFields();
126  sealRLP = ret->sealRLP();
127  }
128  return ret;
129 }
130 
131 void ChainParams::populateFromGenesis(bytes const& _genesisRLP, AccountMap const& _state)
132 {
133  BlockHeader bi(_genesisRLP, RLP(&_genesisRLP)[0].isList() ? BlockData : HeaderData);
134  parentHash = bi.parentHash();
135  author = bi.author();
136  difficulty = bi.difficulty();
137  gasLimit = bi.gasLimit();
138  gasUsed = bi.gasUsed();
139  timestamp = bi.timestamp();
140  extraData = bi.extraData();
141  genesisState = _state;
142  RLP r(_genesisRLP);
143  sealFields = r[0].itemCount() - BlockHeader::BasicFields;
144  sealRLP.clear();
145  for (unsigned i = BlockHeader::BasicFields; i < r[0].itemCount(); ++i)
146  sealRLP += r[0][i].data();
147 
148  calculateStateRoot(true);
149 
150  auto b = genesisBlock();
151  if (b != _genesisRLP)
152  {
153  cdebug << "Block passed:" << bi.hash() << bi.hash(WithoutSeal);
154  cdebug << "Genesis now:" << BlockHeader::headerHashFromBlock(b);
155  cdebug << RLP(b);
156  cdebug << RLP(_genesisRLP);
157  throw 0;
158  }
159 }
160 
161 h256 ChainParams::calculateStateRoot(bool _force) const
162 {
163  MemoryDB db;
165  state.init();
166  if (!stateRoot || _force)
167  {
168  // TODO: use hash256
169  //stateRoot = hash256(toBytesMap(gs));
171  stateRoot = state.root();
172  }
173  return stateRoot;
174 }
175 
176 bytes ChainParams::genesisBlock() const
177 {
178  RLPStream block(3);
179 
180  calculateStateRoot();
181 
182  block.appendList(BlockHeader::BasicFields + sealFields)
183  << parentHash
184  << EmptyListSHA3 // sha3(uncles)
185  << author
186  << stateRoot
187  << EmptyTrie // transactions
188  << EmptyTrie // receipts
189  << LogBloom()
190  << difficulty
191  << 0 // number
192  << gasLimit
193  << gasUsed // gasUsed
194  << timestamp
195  << extraData;
196  block.appendRaw(sealRLP, sealFields);
197  block.appendRaw(RLPEmptyList);
198  block.appendRaw(RLPEmptyList);
199  return block.out();
200 }
const Object & get_obj() const
Adapted from code found on http://stackoverflow.com/questions/180947/base64-decode-snippet-in-c Origi...
Definition: Arith256.cpp:15
h256 calculateStateRoot(bool _force=false) const
h256 EmptyListSHA3
Definition: SHA3.cpp:36
std::unordered_map< Address, Account > AccountMap
Definition: Account.h:239
bytes rlp(_T _t)
Export a single item in RLP format, returning a byte array.
Definition: RLP.h:467
h256 hash(IncludeSeal _i=WithSeal) const
Definition: BlockHeader.cpp:64
ChainParams loadGenesisState(std::string const &_json, h256 const &_stateRoot=h256()) const
Definition: ChainParams.cpp:80
size_t itemCount() const
Definition: RLP.h:118
Encapsulation of a block header.
Definition: BlockHeader.h:95
Models the state of a single Ethereum account.
Definition: Account.h:67
std::unordered_map< std::string, std::string > otherParams
Additional parameters.
bytes const & out() const
Read the byte stream.
Definition: RLP.h:433
std::unordered_map< Address, Account > const & genesisState()
h160 Address
An Ethereum address: 20 bytes.
Definition: Common.h:62
h256 const EmptyTrie
Definition: OverlayDB.cpp:33
std::hash for asio::adress
Definition: Common.h:323
assert(len-trim+(2 *lenIndices)<=WIDTH)
Different view on a GenericTrieDB that can use different key types.
Definition: TrieDB.h:320
h256 const & parentHash() const
Definition: BlockHeader.h:154
#define cdebug
Definition: Log.h:302
bytes fromHex(std::string const &_s, WhenError _throw=WhenError::DontThrow)
Definition: CommonData.cpp:99
bool read_string(const String_type &s, Value_type &value)
ChainParams loadGenesis(std::string const &_json, h256 const &_stateRoot=h256()) const
Definition: ChainParams.cpp:88
bytes const & extraData() const
Definition: BlockHeader.h:164
h256 stateRoot
Only pre-populate if known equivalent to genesisState&#39;s root. If they&#39;re different Bad Things Will Ha...
Definition: ChainParams.h:55
std::unordered_map< Address, PrecompiledContract > precompiled
Precompiled contracts as specified in the chain params.
std::vector< byte > bytes
Definition: Common.h:75
RLPStream & appendList(size_t _items)
Appends a list.
Definition: RLP.cpp:276
FixedHash< 32 > h256
Definition: FixedHash.h:340
boost::multiprecision::number< boost::multiprecision::cpp_int_backend< 256, 256, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void >> u256
Definition: Common.h:125
AccountMap genesisState
Definition: ChainParams.h:56
#define b(i, j)
u256 const & timestamp() const
Definition: BlockHeader.h:156
mConfig::Object_type mObject
h256 parentHash
Genesis params.
Definition: ChainParams.h:48
Address const & author() const
Definition: BlockHeader.h:157
Value_type::String_type write_string(const Value_type &value, bool pretty)
AccountMap jsonToAccountMap(std::string const &_json, u256 const &_defaultNonce=0, AccountMaskMap *o_mask=nullptr, PrecompiledContractMap *o_precompiled=nullptr)
Definition: Account.cpp:50
std::string sealEngineName
The chain sealer name: e.g. Ethash, NoProof, BasicAuthority.
u256 const & gasLimit() const
Definition: BlockHeader.h:163
void setChainParams(ChainOperationParams const &_params)
Definition: SealEngine.h:76
FixedHash< 20 > h160
Definition: FixedHash.h:341
h2048 LogBloom
The log bloom&#39;s size (2048-bit).
Definition: Common.h:58
virtual bytes sealRLP() const
Definition: SealEngine.h:53
AddressHash commit(AccountMap const &_cache, SecureTrieDB< Address, DB > &_state)
Definition: State.h:345
u256 blockReward
General chain params.
virtual unsigned sealFields() const
Definition: SealEngine.h:52
u256 const & gasUsed() const
Definition: BlockHeader.h:161
std::string get_str(std::string::const_iterator begin, std::string::const_iterator end)
Class for writing to an RLP bytestream.
Definition: RLP.h:383
RLPStream & appendRaw(bytesConstRef _rlp, size_t _itemCount=1)
Appends raw (pre-serialised) RLP data. Use with caution.
Definition: RLP.cpp:230
u256 const & difficulty() const
Definition: BlockHeader.h:166
uint8_t const * data
Definition: sha3.h:19
Class for interpreting Recursive Linear-Prefix Data.
Definition: RLP.h:64
bytes RLPEmptyList
The empty list in RLP format.
Definition: RLP.cpp:27