/
fetch.go
214 lines (201 loc) · 6.72 KB
/
fetch.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
package fetcher
import (
"context"
"math/big"
"time"
"github.com/WeTrustPlatform/account-indexer/core/types"
"github.com/WeTrustPlatform/account-indexer/service"
ethereum "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
gethcommon "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
gethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
log "github.com/sirupsen/logrus"
)
//EthClient the Client of geth
type EthClient interface {
SubscribeNewHead(ctx context.Context, ch chan<- *gethtypes.Header) (ethereum.Subscription, error)
BlockByNumber(ctx context.Context, number *big.Int) (*gethtypes.Block, error)
TransactionSender(ctx context.Context, tx *gethtypes.Transaction, block common.Hash, index uint) (common.Address, error)
HeaderByNumber(ctx context.Context, number *big.Int) (*gethtypes.Header, error)
TransactionReceipt(ctx context.Context, txHash common.Hash) (*gethtypes.Receipt, error)
TransactionByHash(ctx context.Context, hash common.Hash) (*gethtypes.Transaction, bool, error)
Close()
}
// Fetch the interface to interact with blockchain
type Fetch interface {
RealtimeFetch(ch chan<- *types.BLockDetail)
FetchABlock(blockNumber *big.Int) (*types.BLockDetail, error)
GetLatestBlock() (*big.Int, error)
TransactionByHash(txHash string) (*types.TransactionExtra, error)
}
// ChainFetch the real implementation
type ChainFetch struct {
Client EthClient
blockHeaderChannel chan *gethtypes.Header
ethSub ethereum.Subscription
}
// NewChainFetch new ChainFetch instance
func NewChainFetch() (*ChainFetch, error) {
ipcPath := service.GetIpcManager().GetIPC()
client, err := ethclient.Dial(ipcPath)
if err != nil {
log.WithFields(log.Fields{
"ipc": ipcPath,
"error": err.Error(),
}).Error("ChainFetch: Cannot dial")
switchIPC()
return nil, err
}
fetcher := &ChainFetch{Client: client}
fetcher.blockHeaderChannel = nil
return fetcher, err
}
// IpcUpdated no need to implement IpcSubscriber interface
// Let indexer update me
func (cf *ChainFetch) IpcUpdated() {
// finish any ongoing go-routines of this fetcher
if cf.ethSub != nil {
cf.ethSub.Unsubscribe()
}
log.Info("ChainFetch: Unsubscribed the old ipc, wait for 30s")
time.Sleep(30 * time.Second)
log.Info("ChainFetch: 30s passed, closing blockHeaderChannel")
// writer should be the one to close the channel?
if cf.blockHeaderChannel != nil {
// This should finish the RealtimeFetch for loop
close(cf.blockHeaderChannel)
}
cf.Client.Close()
}
// RealtimeFetch fetch data from blockchain
func (cf *ChainFetch) RealtimeFetch(ch chan<- *types.BLockDetail) {
// don't subscribe ever, let indexer do it
ctx := context.Background()
cf.blockHeaderChannel = make(chan *gethtypes.Header)
ethSub, err := cf.Client.SubscribeNewHead(ctx, cf.blockHeaderChannel)
if err != nil {
log.WithField("ipc", service.GetIpcManager().GetIPC()).Error("ChainFetch: Cannot do newHead subscribe to this ipc")
switchIPC()
return
}
cf.ethSub = ethSub
log.Info("ChainFetch: RealtimeFetch Waiting for new block hearders...")
for {
receivedHeader, ok := <-cf.blockHeaderChannel
if !ok {
// switched ipc
log.Info("ChainFetch: Stopping SubscribeNewHead, ipc is switched?")
close(ch)
break
}
blockNumber := receivedHeader.Number
blockDetail, err := cf.FetchABlock(blockNumber)
if err == nil {
ch <- blockDetail
} else {
// Finish the Realtime process, someone will switch the IPC
log.WithField("blockNumber", blockNumber.String()).Info("ChainFetch: RealtimeFetch Cannot get block detail")
close(ch)
break
}
}
log.Info("ChainFetch: Stopped RealtimeFetch")
}
// FetchABlock fetch a block by block number
func (cf *ChainFetch) FetchABlock(blockNumber *big.Int) (*types.BLockDetail, error) {
ctx := context.Background()
aBlock, err := cf.Client.BlockByNumber(ctx, blockNumber)
if err != nil {
log.WithField("error", err.Error()).Error("ChainFetch: FetchABlock BlockByNumber returns error")
switchIPC()
return &types.BLockDetail{}, err
}
transactions := []types.TransactionDetail{}
if len(aBlock.Transactions()) > 0 {
for index, tx := range aBlock.Transactions() {
sender, err := cf.Client.TransactionSender(ctx, tx, aBlock.Hash(), uint(index))
if err != nil {
log.Error("ChainFetch: FetchABlock TransactionSender returns error " + err.Error())
switchIPC()
return &types.BLockDetail{}, err
}
// Some transactions have nil To, for example Contract creation
to := ""
if tx.To() != nil {
to = tx.To().String()
}
transaction := types.TransactionDetail{
From: sender.String(),
To: to,
TxHash: tx.Hash().String(),
Value: tx.Value(),
}
transactions = append(transactions, transaction)
// Index transactions that create contract too
if tx.To() == nil && (tx.Value() == nil || tx.Value().Int64() == 0) {
txRecp, err := cf.Client.TransactionReceipt(ctx, tx.Hash())
if err == nil {
if txRecp != nil {
transaction := types.TransactionDetail{
From: "",
To: txRecp.ContractAddress.String(),
TxHash: tx.Hash().String(),
Value: tx.Value(),
}
transactions = append(transactions, transaction)
}
} else {
log.WithFields(log.Fields{
"txHash": tx.Hash().String(),
"error": err.Error(),
}).Warn("ChainFetch: FetchABlock cannot get receipt for transaction")
// https://github.com/WeTrustPlatform/account-indexer/issues/18
// We trust our geth nodes, some other nodes always return error for this API
// switchIPC()
// return &types.BLockDetail{}, err
}
}
}
}
blockDetail := types.BLockDetail{
BlockNumber: aBlock.Number(),
Time: new(big.Int).SetUint64(aBlock.Time()),
Transactions: transactions,
}
return &blockDetail, nil
}
// TransactionByHash query geth node to get addtional data of tx
func (cf *ChainFetch) TransactionByHash(txHash string) (*types.TransactionExtra, error) {
ctx := context.Background()
byteArr, err := hexutil.Decode(txHash)
hash := gethcommon.BytesToHash(byteArr)
if err != nil {
return nil, err
}
tx, _, err := cf.Client.TransactionByHash(ctx, hash)
if err != nil {
return nil, err
}
return &types.TransactionExtra{
Data: tx.Data(),
Gas: tx.Gas(),
GasPrice: tx.GasPrice(),
}, nil
}
// GetLatestBlock get latest known block by geth node
func (cf *ChainFetch) GetLatestBlock() (*big.Int, error) {
ctx := context.Background()
// nil means latest known header according to ethclient doc
header, err := cf.Client.HeaderByNumber(ctx, nil)
if err != nil {
switchIPC()
return big.NewInt(-1), err
}
blockNumber := header.Number
return blockNumber, nil
}
func switchIPC() {
go service.GetIpcManager().ForceChangeIPC()
}