forked from ethereum/go-ethereum
-
Notifications
You must be signed in to change notification settings - Fork 278
/
blob_scan_client.go
78 lines (70 loc) · 2.28 KB
/
blob_scan_client.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
package blob_client
import (
"context"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/url"
"github.com/scroll-tech/go-ethereum/common"
"github.com/scroll-tech/go-ethereum/crypto/kzg4844"
)
type BlobScanClient struct {
client *http.Client
apiEndpoint string
}
func NewBlobScanClient(apiEndpoint string) *BlobScanClient {
return &BlobScanClient{
client: http.DefaultClient,
apiEndpoint: apiEndpoint,
}
}
func (c *BlobScanClient) GetBlobByVersionedHashAndBlockNumber(ctx context.Context, versionedHash common.Hash, blockNumber uint64) (*kzg4844.Blob, error) {
// blobscan api docs https://api.blobscan.com/#/blobs/blob-getByBlobId
path, err := url.JoinPath(c.apiEndpoint, versionedHash.String())
if err != nil {
return nil, fmt.Errorf("failed to join path, err: %w", err)
}
req, err := http.NewRequestWithContext(ctx, "GET", path, nil)
if err != nil {
return nil, fmt.Errorf("cannot create request, err: %w", err)
}
req.Header.Set("accept", "application/json")
resp, err := c.client.Do(req)
if err != nil {
return nil, fmt.Errorf("cannot do request, err: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
if resp.StatusCode == http.StatusNotFound {
return nil, fmt.Errorf("no blob with versioned hash : %s", versionedHash.String())
}
var res ErrorRespBlobScan
err = json.NewDecoder(resp.Body).Decode(&res)
if err != nil {
return nil, fmt.Errorf("failed to decode result into struct, err: %w", err)
}
return nil, fmt.Errorf("error while fetching blob, message: %s, code: %s, versioned hash: %s", res.Message, res.Code, versionedHash.String())
}
var result BlobRespBlobScan
err = json.NewDecoder(resp.Body).Decode(&result)
if err != nil {
return nil, fmt.Errorf("failed to decode result into struct, err: %w", err)
}
blobBytes, err := hex.DecodeString(result.Data[2:])
if err != nil {
return nil, fmt.Errorf("failed to decode data to bytes, err: %w", err)
}
if len(blobBytes) != lenBlobBytes {
return nil, fmt.Errorf("len of blob data is not correct, expected: %d, got: %d", lenBlobBytes, len(blobBytes))
}
blob := kzg4844.Blob(blobBytes)
return &blob, nil
}
type BlobRespBlobScan struct {
Data string `json:"data"`
}
type ErrorRespBlobScan struct {
Message string `json:"message"`
Code string `json:"code"`
}