-
Notifications
You must be signed in to change notification settings - Fork 24
/
ethereum_rosetta.go
375 lines (324 loc) · 10.9 KB
/
ethereum_rosetta.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
package ethereum
import (
"context"
"fmt"
"math/big"
"strconv"
"strings"
"go.uber.org/zap"
"golang.org/x/xerrors"
"google.golang.org/protobuf/types/known/anypb"
"github.com/coinbase/chainstorage/internal/blockchain/bootstrap"
"github.com/coinbase/chainstorage/internal/blockchain/parser/ethereum/types"
"github.com/coinbase/chainstorage/internal/blockchain/parser/internal"
"github.com/coinbase/chainstorage/internal/config"
"github.com/coinbase/chainstorage/internal/utils/log"
"github.com/coinbase/chainstorage/protos/coinbase/c3/common"
api "github.com/coinbase/chainstorage/protos/coinbase/chainstorage"
rosetta "github.com/coinbase/chainstorage/protos/coinbase/crypto/rosetta/types"
)
const (
// UnclesRewardMultiplier is the uncle reward multiplier.
// Ref: https://github.com/coinbase/rosetta-ethereum/blob/79a9b97d0a3ed08ae151a3f313aa57b88dd128a4/ethereum/types.go#L108
UnclesRewardMultiplier = 32
// MaxUncleDepth is the maximum depth for
// an uncle to be rewarded.
// Ref: https://github.com/coinbase/rosetta-ethereum/blob/79a9b97d0a3ed08ae151a3f313aa57b88dd128a4/ethereum/types.go#L112
MaxUncleDepth = int64(8)
// ethereumZeroAddress is the zero address
ethereumZeroAddress = "0x0000000000000000000000000000000000000000"
)
type (
ethereumRosettaParserImpl struct {
logger *zap.Logger
config *config.Config
nativeParser internal.NativeParser
}
)
var (
ethereumRosettaCurrency = rosetta.Currency{
Symbol: "ETH",
Decimals: 18,
}
FrontierBlockReward = int64(5e+18) // Block reward in wei for successfully mining a block
ByzantiumBlockReward = int64(3e+18) // Block reward in wei for successfully mining a block upward from Byzantium
ConstantinopleBlockReward = int64(2e+18) // Block reward in wei for successfully mining a block upward from Constantinople
)
func NewEthereumRosettaParser(params internal.ParserParams, nativeParser internal.NativeParser, opts ...internal.ParserFactoryOption) (internal.RosettaParser, error) {
// TODO: add support for more node types so that other chains can build rosetta parsers backed by this parser
options := ðereumParserOptions{
nodeType: types.EthereumNodeType_ARCHIVAL,
}
for _, opt := range opts {
opt(options)
}
return ðereumRosettaParserImpl{
logger: log.WithPackage(params.Logger),
config: params.Config,
nativeParser: nativeParser,
}, nil
}
func (p *ethereumRosettaParserImpl) ParseBlock(ctx context.Context, rawBlock *api.Block) (*api.RosettaBlock, error) {
// TODO(ben): Contact rosetta team to get genesis info for holesky.
if p.config.Network() == common.Network_NETWORK_ETHEREUM_HOLESKY {
return nil, internal.ErrNotImplemented
}
nativeBlock, err := p.nativeParser.ParseBlock(ctx, rawBlock)
if err != nil {
return nil, xerrors.Errorf("failed to parse block into native format: %w", err)
}
block := nativeBlock.GetEthereum()
if block == nil {
return nil, xerrors.New("failed to find ethereum block")
}
blockIdentifier := &rosetta.BlockIdentifier{
Index: int64(rawBlock.GetMetadata().GetHeight()),
Hash: rawBlock.GetMetadata().GetHash(),
}
parentBlockIdentifier := &rosetta.BlockIdentifier{
Index: int64(rawBlock.GetMetadata().GetParentHeight()),
Hash: rawBlock.GetMetadata().GetParentHash(),
}
transactions, err := p.getRosettaTransactions(block, rawBlock.GetEthereum())
if err != nil {
return nil, xerrors.Errorf("failed to parse block transactions: %w", err)
}
if nativeBlock.Height == 0 {
// For ethereum mainnet, we use this allocation file as reference:
// https://github.com/coinbase/rosetta-ethereum/blob/master/rosetta-cli-conf/mainnet/bootstrap_balances.json
genesisAllocation, err := bootstrap.GenerateGenesisAllocations(p.config.Chain.Network)
if err != nil {
return nil, err
}
genesisTransactions, err := p.getGenesisTransactions(genesisAllocation)
if err != nil {
return nil, xerrors.Errorf("failed to generate genesis transactions: %w", err)
}
transactions = append(transactions, genesisTransactions...)
}
return &api.RosettaBlock{
Block: &rosetta.Block{
BlockIdentifier: blockIdentifier,
ParentBlockIdentifier: parentBlockIdentifier,
Timestamp: block.GetHeader().Timestamp,
Transactions: transactions,
Metadata: nil,
},
}, nil
}
func (p *ethereumRosettaParserImpl) getRosettaTransactions(block *api.EthereumBlock, blobData *api.EthereumBlobdata) ([]*rosetta.Transaction, error) {
rosettaTxs, err := getRosettaTransactionsFromCSBlock(block, blobData, block.Header.Miner, ðereumRosettaCurrency, p.feeOps, p.tokenTransferOpsFn)
if err != nil {
return nil, err
}
rosettaTransactions := make([]*rosetta.Transaction, len(rosettaTxs)+1)
// compute the reward transaction
rosettaTransactions[0] = p.createBlockRewardTransaction(block)
for i := range rosettaTxs {
rosettaTransactions[i+1] = rosettaTxs[i]
}
return rosettaTransactions, nil
}
// Ref: https://github.com/coinbase/rosetta-ethereum/blob/3a9db2f08ab5fae90cd8d08876ba69a9097e29f5/ethereum/client.go#L948
func (p *ethereumRosettaParserImpl) miningReward(blockHeight uint64) int64 {
if blockHeight == 0 {
return 0
}
mergeHeight, ok := mergeHeights[p.config.Chain.Network]
if !ok {
return 0
}
var blockReward int64
switch p.config.Chain.Network {
case common.Network_NETWORK_ETHEREUM_MAINNET:
blockReward = FrontierBlockReward
if blockHeight >= ethByzantiumHardForkHeight {
blockReward = ByzantiumBlockReward
}
if blockHeight >= ethConstantinopleForkHeight {
blockReward = ConstantinopleBlockReward
}
// No more mining reward after ETH merge
if blockHeight >= mergeHeight {
blockReward = 0
}
case common.Network_NETWORK_ETHEREUM_GOERLI:
// for goerli, initial block reward is 2 ETH
blockReward = ConstantinopleBlockReward
// No more mining reward after ETH merge
if blockHeight >= mergeHeight {
blockReward = 0
}
}
return blockReward
}
// Ref: https://github.com/coinbase/rosetta-ethereum/blob/3a9db2f08ab5fae90cd8d08876ba69a9097e29f5/ethereum/client.go#L967
func (p *ethereumRosettaParserImpl) createBlockRewardTransaction(block *api.EthereumBlock) *rosetta.Transaction {
var ops []*rosetta.Operation
miningReward := p.miningReward(block.Header.Number)
// Calculate miner rewards
minerReward := miningReward
numUncles := len(block.Uncles)
if numUncles > 0 {
reward := new(big.Float)
uncleReward := float64(numUncles) / UnclesRewardMultiplier
rewardFloat := reward.Mul(big.NewFloat(uncleReward), big.NewFloat(float64(miningReward)))
rewardInt, _ := rewardFloat.Int64()
minerReward += rewardInt
}
miningRewardOp := &rosetta.Operation{
OperationIdentifier: &rosetta.OperationIdentifier{
Index: 0,
},
Type: opTypeMinerReward,
Status: opStatusSuccess,
Account: &rosetta.AccountIdentifier{
Address: block.GetHeader().GetMiner(),
},
Amount: &rosetta.Amount{
Value: strconv.FormatInt(minerReward, 10),
Currency: ðereumRosettaCurrency,
},
Metadata: map[string]*anypb.Any{},
}
ops = append(ops, miningRewardOp)
// Calculate uncle rewards
for _, b := range block.Uncles {
uncleMiner := b.Miner
uncleBlock := int64(b.Number)
uncleRewardBlock := new(
big.Int,
).Mul(
big.NewInt(uncleBlock+MaxUncleDepth-int64(block.Header.Number)),
big.NewInt(miningReward/MaxUncleDepth),
)
uncleRewardOp := &rosetta.Operation{
OperationIdentifier: &rosetta.OperationIdentifier{
Index: int64(len(ops)),
},
Type: opTypeUncleReward,
Status: opStatusSuccess,
Account: &rosetta.AccountIdentifier{
Address: uncleMiner,
},
Amount: &rosetta.Amount{
Value: uncleRewardBlock.String(),
Currency: ðereumRosettaCurrency,
},
Metadata: map[string]*anypb.Any{},
}
ops = append(ops, uncleRewardOp)
}
return &rosetta.Transaction{
TransactionIdentifier: &rosetta.TransactionIdentifier{
Hash: block.Header.Hash,
},
Operations: ops,
Metadata: map[string]*anypb.Any{},
}
}
func (p *ethereumRosettaParserImpl) feeOps(transaction *api.EthereumTransaction, miner string, block *api.EthereumBlock) ([]*rosetta.Operation, error) {
feeDetails, err := getFeeDetails(transaction, block)
if err != nil {
return nil, xerrors.Errorf("failed to calculate ethereum fee details: %w", err)
}
minerEarnedAmount := feeDetails.feeAmount
if feeDetails.feeBurned != nil {
minerEarnedAmount = new(big.Int).Sub(feeDetails.feeAmount, feeDetails.feeBurned)
}
ops := []*rosetta.Operation{
{
OperationIdentifier: &rosetta.OperationIdentifier{
Index: 0,
},
Type: opTypeFee,
Status: opStatusSuccess,
Account: &rosetta.AccountIdentifier{
Address: transaction.From,
},
Amount: &rosetta.Amount{
Value: new(big.Int).Neg(minerEarnedAmount).String(),
Currency: ðereumRosettaCurrency,
},
Metadata: map[string]*anypb.Any{},
},
{
OperationIdentifier: &rosetta.OperationIdentifier{
Index: 1,
},
RelatedOperations: []*rosetta.OperationIdentifier{
{
Index: 0,
},
},
Type: opTypeFee,
Status: opStatusSuccess,
Account: &rosetta.AccountIdentifier{
Address: miner,
},
Amount: &rosetta.Amount{
Value: minerEarnedAmount.String(),
Currency: ðereumRosettaCurrency,
},
Metadata: map[string]*anypb.Any{},
},
}
if feeDetails.feeBurned == nil {
return ops, nil
}
burntOp := &rosetta.Operation{
OperationIdentifier: &rosetta.OperationIdentifier{
Index: 2,
},
Type: opTypeFee,
Status: opStatusSuccess,
Account: &rosetta.AccountIdentifier{
Address: transaction.From,
},
Amount: &rosetta.Amount{
Value: new(big.Int).Neg(feeDetails.feeBurned).String(),
Currency: ðereumRosettaCurrency,
},
}
ops = append(ops, burntOp)
return ops, nil
}
func (p *ethereumRosettaParserImpl) tokenTransferOpsFn(transaction *api.EthereumTransaction, startIndex int) ([]*rosetta.Operation, error) {
return []*rosetta.Operation{}, nil
}
func (p *ethereumRosettaParserImpl) getGenesisTransactions(allocations []*bootstrap.GenesisAllocation) ([]*rosetta.Transaction, error) {
var genesisTxns []*rosetta.Transaction
for _, allo := range allocations {
address := allo.AccountIdentifier.Address
_, err := internal.ChecksumAddress(address)
if err != nil {
return nil, xerrors.Errorf("%s is not a valid address", address)
}
addressLower := strings.ToLower(address)
genesisOp := &rosetta.Operation{
OperationIdentifier: &rosetta.OperationIdentifier{
Index: 0,
},
Type: opTypeGenesis,
Status: opStatusSuccess,
Account: &rosetta.AccountIdentifier{
Address: addressLower,
},
Amount: &rosetta.Amount{
Value: allo.Value,
Currency: ðereumRosettaCurrency,
},
Metadata: map[string]*anypb.Any{},
}
txnIdentifier := fmt.Sprintf("GENESIS_%s", addressLower[2:])
txn := &rosetta.Transaction{
TransactionIdentifier: &rosetta.TransactionIdentifier{
Hash: txnIdentifier,
},
Operations: []*rosetta.Operation{genesisOp},
Metadata: map[string]*anypb.Any{},
}
genesisTxns = append(genesisTxns, txn)
}
return genesisTxns, nil
}