generated from mrz1836/go-template
-
Notifications
You must be signed in to change notification settings - Fork 10
/
sync_merkleroots.go
72 lines (59 loc) · 2.33 KB
/
sync_merkleroots.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
package walletclient
import (
"context"
"fmt"
"net/http"
"strings"
"github.com/bitcoin-sv/spv-wallet/models"
)
// MerkleRootsRepository is an interface responsible for storing synchronized MerkleRoots and retrieving the last evaluation key from the database.
type MerkleRootsRepository interface {
// GetLastMerkleRoot should return the Merkle root with the highest height from your memory, or undefined if empty.
GetLastMerkleRoot() string
// SaveMerkleRoots should store newly synced merkle roots into your storage;
// NOTE: items are sorted in ascending order by block height.
SaveMerkleRoots(syncedMerkleRoots []models.MerkleRoot) error
}
// SyncMerkleRoots syncs merkleroots known to spv-wallet with the client database
// If timeout is needed pass context.WithTimeout() as ctx param
func (wc *WalletClient) SyncMerkleRoots(ctx context.Context, repo MerkleRootsRepository) error {
lastEvaluatedKey := repo.GetLastMerkleRoot()
requestPath := "merkleroots"
lastEvaluatedKeyQuery := ""
previousLastEvaluatedKey := lastEvaluatedKey
if lastEvaluatedKey != "" {
lastEvaluatedKeyQuery = fmt.Sprintf("?lastEvaluatedKey=%s", lastEvaluatedKey)
}
for {
select {
case <-ctx.Done():
return ErrSyncMerkleRootsTimeout
default:
url := fmt.Sprintf("/%s%s", requestPath, lastEvaluatedKeyQuery)
var merkleRootsResponse models.ExclusiveStartKeyPage[[]models.MerkleRoot]
err := wc.doHTTPRequest(ctx, http.MethodGet, url, nil, wc.xPriv, true, &merkleRootsResponse)
if err != nil {
// In case if the context deadline exceeds its limit during http request, httpClient
// cancels the request wrapping it as spverror, so we need to check if the message
// is the same as context deadline exceeded error
if strings.Contains(err.Error(), context.DeadlineExceeded.Error()) {
return ErrSyncMerkleRootsTimeout
}
return WrapError(err)
}
lastEvaluatedKey = merkleRootsResponse.Page.LastEvaluatedKey
if lastEvaluatedKey != "" && previousLastEvaluatedKey == lastEvaluatedKey {
return ErrStaleLastEvaluatedKey
}
err = repo.SaveMerkleRoots(merkleRootsResponse.Content)
if err != nil {
return err
}
previousLastEvaluatedKey = lastEvaluatedKey
if previousLastEvaluatedKey == "" {
return nil
}
lastEvaluatedKeyQuery = fmt.Sprintf("?lastEvaluatedKey=%s", previousLastEvaluatedKey)
}
}
}