-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetch.go
65 lines (49 loc) · 1.6 KB
/
fetch.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
package doc
import (
"context"
"fmt"
"github.com/bahner/go-ma/api"
"github.com/bahner/go-ma/did"
cbor "github.com/fxamacker/cbor/v2"
"github.com/ipfs/go-cid"
log "github.com/sirupsen/logrus"
)
// Takes a DID and fetches the document from IPFS.
// Eg. Fetch("did:ma:k51qzi5uqu5dj9807pbuod1pplf0vxh8m4lfy3ewl9qbm2s8dsf9ugdf9gedhr#bahner")
// The cached flag determines whether the document should be fetched from IPNS cache or not.
func Fetch(didStr string, cached bool) (*Document, cid.Cid, error) {
d, err := did.New(didStr)
if err != nil {
return nil, cid.Cid{}, err
}
return FetchFromDID(d, cached)
}
// Fetched the document from IPFS using the DID object.
// The cached flag determines whether the document should be fetched from IPNS cache or not.
func FetchFromDID(d did.DID, cached bool) (*Document, cid.Cid, error) {
var document = &Document{}
ipfsAPI := api.GetIPFSAPI()
ip, err := d.Path()
if err != nil {
return nil, cid.Cid{}, fmt.Errorf("fetchFromDID: %w", err)
}
c, err := api.ResolveRootCID(ip.String(), cached)
if err != nil {
return nil, cid.Cid{}, fmt.Errorf("fetchFromDID: %w", err)
}
log.Debugf("Fetching CID: %s", c)
node, err := ipfsAPI.Dag().Get(context.Background(), c)
if err != nil {
return nil, cid.Cid{}, fmt.Errorf("fetchFromDID: %w", err)
}
err = cbor.Unmarshal(node.RawData(), document)
if err != nil {
return nil, cid.Cid{}, fmt.Errorf("fetchFromDID: %w", err)
}
err = document.Verify()
if err != nil {
return nil, cid.Cid{}, fmt.Errorf("fetchFromDID: %w", err)
}
log.Debugf("Fetched and cached document for : %s", d.Id)
return document, c, nil
}