forked from OffchainLabs/nitro
-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.go
318 lines (271 loc) · 10.4 KB
/
main.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
// Copyright 2021-2022, Offchain Labs, Inc.
// For license information, see https://github.com/nitro/blob/master/LICENSE
package main
import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/consensus"
"github.com/ethereum/go-ethereum/core/rawdb"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rlp"
"github.com/offchainlabs/nitro/arbos"
"github.com/offchainlabs/nitro/arbos/arbosState"
"github.com/offchainlabs/nitro/arbos/arbostypes"
"github.com/offchainlabs/nitro/arbos/burn"
"github.com/offchainlabs/nitro/arbos/espresso"
"github.com/offchainlabs/nitro/arbstate"
"github.com/offchainlabs/nitro/arbutil"
"github.com/offchainlabs/nitro/cmd/chaininfo"
"github.com/offchainlabs/nitro/das/dastree"
"github.com/offchainlabs/nitro/gethhook"
"github.com/offchainlabs/nitro/wavmio"
)
func getBlockHeaderByHash(hash common.Hash) *types.Header {
enc, err := wavmio.ResolveTypedPreimage(arbutil.Keccak256PreimageType, hash)
if err != nil {
panic(fmt.Errorf("Error resolving preimage: %w", err))
}
header := &types.Header{}
err = rlp.DecodeBytes(enc, &header)
if err != nil {
panic(fmt.Errorf("Error parsing resolved block header: %w", err))
}
return header
}
func getHotShotCommitment(seqNum uint64) *espresso.Commitment {
headerBytes := espresso.Commitment(wavmio.ReadHotShotCommitment(seqNum))
log.Info("HotShot commitment", "commit", headerBytes)
return &headerBytes
}
type WavmChainContext struct{}
func (c WavmChainContext) Engine() consensus.Engine {
return arbos.Engine{}
}
func (c WavmChainContext) GetHeader(hash common.Hash, num uint64) *types.Header {
header := getBlockHeaderByHash(hash)
if !header.Number.IsUint64() || header.Number.Uint64() != num {
panic(fmt.Sprintf("Retrieved wrong block number for header hash %v -- requested %v but got %v", hash, num, header.Number.String()))
}
return header
}
type WavmInbox struct{}
func (i WavmInbox) PeekSequencerInbox() ([]byte, error) {
pos := wavmio.GetInboxPosition()
res := wavmio.ReadInboxMessage(pos)
log.Info("PeekSequencerInbox", "pos", pos, "res[:8]", res[:8])
return res, nil
}
func (i WavmInbox) GetSequencerInboxPosition() uint64 {
pos := wavmio.GetInboxPosition()
log.Info("GetSequencerInboxPosition", "pos", pos)
return pos
}
func (i WavmInbox) AdvanceSequencerInbox() {
log.Info("AdvanceSequencerInbox")
wavmio.AdvanceInboxMessage()
}
func (i WavmInbox) GetPositionWithinMessage() uint64 {
pos := wavmio.GetPositionWithinMessage()
log.Info("GetPositionWithinMessage", "pos", pos)
return pos
}
func (i WavmInbox) SetPositionWithinMessage(pos uint64) {
log.Info("SetPositionWithinMessage", "pos", pos)
wavmio.SetPositionWithinMessage(pos)
}
func (i WavmInbox) ReadDelayedInbox(seqNum uint64) (*arbostypes.L1IncomingMessage, error) {
log.Info("ReadDelayedMsg", "seqNum", seqNum)
data := wavmio.ReadDelayedInboxMessage(seqNum)
return arbostypes.ParseIncomingL1Message(bytes.NewReader(data), func(batchNum uint64) ([]byte, error) {
return wavmio.ReadInboxMessage(batchNum), nil
})
}
type PreimageDASReader struct {
}
func (dasReader *PreimageDASReader) GetByHash(ctx context.Context, hash common.Hash) ([]byte, error) {
oracle := func(hash common.Hash) ([]byte, error) {
return wavmio.ResolveTypedPreimage(arbutil.Keccak256PreimageType, hash)
}
return dastree.Content(hash, oracle)
}
func (dasReader *PreimageDASReader) HealthCheck(ctx context.Context) error {
return nil
}
func (dasReader *PreimageDASReader) ExpirationPolicy(ctx context.Context) (arbstate.ExpirationPolicy, error) {
return arbstate.DiscardImmediately, nil
}
// To generate:
// key, _ := crypto.HexToECDSA("0000000000000000000000000000000000000000000000000000000000000001")
// sig, _ := crypto.Sign(make([]byte, 32), key)
// println(hex.EncodeToString(sig))
const sampleSignature = "a0b37f8fba683cc68f6574cd43b39f0343a50008bf6ccea9d13231d9e7e2e1e411edc8d307254296264aebfc3dc76cd8b668373a072fd64665b50000e9fcce5201"
// We call this early to populate the secp256k1 ecc basepoint cache in the cached early machine state.
// That means we don't need to re-compute it for every block.
func populateEcdsaCaches() {
signature, err := hex.DecodeString(sampleSignature)
if err != nil {
log.Warn("failed to decode sample signature to populate ECDSA cache", "err", err)
return
}
_, err = crypto.Ecrecover(make([]byte, 32), signature)
if err != nil {
log.Warn("failed to recover signature to populate ECDSA cache", "err", err)
return
}
}
func main() {
wavmio.StubInit()
gethhook.RequireHookedGeth()
glogger := log.NewGlogHandler(log.StreamHandler(os.Stderr, log.TerminalFormat(false)))
glogger.Verbosity(log.LvlError)
log.Root().SetHandler(glogger)
populateEcdsaCaches()
raw := rawdb.NewDatabase(PreimageDb{})
db := state.NewDatabase(raw)
lastBlockHash := wavmio.GetLastBlockHash()
var lastBlockHeader *types.Header
var lastBlockStateRoot common.Hash
if lastBlockHash != (common.Hash{}) {
lastBlockHeader = getBlockHeaderByHash(lastBlockHash)
lastBlockStateRoot = lastBlockHeader.Root
}
log.Info("Initial State", "lastBlockHash", lastBlockHash, "lastBlockStateRoot", lastBlockStateRoot)
statedb, err := state.NewDeterministic(lastBlockStateRoot, db)
if err != nil {
panic(fmt.Sprintf("Error opening state db: %v", err.Error()))
}
readMessage := func(dasEnabled bool) *arbostypes.MessageWithMetadata {
var delayedMessagesRead uint64
if lastBlockHeader != nil {
delayedMessagesRead = lastBlockHeader.Nonce.Uint64()
}
var dasReader arbstate.DataAvailabilityReader
if dasEnabled {
dasReader = &PreimageDASReader{}
}
backend := WavmInbox{}
var keysetValidationMode = arbstate.KeysetPanicIfInvalid
if backend.GetPositionWithinMessage() > 0 {
keysetValidationMode = arbstate.KeysetDontValidate
}
inboxMultiplexer := arbstate.NewInboxMultiplexer(backend, delayedMessagesRead, dasReader, keysetValidationMode)
ctx := context.Background()
message, err := inboxMultiplexer.Pop(ctx)
if err != nil {
panic(fmt.Sprintf("Error reading from inbox multiplexer: %v", err.Error()))
}
return message
}
var newBlock *types.Block
if lastBlockStateRoot != (common.Hash{}) {
// ArbOS has already been initialized.
// Load the chain config and then produce a block normally.
initialArbosState, err := arbosState.OpenSystemArbosState(statedb, nil, true)
if err != nil {
panic(fmt.Sprintf("Error opening initial ArbOS state: %v", err.Error()))
}
chainId, err := initialArbosState.ChainId()
if err != nil {
panic(fmt.Sprintf("Error getting chain ID from initial ArbOS state: %v", err.Error()))
}
genesisBlockNum, err := initialArbosState.GenesisBlockNum()
if err != nil {
panic(fmt.Sprintf("Error getting genesis block number from initial ArbOS state: %v", err.Error()))
}
chainConfigJson, err := initialArbosState.ChainConfig()
if err != nil {
panic(fmt.Sprintf("Error getting chain config from initial ArbOS state: %v", err.Error()))
}
var chainConfig *params.ChainConfig
if len(chainConfigJson) > 0 {
chainConfig = ¶ms.ChainConfig{}
err = json.Unmarshal(chainConfigJson, chainConfig)
if err != nil {
panic(fmt.Sprintf("Error parsing chain config: %v", err.Error()))
}
if chainConfig.ChainID.Cmp(chainId) != 0 {
panic(fmt.Sprintf("Error: chain id mismatch, chainID: %v, chainConfig.ChainID: %v", chainId, chainConfig.ChainID))
}
if chainConfig.ArbitrumChainParams.GenesisBlockNum != genesisBlockNum {
panic(fmt.Sprintf("Error: genesis block number mismatch, genesisBlockNum: %v, chainConfig.ArbitrumParams.GenesisBlockNum: %v", genesisBlockNum, chainConfig.ArbitrumChainParams.GenesisBlockNum))
}
} else {
log.Info("Falling back to hardcoded chain config.")
chainConfig, err = chaininfo.GetChainConfig(chainId, "", genesisBlockNum, []string{}, "")
if err != nil {
panic(err)
}
}
message := readMessage(chainConfig.ArbitrumChainParams.DataAvailabilityCommittee)
chainContext := WavmChainContext{}
batchFetcher := func(batchNum uint64) ([]byte, error) {
return wavmio.ReadInboxMessage(batchNum), nil
}
seqNum := wavmio.GetInboxPosition()
// Espresso-specific validation
// TODO test: https://github.com/EspressoSystems/espresso-sequencer/issues/772
if chainConfig.Espresso {
hotShotCommitment := getHotShotCommitment(seqNum)
jst := message.Message.Header.BlockJustification
if jst == nil {
panic("batch missing espresso justification")
}
hotshotHeader := jst.Header
if *hotShotCommitment != hotshotHeader.Commit() {
panic("invalid hotshot header")
}
var roots = []*espresso.NmtRoot{&hotshotHeader.TransactionsRoot}
var proofs = []*espresso.NmtProof{&message.Message.Header.BlockJustification.Proof}
txs, err := arbos.ParseEspressoTransactions(message.Message)
if err != nil {
panic(err)
}
err = espresso.ValidateBatchTransactions(chainConfig.ChainID.Uint64(), roots, proofs, txs)
if err != nil {
panic(err)
}
}
newBlock, _, err = arbos.ProduceBlock(message.Message, message.DelayedMessagesRead, lastBlockHeader, statedb, chainContext, chainConfig, batchFetcher)
if err != nil {
panic(err)
}
} else {
// Initialize ArbOS with this init message and create the genesis block.
message := readMessage(false)
initMessage, err := message.Message.ParseInitMessage()
if err != nil {
panic(err)
}
chainConfig := initMessage.ChainConfig
if chainConfig == nil {
log.Info("No chain config in the init message. Falling back to hardcoded chain config.")
chainConfig, err = chaininfo.GetChainConfig(initMessage.ChainId, "", 0, []string{}, "")
if err != nil {
panic(err)
}
}
_, err = arbosState.InitializeArbosState(statedb, burn.NewSystemBurner(nil, false), chainConfig, initMessage)
if err != nil {
panic(fmt.Sprintf("Error initializing ArbOS: %v", err.Error()))
}
newBlock = arbosState.MakeGenesisBlock(common.Hash{}, 0, 0, statedb.IntermediateRoot(true), chainConfig)
}
newBlockHash := newBlock.Hash()
log.Info("Final State", "newBlockHash", newBlockHash, "StateRoot", newBlock.Root())
extraInfo := types.DeserializeHeaderExtraInformation(newBlock.Header())
if extraInfo.ArbOSFormatVersion == 0 {
panic(fmt.Sprintf("Error deserializing header extra info: %+v", newBlock.Header()))
}
wavmio.SetLastBlockHash(newBlockHash)
wavmio.SetSendRoot(extraInfo.SendRoot)
wavmio.StubFinal()
}