/
netstore.go
77 lines (66 loc) · 2.08 KB
/
netstore.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
// Copyright 2020 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package netstore
import (
"context"
"errors"
"fmt"
"github.com/ethersphere/bee/pkg/retrieval"
"github.com/ethersphere/bee/pkg/storage"
"github.com/ethersphere/bee/pkg/swarm"
)
type store struct {
storage.Storer
retrieval retrieval.Interface
validators []swarm.ChunkValidator
}
// New returns a new NetStore that wraps a given Storer.
func New(s storage.Storer, r retrieval.Interface, validators ...swarm.ChunkValidator) storage.Storer {
return &store{Storer: s, retrieval: r, validators: validators}
}
// Get retrieves a given chunk address.
// It will request a chunk from the network whenever it cannot be found locally.
func (s *store) Get(ctx context.Context, mode storage.ModeGet, addr swarm.Address) (ch swarm.Chunk, err error) {
ch, err = s.Storer.Get(ctx, mode, addr)
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
// request from network
data, err := s.retrieval.RetrieveChunk(ctx, addr)
if err != nil {
return nil, fmt.Errorf("netstore retrieve chunk: %w", err)
}
ch = swarm.NewChunk(addr, data)
if !s.valid(ch) {
return nil, storage.ErrInvalidChunk
}
_, err = s.Storer.Put(ctx, storage.ModePutRequest, ch)
if err != nil {
return nil, fmt.Errorf("netstore retrieve put: %w", err)
}
return ch, nil
}
return nil, fmt.Errorf("netstore get: %w", err)
}
return ch, nil
}
// Put stores a given chunk in the local storage.
// returns a storage.ErrInvalidChunk error when
// encountering an invalid chunk.
func (s *store) Put(ctx context.Context, mode storage.ModePut, chs ...swarm.Chunk) (exist []bool, err error) {
for _, ch := range chs {
if !s.valid(ch) {
return nil, storage.ErrInvalidChunk
}
}
return s.Storer.Put(ctx, mode, chs...)
}
// checks if a particular chunk is valid using the built in validators
func (s *store) valid(ch swarm.Chunk) (ok bool) {
for _, v := range s.validators {
if ok = v.Validate(ch); ok {
return true
}
}
return false
}