-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathstream.go
More file actions
202 lines (177 loc) · 5.94 KB
/
Copy pathstream.go
File metadata and controls
202 lines (177 loc) · 5.94 KB
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
package api
import (
"context"
"fmt"
"github.com/ethereum/go-ethereum/common/hexutil"
gethTypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/eth/filters"
"github.com/ethereum/go-ethereum/rpc"
evmTypes "github.com/onflow/flow-go/fvm/evm/types"
"github.com/rs/zerolog"
"github.com/onflow/flow-evm-gateway/config"
ethTypes "github.com/onflow/flow-evm-gateway/eth/types"
"github.com/onflow/flow-evm-gateway/models"
"github.com/onflow/flow-evm-gateway/services/logs"
"github.com/onflow/flow-evm-gateway/storage"
)
type StreamAPI struct {
logger zerolog.Logger
config config.Config
blocks storage.BlockIndexer
transactions storage.TransactionIndexer
receipts storage.ReceiptIndexer
blocksPublisher *models.Publisher[*models.Block]
transactionsPublisher *models.Publisher[*gethTypes.Transaction]
logsPublisher *models.Publisher[[]*gethTypes.Log]
}
func NewStreamAPI(
logger zerolog.Logger,
config config.Config,
blocks storage.BlockIndexer,
transactions storage.TransactionIndexer,
receipts storage.ReceiptIndexer,
blocksPublisher *models.Publisher[*models.Block],
transactionsPublisher *models.Publisher[*gethTypes.Transaction],
logsPublisher *models.Publisher[[]*gethTypes.Log],
) *StreamAPI {
return &StreamAPI{
logger: logger,
config: config,
blocks: blocks,
transactions: transactions,
receipts: receipts,
blocksPublisher: blocksPublisher,
transactionsPublisher: transactionsPublisher,
logsPublisher: logsPublisher,
}
}
// NewHeads send a notification each time a new block is appended to the chain.
func (s *StreamAPI) NewHeads(ctx context.Context) (*rpc.Subscription, error) {
return newSubscription(
ctx,
s.logger,
s.blocksPublisher,
func(notifier *rpc.Notifier, sub *rpc.Subscription) func(block *models.Block) error {
return func(block *models.Block) error {
blockHeader, err := s.prepareBlockHeader(block)
if err != nil {
return fmt.Errorf("failed to get block header response: %w", err)
}
return notifier.Notify(sub.ID, blockHeader)
}
},
)
}
// NewPendingTransactions creates a subscription that is triggered each time a
// transaction enters the transaction pool. If fullTx is true the full tx is
// sent to the client, otherwise the hash is sent.
func (s *StreamAPI) NewPendingTransactions(ctx context.Context, fullTx *bool) (*rpc.Subscription, error) {
return newSubscription(
ctx,
s.logger,
s.transactionsPublisher,
func(notifier *rpc.Notifier, sub *rpc.Subscription) func(*gethTypes.Transaction) error {
return func(tx *gethTypes.Transaction) error {
if fullTx != nil && *fullTx {
return notifier.Notify(sub.ID, tx)
}
return notifier.Notify(sub.ID, tx.Hash())
}
},
)
}
// Logs creates a subscription that fires for all new log that match the given filter criteria.
func (s *StreamAPI) Logs(ctx context.Context, criteria filters.FilterCriteria) (*rpc.Subscription, error) {
return newSubscription(
ctx,
s.logger,
s.logsPublisher,
func(notifier *rpc.Notifier, sub *rpc.Subscription) func([]*gethTypes.Log) error {
return func(allLogs []*gethTypes.Log) error {
for _, log := range allLogs {
// todo we could optimize this matching for cases where we have multiple subscriptions
// using the same filter criteria, we could only filter once and stream to all subscribers
if !logs.ExactMatch(log, criteria) {
continue
}
if err := notifier.Notify(sub.ID, log); err != nil {
return err
}
}
return nil
}
},
)
}
func (s *StreamAPI) prepareBlockHeader(
block *models.Block,
) (*ethTypes.BlockHeader, error) {
h, err := block.Hash()
if err != nil {
s.logger.Error().Err(err).Msg("failed to calculate hash for block by number")
return nil, err
}
blockHeader := ðTypes.BlockHeader{
Number: hexutil.Uint64(block.Height),
Hash: h,
ParentHash: block.ParentBlockHash,
Nonce: gethTypes.BlockNonce{0x1},
Sha3Uncles: gethTypes.EmptyUncleHash,
LogsBloom: gethTypes.CreateBloom(&gethTypes.Receipt{}).Bytes(),
TransactionsRoot: block.TransactionHashRoot,
ReceiptsRoot: block.ReceiptRoot,
Miner: evmTypes.CoinbaseAddress.ToCommon(),
GasLimit: hexutil.Uint64(BlockGasLimit),
Timestamp: hexutil.Uint64(block.Timestamp),
}
txHashes := block.TransactionHashes
if len(txHashes) > 0 {
totalGasUsed := hexutil.Uint64(0)
receipts := gethTypes.Receipts{}
for _, txHash := range txHashes {
txReceipt, err := s.receipts.GetByTransactionID(txHash)
if err != nil {
return nil, err
}
totalGasUsed += hexutil.Uint64(txReceipt.GasUsed)
receipts = append(receipts, txReceipt.ToGethReceipt())
}
blockHeader.GasUsed = totalGasUsed
// TODO(m-Peter): Consider if its worthwhile to move this in storage.
blockHeader.LogsBloom = gethTypes.MergeBloom(receipts).Bytes()
}
return blockHeader, nil
}
func newSubscription[T any](
ctx context.Context,
logger zerolog.Logger,
publisher *models.Publisher[T],
callback func(notifier *rpc.Notifier, sub *rpc.Subscription) func(T) error,
) (*rpc.Subscription, error) {
notifier, supported := rpc.NotifierFromContext(ctx)
if !supported {
return nil, rpc.ErrNotificationsUnsupported
}
rpcSub := notifier.CreateSubscription()
subs := models.NewSubscription(logger, callback(notifier, rpcSub))
l := logger.With().
Str("gateway-subscription-id", fmt.Sprintf("%p", subs)).
Str("ethereum-subscription-id", string(rpcSub.ID)).
Logger()
publisher.Subscribe(subs)
go func() {
defer publisher.Unsubscribe(subs)
for {
select {
case err := <-subs.Error():
l.Debug().Err(err).Msg("subscription returned error")
return
case err := <-rpcSub.Err():
l.Debug().Err(err).Msg("client unsubscribed")
return
}
}
}()
l.Info().Msg("new heads subscription created")
return rpcSub, nil
}