forked from gochain/gochain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backend.go
281 lines (251 loc) · 9.34 KB
/
backend.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
// Copyright 2016 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
// Package les implements the Light GoChain Subprotocol.
package les
import (
"context"
"fmt"
"sync"
"time"
"github.com/gochain-io/gochain/accounts"
"github.com/gochain-io/gochain/common"
"github.com/gochain-io/gochain/common/hexutil"
"github.com/gochain-io/gochain/consensus"
"github.com/gochain-io/gochain/core"
"github.com/gochain-io/gochain/core/bloombits"
"github.com/gochain-io/gochain/core/types"
"github.com/gochain-io/gochain/eth"
"github.com/gochain-io/gochain/eth/downloader"
"github.com/gochain-io/gochain/eth/filters"
"github.com/gochain-io/gochain/eth/gasprice"
"github.com/gochain-io/gochain/ethdb"
"github.com/gochain-io/gochain/event"
"github.com/gochain-io/gochain/internal/ethapi"
"github.com/gochain-io/gochain/light"
"github.com/gochain-io/gochain/log"
"github.com/gochain-io/gochain/node"
"github.com/gochain-io/gochain/p2p"
"github.com/gochain-io/gochain/p2p/discv5"
"github.com/gochain-io/gochain/params"
rpc "github.com/gochain-io/gochain/rpc"
)
type LightGoChain struct {
config *eth.Config
odr *LesOdr
relay *LesTxRelay
chainConfig *params.ChainConfig
// Channel for shutting down the service
shutdownChan chan bool
// Handlers
peers *peerSet
txPool *light.TxPool
blockchain *light.LightChain
protocolManager *ProtocolManager
serverPool *serverPool
reqDist *requestDistributor
retriever *retrieveManager
// DB interfaces
chainDb ethdb.Database // Block chain database
bloomRequests chan chan *bloombits.Retrieval // Channel receiving bloom data retrieval requests
bloomIndexer, chtIndexer, bloomTrieIndexer *core.ChainIndexer
ApiBackend *LesApiBackend
eventMux *event.TypeMux
engine consensus.Engine
accountManager *accounts.Manager
networkId uint64
netRPCService *ethapi.PublicNetAPI
wg sync.WaitGroup
}
func New(ctx context.Context, sctx *node.ServiceContext, config *eth.Config) (*LightGoChain, error) {
chainDb, err := eth.CreateDB(sctx, config, "lightchaindata")
if err != nil {
return nil, err
}
if config.Genesis == nil {
config.Genesis = core.DefaultGenesisBlock()
}
chainConfig, genesisHash, genesisErr := core.SetupGenesisBlock(chainDb, config.Genesis)
if _, isCompat := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !isCompat {
return nil, genesisErr
}
if config.Genesis == nil {
if genesisHash == params.MainnetGenesisHash {
config.Genesis = core.DefaultGenesisBlock()
}
}
log.Info("Initialised chain configuration", "config", chainConfig)
peers := newPeerSet()
quitSync := make(chan struct{})
leth := &LightGoChain{
config: config,
chainConfig: chainConfig,
chainDb: chainDb,
eventMux: sctx.EventMux,
peers: peers,
reqDist: newRequestDistributor(peers, quitSync),
accountManager: sctx.AccountManager,
engine: eth.CreateConsensusEngine(sctx, &config.Ethash, chainConfig, chainDb),
shutdownChan: make(chan bool),
networkId: config.NetworkId,
bloomRequests: make(chan chan *bloombits.Retrieval),
bloomIndexer: eth.NewBloomIndexer(chainDb, light.BloomTrieFrequency),
chtIndexer: light.NewChtIndexer(chainDb, true),
bloomTrieIndexer: light.NewBloomTrieIndexer(chainDb, true),
}
leth.relay = NewLesTxRelay(peers, leth.reqDist)
leth.serverPool = newServerPool(chainDb, quitSync, &leth.wg)
leth.retriever = newRetrieveManager(peers, leth.reqDist, leth.serverPool)
leth.odr = NewLesOdr(chainDb, leth.chtIndexer, leth.bloomTrieIndexer, leth.bloomIndexer, leth.retriever)
if leth.blockchain, err = light.NewLightChain(leth.odr, leth.chainConfig, leth.engine); err != nil {
return nil, err
}
leth.bloomIndexer.Start(leth.blockchain)
// Rewind the chain in case of an incompatible config upgrade.
if compat, ok := genesisErr.(*params.ConfigCompatError); ok {
log.Warn("Rewinding chain to upgrade configuration", "err", compat)
leth.blockchain.SetHead(compat.RewindTo)
if err := core.WriteChainConfig(chainDb, genesisHash, chainConfig); err != nil {
log.Error("Cannot write chain config during rewind", "hash", genesisHash, "err", err)
}
}
leth.txPool = light.NewTxPool(leth.chainConfig, leth.blockchain, leth.relay)
if leth.protocolManager, err = NewProtocolManager(ctx, leth.chainConfig, true, ClientProtocolVersions, config.NetworkId, leth.eventMux, leth.engine, leth.peers, leth.blockchain, nil, chainDb, leth.odr, leth.relay, quitSync, &leth.wg); err != nil {
return nil, err
}
leth.ApiBackend = &LesApiBackend{
eth: leth,
gpo: nil,
}
if g := leth.config.Genesis; g != nil {
leth.ApiBackend.initialSupply = g.Alloc.Total()
}
gpoParams := config.GPO
if gpoParams.Default == nil {
gpoParams.Default = config.GasPrice
}
leth.ApiBackend.gpo = gasprice.NewOracle(leth.ApiBackend, gpoParams)
return leth, nil
}
func lesTopic(genesisHash common.Hash, protocolVersion uint) discv5.Topic {
var name string
switch protocolVersion {
case lpv1:
name = "LES"
case lpv2:
name = "LES2"
default:
panic(nil)
}
return discv5.Topic(name + "@" + common.Bytes2Hex(genesisHash.Bytes()[0:8]))
}
type LightDummyAPI struct{}
// Etherbase is the address that mining rewards will be send to
func (s *LightDummyAPI) Etherbase() (common.Address, error) {
return common.Address{}, fmt.Errorf("not supported")
}
// Coinbase is the address that mining rewards will be send to (alias for Etherbase)
func (s *LightDummyAPI) Coinbase() (common.Address, error) {
return common.Address{}, fmt.Errorf("not supported")
}
// Hashrate returns the POW hashrate
func (s *LightDummyAPI) Hashrate() hexutil.Uint {
return 0
}
// Mining returns an indication if this node is currently mining.
func (s *LightDummyAPI) Mining() bool {
return false
}
// APIs returns the collection of RPC services the ethereum package offers.
// NOTE, some of these services probably need to be moved to somewhere else.
func (s *LightGoChain) APIs() []rpc.API {
return append(ethapi.GetAPIs(s.ApiBackend), []rpc.API{
{
Namespace: "eth",
Version: "1.0",
Service: &LightDummyAPI{},
Public: true,
}, {
Namespace: "eth",
Version: "1.0",
Service: downloader.NewPublicDownloaderAPI(s.protocolManager.downloader, s.eventMux),
Public: true,
}, {
Namespace: "eth",
Version: "1.0",
Service: filters.NewPublicFilterAPI(s.ApiBackend, true),
Public: true,
}, {
Namespace: "net",
Version: "1.0",
Service: s.netRPCService,
Public: true,
},
}...)
}
func (s *LightGoChain) ResetWithGenesisBlock(gb *types.Block) {
s.blockchain.ResetWithGenesisBlock(gb)
}
func (s *LightGoChain) BlockChain() *light.LightChain { return s.blockchain }
func (s *LightGoChain) TxPool() *light.TxPool { return s.txPool }
func (s *LightGoChain) Engine() consensus.Engine { return s.engine }
func (s *LightGoChain) LesVersion() int { return int(s.protocolManager.SubProtocols[0].Version) }
func (s *LightGoChain) Downloader() *downloader.Downloader { return s.protocolManager.downloader }
func (s *LightGoChain) EventMux() *event.TypeMux { return s.eventMux }
// Protocols implements node.Service, returning all the currently configured
// network protocols to start.
func (s *LightGoChain) Protocols() []p2p.Protocol {
return s.protocolManager.SubProtocols
}
// Start implements node.Service, starting all internal goroutines needed by the
// GoChain protocol implementation.
func (s *LightGoChain) Start(srvr *p2p.Server) error {
s.startBloomHandlers()
log.Warn("Light client mode is an experimental feature")
s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.networkId)
// clients are searching for the first advertised protocol in the list
protocolVersion := AdvertiseProtocolVersions[0]
s.serverPool.start(srvr, lesTopic(s.blockchain.Genesis().Hash(), protocolVersion))
s.protocolManager.Start(s.config.LightPeers)
return nil
}
// Stop implements node.Service, terminating all internal goroutines used by the
// GoChain protocol.
func (s *LightGoChain) Stop() error {
s.odr.Stop()
if s.bloomIndexer != nil {
if err := s.bloomIndexer.Close(); err != nil {
log.Error("cannot close bloom indexer", "err", err)
}
}
if s.chtIndexer != nil {
if err := s.chtIndexer.Close(); err != nil {
log.Error("cannot close chain indexer", "err", err)
}
}
if s.bloomTrieIndexer != nil {
if err := s.bloomTrieIndexer.Close(); err != nil {
log.Error("cannot close bloom trie indexer", "err", err)
}
}
s.blockchain.Stop()
s.protocolManager.Stop()
s.txPool.Stop()
s.eventMux.Stop()
time.Sleep(time.Millisecond * 200)
s.chainDb.Close()
close(s.shutdownChan)
return nil
}