-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathclient.go
More file actions
412 lines (364 loc) · 11.5 KB
/
Copy pathclient.go
File metadata and controls
412 lines (364 loc) · 11.5 KB
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
package fulamobile
import (
"bytes"
"context"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/json"
"errors"
"io"
"github.com/functionland/go-fula/blockchain"
"github.com/functionland/go-fula/exchange"
"github.com/ipfs/go-cid"
"github.com/ipfs/go-datastore"
"github.com/ipld/go-ipld-prime"
_ "github.com/ipld/go-ipld-prime/codec/dagcbor"
_ "github.com/ipld/go-ipld-prime/codec/dagjson"
_ "github.com/ipld/go-ipld-prime/codec/raw"
cidlink "github.com/ipld/go-ipld-prime/linking/cid"
ipldmc "github.com/ipld/go-ipld-prime/multicodec"
basicnode "github.com/ipld/go-ipld-prime/node/basic"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/multiformats/go-multicodec"
)
// Note to self; copied from gomobile docs:
// All exported symbols in the package must have types that are supported. Supported types include:
// * Signed integer and floating point types.
// * String and boolean types.
// * Byte slice types.
// * Note that byte slices are passed by reference and support mutation.
// * Any function type all of whose parameters and results have supported types.
// * Functions must return either no results, one result, or two results where the type of the second is the built-in 'error' type.
// * Any interface type, all of whose exported methods have supported function types.
// * Any struct type, all of whose exported methods have supported function types and all of whose exported fields have supported types.
var rootDatastoreKey = datastore.NewKey("/")
type Client struct {
h host.Host
ds datastore.Batching
ls ipld.LinkSystem
ex exchange.Exchange
bl blockchain.Blockchain
bloxPid peer.ID
}
func NewClient(cfg *Config) (*Client, error) {
var mc Client
if err := cfg.init(&mc); err != nil {
return nil, err
}
return &mc, nil
}
// ConnectToBlox attempts to connect to blox via the configured address. This function can be used
// to check if blox is currently accessible.
func (c *Client) ConnectToBlox() error {
if _, ok := c.ex.(exchange.NoopExchange); ok {
return nil
}
return c.h.Connect(context.TODO(), c.h.Peerstore().PeerInfo(c.bloxPid))
}
// ID returns the libp2p peer ID of the client.
func (c *Client) ID() string {
return c.h.ID().String()
}
// Get gets the value corresponding to the given key from the local ipld.LinkSystem
// The key must be a valid ipld.Link and the value returned is encoded ipld.Node.
// If data is not found locally, an attempt is made to automatically fetch the data
// from blox at Config.BloxAddr address.
func (c *Client) Get(key []byte) ([]byte, error) {
l, err := toLink(key)
if err != nil {
return nil, err
}
ctx := context.TODO()
node, err := c.ls.Load(ipld.LinkContext{Ctx: ctx}, l, basicnode.Prototype.Any)
if err != nil {
return nil, err
}
encoder, err := ipldmc.LookupEncoder(l.Cid.Prefix().GetCodec())
if err != nil {
return nil, err
}
var buf bytes.Buffer
if err := encoder(node, &buf); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// Has checks whether the value corresponding to the given key is present in the local datastore.
// The key must be a valid ipld.Link.
func (c *Client) Has(key []byte) (bool, error) {
link, err := toLink(key)
if err != nil {
return false, err
}
return c.hasLink(link)
}
func (c *Client) hasLink(l ipld.Link) (bool, error) {
return c.ds.Has(context.Background(), datastore.NewKey(l.Binary()))
}
func toLink(key []byte) (cidlink.Link, error) {
_, cc, err := cid.CidFromBytes(key)
if err != nil {
return cidlink.Link{}, err
}
return cidlink.Link{Cid: cc}, nil
}
// Pull downloads the data corresponding to the given key from blox at Config.BloxAddr.
// The key must be a valid ipld.Link.
func (c *Client) Pull(key []byte) error {
l, err := toLink(key)
if err != nil {
return err
}
if exists, err := c.hasLink(l); err != nil {
return err
} else if exists {
return nil
}
return c.ex.Pull(context.TODO(), c.bloxPid, l)
}
// Push requests blox at Config.BloxAddr to download the given key from this node.
// The key must be a valid ipld.Link, and the addr must be a valid multiaddr that includes peer ID.
// The value corresponding to the given key must be stored in the local datastore prior to calling
// this function.
// See: Client.Put.
func (c *Client) Push(key []byte) error {
l, err := toLink(key)
if err != nil {
return err
}
return c.pushLink(context.TODO(), l)
}
func (c *Client) pushLink(ctx context.Context, l ipld.Link) error {
if exists, err := c.hasLink(l); err != nil {
return err
} else if !exists {
return errors.New("value not found locally")
}
if err := c.ex.Push(ctx, c.bloxPid, l); err != nil {
return err
}
return c.markAsPushedSuccessfully(ctx, l)
}
// Put stores the given value onto the ipld.LinkSystem and returns its corresponding link.
// The value is decoded using the decoder that corresponds to the given codec. Therefore,
// the given value must be a valid ipld.Node.
// Upon successful local storage of the given value, it is automatically pushed to the blox
// at Config.BloxAddr address.
func (c *Client) Put(value []byte, codec int64) ([]byte, error) {
ctx := context.TODO()
ucodec := uint64(codec)
decode, err := ipldmc.LookupDecoder(ucodec)
if err != nil {
return nil, err
}
buf := bytes.NewBuffer(value)
nb := basicnode.Prototype.Any.NewBuilder()
if err := decode(nb, buf); err != nil {
return nil, err
}
node := nb.Build()
link, err := c.ls.Store(ipld.LinkContext{Ctx: ctx},
cidlink.LinkPrototype{
Prefix: cid.Prefix{
Version: 1,
Codec: ucodec,
MhType: uint64(multicodec.Sha2_256),
MhLength: -1,
},
},
node)
if err != nil {
return nil, err
}
return link.(cidlink.Link).Cid.Bytes(), nil
}
func (c *Client) ListFailedPushes() (*LinkIterator, error) {
links, err := c.listFailedPushes(context.TODO())
if err != nil {
return nil, err
}
return &LinkIterator{links: links}, nil
}
func (c *Client) ListFailedPushesAsString() (*StringIterator, error) {
links, err := c.listFailedPushesAsString(context.TODO())
if err != nil {
return nil, err
}
return &StringIterator{links: links}, nil
}
// RetryFailedPushes retries pushing all links that failed to push.
// The retry is disrupted as soon as a failure occurs.
// See ListFailedPushes.
func (c *Client) RetryFailedPushes() error {
ctx := context.TODO()
links, err := c.listFailedPushes(ctx)
if err != nil {
return err
}
for _, link := range links {
if err := c.pushLink(ctx, link); err != nil {
return err
}
}
return nil
}
// Flush guarantees that all values stored locally are synced to the baking local storage.
func (c *Client) Flush() error {
return c.ds.Sync(context.TODO(), rootDatastoreKey)
}
// SetAuth sets authorization on the given peer ID for the given subject.
func (c *Client) SetAuth(on string, subject string, allow bool) error {
onp, err := peer.Decode(on)
if err != nil {
return err
}
subp, err := peer.Decode(subject)
if err != nil {
return err
}
return c.ex.SetAuth(context.TODO(), onp, subp, allow)
}
// Shutdown closes all resources used by Client.
// After calling this function Client must be discarded.
func (c *Client) Shutdown() error {
ctx := context.TODO()
xErr := c.ex.Shutdown(ctx)
hErr := c.h.Close()
fErr := c.Flush()
dsErr := c.ds.Close()
switch {
case hErr != nil:
return hErr
case fErr != nil:
return fErr
case dsErr != nil:
return dsErr
default:
return xErr
}
}
func (c *Client) IPNSPublish(identity string, identityLink []byte) string {
//TODO: Implement IPNSPublish
return "/ipns/QmRrFsi8WQH4MZEW3QjF74CJ4VzRTvYVGQgb2rP1eLJxAf"
}
func (c *Client) IPNSResolve(identity string) ([]byte, error) {
//TODO: Implement IPNSResolve
return []byte("QmRrFsi8WQH4MZEW3QjF74CJ4VzRTvYVGQgb2rP1eLJxAf"), nil
}
// This stores the encrypted root Cid in an IPLD node and links rootCid to it.
// We use the identity as the value of a new IPLD node and link rootCid to it.
// Essentially, you're creating a new IPLD node with the content of identity and a link to rootCid.
func (c *Client) StoreEncryptedWithIdentity(identity string, appID string, encryptedRootCID string) (string, error) {
// Create appID-encryptedRootCID map
appIDEncryptedRootCIDMap := map[string]interface{}{appID: encryptedRootCID}
appIDEncryptedRootCIDMapBytes, err := json.Marshal(appIDEncryptedRootCIDMap)
if err != nil {
return "", err
}
// Store appID-encryptedRootCID map
appIDEncryptedRootCIDLink, err := c.Put(appIDEncryptedRootCIDMapBytes, int64(multicodec.Json))
if err != nil {
return "", err
}
// Create identity-appIDEncryptedRootCIDLink map
identityLinkMap := map[string]interface{}{identity: appIDEncryptedRootCIDLink}
identityLinkMapBytes, err := json.Marshal(identityLinkMap)
if err != nil {
return "", err
}
// Store identity-appIDEncryptedRootCIDLink map
identityLink, err := c.Put(identityLinkMapBytes, int64(multicodec.Json))
if err != nil {
return "", err
}
// Publish new identity link to IPNS
ipnsName := c.IPNSPublish(identity, identityLink)
return ipnsName, nil
}
func (c *Client) GetEncryptedRootCID(identity string, appID string) ([]byte, error) {
// Retrieve the IPNS record
identityLink, err := c.IPNSResolve(identity)
if err != nil {
return nil, err
}
// Load identity link map
identityLinkMapBytes, err := c.Get(identityLink)
if err != nil {
return nil, err
}
var identityLinkMap map[string][]byte
err = json.Unmarshal(identityLinkMapBytes, &identityLinkMap)
if err != nil {
return nil, err
}
// Load appID-encryptedRootCID map
appIDEncryptedRootCIDMapBytes, err := c.Get(identityLinkMap[identity])
if err != nil {
return nil, err
}
var appIDEncryptedRootCIDMap map[string][]byte
err = json.Unmarshal(appIDEncryptedRootCIDMapBytes, &appIDEncryptedRootCIDMap)
if err != nil {
return nil, err
}
encryptedRootCID := appIDEncryptedRootCIDMap[appID]
return encryptedRootCID, nil
}
// This function will encrypt the provided plaintext with the provided key using AES
func encrypt(plaintext []byte, key []byte) ([]byte, error) {
c, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
return gcm.Seal(nonce, nonce, plaintext, nil), nil
}
// This function will decrypt the provided ciphertext with the provided key using AES
func decrypt(ciphertext []byte, key []byte) ([]byte, error) {
c, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return nil, err
}
nonceSize := gcm.NonceSize()
if len(ciphertext) < nonceSize {
return nil, errors.New("ciphertext too short")
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
return gcm.Open(nil, nonce, ciphertext, nil)
}
func (c *Client) StoreWithIdentityAndEncrypt(identity string, appID string, rootCidStr string, key []byte) (string, error) {
// Convert rootCidStr to []byte
rootCid := []byte(rootCidStr)
// Encrypt rootCid
encryptedRootCid, err := encrypt(rootCid, key)
if err != nil {
return "", err
}
return c.StoreEncryptedWithIdentity(identity, appID, string(encryptedRootCid))
}
func (c *Client) GetByIdentityAndDecrypt(identity string, appID string, key []byte) (string, error) {
// The node should be Bytes, so convert it
encryptedRootCid, err := c.GetEncryptedRootCID(identity, appID)
if err != nil {
return "", err
}
// Decrypt the rootCid
decryptedRootCid, err := decrypt([]byte(encryptedRootCid), key)
if err != nil {
return "", err
}
return string(decryptedRootCid), nil
}