-
Notifications
You must be signed in to change notification settings - Fork 19.5k
/
simulated_beacon.go
231 lines (209 loc) · 6.49 KB
/
simulated_beacon.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
// Copyright 2023 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package catalyst
import (
"errors"
"fmt"
"sync"
"time"
"github.com/ethereum/go-ethereum/beacon/engine"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/node"
"github.com/ethereum/go-ethereum/rpc"
)
// withdrawalQueue implements a FIFO queue which holds withdrawals that are
// pending inclusion.
type withdrawalQueue struct {
pending chan *types.Withdrawal
}
// add queues a withdrawal for future inclusion.
func (w *withdrawalQueue) add(withdrawal *types.Withdrawal) error {
select {
case w.pending <- withdrawal:
break
default:
return errors.New("withdrawal queue full")
}
return nil
}
// gatherPending returns a number of queued withdrawals up to a maximum count.
func (w *withdrawalQueue) gatherPending(maxCount int) []*types.Withdrawal {
withdrawals := []*types.Withdrawal{}
for {
select {
case withdrawal := <-w.pending:
withdrawals = append(withdrawals, withdrawal)
if len(withdrawals) == maxCount {
break
}
default:
return withdrawals
}
}
}
type SimulatedBeacon struct {
shutdownCh chan struct{}
eth *eth.Ethereum
period uint64
withdrawals withdrawalQueue
feeRecipient common.Address
feeRecipientLock sync.Mutex // lock gates concurrent access to the feeRecipient
engineAPI *ConsensusAPI
curForkchoiceState engine.ForkchoiceStateV1
lastBlockTime uint64
}
func NewSimulatedBeacon(period uint64, eth *eth.Ethereum) (*SimulatedBeacon, error) {
chainConfig := eth.APIBackend.ChainConfig()
if !chainConfig.IsDevMode {
return nil, errors.New("incompatible pre-existing chain configuration")
}
block := eth.BlockChain().CurrentBlock()
current := engine.ForkchoiceStateV1{
HeadBlockHash: block.Hash(),
SafeBlockHash: block.Hash(),
FinalizedBlockHash: block.Hash(),
}
engineAPI := NewConsensusAPI(eth)
// if genesis block, send forkchoiceUpdated to trigger transition to PoS
if block.Number.Sign() == 0 {
if _, err := engineAPI.ForkchoiceUpdatedV2(current, nil); err != nil {
return nil, err
}
}
return &SimulatedBeacon{
eth: eth,
period: period,
shutdownCh: make(chan struct{}),
engineAPI: engineAPI,
lastBlockTime: block.Time,
curForkchoiceState: current,
withdrawals: withdrawalQueue{make(chan *types.Withdrawal, 20)},
}, nil
}
func (c *SimulatedBeacon) setFeeRecipient(feeRecipient common.Address) {
c.feeRecipientLock.Lock()
c.feeRecipient = feeRecipient
c.feeRecipientLock.Unlock()
}
// Start invokes the SimulatedBeacon life-cycle function in a goroutine.
func (c *SimulatedBeacon) Start() error {
if c.period == 0 {
go c.loopOnDemand()
} else {
go c.loop()
}
return nil
}
// Stop halts the SimulatedBeacon service.
func (c *SimulatedBeacon) Stop() error {
close(c.shutdownCh)
return nil
}
// sealBlock initiates payload building for a new block and creates a new block
// with the completed payload.
func (c *SimulatedBeacon) sealBlock(withdrawals []*types.Withdrawal) error {
tstamp := uint64(time.Now().Unix())
if tstamp <= c.lastBlockTime {
tstamp = c.lastBlockTime + 1
}
c.feeRecipientLock.Lock()
feeRecipient := c.feeRecipient
c.feeRecipientLock.Unlock()
fcResponse, err := c.engineAPI.ForkchoiceUpdatedV2(c.curForkchoiceState, &engine.PayloadAttributes{
Timestamp: tstamp,
SuggestedFeeRecipient: feeRecipient,
Withdrawals: withdrawals,
})
if err != nil {
return fmt.Errorf("error calling forkchoice update: %v", err)
}
envelope, err := c.engineAPI.getFullPayload(*fcResponse.PayloadID)
if err != nil {
return fmt.Errorf("error retrieving payload: %v", err)
}
payload := envelope.ExecutionPayload
// mark the payload as canon
if _, err = c.engineAPI.NewPayloadV2(*payload); err != nil {
return fmt.Errorf("failed to mark payload as canonical: %v", err)
}
c.curForkchoiceState = engine.ForkchoiceStateV1{
HeadBlockHash: payload.BlockHash,
SafeBlockHash: payload.BlockHash,
FinalizedBlockHash: payload.BlockHash,
}
// mark the block containing the payload as canonical
if _, err = c.engineAPI.ForkchoiceUpdatedV2(c.curForkchoiceState, nil); err != nil {
return fmt.Errorf("failed to mark block as canonical: %v", err)
}
c.lastBlockTime = payload.Timestamp
return nil
}
// loopOnDemand runs the block production loop for "on-demand" configuration (period = 0)
func (c *SimulatedBeacon) loopOnDemand() {
var (
newTxs = make(chan core.NewTxsEvent)
sub = c.eth.TxPool().SubscribeNewTxsEvent(newTxs)
)
defer sub.Unsubscribe()
for {
select {
case <-c.shutdownCh:
return
case w := <-c.withdrawals.pending:
withdrawals := append(c.withdrawals.gatherPending(9), w)
if err := c.sealBlock(withdrawals); err != nil {
log.Error("Error performing sealing-work", "err", err)
return
}
case <-newTxs:
withdrawals := c.withdrawals.gatherPending(10)
if err := c.sealBlock(withdrawals); err != nil {
log.Error("Error performing sealing-work", "err", err)
return
}
}
}
}
// loopOnDemand runs the block production loop for non-zero period configuration
func (c *SimulatedBeacon) loop() {
timer := time.NewTimer(0)
for {
select {
case <-c.shutdownCh:
return
case <-timer.C:
withdrawals := c.withdrawals.gatherPending(10)
if err := c.sealBlock(withdrawals); err != nil {
log.Error("Error performing sealing-work", "err", err)
return
}
timer.Reset(time.Second * time.Duration(c.period))
}
}
}
func RegisterSimulatedBeaconAPIs(stack *node.Node, sim *SimulatedBeacon) {
stack.RegisterAPIs([]rpc.API{
{
Namespace: "dev",
Service: &api{sim},
Version: "1.0",
},
})
}