-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwriter_with_verify_hash.go
More file actions
90 lines (70 loc) · 2.15 KB
/
writer_with_verify_hash.go
File metadata and controls
90 lines (70 loc) · 2.15 KB
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
package ethwal
import (
"context"
"errors"
"fmt"
"github.com/0xsequence/ethkit/go-ethereum/common"
)
var ErrParentHashMismatch = errors.New("parent hash mismatch")
type BlockHashGetter func(ctx context.Context, blockNum uint64) (common.Hash, error)
func BlockHashGetterFromReader[T any](options Options) BlockHashGetter {
return func(ctx context.Context, blockNum uint64) (common.Hash, error) {
reader, err := NewReader[T](options)
if err != nil {
return common.Hash{}, fmt.Errorf("failed to create reader: %w", err)
}
defer reader.Close()
err = reader.Seek(ctx, blockNum)
if err != nil {
return common.Hash{}, fmt.Errorf("failed to seek to block %d: %w", blockNum, err)
}
block, err := reader.Read(ctx)
if err != nil {
return common.Hash{}, fmt.Errorf("failed to read block %d: %w", blockNum, err)
}
return block.Hash, nil
}
}
type writerWithVerifyHash[T any] struct {
Writer[T]
blockHashGetter BlockHashGetter
prevHash common.Hash
}
var _ Writer[any] = (*writerWithVerifyHash[any])(nil)
func NewWriterWithVerifyHash[T any](writer Writer[T], blockHashGetter BlockHashGetter) Writer[T] {
return &writerWithVerifyHash[T]{Writer: writer, blockHashGetter: blockHashGetter}
}
func (w *writerWithVerifyHash[T]) Write(ctx context.Context, b Block[T]) error {
// Skip if block is already written
if b.Number <= w.Writer.BlockNum() {
return nil
}
// Skip validation if block is first block
if b.Number == 1 {
if err := w.Writer.Write(ctx, b); err != nil {
return fmt.Errorf("failed to write block: %w", err)
}
w.prevHash = b.Hash
return nil
}
// Get previous hash if not already set
if w.prevHash == (common.Hash{}) {
prevHash, err := w.blockHashGetter(ctx, b.Number-1)
if err != nil {
return fmt.Errorf("failed to get block hash: %w", err)
}
w.prevHash = prevHash
}
// Validate parent hash
if b.Parent != w.prevHash {
return fmt.Errorf("%w, expected %s, got %s", ErrParentHashMismatch, b.Parent.String(), w.prevHash.String())
}
// Write block
err := w.Writer.Write(ctx, b)
if err != nil {
return fmt.Errorf("failed to write block: %w", err)
}
// Update prev hash
w.prevHash = b.Hash
return nil
}