-
Notifications
You must be signed in to change notification settings - Fork 19
/
nullchain.go
374 lines (316 loc) · 10.3 KB
/
nullchain.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
// Copyright (c) 2022 Gobalsky Labs Limited
//
// Use of this software is governed by the Business Source License included
// in the LICENSE.VEGA file and at https://www.mariadb.com/bsl11.
//
// Change Date: 18 months from the later of the date of the first publicly
// available Distribution of this version of the repository, and 25 June 2022.
//
// On the date above, in accordance with the Business Source License, use
// of this software will be governed by version 3 or later of the GNU General
// Public License.
package nullchain
import (
"context"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"net"
"net/http"
"strconv"
"sync"
"time"
"code.vegaprotocol.io/vega/core/blockchain"
vgcrypto "code.vegaprotocol.io/vega/libs/crypto"
vgfs "code.vegaprotocol.io/vega/libs/fs"
vgrand "code.vegaprotocol.io/vega/libs/rand"
"code.vegaprotocol.io/vega/logging"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/p2p"
"github.com/tendermint/tendermint/proto/tendermint/crypto"
"github.com/tendermint/tendermint/proto/tendermint/types"
tmctypes "github.com/tendermint/tendermint/rpc/core/types"
tmtypes "github.com/tendermint/tendermint/types"
)
const namedLogger = "nullchain"
var (
ErrNotImplemented = errors.New("not implemented for nullblockchain")
ErrGenesisFileRequired = errors.New("--blockchain.nullchain.genesis-file is required")
)
//go:generate go run github.com/golang/mock/mockgen -destination mocks/application_service_mock.go -package mocks code.vegaprotocol.io/vega/core/blockchain/nullchain ApplicationService
type ApplicationService interface {
InitChain(res abci.RequestInitChain) (resp abci.ResponseInitChain)
BeginBlock(req abci.RequestBeginBlock) (resp abci.ResponseBeginBlock)
EndBlock(req abci.RequestEndBlock) (resp abci.ResponseEndBlock)
Commit() (resp abci.ResponseCommit)
DeliverTx(req abci.RequestDeliverTx) (resp abci.ResponseDeliverTx)
Info(req abci.RequestInfo) (resp abci.ResponseInfo)
}
type NullBlockchain struct {
log *logging.Logger
app ApplicationService
srvAddress string
chainID string
genesisFile string
genesisTime time.Time
blockDuration time.Duration
transactionsPerBlock uint64
now time.Time
blockHeight int64
pending []*abci.RequestDeliverTx
srv *http.Server
mu sync.Mutex
}
func NewClient(
log *logging.Logger,
cfg blockchain.NullChainConfig,
) *NullBlockchain {
// setup logger
log = log.Named(namedLogger)
log.SetLevel(cfg.Level.Get())
now := time.Now()
n := &NullBlockchain{
log: log,
srvAddress: net.JoinHostPort(cfg.IP, strconv.Itoa(cfg.Port)),
chainID: vgrand.RandomStr(12),
transactionsPerBlock: cfg.TransactionsPerBlock,
blockDuration: cfg.BlockDuration.Duration,
genesisFile: cfg.GenesisFile,
genesisTime: now,
now: now,
blockHeight: 1,
pending: make([]*abci.RequestDeliverTx, 0),
}
return n
}
func (n *NullBlockchain) SetABCIApp(app ApplicationService) {
n.app = app
}
// ReloadConf update the internal configuration.
func (n *NullBlockchain) ReloadConf(cfg blockchain.Config) {
n.mu.Lock()
defer n.mu.Unlock()
n.log.Info("reloading configuration")
if n.log.GetLevel() != cfg.Level.Get() {
n.log.Info("updating log level",
logging.String("old", n.log.GetLevel().String()),
logging.String("new", cfg.Level.String()),
)
n.log.SetLevel(cfg.Level.Get())
}
n.blockDuration = cfg.Null.BlockDuration.Duration
n.transactionsPerBlock = cfg.Null.TransactionsPerBlock
}
func (n *NullBlockchain) StartChain() error {
// call info to keep the flow the same, and allow things like snapshots to initialise
n.app.Info(abci.RequestInfo{})
err := n.InitChain(n.genesisFile)
if err != nil {
return err
}
// Start the first block
n.BeginBlock()
return nil
}
func (n *NullBlockchain) processBlock() {
n.log.Debugf("processing block %d with %d transactions", n.blockHeight, len(n.pending))
for _, tx := range n.pending {
n.app.DeliverTx(*tx)
}
n.pending = n.pending[:0]
n.EndBlock()
n.app.Commit()
// Increment time, blockheight, and start a new block
n.blockHeight++
n.now = n.now.Add(n.blockDuration)
n.BeginBlock()
}
func (n *NullBlockchain) handleTransaction(tx []byte) {
n.mu.Lock()
defer n.mu.Unlock()
n.pending = append(n.pending, &abci.RequestDeliverTx{Tx: tx})
n.log.Debugf("transaction added to block: %d of %d", len(n.pending), n.transactionsPerBlock)
if len(n.pending) == int(n.transactionsPerBlock) {
n.processBlock()
}
}
// ForwardTime moves the chain time forward by the given duration, delivering any pending
// transaction and creating any extra empty blocks if time is stepped forward by more than
// a block duration.
func (n *NullBlockchain) ForwardTime(d time.Duration) {
n.log.Debugf("time-forwarding by %s", d)
nBlocks := d / n.blockDuration
if nBlocks == 0 {
n.log.Debugf("not a full block-duration, not moving time: %s < %s", d, n.blockDuration)
return
}
n.mu.Lock()
defer n.mu.Unlock()
for i := 0; i < int(nBlocks); i++ {
n.processBlock()
}
}
// InitChain processes the given genesis file setting the chain's time, and passing the
// appstate through to the processors InitChain.
func (n *NullBlockchain) InitChain(genesisFile string) error {
n.log.Debugf("creating chain",
logging.String("genesisFile", genesisFile),
)
exists, err := vgfs.FileExists(genesisFile)
if !exists || err != nil {
return ErrGenesisFileRequired
}
b, err := vgfs.ReadFile(genesisFile)
if err != nil {
return err
}
// Parse the appstate of the genesis file, same layout as a TM genesis-file
genesis := struct {
GenesisTime *time.Time `json:"genesis_time"`
ChainID string `json:"chain_id"`
Appstate json.RawMessage `json:"app_state"`
}{}
err = json.Unmarshal(b, &genesis)
if err != nil {
return err
}
// Set genesis-time and chain-id from genesis file
if genesis.GenesisTime != nil {
n.genesisTime = *genesis.GenesisTime
n.now = *genesis.GenesisTime
}
if len(genesis.ChainID) != 0 {
n.chainID = genesis.ChainID
}
// read appstate so that we can set the validators
appstate := struct {
Validators map[string]struct{} `json:"validators"`
}{}
err = json.Unmarshal(genesis.Appstate, &appstate)
if err != nil {
return err
}
validators := make([]abci.ValidatorUpdate, 0, len(appstate.Validators))
for k := range appstate.Validators {
pubKey, _ := base64.StdEncoding.DecodeString(k)
validators = append(validators,
abci.ValidatorUpdate{
PubKey: crypto.PublicKey{
Sum: &crypto.PublicKey_Ed25519{
Ed25519: pubKey,
},
},
},
)
}
n.log.Debug("sending InitChain into core",
logging.String("chainID", n.chainID),
logging.Int64("blockHeight", n.blockHeight),
logging.String("time", n.now.String()),
logging.Int("n_validators", len(validators)),
)
n.app.InitChain(
abci.RequestInitChain{
Time: n.now,
ChainId: n.chainID,
InitialHeight: n.blockHeight,
AppStateBytes: genesis.Appstate,
Validators: validators,
},
)
return nil
}
func (n *NullBlockchain) BeginBlock() *NullBlockchain {
n.log.Debug("sending BeginBlock",
logging.String("time", n.now.String()),
)
hash, _ := hex.DecodeString(vgcrypto.RandomHash())
r := abci.RequestBeginBlock{
Header: types.Header{
Time: n.now,
Height: n.blockHeight,
ChainID: n.chainID,
},
Hash: hash,
}
n.app.BeginBlock(r)
return n
}
func (n *NullBlockchain) EndBlock() *NullBlockchain {
n.log.Debug("sending EndBlock",
logging.Int64("blockHeight", n.blockHeight),
)
r := abci.RequestEndBlock{
Height: n.blockHeight,
}
n.app.EndBlock(r)
return n
}
func (n *NullBlockchain) GetGenesisTime(context.Context) (time.Time, error) {
return n.genesisTime, nil
}
func (n *NullBlockchain) GetChainID(context.Context) (string, error) {
return n.chainID, nil
}
func (n *NullBlockchain) GetStatus(context.Context) (*tmctypes.ResultStatus, error) {
return &tmctypes.ResultStatus{
NodeInfo: p2p.DefaultNodeInfo{
Version: "0.34.20",
},
SyncInfo: tmctypes.SyncInfo{
CatchingUp: false,
},
}, nil
}
func (n *NullBlockchain) GetNetworkInfo(context.Context) (*tmctypes.ResultNetInfo, error) {
return &tmctypes.ResultNetInfo{
Listening: true,
Listeners: []string{},
NPeers: 0,
}, nil
}
func (n *NullBlockchain) GetUnconfirmedTxCount(context.Context) (int, error) {
n.mu.Lock()
defer n.mu.Unlock()
return len(n.pending), nil
}
func (n *NullBlockchain) Health(_ context.Context) (*tmctypes.ResultHealth, error) {
return &tmctypes.ResultHealth{}, nil
}
func (n *NullBlockchain) SendTransactionAsync(ctx context.Context, tx []byte) (*tmctypes.ResultBroadcastTx, error) {
go func() {
n.handleTransaction(tx)
}()
randHash := []byte(vgrand.RandomStr(64))
return &tmctypes.ResultBroadcastTx{Hash: randHash}, nil
}
func (n *NullBlockchain) CheckTransaction(ctx context.Context, tx []byte) (*tmctypes.ResultCheckTx, error) {
return &tmctypes.ResultCheckTx{}, nil
}
func (n *NullBlockchain) SendTransactionSync(ctx context.Context, tx []byte) (*tmctypes.ResultBroadcastTx, error) {
n.handleTransaction(tx)
randHash := []byte(vgrand.RandomStr(64))
return &tmctypes.ResultBroadcastTx{Hash: randHash}, nil
}
func (n *NullBlockchain) SendTransactionCommit(ctx context.Context, tx []byte) (*tmctypes.ResultBroadcastTxCommit, error) {
// I think its worth only implementing this if needed. With time-forwarding we already have
// control over when a block ends and gets committed, so I don't think its worth adding the
// the complexity of trying to keep track of tx deliveries here.
n.log.Error("not implemented")
randHash := []byte(vgrand.RandomStr(64))
return &tmctypes.ResultBroadcastTxCommit{Hash: randHash}, ErrNotImplemented
}
func (n *NullBlockchain) Validators(_ context.Context, _ *int64) ([]*tmtypes.Validator, error) {
// TODO: if we are feeling brave we, could pretend to have a validator set and open
// up the nullblockchain to more code paths
return []*tmtypes.Validator{}, nil
}
func (n *NullBlockchain) GenesisValidators(_ context.Context) ([]*tmtypes.Validator, error) {
n.log.Error("not implemented")
return nil, ErrNotImplemented
}
func (n *NullBlockchain) Subscribe(context.Context, func(tmctypes.ResultEvent) error, ...string) error {
n.log.Error("not implemented")
return ErrNotImplemented
}