-
Notifications
You must be signed in to change notification settings - Fork 0
/
fch.go
257 lines (229 loc) · 8.97 KB
/
fch.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
package fch
import (
"context"
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/math"
"github.com/ethereum/go-ethereum/core/bloombits"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/params"
"github.com/Timestopeofficial/feechain/api/proto"
"github.com/Timestopeofficial/feechain/block"
"github.com/Timestopeofficial/feechain/core"
"github.com/Timestopeofficial/feechain/core/state"
"github.com/Timestopeofficial/feechain/core/types"
"github.com/Timestopeofficial/feechain/core/vm"
nodeconfig "github.com/Timestopeofficial/feechain/internal/configs/node"
commonRPC "github.com/Timestopeofficial/feechain/rpc/common"
"github.com/Timestopeofficial/feechain/shard"
staking "github.com/Timestopeofficial/feechain/staking/types"
lru "github.com/hashicorp/golang-lru"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/pkg/errors"
"golang.org/x/sync/singleflight"
)
const (
// BloomBitsBlocks is the number of blocks a single bloom bit section vector
// contains on the server side.
BloomBitsBlocks uint64 = 4096
leaderCacheSize = 250 // Approx number of BLS keys in committee
undelegationPayoutsCacheSize = 500 // max number of epochs to store in cache
preStakingBlockRewardsCacheSize = 1024 // max number of block rewards to store in cache
totalStakeCacheDuration = 20 // number of blocks where the returned total stake will remain the same
)
var (
// ErrFinalizedTransaction is returned if the transaction to be submitted is already on-chain
ErrFinalizedTransaction = errors.New("transaction already finalized")
)
// Feechain implements the Feechain full node service.
type Feechain struct {
// Channel for shutting down the service
ShutdownChan chan bool // Channel for shutting down the Feechain
BloomRequests chan chan *bloombits.Retrieval // Channel receiving bloom data retrieval requests
BlockChain *core.BlockChain
BeaconChain *core.BlockChain
TxPool *core.TxPool
CxPool *core.CxPool // CxPool is used to store the blockHashes of blocks containing cx receipts to be sent
// DB interfaces
BloomIndexer *core.ChainIndexer // Bloom indexer operating during block imports
NodeAPI NodeAPI
// ChainID is used to identify which network we are using
ChainID uint64
// EthCompatibleChainID is used to identify the Ethereum compatible chain ID
EthChainID uint64
// RPCGasCap is the global gas cap for eth-call variants.
RPCGasCap *big.Int `toml:",omitempty"`
ShardID uint32
// Gas price suggestion oracle
gpo *Oracle
// Internals
eventMux *event.TypeMux
chainDb ethdb.Database // Block chain database
// group for units of work which can be executed with duplicate suppression.
group singleflight.Group
// leaderCache to save on recomputation every epoch.
leaderCache *lru.Cache
// undelegationPayoutsCache to save on recomputation every epoch
undelegationPayoutsCache *lru.Cache
// preStakingBlockRewardsCache to save on recomputation for commonly checked blocks in epoch < staking epoch
preStakingBlockRewardsCache *lru.Cache
// totalStakeCache to save on recomputation for `totalStakeCacheDuration` blocks.
totalStakeCache *totalStakeCache
}
// NodeAPI is the list of functions from node used to call rpc apis.
type NodeAPI interface {
AddPendingStakingTransaction(*staking.StakingTransaction) error
AddPendingTransaction(newTx *types.Transaction) error
Blockchain() *core.BlockChain
Beaconchain() *core.BlockChain
GetTransactionsHistory(address, txType, order string) ([]common.Hash, error)
GetStakingTransactionsHistory(address, txType, order string) ([]common.Hash, error)
GetTransactionsCount(address, txType string) (uint64, error)
GetStakingTransactionsCount(address, txType string) (uint64, error)
IsCurrentlyLeader() bool
IsOutOfSync(shardID uint32) bool
SyncStatus(shardID uint32) (bool, uint64, uint64)
SyncPeers() map[string]int
ReportStakingErrorSink() types.TransactionErrorReports
ReportPlainErrorSink() types.TransactionErrorReports
PendingCXReceipts() []*types.CXReceiptsProof
GetNodeBootTime() int64
PeerConnectivity() (int, int, int)
ListPeer(topic string) []peer.ID
ListTopic() []string
ListBlockedPeer() []peer.ID
GetConsensusInternal() commonRPC.ConsensusInternal
IsBackup() bool
SetNodeBackupMode(isBackup bool) bool
// debug API
GetConsensusMode() string
GetConsensusPhase() string
GetConsensusViewChangingID() uint64
GetConsensusCurViewID() uint64
GetConfig() commonRPC.Config
ShutDown()
GetLastSigningPower() (float64, error)
}
// New creates a new Feechain object (including the
// initialisation of the common Feechain object)
func New(
nodeAPI NodeAPI, txPool *core.TxPool, cxPool *core.CxPool, shardID uint32,
) *Feechain {
chainDb := nodeAPI.Blockchain().ChainDb()
leaderCache, _ := lru.New(leaderCacheSize)
undelegationPayoutsCache, _ := lru.New(undelegationPayoutsCacheSize)
preStakingBlockRewardsCache, _ := lru.New(preStakingBlockRewardsCacheSize)
totalStakeCache := newTotalStakeCache(totalStakeCacheDuration)
bloomIndexer := NewBloomIndexer(chainDb, params.BloomBitsBlocks, params.BloomConfirms)
bloomIndexer.Start(nodeAPI.Blockchain())
backend := &Feechain{
ShutdownChan: make(chan bool),
BloomRequests: make(chan chan *bloombits.Retrieval),
BloomIndexer: bloomIndexer,
BlockChain: nodeAPI.Blockchain(),
BeaconChain: nodeAPI.Beaconchain(),
TxPool: txPool,
CxPool: cxPool,
eventMux: new(event.TypeMux),
chainDb: chainDb,
NodeAPI: nodeAPI,
ChainID: nodeAPI.Blockchain().Config().ChainID.Uint64(),
EthChainID: nodeAPI.Blockchain().Config().EthCompatibleChainID.Uint64(),
ShardID: shardID,
leaderCache: leaderCache,
totalStakeCache: totalStakeCache,
undelegationPayoutsCache: undelegationPayoutsCache,
preStakingBlockRewardsCache: preStakingBlockRewardsCache,
}
// Setup gas price oracle
gpoParams := GasPriceConfig{
Blocks: 20,
Percentile: 60,
Default: big.NewInt(1e12),
}
gpo := NewOracle(backend, gpoParams)
backend.gpo = gpo
return backend
}
// SingleFlightRequest ..
func (fch *Feechain) SingleFlightRequest(
key string,
fn func() (interface{}, error),
) (interface{}, error) {
res, err, _ := fch.group.Do(key, fn)
return res, err
}
// SingleFlightForgetKey ...
func (fch *Feechain) SingleFlightForgetKey(key string) {
fch.group.Forget(key)
}
// ProtocolVersion ...
func (fch *Feechain) ProtocolVersion() int {
return proto.ProtocolVersion
}
// IsLeader exposes if node is currently leader
func (fch *Feechain) IsLeader() bool {
return fch.NodeAPI.IsCurrentlyLeader()
}
// GetNodeMetadata ..
func (fch *Feechain) GetNodeMetadata() commonRPC.NodeMetadata {
header := fch.CurrentBlock().Header()
cfg := nodeconfig.GetShardConfig(header.ShardID())
var blockEpoch *uint64
if header.ShardID() == shard.BeaconChainShardID {
sched := shard.Schedule.InstanceForEpoch(header.Epoch())
b := sched.BlocksPerEpoch()
blockEpoch = &b
}
blsKeys := []string{}
if cfg.ConsensusPriKey != nil {
for _, key := range cfg.ConsensusPriKey {
blsKeys = append(blsKeys, key.Pub.Bytes.Hex())
}
}
c := commonRPC.C{}
c.TotalKnownPeers, c.Connected, c.NotConnected = fch.NodeAPI.PeerConnectivity()
syncPeers := fch.NodeAPI.SyncPeers()
consensusInternal := fch.NodeAPI.GetConsensusInternal()
return commonRPC.NodeMetadata{
BLSPublicKey: blsKeys,
Version: nodeconfig.GetVersion(),
NetworkType: string(cfg.GetNetworkType()),
ChainConfig: *fch.ChainConfig(),
IsLeader: fch.IsLeader(),
ShardID: fch.ShardID,
CurrentBlockNum: header.Number().Uint64(),
CurrentEpoch: header.Epoch().Uint64(),
BlocksPerEpoch: blockEpoch,
Role: cfg.Role().String(),
DNSZone: cfg.DNSZone,
Archival: cfg.GetArchival(),
IsBackup: fch.NodeAPI.IsBackup(),
NodeBootTime: fch.NodeAPI.GetNodeBootTime(),
PeerID: nodeconfig.GetPeerID(),
Consensus: consensusInternal,
C: c,
SyncPeers: syncPeers,
}
}
// GetEVM returns a new EVM entity
func (fch *Feechain) GetEVM(ctx context.Context, msg core.Message, state *state.DB, header *block.Header) (*vm.EVM, error) {
state.SetBalance(msg.From(), math.MaxBig256)
vmCtx := core.NewEVMContext(msg, header, fch.BlockChain, nil)
return vm.NewEVM(vmCtx, state, fch.BlockChain.Config(), *fch.BlockChain.GetVMConfig()), nil
}
// ChainDb ..
func (fch *Feechain) ChainDb() ethdb.Database {
return fch.chainDb
}
// EventMux ..
func (fch *Feechain) EventMux() *event.TypeMux {
return fch.eventMux
}
// BloomStatus ...
// TODO: this is not implemented or verified yet for feechain.
func (fch *Feechain) BloomStatus() (uint64, uint64) {
sections, _, _ := fch.BloomIndexer.Sections()
return BloomBitsBlocks, sections
}