/
main.go
435 lines (388 loc) · 13.9 KB
/
main.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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
package backend
import (
"context"
"crypto"
"encoding/hex"
"fmt"
"log/slog"
"math/rand"
"net/http"
"sync"
"time"
"github.com/ainvaltin/httpsrv"
"github.com/alphabill-org/alphabill/logger"
"github.com/alphabill-org/alphabill/network/protocol/genesis"
"github.com/alphabill-org/alphabill/predicates"
"github.com/alphabill-org/alphabill/predicates/templates"
"github.com/alphabill-org/alphabill/txsystem/money"
"github.com/alphabill-org/alphabill/types"
"go.opentelemetry.io/contrib/instrumentation/github.com/gorilla/mux/otelmux"
"go.opentelemetry.io/otel/trace"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/semaphore"
"github.com/alphabill-org/alphabill-wallet/client/grpc"
"github.com/alphabill-org/alphabill-wallet/internal/debug"
sdk "github.com/alphabill-org/alphabill-wallet/wallet"
"github.com/alphabill-org/alphabill-wallet/wallet/account"
"github.com/alphabill-org/alphabill-wallet/wallet/blocksync"
)
type (
WalletBackendService interface {
GetBills(pubKey []byte, includeDCBills bool, offsetKey []byte, limit int) ([]*Bill, []byte, error)
GetBill(unitID []byte) (*Bill, error)
GetFeeCreditBill(unitID []byte) (*Bill, error)
GetRoundNumber(ctx context.Context) (*sdk.RoundNumber, error)
SendTransactions(ctx context.Context, txs []*types.TransactionOrder) map[string]string
GetTxProof(unitID types.UnitID, txHash sdk.TxHash) (*sdk.Proof, error)
HandleTransactionsSubmission(egp *errgroup.Group, sender sdk.PubKey, txs []*types.TransactionOrder)
GetTxHistoryRecords(hash sdk.PubKeyHash, dbStartKey []byte, count int) ([]*sdk.TxHistoryRecord, []byte, error)
}
ABClient interface {
SendTransaction(ctx context.Context, tx *types.TransactionOrder) error
GetRoundNumber(ctx context.Context) (uint64, error)
}
WalletBackend struct {
store BillStore
abc ABClient
}
Bills struct {
Bills []*Bill `json:"bills"`
}
Bill struct {
Id []byte `json:"id"`
Value uint64 `json:"value"`
TxHash []byte `json:"txHash"`
DCTargetUnitID []byte `json:"dcTargetUnitId,omitempty"`
DCTargetUnitBacklink []byte `json:"dcTargetUnitBacklink,omitempty"`
OwnerPredicate []byte `json:"ownerPredicate"`
Locked sdk.LockReason `json:"locked"`
}
Pubkey struct {
Pubkey []byte `json:"pubkey"`
PubkeyHash *account.KeyHashes `json:"pubkeyHash"`
}
// BillStore type for creating BillStoreTx transactions
BillStore interface {
Do() BillStoreTx
WithTransaction(func(tx BillStoreTx) error) error
}
// BillStoreTx type for managing units by their ID and owner condition
BillStoreTx interface {
GetBlockNumber() (uint64, error)
SetBlockNumber(blockNumber uint64) error
GetBill(unitID []byte) (*Bill, error)
GetBills(ownerCondition []byte, includeDCBills bool, offsetKey []byte, limit int) ([]*Bill, []byte, error)
SetBill(bill *Bill, proof *sdk.Proof) error
RemoveBill(unitID []byte) error
SetBillExpirationTime(blockNumber uint64, unitID []byte) error
DeleteExpiredBills(blockNumber uint64) error
GetFeeCreditBill(unitID []byte) (*Bill, error)
SetFeeCreditBill(fcb *Bill, proof *sdk.Proof) error
GetSystemDescriptionRecords() ([]*genesis.SystemDescriptionRecord, error)
SetSystemDescriptionRecords(sdrs []*genesis.SystemDescriptionRecord) error
GetTxProof(unitID types.UnitID, txHash sdk.TxHash) (*sdk.Proof, error)
StoreTxHistoryRecord(hash sdk.PubKeyHash, rec *sdk.TxHistoryRecord) error
GetTxHistoryRecords(hash sdk.PubKeyHash, dbStartKey []byte, count int) ([]*sdk.TxHistoryRecord, []byte, error)
StoreTxProof(unitID types.UnitID, txHash sdk.TxHash, txProof *sdk.Proof) error
}
p2pkhOwnerPredicates struct {
sha256 []byte
}
Config struct {
ABMoneySystemIdentifier types.SystemID
AlphabillUrl string
ServerAddr string
DbFile string
ListBillsPageLimit int
InitialBill InitialBill
SystemDescriptionRecords []*genesis.SystemDescriptionRecord
Logger *slog.Logger
Observe Observability
}
InitialBill struct {
Id []byte
Value uint64
Predicate []byte
}
Observability interface {
Tracer(name string, options ...trace.TracerOption) trace.Tracer
TracerProvider() trace.TracerProvider
Logger() *slog.Logger
}
)
func Run(ctx context.Context, config *Config) error {
if config.Logger != nil {
config.Logger.Info(fmt.Sprintf("starting money backend: BuildInfo=%s", debug.ReadBuildInfo()))
}
store, err := newBoltBillStore(config.DbFile)
if err != nil {
return fmt.Errorf("failed to get storage: %w", err)
}
// if first run:
// store initial bill to avoid some edge cases
// store system description records and partition fee bills to avoid providing them every run
err = store.WithTransaction(func(txc BillStoreTx) error {
blockNumber, err := txc.GetBlockNumber()
if err != nil {
return err
}
if blockNumber > 0 {
return nil
}
ib := config.InitialBill
err = txc.SetBill(&Bill{
Id: ib.Id,
Value: ib.Value,
OwnerPredicate: ib.Predicate,
}, nil)
if err != nil {
return fmt.Errorf("failed to store initial bill: %w", err)
}
err = txc.SetSystemDescriptionRecords(config.SystemDescriptionRecords)
if err != nil {
return fmt.Errorf("failed to store system description records: %w", err)
}
for _, sdr := range config.SystemDescriptionRecords {
err = txc.SetBill(&Bill{
Id: sdr.FeeCreditBill.UnitID,
OwnerPredicate: sdr.FeeCreditBill.OwnerPredicate,
}, nil)
if err != nil {
return err
}
}
return nil
})
if err != nil {
return err
}
abc, err := grpc.New(grpc.AlphabillClientConfig{Uri: config.AlphabillUrl}, config.Observe)
if err != nil {
return err
}
defer func() {
if err := abc.Close(); err != nil {
config.Logger.Warn("closing AB client", logger.Error(err))
}
}()
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error {
config.Logger.Info(fmt.Sprintf("money backend REST server starting on %s", config.ServerAddr))
handler := &moneyRestAPI{
Service: &WalletBackend{store: store, abc: abc},
ListBillsPageLimit: config.ListBillsPageLimit,
SystemID: config.ABMoneySystemIdentifier,
rw: &sdk.ResponseWriter{LogErr: func(err error) { config.Logger.Error(err.Error()) }},
log: config.Logger,
tracer: config.Observe.Tracer("moneyRestAPI"),
}
routes := handler.Router()
routes.Use(otelmux.Middleware("money_backend", otelmux.WithTracerProvider(config.Observe.TracerProvider())))
return httpsrv.Run(ctx,
http.Server{
Addr: config.ServerAddr,
Handler: routes,
ReadTimeout: 10 * time.Second,
ReadHeaderTimeout: 2 * time.Second,
WriteTimeout: 20 * time.Second,
IdleTimeout: 30 * time.Second,
},
httpsrv.ShutdownTimeout(5*time.Second),
)
})
g.Go(func() error {
blockProcessor, err := NewBlockProcessor(store, config.ABMoneySystemIdentifier, config.Logger)
if err != nil {
return fmt.Errorf("failed to create block processor: %w", err)
}
getBlockNumber := func() (uint64, error) { return store.Do().GetBlockNumber() }
// we act as if all errors returned by block sync are recoverable ie we
// just retry in a loop until ctx is cancelled
for {
config.Logger.DebugContext(ctx, "starting block sync")
err := runBlockSync(ctx, abc.GetBlocks, getBlockNumber, 100, blockProcessor.ProcessBlock)
if err != nil {
config.Logger.Error("synchronizing blocks returned error", logger.Error(err))
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(time.Duration(rand.Int31n(10)+10) * time.Second):
}
}
})
return g.Wait()
}
func runBlockSync(ctx context.Context, getBlocks blocksync.BlocksLoaderFunc, getBlockNumber func() (uint64, error), batchSize int, processor blocksync.BlockProcessorFunc) error {
blockNumber, err := getBlockNumber()
if err != nil {
return fmt.Errorf("failed to read current block number for a sync starting point: %w", err)
}
// on bootstrap storage returns 0 as current block and as block numbering
// starts from 1 by adding 1 to it we start with the first block
return blocksync.Run(ctx, getBlocks, blockNumber+1, 0, batchSize, processor)
}
// GetBills returns first N=limit bills for given owner predicate starting from the offsetKey
// or if offsetKey is nil then starting from the very first key.
// Always returns the next key if it exists i.e. even if limit=0.
// Furthermore, the next key might not match the filter (isDCBill).
func (w *WalletBackend) GetBills(pubkey []byte, includeDCBills bool, offsetKey []byte, limit int) ([]*Bill, []byte, error) {
keyHashes := account.NewKeyHash(pubkey)
ownerPredicates := newOwnerPredicates(keyHashes)
nextKey := offsetKey
bills := make([]*Bill, 0, limit)
for _, predicate := range [][]byte{ownerPredicates.sha256} {
remainingLimit := limit - len(bills)
batch, batchNextKey, err := w.store.Do().GetBills(predicate, includeDCBills, nextKey, remainingLimit)
if err != nil {
return nil, nil, err
}
bills = append(bills, batch...)
nextKey = batchNextKey
if nextKey != nil {
break // more bills in the same predicate batch; return response immediately
}
// no more bills in this predicate; move to the next predicate to load more bills
}
return bills, nextKey, nil
}
// GetBill returns most recently seen bill with given unit id.
func (w *WalletBackend) GetBill(unitID []byte) (*Bill, error) {
return w.store.Do().GetBill(unitID)
}
func (w *WalletBackend) GetTxProof(unitID types.UnitID, txHash sdk.TxHash) (*sdk.Proof, error) {
return w.store.Do().GetTxProof(unitID, txHash)
}
// GetFeeCreditBill returns most recently seen fee credit bill with given unit id.
func (w *WalletBackend) GetFeeCreditBill(unitID []byte) (*Bill, error) {
return w.store.Do().GetFeeCreditBill(unitID)
}
// GetRoundNumber returns the latest round number in node and backend.
func (w *WalletBackend) GetRoundNumber(ctx context.Context) (*sdk.RoundNumber, error) {
nodeRoundNumber, err := w.abc.GetRoundNumber(ctx)
if err != nil {
return nil, fmt.Errorf("failed to fetch node round number: %w", err)
}
backendRoundNumber, err := w.store.Do().GetBlockNumber()
if err != nil {
return nil, fmt.Errorf("failed to load backend round number: %w", err)
}
return &sdk.RoundNumber{
RoundNumber: nodeRoundNumber,
LastIndexedRoundNumber: backendRoundNumber,
}, nil
}
// TODO: Share functionaly with tokens partiton
// SendTransactions forwards transactions to partiton node(s).
func (w *WalletBackend) SendTransactions(ctx context.Context, txs []*types.TransactionOrder) map[string]string {
errs := make(map[string]string)
var m sync.Mutex
const maxWorkers = 5
sem := semaphore.NewWeighted(maxWorkers)
for _, tx := range txs {
if err := sem.Acquire(ctx, 1); err != nil {
break
}
go func(tx *types.TransactionOrder) {
defer sem.Release(1)
if err := w.abc.SendTransaction(ctx, tx); err != nil {
m.Lock()
errs[hex.EncodeToString(tx.UnitID())] =
fmt.Errorf("failed to forward tx: %w", err).Error()
m.Unlock()
}
}(tx)
}
semCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
if err := sem.Acquire(semCtx, maxWorkers); err != nil {
m.Lock()
errs["waiting-for-workers"] = err.Error()
m.Unlock()
}
return errs
}
func (w *WalletBackend) GetTxHistoryRecords(hash sdk.PubKeyHash, dbStartKey []byte, count int) ([]*sdk.TxHistoryRecord, []byte, error) {
return w.store.Do().GetTxHistoryRecords(hash, dbStartKey, count)
}
func (w *WalletBackend) HandleTransactionsSubmission(egp *errgroup.Group, sender sdk.PubKey, txs []*types.TransactionOrder) {
egp.Go(func() error { return w.storeIncomingTransactions(sender, txs) })
}
func (w *WalletBackend) storeIncomingTransactions(sender sdk.PubKey, txs []*types.TransactionOrder) error {
for _, tx := range txs {
var newOwners []sdk.Predicate
switch tx.PayloadType() {
case money.PayloadTypeTransfer:
attrs := &money.TransferAttributes{}
err := tx.UnmarshalAttributes(attrs)
if err != nil {
return err
}
newOwners = append(newOwners, attrs.NewBearer)
case money.PayloadTypeSplit:
attrs := &money.SplitAttributes{}
err := tx.UnmarshalAttributes(attrs)
if err != nil {
return err
}
for _, targetUnit := range attrs.TargetUnits {
newOwners = append(newOwners, targetUnit.OwnerCondition)
}
}
for _, newOwner := range newOwners {
rec := &sdk.TxHistoryRecord{
UnitID: tx.UnitID(),
TxHash: tx.Hash(crypto.SHA256),
Timeout: tx.Timeout(),
State: sdk.UNCONFIRMED,
Kind: sdk.OUTGOING,
CounterParty: extractOwnerHashFromP2pkh(newOwner),
}
if err := w.store.Do().StoreTxHistoryRecord(sender.Hash(), rec); err != nil {
return fmt.Errorf("failed to store tx history record: %w", err)
}
}
}
return nil
}
// extractOwnerFromP2pkh extracts owner from p2pkh predicate.
func extractOwnerHashFromP2pkh(bearer sdk.Predicate) sdk.PubKeyHash {
pkh, _ := templates.ExtractPubKeyHashFromP2pkhPredicate(bearer)
return pkh
}
func extractOwnerKeyFromProof(signature sdk.Predicate) sdk.PubKey {
pk, _ := predicates.ExtractPubKey(signature)
return pk
}
func (b *Bill) ToGenericBill() *sdk.Bill {
return &sdk.Bill{
Id: b.Id,
Value: b.Value,
TxHash: b.TxHash,
DCTargetUnitID: b.DCTargetUnitID,
DCTargetUnitBacklink: b.DCTargetUnitBacklink,
Locked: b.Locked,
}
}
func (b *Bill) ToGenericBills() *sdk.Bills {
return &sdk.Bills{
Bills: []*sdk.Bill{
b.ToGenericBill(),
},
}
}
func (b *Bill) getValue() uint64 {
if b != nil {
return b.Value
}
return 0
}
func (b *Bill) IsDCBill() bool {
if b != nil {
return len(b.DCTargetUnitID) > 0
}
return false
}
func newOwnerPredicates(hashes *account.KeyHashes) *p2pkhOwnerPredicates {
return &p2pkhOwnerPredicates{sha256: templates.NewP2pkh256BytesFromKeyHash(hashes.Sha256)}
}