Fabcoin Core  0.16.2
P2P Digital Currency
Client.h
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 #pragma once
23 
24 #include <thread>
25 #include <condition_variable>
26 #include <mutex>
27 #include <list>
28 #include <queue>
29 #include <atomic>
30 #include <string>
31 #include <array>
32 #include <libdevcore/Common.h>
33 #include <libdevcore/CommonIO.h>
34 #include <libdevcore/Guards.h>
35 #include <libdevcore/Worker.h>
36 #include <libethcore/SealEngine.h>
37 #include <libethcore/ABI.h>
38 #include <libp2p/Common.h>
39 #include "BlockChain.h"
40 #include "Block.h"
41 #include "CommonNet.h"
42 #include "ClientBase.h"
43 
44 namespace dev
45 {
46 namespace eth
47 {
48 
49 class Client;
50 class DownloadMan;
51 
53 {
54  Active = 0,
57 };
58 
59 struct ClientNote: public LogChannel { static const char* name(); static const int verbosity = 2; };
60 struct ClientChat: public LogChannel { static const char* name(); static const int verbosity = 4; };
61 struct ClientTrace: public LogChannel { static const char* name(); static const int verbosity = 7; };
62 struct ClientDetail: public LogChannel { static const char* name(); static const int verbosity = 14; };
63 
65 {
66  unsigned ticks = 0;
67  std::chrono::system_clock::time_point since = std::chrono::system_clock::now();
68 };
69 
70 std::ostream& operator<<(std::ostream& _out, ActivityReport const& _r);
71 
75 class Client: public ClientBase, protected Worker
76 {
77 public:
78  Client(
79  ChainParams const& _params,
80  int _networkID,
81  p2p::Host* _host,
82  std::shared_ptr<GasPricer> _gpForAdoption,
83  std::string const& _dbPath = std::string(),
84  WithExisting _forceAction = WithExisting::Trust,
86  );
88  virtual ~Client();
89 
91  ChainParams const& chainParams() const { return bc().chainParams(); }
92 
94  void setGasPricer(std::shared_ptr<GasPricer> _gp) { m_gp = _gp; }
95  std::shared_ptr<GasPricer> gasPricer() const { return m_gp; }
96 
98  virtual void flushTransactions() override;
99 
101  ImportResult queueBlock(bytes const& _block, bool _isSafe = false);
102 
103  using Interface::call; // to remove warning about hiding virtual function
105  ExecutionResult call(Address _dest, bytes const& _data = bytes(), u256 _gas = 125000, u256 _value = 0, u256 _gasPrice = 1 * ether, Address const& _from = Address());
106 
108  virtual u256 gasLimitRemaining() const override { return m_postSeal.gasLimitRemaining(); }
110  virtual u256 gasBidPrice() const override { return m_gp->bid(); }
111 
112  // [PRIVATE API - only relevant for base clients, not available in general]
114  dev::eth::Block block(h256 const& _blockHash, PopulationStatistics* o_stats) const;
117  dev::eth::State state(unsigned _txi, h256 const& _block) const;
120  dev::eth::State state(unsigned _txi) const;
121 
123  dev::eth::Block postState() const { ReadGuard l(x_postSeal); return m_postSeal; }
125  BlockChain const& blockChain() const { return bc(); }
127  BlockQueueStatus blockQueueStatus() const { return m_bq.status(); }
129  SyncStatus syncStatus() const override;
131  BlockQueue const& blockQueue() const { return m_bq; }
133  OverlayDB const& stateDB() const { return m_stateDB; }
135  TransactionQueue::Status transactionQueueStatus() const { return m_tq.status(); }
136  TransactionQueue::Limits transactionQueueLimits() const { return m_tq.limits(); }
137 
139  std::tuple<ImportRoute, bool, unsigned> syncQueue(unsigned _max = 1);
140 
141  // Sealing stuff:
142  // Note: "mining"/"miner" is deprecated. Use "sealing"/"sealer".
143 
144  virtual Address author() const override { ReadGuard l(x_preSeal); return m_preSeal.author(); }
145  virtual void setAuthor(Address const& _us) override { WriteGuard l(x_preSeal); m_preSeal.setAuthor(_us); }
146 
148  strings sealers() const { return sealEngine()->sealers(); }
150  std::string sealer() const { return sealEngine()->sealer(); }
152  void setSealer(std::string const& _id) { sealEngine()->setSealer(_id); if (wouldSeal()) startSealing(); }
154  bytes sealOption(std::string const& _name) const { return sealEngine()->option(_name); }
156  bool setSealOption(std::string const& _name, bytes const& _value) { auto ret = sealEngine()->setOption(_name, _value); if (wouldSeal()) startSealing(); return ret; }
157 
159  void startSealing() override;
161  void stopSealing() override { m_wouldSeal = false; }
163  bool wouldSeal() const override { return m_wouldSeal; }
164 
166  bool isSyncing() const override;
168  bool isMajorSyncing() const override;
169 
171  u256 networkId() const override;
173  void setNetworkId(u256 const& _n) override;
174 
176  SealEngineFace* sealEngine() const override { return bc().sealEngine(); }
177 
178  // Debug stuff:
179 
180  DownloadMan const* downloadMan() const;
182  void clearPending();
184  void killChain() { reopenChain(WithExisting::Kill); }
186  void reopenChain(ChainParams const& _p, WithExisting _we = WithExisting::Trust);
187  void reopenChain(WithExisting _we);
189  void retryUnknown() { m_bq.retryAllUnknown(); }
191  ActivityReport activityReport() { ActivityReport ret; std::swap(m_report, ret); return ret; }
193  void setExtraData(bytes const& _extraData) { m_extraData = _extraData; }
195  void rewind(unsigned _n);
197  void rescue() { bc().rescue(m_stateDB); }
198 
200  void executeInMainThread(std::function<void()> const& _function);
201 
202  virtual Block block(h256 const& _block) const override;
203  using ClientBase::block;
204 
205 protected:
208  void init(p2p::Host* _extNet, std::string const& _dbPath, WithExisting _forceAction, u256 _networkId);
209 
211  BlockChain& bc() override { return m_bc; }
212  BlockChain const& bc() const override { return m_bc; }
213 
216  virtual Block preSeal() const override { ReadGuard l(x_preSeal); return m_preSeal; }
217  virtual Block postSeal() const override { ReadGuard l(x_postSeal); return m_postSeal; }
218  virtual void prepareForTransaction() override;
219 
222  void appendFromNewPending(TransactionReceipt const& _receipt, h256Hash& io_changed, h256 _sha3);
223 
226  void appendFromBlock(h256 const& _blockHash, BlockPolarity _polarity, h256Hash& io_changed);
227 
230  void noteChanged(h256Hash const& _filters);
231 
233  virtual bool submitSealed(bytes const& _s);
234 
235 protected:
237  void startedWorking() override;
238 
240  void doWork(bool _doWait);
241  void doWork() override { doWork(true); }
242 
244  void doneWorking() override;
245 
247  void rejigSealing();
248 
250  void onDeadBlocks(h256s const& _blocks, h256Hash& io_changed);
251 
253  virtual void onNewBlocks(h256s const& _blocks, h256Hash& io_changed);
254 
256  void resyncStateFromChain();
257 
259  void resetState();
260 
263  void onChainChanged(ImportRoute const& _ir);
264 
266  void syncBlockQueue();
267 
269  void syncTransactionQueue();
270 
272  void onTransactionQueueReady() { m_syncTransactionQueue = true; m_signalled.notify_all(); }
273 
275  void onBlockQueueReady() { m_syncBlockQueue = true; m_signalled.notify_all(); }
276 
279  void onPostStateChanged();
280 
282  void checkWatchGarbage();
283 
285  void tick();
286 
289  void onBadBlock(Exception& _ex) const;
290 
292  void callQueuedFunctions();
293 
296  std::shared_ptr<GasPricer> m_gp;
297 
306  bool remoteActive() const;
307  bool m_remoteWorking = false;
308  std::atomic<bool> m_needStateReset = { false };
310 
311  std::weak_ptr<EthereumHost> m_host;
312 
316 
317  bool m_wouldSeal = false;
318  bool m_wouldButShouldnot = false;
319 
322  mutable std::chrono::system_clock::time_point m_lastTick = std::chrono::system_clock::now();
324 
325  unsigned m_syncAmount = 50;
326 
328 
330  std::queue<std::function<void()>> m_functionQueue;
331 
332  std::condition_variable m_signalled;
334  std::atomic<bool> m_syncTransactionQueue = {false};
335  std::atomic<bool> m_syncBlockQueue = {false};
336 
338 };
339 
340 }
341 }
void stopSealing() override
Stop sealing.
Definition: Client.h:161
std::shared_ptr< GasPricer > gasPricer() const
Definition: Client.h:95
Adapted from code found on http://stackoverflow.com/questions/180947/base64-decode-snippet-in-c Origi...
Definition: Arith256.cpp:15
BlockHeader m_sealingInfo
The header we&#39;re attempting to seal on (derived from m_postSeal).
Definition: Client.h:305
Block m_working
The state of the client which we&#39;re sealing (i.e. it&#39;ll have all the rewards added), while we&#39;re actually working on it.
Definition: Client.h:304
#define function(a, b, c, d, k, s)
std::chrono::system_clock::time_point m_lastGarbageCollection
When did we last both doing GC on the watches?
Definition: Client.h:320
void swap(dev::eth::Watch &_a, dev::eth::Watch &_b)
Definition: Interface.h:284
Implements the blockchain database.
Definition: BlockChain.h:105
void onTransactionQueueReady()
Magically called when m_tq needs syncing. Be nice and don&#39;t block.
Definition: Client.h:272
Block m_postSeal
The state of the client which we&#39;re sealing (i.e. it&#39;ll have all the rewards added).
Definition: Client.h:302
Encapsulation of a block header.
Definition: BlockHeader.h:95
Handler m_tqReady
Definition: Client.h:313
dev::eth::Block postState() const
Get the object representing the current state of Ethereum.
Definition: Client.h:123
static const char * name()
Definition: Client.cpp:54
std::ostream & operator<<(std::ostream &_out, BlockHeader const &_bi)
Definition: BlockHeader.h:194
The Host class Capabilities should be registered prior to startNetwork, since m_capabilities is not t...
Definition: Host.h:129
h160 Address
An Ethereum address: 20 bytes.
Definition: Common.h:62
void setExtraData(bytes const &_extraData)
Set the extra data that goes into sealed blocks.
Definition: Client.h:193
SharedMutex x_preSeal
Lock on m_preSeal.
Definition: Client.h:299
virtual u256 gasLimitRemaining() const override
Get the remaining gas limit in this block.
Definition: Client.h:108
OverlayDB const & stateDB() const
Get the block queue.
Definition: Client.h:133
std::vector< std::string > strings
Definition: Common.h:147
ChainParams const & chainParams() const
Get information on this chain.
Definition: Client.h:91
Description of the result of executing a transaction.
Definition: Transaction.h:69
Model of an Ethereum state, essentially a facade for the trie.
Definition: State.h:161
BlockQueue m_bq
Maintains a list of incoming blocks not yet on the blockchain (to be imported).
Definition: Client.h:295
ClientWorkState
Definition: Client.h:52
Handler m_bqReady
Definition: Client.h:315
void doWork() override
Called continuously following sleep for m_idleWaitMs.
Definition: Client.h:241
ImportResult
Definition: Common.h:97
WithExisting
Definition: Common.h:310
Mutex x_signalled
Definition: Client.h:333
virtual Address author() const override
Get the block author.
Definition: Client.h:144
Active model of a block within the block chain.
Definition: Block.h:73
std::shared_ptr< GasPricer > m_gp
The gas pricer.
Definition: Client.h:296
void onBlockQueueReady()
Magically called when m_bq needs syncing. Be nice and don&#39;t block.
Definition: Client.h:275
bool wouldSeal() const override
Are we sealing now?
Definition: Client.h:163
Base class for all exceptions.
Definition: Exceptions.h:39
bool setSealOption(std::string const &_name, bytes const &_value)
Set option for the sealer.
Definition: Client.h:156
virtual Block preSeal() const override
Returns the state object for the full block (i.e.
Definition: Client.h:216
BlockChain & bc() override
InterfaceStub methods.
Definition: Client.h:211
virtual ExecutionResult call(Address const &_from, u256 _value, Address _dest, bytes const &_data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, FudgeFactor _ff=FudgeFactor::Strict)=0
Makes the given call. Nothing is recorded into the state.
BlockChain const & blockChain() const
Get the object representing the current canonical blockchain.
Definition: Client.h:125
std::shared_ptr< typename Signal< Args... >::HandlerAux > Handler
Definition: Common.h:181
BlockPolarity
Definition: ExtVMFace.h:81
ActivityReport m_report
Definition: Client.h:327
virtual Block postSeal() const override
Definition: Client.h:217
Block block(BlockNumber _h) const
Definition: ClientBase.cpp:583
std::vector< byte > bytes
Definition: Common.h:75
const char * networkId
Fixed-size raw-byte array container type, with an API optimised for storing hashes.
Definition: FixedHash.h:47
Main API hub for interfacing with Ethereum.
Definition: Client.h:75
A queue of blocks.
Definition: BlockQueue.h:225
boost::multiprecision::number< boost::multiprecision::cpp_int_backend< 256, 256, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void >> u256
Definition: Common.h:125
boost::shared_lock< boost::shared_mutex > ReadGuard
Definition: Guards.h:44
void killChain()
Kills the blockchain. Just for debug use.
Definition: Client.h:184
bytes m_extraData
Definition: Client.h:337
boost::unique_lock< boost::shared_mutex > WriteGuard
Definition: Guards.h:47
BlockChain const & bc() const override
Definition: Client.h:212
std::queue< std::function< void()> > m_functionQueue
Functions waiting to be executed in the main thread.
Definition: Client.h:330
std::chrono::system_clock::time_point m_lastGetWork
Is there an active and valid remote worker?
Definition: Client.h:309
BlockChain m_bc
Maintains block database and owns the seal engine.
Definition: Client.h:294
strings sealers() const
Type of sealers available for this seal engine.
Definition: Client.h:148
SharedMutex x_functionQueue
Definition: Client.h:329
boost::shared_mutex SharedMutex
Definition: Guards.h:39
void retryUnknown()
Retries all blocks with unknown parents.
Definition: Client.h:189
Block m_preSeal
The present state of the client.
Definition: Client.h:300
void rescue()
Rescue the chain.
Definition: Client.h:197
clock::time_point time_point
Definition: bench.h:49
std::weak_ptr< EthereumHost > m_host
Our Ethereum Host. Don&#39;t do anything if we can&#39;t lock.
Definition: Client.h:311
The default logging channels.
Definition: Log.h:130
void setSealer(std::string const &_id)
Change sealer.
Definition: Client.h:152
std::unordered_set< h256 > h256Hash
Definition: FixedHash.h:349
SealEngineFace * sealEngine() const override
Get the seal engine.
Definition: Client.h:176
TransactionQueue::Status transactionQueueStatus() const
Get some information on the transaction queue.
Definition: Client.h:135
std::string sealer() const
Current sealer in use.
Definition: Client.h:150
std::mutex Mutex
Definition: Guards.h:37
TransactionQueue::Limits transactionQueueLimits() const
Definition: Client.h:136
ActivityReport activityReport()
Get a report of activity.
Definition: Client.h:191
SharedMutex x_working
Lock on m_working.
Definition: Client.h:303
OverlayDB m_stateDB
Acts as the central point for the state database, so multiple States can share it.
Definition: Client.h:298
std::vector< h256 > h256s
Definition: FixedHash.h:345
BlockQueue const & blockQueue() const
Get the block queue.
Definition: Client.h:131
virtual u256 gasBidPrice() const override
Get the gas bid price.
Definition: Client.h:110
SharedMutex x_postSeal
Lock on m_postSeal.
Definition: Client.h:301
static const int verbosity
Definition: Client.h:59
std::condition_variable m_signalled
Definition: Client.h:332
virtual void setAuthor(Address const &_us) override
Set the block author address.
Definition: Client.h:145
void setGasPricer(std::shared_ptr< GasPricer > _gp)
Resets the gas pricer to some other object.
Definition: Client.h:94
bytes sealOption(std::string const &_name) const
Review option for the sealer.
Definition: Client.h:154
BlockQueueStatus blockQueueStatus() const
Get some information on the block queue.
Definition: Client.h:127
Handler< h256 const & > m_tqReplaced
Definition: Client.h:314