forked from onepeerlabs/bee-lite
/
utils.go
308 lines (268 loc) · 8.57 KB
/
utils.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
package beelite
import (
"context"
"errors"
"fmt"
"math/big"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethersphere/bee/pkg/api"
chaincfg "github.com/ethersphere/bee/pkg/config"
"github.com/ethersphere/bee/pkg/crypto"
"github.com/ethersphere/bee/pkg/feeds"
beelog "github.com/ethersphere/bee/pkg/log"
"github.com/ethersphere/bee/pkg/postage"
"github.com/ethersphere/bee/pkg/postage/postagecontract"
"github.com/ethersphere/bee/pkg/settlement/swap/chequebook"
"github.com/ethersphere/bee/pkg/storage"
storer "github.com/ethersphere/bee/pkg/storer"
"github.com/ethersphere/bee/pkg/swarm"
"github.com/ethersphere/bee/pkg/topology"
)
const (
LoggerName = "beelite"
feedMetadataEntryOwner = "swarm-feed-owner"
feedMetadataEntryTopic = "swarm-feed-topic"
feedMetadataEntryType = "swarm-feed-type"
balanceCheckBackoffDuration = 20 * time.Second
erc20SmallUnitStr = "10000000000000000"
ethSmallUnitStr = "1000000000000000000"
overlayNonce = "overlayV2_nonce"
noncedOverlayKey = "nonce-overlay"
)
type Beelite struct {
bee *Bee
overlayEthAddress common.Address
feedFactory feeds.Factory
storer api.Storer
logger beelog.Logger
topologyDriver topology.Driver
ctx context.Context
chequebookSvc chequebook.Service
post postage.Service
signer crypto.Signer
postageContract postagecontract.Interface
stamperStore storage.Store
batchStore postage.Storer
beeNodeMode api.BeeNodeMode
}
type putterOptions struct {
BatchID []byte
TagID uint64
Deferred bool
Pin bool
}
type putterSessionWrapper struct {
storer.PutterSession
stamper postage.Stamper
save func() error
}
// noOpChequebookService is a noOp implementation for chequebook.Service interface.
type noOpChequebookService struct{}
func (m *noOpChequebookService) Deposit(context.Context, *big.Int) (hash common.Hash, err error) {
return hash, postagecontract.ErrChainDisabled
}
func (m *noOpChequebookService) Withdraw(context.Context, *big.Int) (hash common.Hash, err error) {
return hash, postagecontract.ErrChainDisabled
}
func (m *noOpChequebookService) WaitForDeposit(context.Context, common.Hash) error {
return postagecontract.ErrChainDisabled
}
func (m *noOpChequebookService) Balance(context.Context) (*big.Int, error) {
return nil, postagecontract.ErrChainDisabled
}
func (m *noOpChequebookService) AvailableBalance(context.Context) (*big.Int, error) {
return nil, postagecontract.ErrChainDisabled
}
func (m *noOpChequebookService) Address() common.Address {
return common.Address{}
}
func (m *noOpChequebookService) Issue(context.Context, common.Address, *big.Int, chequebook.SendChequeFunc) (*big.Int, error) {
return nil, postagecontract.ErrChainDisabled
}
func (m *noOpChequebookService) LastCheque(common.Address) (*chequebook.SignedCheque, error) {
return nil, postagecontract.ErrChainDisabled
}
func (m *noOpChequebookService) LastCheques() (map[common.Address]*chequebook.SignedCheque, error) {
return nil, postagecontract.ErrChainDisabled
}
func newLogger(loggerName string, verbosity string) (beelog.Logger, error) {
var (
vLevel beelog.Level
)
switch verbosity {
case "0", "silent":
vLevel = beelog.VerbosityInfo
case "1", "error":
vLevel = beelog.VerbosityError
case "2", "warn":
vLevel = beelog.VerbosityWarning
case "3", "info":
vLevel = beelog.VerbosityInfo
case "4", "debug":
vLevel = beelog.VerbosityDebug
case "5", "trace":
vLevel = beelog.VerbosityDebug + 1
default:
return nil, fmt.Errorf("unknown verbosity level %q", verbosity)
}
beelog.ModifyDefaults(
beelog.WithTimestamp(),
beelog.WithLogMetrics(),
)
return beelog.NewLogger(
loggerName,
beelog.WithVerbosity(vLevel),
).Register(), nil
}
func getConfigByNetworkID(networkID uint64) *networkConfig {
config := networkConfig{
blockTime: 5 * time.Second,
}
switch networkID {
case chaincfg.Mainnet.NetworkID:
config.bootNodes = []string{"/dnsaddr/mainnet.ethswarm.org"}
config.blockTime = 5 * time.Second
config.chainID = chaincfg.Mainnet.ChainID
case 5: // Staging.
config.chainID = chaincfg.Testnet.ChainID
case chaincfg.Testnet.NetworkID:
config.bootNodes = []string{"/dnsaddr/testnet.ethswarm.org"}
config.blockTime = 15 * time.Second
config.chainID = chaincfg.Testnet.ChainID
default: // Will use the value provided by the chain.
config.chainID = -1
}
return &config
}
var (
errBatchUnusable = errors.New("batch not usable")
errUnsupportedDevNodeOperation = errors.New("operation not supported in dev mode")
)
func (p *putterSessionWrapper) Cleanup() error {
return errors.Join(p.PutterSession.Cleanup(), p.save())
}
func (p *putterSessionWrapper) Put(ctx context.Context, chunk swarm.Chunk) error {
stamp, err := p.stamper.Stamp(chunk.Address())
if err != nil {
return err
}
return p.PutterSession.Put(ctx, chunk.WithStamp(stamp))
}
func (p *putterSessionWrapper) Done(ref swarm.Address) error {
err := p.PutterSession.Done(ref)
if err != nil {
return err
}
return p.save()
}
func (bl *Beelite) getStamper(batchID []byte) (postage.Stamper, func() error, error) {
exists, err := bl.batchStore.Exists(batchID)
if err != nil {
return nil, nil, fmt.Errorf("batch exists: %w", err)
}
issuer, save, err := bl.post.GetStampIssuer(batchID)
if err != nil {
return nil, nil, fmt.Errorf("stamp issuer: %w", err)
}
if usable := exists && bl.post.IssuerUsable(issuer); !usable {
return nil, nil, errBatchUnusable
}
return postage.NewStamper(bl.stamperStore, issuer, bl.signer), save, nil
}
func (bl *Beelite) newStamperPutter(ctx context.Context, opts putterOptions) (storer.PutterSession, error) {
if !opts.Deferred && bl.BeeNodeMode() == api.DevMode {
return nil, errUnsupportedDevNodeOperation
}
stamper, save, err := bl.getStamper(opts.BatchID)
if err != nil {
return nil, fmt.Errorf("get stamper: %w", err)
}
var session storer.PutterSession
if opts.Deferred || opts.Pin {
session, err = bl.storer.Upload(ctx, opts.Pin, opts.TagID)
} else {
session = bl.storer.DirectUpload()
}
if err != nil {
return nil, fmt.Errorf("failed creating session: %w", err)
}
return &putterSessionWrapper{
PutterSession: session,
stamper: stamper,
save: save,
}, nil
}
// getOrCreateSessionID attempts to get the session if an tag id is supplied, and returns an error
// if it does not exist. If no id is supplied, it will attempt to create a new session and return it.
func (bl *Beelite) getOrCreateSessionID(tagUid uint64) (uint64, error) {
var (
tag storer.SessionInfo
err error
)
// if tag ID is not supplied, create a new tag
if tagUid == 0 {
tag, err = bl.storer.NewSession()
} else {
tag, err = bl.storer.Session(tagUid)
}
return tag.TagID, err
}
// checkOverlay checks the overlay is the same as stored in the statestore
func checkOverlay(storer storage.StateStorer, overlay swarm.Address) error {
var storedOverlay swarm.Address
err := storer.Get(noncedOverlayKey, &storedOverlay)
if err != nil {
if !errors.Is(err, storage.ErrNotFound) {
return err
}
return storer.Put(noncedOverlayKey, overlay)
}
if !storedOverlay.Equal(overlay) {
return fmt.Errorf("overlay address changed. was %s before but now is %s", storedOverlay, overlay)
}
return nil
}
func overlayNonceExists(s storage.StateStorer) ([]byte, bool, error) {
nonce := make([]byte, 32)
if err := s.Get(overlayNonce, &nonce); err != nil {
if errors.Is(err, storage.ErrNotFound) {
return nonce, false, nil
}
return nil, false, err
}
return nonce, true, nil
}
func setOverlay(s storage.StateStorer, overlay swarm.Address, nonce []byte) error {
return errors.Join(
s.Put(overlayNonce, nonce),
s.Put(noncedOverlayKey, overlay),
)
}
func (bl *Beelite) ChequebookAddr() common.Address {
if bl.chequebookSvc != nil {
return bl.chequebookSvc.Address()
}
return common.HexToAddress(swarm.ZeroAddress.String())
}
func (bl *Beelite) ChequebookBalance() (*big.Int, error) {
if bl.chequebookSvc != nil {
return bl.chequebookSvc.Balance(bl.ctx)
}
return nil, fmt.Errorf("chequebook not initialised")
}
func (bl *Beelite) ChequebookWithdraw(amount *big.Int) (common.Hash, error) {
if bl.chequebookSvc != nil {
return bl.chequebookSvc.Withdraw(bl.ctx, amount)
}
return common.HexToHash(""), fmt.Errorf("chequebook not initialised")
}
func (bl *Beelite) OverlayEthAddress() common.Address {
return bl.overlayEthAddress
}
func (bl *Beelite) BeeNodeMode() api.BeeNodeMode {
return bl.beeNodeMode
}
func (bl *Beelite) ConnectedPeerCount() int {
return bl.topologyDriver.Snapshot().Connected
}