/
backend.go
503 lines (425 loc) · 14.8 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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
package api
import (
"context"
"crypto/ecdsa"
"errors"
"math"
"math/big"
"sync"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
gethcore "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/bloombits"
gethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/rpc"
"github.com/smartbch/moeingevm/types"
"github.com/smartbch/smartbch/app"
"github.com/smartbch/smartbch/crosschain"
cctypes "github.com/smartbch/smartbch/crosschain/types"
"github.com/smartbch/smartbch/param"
"github.com/smartbch/smartbch/staking"
stakingtypes "github.com/smartbch/smartbch/staking/types"
)
var _ BackendService = &apiBackend{}
const (
// Ethereum Wire Protocol
// https://github.com/ethereum/devp2p/blob/master/caps/eth.md
protocolVersion = 63
)
var SEP206ContractAddress [20]byte = [20]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x27, 0x11}
type apiBackend struct {
//extRPCEnabled bool
node ITmNode
app app.IApp
//gpo *gasprice.Oracle
//chainSideFeed event.Feed
//chainHeadFeed event.Feed
//blockProcFeed event.Feed
txFeed event.Feed
//logsFeed event.Feed
rmLogsFeed event.Feed
//pendingLogsFeed event.Feed
rpcPrivateKeyLock sync.RWMutex
rpcPrivateKey *ecdsa.PrivateKey
}
func NewBackend(node ITmNode, app app.IApp) BackendService {
return &apiBackend{
node: node,
app: app,
}
}
func (backend *apiBackend) ChainId() *big.Int {
return backend.app.ChainID().ToBig()
}
func (backend *apiBackend) GetStorageAt(address common.Address, key string, height int64) []byte {
ctx := backend.app.GetRpcContextAtHeight(height)
defer ctx.Close(false)
if address == common.Address(SEP206ContractAddress) {
return ctx.GetStorageAt(2000, key)
}
acc := ctx.GetAccount(address)
if acc == nil {
return nil
}
return ctx.GetStorageAt(acc.Sequence(), key)
}
func (backend *apiBackend) GetCode(contract common.Address, height int64) (bytecode []byte, codeHash []byte) {
ctx := backend.app.GetRpcContextAtHeight(height)
defer ctx.Close(false)
info := ctx.GetCode(contract)
if info != nil {
bytecode = info.BytecodeSlice()
codeHash = info.CodeHashSlice()
}
return
}
func (backend *apiBackend) GetBalance(owner common.Address, height int64) (*big.Int, error) {
ctx := backend.app.GetRpcContextAtHeight(height)
defer ctx.Close(false)
b, err := ctx.GetBalance(owner)
if err != nil {
return nil, err
}
return b.ToBig(), nil
}
func (backend *apiBackend) GetNonce(address common.Address, height int64) (uint64, error) {
ctx := backend.app.GetRpcContextAtHeight(height)
defer ctx.Close(false)
if acc := ctx.GetAccount(address); acc != nil {
return acc.Nonce(), nil
}
return 0, types.ErrAccNotFound
}
func (backend *apiBackend) GetTransaction(txHash common.Hash) (tx *types.Transaction, sig [65]byte, err error) {
ctx := backend.app.GetHistoryOnlyContext()
defer ctx.Close(false)
if tx, sig, err = ctx.GetTxByHash(txHash); err != nil {
return
}
if tx == nil {
err = errors.New("tx with specific hash not exist")
}
return
}
func (backend *apiBackend) BlockByHash(hash common.Hash) (*types.Block, error) {
ctx := backend.app.GetHistoryOnlyContext()
defer ctx.Close(false)
block, err := ctx.GetBlockByHash(hash)
if err != nil {
return nil, err
}
return block, nil
}
func (backend *apiBackend) BlockByNumber(number int64) (*types.Block, error) {
ctx := backend.app.GetHistoryOnlyContext()
defer ctx.Close(false)
return ctx.GetBlockByHeight(uint64(number))
}
func (backend *apiBackend) ProtocolVersion() int {
return protocolVersion
}
func (backend *apiBackend) LatestHeight() int64 {
appCtx := backend.app.GetHistoryOnlyContext()
defer appCtx.Close(false)
return appCtx.GetLatestHeight()
}
func (backend *apiBackend) CurrentBlock() (*types.Block, error) {
appCtx := backend.app.GetHistoryOnlyContext()
defer appCtx.Close(false)
block, err := appCtx.GetBlockByHeight(uint64(appCtx.GetLatestHeight()))
if err != nil {
return nil, err
}
return block, nil
}
func (backend *apiBackend) SendRawTx(signedTx []byte) (common.Hash, error) {
return backend.node.BroadcastTxSync(signedTx)
}
// CallForSbch use app.RunTxForSbchRpc and returns more detailed result info
func (backend *apiBackend) CallForSbch(tx *gethtypes.Transaction, sender common.Address, height int64) *CallDetail {
runner, _ := backend.app.RunTxForSbchRpc(tx, sender, height)
return &CallDetail{
Status: runner.Status,
GasUsed: runner.GasUsed,
OutData: runner.OutData,
Logs: runner.Logs,
CreatedContractAddress: runner.CreatedContractAddress,
InternalTxCalls: runner.InternalTxCalls,
InternalTxReturns: runner.InternalTxReturns,
RwLists: runner.RwLists,
}
}
func (backend *apiBackend) Call(tx *gethtypes.Transaction, sender common.Address, height int64) (statusCode int, retData []byte) {
runner, _ := backend.app.RunTxForRpc(tx, sender, false, height)
return runner.Status, runner.OutData
}
func (backend *apiBackend) EstimateGas(tx *gethtypes.Transaction, sender common.Address, height int64) (statusCode int, retData []byte, gas int64) {
runner, gas := backend.app.RunTxForRpc(tx, sender, true, height)
return runner.Status, runner.OutData, gas
}
func (backend *apiBackend) QueryLogs(addresses []common.Address, topics [][]common.Hash, startHeight, endHeight uint32, filter types.FilterFunc) ([]types.Log, error) {
ctx := backend.app.GetHistoryOnlyContext()
defer ctx.Close(false)
return ctx.QueryLogs(addresses, topics, startHeight, endHeight, filter)
}
func (backend *apiBackend) QueryTxBySrc(addr common.Address, startHeight, endHeight, limit uint32) (tx []*types.Transaction, sigs [][65]byte, err error) {
ctx := backend.app.GetHistoryOnlyContext()
defer ctx.Close(false)
return ctx.QueryTxBySrc(addr, startHeight, endHeight, limit)
}
func (backend *apiBackend) QueryTxByDst(addr common.Address, startHeight, endHeight, limit uint32) (tx []*types.Transaction, sigs [][65]byte, err error) {
ctx := backend.app.GetHistoryOnlyContext()
defer ctx.Close(false)
return ctx.QueryTxByDst(addr, startHeight, endHeight, limit)
}
func (backend *apiBackend) QueryTxByAddr(addr common.Address, startHeight, endHeight, limit uint32) (tx []*types.Transaction, sigs [][65]byte, err error) {
ctx := backend.app.GetHistoryOnlyContext()
defer ctx.Close(false)
return ctx.QueryTxByAddr(addr, startHeight, endHeight, limit)
}
func (backend *apiBackend) SbchQueryLogs(addr common.Address, topics []common.Hash, startHeight, endHeight, limit uint32) ([]types.Log, error) {
ctx := backend.app.GetHistoryOnlyContext()
defer ctx.Close(false)
return ctx.BasicQueryLogs(addr, topics, startHeight, endHeight, limit)
}
func (backend *apiBackend) GetTxListByHeight(height uint32) (txs []*types.Transaction, sigs [][65]byte, err error) {
return backend.GetTxListByHeightWithRange(height, 0, math.MaxInt32)
}
func (backend *apiBackend) GetTxListByHeightWithRange(height uint32, start, end int) (tx []*types.Transaction, sigs [][65]byte, err error) {
ctx := backend.app.GetHistoryOnlyContext()
defer ctx.Close(false)
return ctx.GetTxListByHeightWithRange(height, start, end)
}
func (backend *apiBackend) GetToAddressCount(addr common.Address) int64 {
ctx := backend.app.GetHistoryOnlyContext()
defer ctx.Close(false)
return ctx.GetToAddressCount(addr)
}
func (backend *apiBackend) GetFromAddressCount(addr common.Address) int64 {
ctx := backend.app.GetHistoryOnlyContext()
defer ctx.Close(false)
return ctx.GetFromAddressCount(addr)
}
func (backend *apiBackend) GetSep20ToAddressCount(contract common.Address, addr common.Address) int64 {
ctx := backend.app.GetHistoryOnlyContext()
defer ctx.Close(false)
return ctx.GetSep20ToAddressCount(contract, addr)
}
func (backend *apiBackend) GetSep20FromAddressCount(contract common.Address, addr common.Address) int64 {
ctx := backend.app.GetHistoryOnlyContext()
defer ctx.Close(false)
return ctx.GetSep20FromAddressCount(contract, addr)
}
func (backend *apiBackend) GetCurrEpoch() *stakingtypes.Epoch {
return backend.app.GetCurrEpoch()
}
// [start, end)
func (backend *apiBackend) GetEpochs(start, end uint64) ([]*stakingtypes.Epoch, error) {
if start >= end {
return nil, errors.New("invalid start or empty epochs")
}
ctx := backend.app.GetRpcContext()
defer ctx.Close(false)
result := make([]*stakingtypes.Epoch, 0, end-start)
info := staking.LoadStakingInfo(ctx)
for epochNum := int64(start); epochNum < int64(end) && epochNum <= info.CurrEpochNum; epochNum++ {
epoch, ok := staking.LoadEpoch(ctx, epochNum)
if ok {
result = append(result, &epoch)
}
}
return result, nil
}
func (backend *apiBackend) GetEpochList(from string) ([]*stakingtypes.Epoch, error) {
switch from {
case "watcher":
return backend.app.GetWatcherEpochList(), nil
case "app":
return backend.app.GetAppEpochList(), nil
case "storage":
fallthrough
default:
return backend.GetEpochs(0, 999)
}
}
// [start, end)
func (backend *apiBackend) GetCCEpochs(start, end uint64) ([]*cctypes.CCEpoch, error) {
if start >= end {
return nil, errors.New("invalid start or empty cc epochs")
}
ctx := backend.app.GetRpcContext()
defer ctx.Close(false)
result := make([]*cctypes.CCEpoch, 0, end-start)
info := crosschain.LoadCCInfo(ctx)
for epochNum := int64(start); epochNum < int64(end) && epochNum <= info.CurrEpochNum; epochNum++ {
epoch, ok := crosschain.LoadCCEpoch(ctx, epochNum)
if ok {
result = append(result, &epoch)
}
}
return result, nil
}
func (backend *apiBackend) HeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*types.Header, error) {
if blockNr == rpc.LatestBlockNumber {
blockNr = rpc.BlockNumber(backend.app.GetLatestBlockNum())
}
appCtx := backend.app.GetHistoryOnlyContext()
defer appCtx.Close(false)
block, err := appCtx.GetBlockByHeight(uint64(blockNr))
if err != nil {
return nil, nil
}
return &types.Header{
Number: hexutil.Uint64(block.Number),
BlockHash: block.Hash,
Bloom: block.LogsBloom,
}, nil
}
func (backend *apiBackend) HeaderByHash(ctx context.Context, blockHash common.Hash) (*types.Header, error) {
appCtx := backend.app.GetHistoryOnlyContext()
defer appCtx.Close(false)
block, err := appCtx.GetBlockByHash(blockHash)
if err != nil {
return nil, err
}
return &types.Header{
Number: hexutil.Uint64(block.Number),
BlockHash: block.Hash,
}, nil
}
func (backend *apiBackend) GetReceipts(ctx context.Context, blockNum uint64) (gethtypes.Receipts, error) {
appCtx := backend.app.GetHistoryOnlyContext()
defer appCtx.Close(false)
receipts := make([]*gethtypes.Receipt, 0, 8)
txs, _, err := appCtx.GetTxListByHeight(uint32(blockNum))
if err == nil {
for _, tx := range txs {
receipts = append(receipts, toGethReceipt(tx))
}
}
return receipts, nil
}
func toGethReceipt(tx *types.Transaction) *gethtypes.Receipt {
return &gethtypes.Receipt{
Status: tx.Status,
CumulativeGasUsed: tx.CumulativeGasUsed,
Bloom: tx.LogsBloom,
Logs: types.ToGethLogs(tx.Logs),
TxHash: tx.Hash,
ContractAddress: tx.ContractAddress,
GasUsed: tx.GasUsed,
BlockHash: tx.BlockHash,
BlockNumber: big.NewInt(tx.BlockNumber),
TransactionIndex: uint(tx.TransactionIndex),
}
}
func (backend *apiBackend) GetLogs(ctx context.Context, blockHash common.Hash) ([][]*gethtypes.Log, error) {
appCtx := backend.app.GetHistoryOnlyContext()
defer appCtx.Close(false)
logs := make([][]*gethtypes.Log, 0, 8)
block, err := appCtx.GetBlockByHash(blockHash)
if err == nil && block != nil {
for _, txHash := range block.Transactions {
tx, _, err := appCtx.GetTxByHash(txHash)
if err == nil && tx != nil {
txLogs := types.ToGethLogs(tx.Logs)
// fix log.TxHash
for _, txLog := range txLogs {
txLog.TxHash = tx.Hash
}
logs = append(logs, txLogs)
}
}
}
return logs, nil
}
func (backend *apiBackend) SubscribeChainEvent(ch chan<- types.ChainEvent) event.Subscription {
return backend.app.SubscribeChainEvent(ch)
}
func (backend *apiBackend) SubscribeLogsEvent(ch chan<- []*gethtypes.Log) event.Subscription {
return backend.app.SubscribeLogsEvent(ch)
}
func (backend *apiBackend) SubscribeNewTxsEvent(ch chan<- gethcore.NewTxsEvent) event.Subscription {
return backend.txFeed.Subscribe(ch)
}
func (backend *apiBackend) SubscribeRemovedLogsEvent(ch chan<- gethcore.RemovedLogsEvent) event.Subscription {
return backend.rmLogsFeed.Subscribe(ch)
}
//func (b2 *apiBackend) SubscribePendingLogsEvent(ch chan<- []*gethtypes.Log) event.Subscription {
// return b2.pendingLogsFeed.Subscribe(ch)
//}
func (backend *apiBackend) BloomStatus() (uint64, uint64) {
return 4096, 0 // this is temporary implementation
}
func (backend *apiBackend) ServiceFilter(ctx context.Context, session *bloombits.MatcherSession) {
panic("implement me")
}
func (backend *apiBackend) NodeInfo() Info {
i := backend.node.GetNodeInfo()
bi := backend.app.LoadBlockInfo()
i.NextBlock.Number = bi.Number
i.NextBlock.Timestamp = bi.Timestamp
i.NextBlock.Hash = bi.Hash
return i
}
func (backend *apiBackend) ValidatorsInfo(height int64) app.ValidatorsInfo {
return backend.app.GetValidatorsInfo(height)
}
func (backend *apiBackend) ValidatorOnlineInfos() (int64, stakingtypes.ValidatorOnlineInfos) {
ctx := backend.app.GetRpcContext()
defer ctx.Close(false)
return ctx.GetLatestHeight(), staking.LoadOnlineInfo(ctx)
}
func (backend *apiBackend) ValidatorWatchInfos() stakingtypes.ValidatorWatchInfos {
ctx := backend.app.GetRpcContext()
defer ctx.Close(false)
return staking.LoadValidatorWatchInfo(ctx)
}
func (backend *apiBackend) IsArchiveMode() bool {
return backend.app.IsArchiveMode()
}
func (backend *apiBackend) GetSeq(address common.Address) uint64 {
ctx := backend.app.GetRpcContextAtHeight(-1)
defer ctx.Close(false)
accInfo := ctx.GetAccount(address)
if accInfo == nil {
return 0
}
return accInfo.Sequence()
}
func (backend *apiBackend) GetPosVotes() map[[32]byte]*big.Int {
ctx := backend.app.GetRpcContext()
defer ctx.Close(false)
return staking.GetPosVotes(ctx, param.XHedgeContractSequence)
}
func (backend *apiBackend) GetSyncBlock(height int64) (blk []byte, err error) {
return backend.app.GetBlockForSync(height)
}
func (backend *apiBackend) GetRpcMaxLogResults() int {
return backend.app.GetRpcMaxLogResults()
}
func (backend *apiBackend) GetRpcPrivateKey() *ecdsa.PrivateKey {
return backend.rpcPrivateKey
}
func (backend *apiBackend) SetRpcPrivateKey(key *ecdsa.PrivateKey) (success bool) {
if backend.rpcPrivateKey == nil {
backend.rpcPrivateKeyLock.Lock()
backend.rpcPrivateKey = key
backend.rpcPrivateKeyLock.Unlock()
return true
}
return false
}
func (backend *apiBackend) WaitRpcKeySet() {
for {
backend.rpcPrivateKeyLock.RLock()
key := backend.rpcPrivateKey
backend.rpcPrivateKeyLock.RUnlock()
time.Sleep(3 * time.Second)
if key != nil {
break
}
}
}