-
Notifications
You must be signed in to change notification settings - Fork 18
/
cmd-x-index-sig-exists.go
330 lines (303 loc) · 8.18 KB
/
cmd-x-index-sig-exists.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
package main
import (
"context"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/dustin/go-humanize"
"github.com/gagliardetto/solana-go"
"github.com/ipfs/go-cid"
"github.com/ipfs/go-libipfs/blocks"
"github.com/ipld/go-car"
"github.com/rpcpool/yellowstone-faithful/bucketteer"
"github.com/rpcpool/yellowstone-faithful/indexes"
"github.com/rpcpool/yellowstone-faithful/indexmeta"
"github.com/rpcpool/yellowstone-faithful/iplddecoders"
"github.com/rpcpool/yellowstone-faithful/readahead"
concurrently "github.com/tejzpr/ordered-concurrently/v3"
"github.com/urfave/cli/v2"
"k8s.io/klog/v2"
)
func newCmd_Index_sigExists() *cli.Command {
var verify bool
var epoch uint64
var network indexes.Network
return &cli.Command{
Name: "sig-exists",
Description: "Create sig-exists index from a CAR file",
ArgsUsage: "<car-path> <index-dir>",
Before: func(c *cli.Context) error {
if network == "" {
network = indexes.NetworkMainnet
}
return nil
},
Flags: []cli.Flag{
// verify hash of transactions:
&cli.BoolFlag{
Name: "verify-hash",
Usage: "verify hash of transactions",
Value: false,
},
// w number of workers:
&cli.UintFlag{
Name: "w",
Usage: "number of workers",
Value: uint(runtime.NumCPU()) * 3,
},
&cli.BoolFlag{
Name: "verify",
Usage: "verify the index after creating it",
Destination: &verify,
},
&cli.Uint64Flag{
Name: "epoch",
Usage: "epoch",
Destination: &epoch,
Required: true,
},
&cli.StringFlag{
Name: "network",
Usage: "network",
Destination: (*string)(&network),
Action: func(c *cli.Context, v string) error {
if !indexes.IsValidNetwork(indexes.Network(v)) {
return fmt.Errorf("invalid network: %s", v)
}
return nil
},
},
},
Action: func(c *cli.Context) error {
carPath := c.Args().First()
var file fs.File
var err error
if carPath == "-" {
file = os.Stdin
} else {
file, err = os.Open(carPath)
if err != nil {
klog.Exit(err.Error())
}
defer file.Close()
}
cachingReader, err := readahead.NewCachingReaderFromReader(file, readahead.DefaultChunkSize)
if err != nil {
klog.Exitf("Failed to create caching reader: %s", err)
}
rd, err := car.NewCarReader(cachingReader)
if err != nil {
klog.Exitf("Failed to open CAR: %s", err)
}
rootCID := rd.Header.Roots[0]
{
roots := rd.Header.Roots
klog.Infof("Roots: %d", len(roots))
for i, root := range roots {
if i == 0 && len(roots) == 1 {
klog.Infof("- %s (Epoch CID)", root.String())
} else {
klog.Infof("- %s", root.String())
}
}
}
indexDir := c.Args().Get(1)
if ok, err := isDirectory(indexDir); err != nil {
return err
} else if !ok {
return fmt.Errorf("index-dir is not a directory")
}
klog.Infof("Creating sig-exists index for %s", carPath)
indexFilePath := formatSigExistsIndexFilePath(indexDir, epoch, rootCID, network)
index, err := bucketteer.NewWriter(
indexFilePath,
)
if err != nil {
return fmt.Errorf("error while opening sig-exists index writer: %w", err)
}
defer func() {
if err := index.Close(); err != nil {
klog.Errorf("Error while closing: %s", err)
}
}()
startedAt := time.Now()
numTransactionsSeen := 0
defer func() {
klog.Infof("Finished in %s", time.Since(startedAt))
klog.Infof("Indexed %s transactions", humanize.Comma(int64(numTransactionsSeen)))
}()
dotEvery := 100_000
klog.Infof("A dot is printed every %s transactions", humanize.Comma(int64(dotEvery)))
numWorkers := c.Uint("w")
if numWorkers == 0 {
numWorkers = uint(runtime.NumCPU())
}
workerInputChan := make(chan concurrently.WorkFunction, numWorkers)
waitExecuted := new(sync.WaitGroup)
waitResultsReceived := new(sync.WaitGroup)
numReceivedAtomic := new(atomic.Int64)
outputChan := concurrently.Process(
c.Context,
workerInputChan,
&concurrently.Options{PoolSize: int(numWorkers), OutChannelBuffer: int(numWorkers)},
)
go func() {
// process the results from the workers
for result := range outputChan {
switch resValue := result.Value.(type) {
case error:
panic(resValue)
case SignatureAndSlot:
sig := resValue.Signature
{
index.Put(sig)
}
waitResultsReceived.Done()
numReceivedAtomic.Add(-1)
default:
panic(fmt.Errorf("unexpected result type: %T", result.Value))
}
}
}()
for {
block, err := rd.Next()
if err != nil {
if errors.Is(err, io.EOF) {
fmt.Println("EOF")
break
}
return err
}
kind := iplddecoders.Kind(block.RawData()[1])
switch kind {
case iplddecoders.KindTransaction:
numTransactionsSeen++
if numTransactionsSeen%dotEvery == 0 {
fmt.Print(".")
}
if numTransactionsSeen%10_000_000 == 0 {
fmt.Println(humanize.Comma(int64(numTransactionsSeen)))
}
{
waitExecuted.Add(1)
waitResultsReceived.Add(1)
numReceivedAtomic.Add(1)
workerInputChan <- newSignatureSlot(
block,
func() {
waitExecuted.Done()
},
)
}
default:
continue
}
}
{
klog.Infof("Waiting for all transactions to be processed...")
waitExecuted.Wait()
klog.Infof("All transactions processed.")
klog.Infof("Waiting to receive all results...")
close(workerInputChan)
waitResultsReceived.Wait()
klog.Infof("All results received")
}
klog.Info("Sealing index...")
sealingStartedAt := time.Now()
meta := indexmeta.Meta{}
if err := meta.AddUint64(indexmeta.MetadataKey_Epoch, epoch); err != nil {
return fmt.Errorf("failed to add epoch to sig_exists index metadata: %w", err)
}
if err := meta.AddCid(indexmeta.MetadataKey_RootCid, rootCID); err != nil {
return fmt.Errorf("failed to add root cid to sig_exists index metadata: %w", err)
}
if err := meta.AddString(indexmeta.MetadataKey_Network, string(network)); err != nil {
return fmt.Errorf("failed to add network to sig_exists index metadata: %w", err)
}
_, err = index.Seal(meta)
if err != nil {
return fmt.Errorf("error while sealing index: %w", err)
}
klog.Infof("Sealed index in %s", time.Since(sealingStartedAt))
klog.Infof("Success: sig-exists index created at %s", indexFilePath)
if verify {
klog.Infof("Verifying index for %s located at %s", carPath, indexFilePath)
startedAt := time.Now()
defer func() {
klog.Infof("Finished in %s", time.Since(startedAt))
}()
err := VerifyIndex_sigExists(context.TODO(), carPath, indexFilePath)
if err != nil {
return cli.Exit(err, 1)
}
klog.Info("Index verified")
return nil
}
return nil
},
}
}
func formatSigExistsIndexFilePath(indexDir string, epoch uint64, rootCID cid.Cid, network indexes.Network) string {
return filepath.Join(
indexDir,
formatFilename_SigExists(epoch, rootCID, network),
)
}
func formatFilename_SigExists(epoch uint64, rootCid cid.Cid, network indexes.Network) string {
return fmt.Sprintf(
"epoch-%d-%s-%s-%s",
epoch,
rootCid.String(),
network,
"sig-exists.index",
)
}
var classicSpewConfig = spew.ConfigState{
Indent: " ",
DisableMethods: true,
DisablePointerMethods: true,
DisablePointerAddresses: true,
}
type SignatureAndSlot struct {
Slot uint64
Signature solana.Signature
}
type sigToEpochParser struct {
blk blocks.Block
done func()
}
func newSignatureSlot(
blk blocks.Block,
done func(),
) *sigToEpochParser {
return &sigToEpochParser{
blk: blk,
done: done,
}
}
func (w sigToEpochParser) Run(ctx context.Context) interface{} {
defer func() {
w.done()
}()
block := w.blk
decoded, err := iplddecoders.DecodeTransaction(block.RawData())
if err != nil {
return fmt.Errorf("error while decoding transaction from nodex %s: %w", block.Cid(), err)
}
sig, err := readFirstSignature(decoded.Data.Bytes())
if err != nil {
return fmt.Errorf("failed to read signature: %w", err)
}
return SignatureAndSlot{
Slot: uint64(decoded.Slot),
Signature: sig,
}
}