forked from ipfs/go-ipfs-api
-
Notifications
You must be signed in to change notification settings - Fork 4
/
storage.go
581 lines (518 loc) · 14.9 KB
/
storage.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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
package shell
import (
"context"
"errors"
"fmt"
"strconv"
"time"
"github.com/libp2p/go-libp2p/core/peer"
utils "github.com/TRON-US/go-btfs-api/utils"
"github.com/gogo/protobuf/proto"
"github.com/tron-us/go-common/v2/json"
ic "github.com/libp2p/go-libp2p/core/crypto"
"github.com/tron-us/go-btfs-common/crypto"
escrowpb "github.com/tron-us/go-btfs-common/protos/escrow"
guardpb "github.com/tron-us/go-btfs-common/protos/guard"
ledgerpb "github.com/tron-us/go-btfs-common/protos/ledger"
cutils "github.com/tron-us/go-btfs-common/utils"
)
type StorageUploadOpts = func(*RequestBuilder) error
type storageUploadResponse struct {
ID string
}
type Shard struct {
ContractId string
Price int64
Host string
Status string
}
type Storage struct {
Status string
Message string
FileHash string
Shards map[string]Shard
}
type ContractItem struct {
Key string `json:"key"`
Contract string `json:"contract"`
}
type Contracts struct {
Contracts []ContractItem `json:contracts`
}
type UnsignedData struct {
Unsigned string
Opcode string
Price int64
}
type StorageOpts = func(*RequestBuilder) error
func UploadMode(mode string) StorageOpts {
return func(rb *RequestBuilder) error {
rb.Option("m", mode)
return nil
}
}
func Hosts(hosts string) StorageOpts {
return func(rb *RequestBuilder) error {
rb.Option("s", hosts)
return nil
}
}
func (d UnsignedData) SignData(privateKey string) ([]byte, error) {
privKey, err := crypto.ToPrivKey(privateKey)
if err != nil {
return nil, err
}
signedData, err := privKey.Sign([]byte(d.Unsigned))
if err != nil {
return nil, err
}
return signedData, nil
}
func (d UnsignedData) SignBalanceData(privateKey string) (*ledgerpb.SignedPublicKey, error) {
privKey, err := crypto.ToPrivKey(privateKey)
if err != nil {
return nil, err
}
pubKeyRaw, err := ic.MarshalPublicKey(privKey.GetPublic())
if err != nil {
return nil, err
}
lgPubKey := &ledgerpb.PublicKey{
Key: pubKeyRaw,
}
sig, err := crypto.Sign(privKey, lgPubKey)
if err != nil {
return nil, err
}
lgSignedPubKey := &ledgerpb.SignedPublicKey{
Key: lgPubKey,
Signature: sig,
}
return lgSignedPubKey, nil
}
func (c Contracts) SignContracts(privateKey string, t string) (*Contracts, error) {
// Perform signing using private key
privKey, err := crypto.ToPrivKey(privateKey)
if err != nil {
return nil, err
}
for idx, element := range c.Contracts {
by, err := cutils.StringToBytes(element.Contract, cutils.Base64)
if err != nil {
return nil, err
}
var signedContract []byte
if t == "escrow" {
escrowContract := &escrowpb.EscrowContract{}
err = proto.Unmarshal(by, escrowContract)
if err != nil {
return nil, err
}
signedContract, err = crypto.Sign(privKey, escrowContract)
if err != nil {
return nil, err
}
} else if t == "guard" {
guardContract := &guardpb.ContractMeta{}
err := proto.Unmarshal(by, guardContract)
if err != nil {
return nil, err
}
signedContract, err = crypto.Sign(privKey, guardContract)
if err != nil {
return nil, err
}
} else {
return nil, errors.New("not support type:" + t)
}
// This overwrites
str, err := cutils.BytesToString(signedContract, cutils.Base64)
if err != nil {
return nil, err
}
c.Contracts[idx].Contract = str
if err != nil {
return nil, err
}
}
return &c, nil
}
// Set storage upload time.
func StorageLength(length int) StorageUploadOpts {
return func(rb *RequestBuilder) error {
rb.Option("storage-length", length)
return nil
}
}
func (s *Shell) GetUts() string {
return strconv.FormatInt(time.Now().Unix(), 10)
}
func NewSessionSignature(hash string, peerIdStr string, uts string, verifyBefore bool) (string, error) {
// Create offline session signature input data
inputDataStr := fmt.Sprintf("%s%s%s", hash, peerIdStr, uts)
// Sign sessionSignature
privKey, err := crypto.ToPrivKey(utils.GetPrivateKey())
if err != nil {
return "", err
}
sig, err := privKey.Sign([]byte(inputDataStr))
if err != nil {
return "", err
}
sigStr, err := cutils.BytesToString(sig, cutils.Base64)
if err != nil {
return "", err
}
utils.SetSessionSignature(sigStr)
peerId, err := peer.IDFromBytes([]byte(utils.GetPeerId()))
if err != nil {
return "", err
}
if verifyBefore {
err = VerifySessionSignature(peerId, inputDataStr, sigStr)
if err != nil {
return "", err
}
}
return sigStr, nil
}
func VerifySessionSignature(offSignRenterPid peer.ID, data string, sessionSigStr string) error {
// get renter's public key
pubKey, err := offSignRenterPid.ExtractPublicKey()
if err != nil {
return err
}
sigBytes, err := cutils.StringToBytes(sessionSigStr, cutils.Base64)
if err != nil {
return err
}
ok, err := pubKey.Verify([]byte(data), sigBytes)
if !ok || err != nil {
return fmt.Errorf("can't verify session signature: %v", err)
}
return nil
}
func getSessionSignature() (string, error) {
if utils.ApiConfig.SessionSignature == "" {
return "", errors.New("API session signature is not yet created. NewSessionSignature() should be called.")
}
return utils.GetSessionSignature(), nil
}
// Storage upload api.
func (s *Shell) StorageUpload(hash string, options ...StorageUploadOpts) (string, error) {
var out storageUploadResponse
rb := s.Request("storage/upload", hash)
for _, option := range options {
_ = option(rb)
}
return out.ID, rb.Exec(context.Background(), &out)
}
// Storage upload api.
func (s *Shell) StorageUploadOffSign(hash string, uts string, options ...StorageUploadOpts) (string, error) {
var out storageUploadResponse
offlinePeerSessionSignature, err := NewSessionSignature(hash, utils.GetPeerId(), uts, false)
if err != nil {
return "", err
}
rb := s.Request("storage/upload", hash, utils.GetPeerId(), uts, offlinePeerSessionSignature)
for _, option := range options {
_ = option(rb)
}
return out.ID, rb.Exec(context.Background(), &out)
}
// Storage upload status api.
func (s *Shell) StorageUploadStatus(id string) (*Storage, error) {
var out Storage
rb := s.Request("storage/upload/status", id)
return &out, rb.Exec(context.Background(), &out)
}
// Storage upload get offline contract batch api.
func (s *Shell) StorageUploadGetContractBatch(sid string, uts string, t string) (*Contracts, error) {
var out Contracts
offlinePeerSessionSignature, err := getSessionSignature()
if err != nil {
return nil, err
}
rb := s.Request("storage/upload/getcontractbatch", sid, utils.GetPeerId(), uts, offlinePeerSessionSignature, t)
return &out, rb.Exec(context.Background(), &out)
}
// Storage upload get offline unsigned data api.
func (s *Shell) StorageUploadGetUnsignedData(sid string, uts string, sessionStatus string) (*UnsignedData, error) {
var out UnsignedData
offlinePeerSessionSignature, err := getSessionSignature()
if err != nil {
return nil, err
}
rb := s.Request("storage/upload/getunsigned", sid, utils.GetPeerId(), uts, offlinePeerSessionSignature, sessionStatus)
return &out, rb.Exec(context.Background(), &out)
}
// Storage upload sign offline contract batch api.
func (s *Shell) StorageUploadSignBatch(sid string, unsignedBatchContracts *Contracts, uts string, t string) error {
var signedBatchContracts *Contracts
var errSign error
offlinePeerSessionSignature, err := getSessionSignature()
if err != nil {
return err
}
signedBatchContracts, errSign = unsignedBatchContracts.SignContracts(utils.GetPrivateKey(), t)
if errSign != nil {
return err
}
bytesSignBatch, err := json.Marshal(signedBatchContracts.Contracts)
if err != nil {
return err
}
rb := s.Request("storage/upload/signcontractbatch", sid, utils.GetPeerId(), uts, offlinePeerSessionSignature,
t, string(bytesSignBatch))
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
errSign = rb.Exec(ctx, nil)
return errSign
}
// Storage upload sign offline data api.
func (s *Shell) StorageUploadSign(id string, hash string, unsignedData *UnsignedData, uts string, sessionStatus string) ([]byte, error) {
var out []byte
var rb *RequestBuilder
offlinePeerSessionSignature, err := getSessionSignature()
if err != nil {
return nil, err
}
signedBytes, err := unsignedData.SignData(utils.GetPrivateKey())
if err != nil {
return nil, err
}
rb = s.Request("storage/upload/sign", id, utils.GetPeerId(), uts, offlinePeerSessionSignature, string(signedBytes), sessionStatus)
return out, rb.Exec(context.Background(), &out)
}
func (s *Shell) StorageUploadSignBalance(id string, unsignedData *UnsignedData, uts string, sessionStatus string) error {
var rb *RequestBuilder
offlinePeerSessionSignature, err := getSessionSignature()
if err != nil {
return err
}
ledgerSignedPublicKey, err := unsignedData.SignBalanceData(utils.GetPrivateKey())
if err != nil {
return err
}
signedBytes, err := proto.Marshal(ledgerSignedPublicKey) // TODO: check if ic.Marshall is necessary!
if err != nil {
return err
}
str, err := cutils.BytesToString(signedBytes, cutils.Base64)
if err != nil {
return err
}
rb = s.Request("storage/upload/sign", id, utils.GetPeerId(), uts, offlinePeerSessionSignature, sessionStatus, str)
return rb.Exec(context.Background(), nil)
}
func (s *Shell) StorageUploadSignPayChannel(id string, unsignedData *UnsignedData, uts string, sessionStatus string,
totalPrice int64) error {
var rb *RequestBuilder
offlinePeerSessionSignature, err := getSessionSignature()
if err != nil {
return err
}
unsignedBytes, err := cutils.StringToBytes(unsignedData.Unsigned, cutils.Base64)
if err != nil {
return err
}
escrowPubKey, err := ic.UnmarshalPublicKey(unsignedBytes)
if err != nil {
return err
}
buyerPubKey, err := crypto.ToPubKey(utils.GetPublicKey())
if err != nil {
return err
}
fromAddr, err := ic.MarshalPublicKey(buyerPubKey)
if err != nil {
return err
}
toAddr, err := ic.MarshalPublicKey(escrowPubKey)
if err != nil {
return err
}
chanCommit := &ledgerpb.ChannelCommit{
Payer: &ledgerpb.PublicKey{Key: fromAddr},
Recipient: &ledgerpb.PublicKey{Key: toAddr},
Amount: totalPrice,
PayerId: time.Now().UnixNano(),
}
buyerPrivKey, err := crypto.ToPrivKey(utils.GetPrivateKey())
if err != nil {
return err
}
buyerChanSig, err := crypto.Sign(buyerPrivKey, chanCommit)
if err != nil {
return err
}
signedChanCommit := &ledgerpb.SignedChannelCommit{
Channel: chanCommit,
Signature: buyerChanSig,
}
signedChanCommitBytes, err := proto.Marshal(signedChanCommit)
if err != nil {
return err
}
signedChanCommitBytesStr, err := cutils.BytesToString(signedChanCommitBytes, cutils.Base64)
if err != nil {
return err
}
rb = s.Request("storage/upload/sign", id, utils.GetPeerId(), uts, offlinePeerSessionSignature, sessionStatus,
signedChanCommitBytesStr)
return rb.Exec(context.Background(), nil)
}
func (s *Shell) StorageUploadSignPayRequest(id string, unsignedData *UnsignedData, uts string,
sessionStatus string) error {
var rb *RequestBuilder
offlinePeerSessionSignature, err := getSessionSignature()
if err != nil {
return err
}
unsignedBytes, err := cutils.StringToBytes(unsignedData.Unsigned, cutils.Base64)
if err != nil {
return err
}
result := new(escrowpb.SignedSubmitContractResult)
err = proto.Unmarshal(unsignedBytes, result)
if err != nil {
return err
}
chanState := result.Result.BuyerChannelState
privKey, err := crypto.ToPrivKey(utils.GetPrivateKey())
if err != nil {
return err
}
sig, err := crypto.Sign(privKey, chanState.Channel)
if err != nil {
return err
}
chanState.FromSignature = sig
payerPubKey, _ := crypto.ToPubKey(utils.GetPublicKey())
raw, err := ic.MarshalPublicKey(payerPubKey)
if err != nil {
return err
}
payinReq := &escrowpb.PayinRequest{
PayinId: result.Result.PayinId,
BuyerAddress: raw,
BuyerChannelState: chanState,
}
payinSig, err := crypto.Sign(privKey, payinReq)
if err != nil {
return err
}
signedPayinReq := &escrowpb.SignedPayinRequest{
Request: payinReq,
BuyerSignature: payinSig,
}
signedPayinReqBytes, err := proto.Marshal(signedPayinReq)
if err != nil {
return err
}
str, err := cutils.BytesToString(signedPayinReqBytes, cutils.Base64)
if err != nil {
return err
}
rb = s.Request("storage/upload/sign", id, utils.GetPeerId(), uts, offlinePeerSessionSignature, sessionStatus, str)
return rb.Exec(context.Background(), nil)
}
func (s *Shell) StorageUploadSignGuardFileMeta(id string, unsignedData *UnsignedData,
uts string, sessionStatus string) error {
var rb *RequestBuilder
offlinePeerSessionSignature, err := getSessionSignature()
if err != nil {
return err
}
unsignedBytes, err := cutils.StringToBytes(unsignedData.Unsigned, cutils.Base64)
if err != nil {
return err
}
meta := new(guardpb.FileStoreMeta)
err = proto.Unmarshal(unsignedBytes, meta)
if err != nil {
return err
}
privKey, err := crypto.ToPrivKey(utils.GetPrivateKey())
if err != nil {
return err
}
signed, err := crypto.Sign(privKey, meta)
if err != nil {
return err
}
str, err := cutils.BytesToString(signed, cutils.Base64)
if err != nil {
return err
}
rb = s.Request("storage/upload/sign", id, utils.GetPeerId(), uts, offlinePeerSessionSignature, sessionStatus, str)
return rb.Exec(context.Background(), nil)
}
func (s *Shell) StorageUploadSignGuardQuestions(id string, unsignedData *UnsignedData,
uts string, sessionStatus string) error {
var rb *RequestBuilder
offlinePeerSessionSignature, err := getSessionSignature()
if err != nil {
return err
}
unsignedBytes, err := cutils.StringToBytes(unsignedData.Unsigned, cutils.Base64)
if err != nil {
return err
}
fcq := new(guardpb.FileChallengeQuestions)
err = proto.Unmarshal(unsignedBytes, fcq)
if err != nil {
return err
}
privKey, err := crypto.ToPrivKey(utils.GetPrivateKey())
if err != nil {
return err
}
for _, sq := range fcq.ShardQuestions {
sign, err := crypto.Sign(privKey, sq)
if err != nil {
return err
}
sq.PreparerSignature = sign
}
signed, err := proto.Marshal(fcq)
if err != nil {
return err
}
str, err := cutils.BytesToString(signed, cutils.Base64)
if err != nil {
return err
}
rb = s.Request("storage/upload/sign", id, utils.GetPeerId(), uts, offlinePeerSessionSignature, sessionStatus, str)
return rb.Exec(context.Background(), nil)
}
func (s *Shell) StorageUploadSignWaitupload(id string, unsignedData *UnsignedData,
uts string, sessionStatus string) error {
var rb *RequestBuilder
offlinePeerSessionSignature, err := getSessionSignature()
if err != nil {
return err
}
unsignedBytes, err := cutils.StringToBytes(unsignedData.Unsigned, cutils.Base64)
if err != nil {
return err
}
meta := new(guardpb.CheckFileStoreMetaRequest)
err = proto.Unmarshal(unsignedBytes, meta)
if err != nil {
return err
}
privKey, err := crypto.ToPrivKey(utils.GetPrivateKey())
if err != nil {
return err
}
signed, err := crypto.Sign(privKey, meta)
if err != nil {
return err
}
str, err := cutils.BytesToString(signed, cutils.Base64)
if err != nil {
return err
}
rb = s.Request("storage/upload/sign", id, utils.GetPeerId(), uts, offlinePeerSessionSignature, sessionStatus, str)
return rb.Exec(context.Background(), nil)
}