/
client.go
469 lines (405 loc) · 10.6 KB
/
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
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
package apiv1
import (
"context"
"crypto/ed25519"
"encoding/json"
"fmt"
"github.com/filinvadim/bigchaindb-go/client"
"github.com/filinvadim/bigchaindb-go/client/operations"
"github.com/filinvadim/bigchaindb-go/models"
"github.com/filinvadim/stubborn"
"github.com/go-openapi/runtime"
httptransport "github.com/go-openapi/runtime/client"
"github.com/gorilla/websocket"
"github.com/mr-tron/base58"
"github.com/pkg/errors"
"io"
"net/http"
"strconv"
"strings"
"time"
)
type (
txMode string
txOp string
RESTClientV1 struct {
ctx context.Context
client *client.BigchainClient
pair *KeyPair
}
bcError string
Transaction = models.Transaction
Block = models.Block
Fulfills = models.Fulfills
Asset = models.Asset
Metadata = models.Metadata
ValidTransaction = models.ValidTransactionResponse
)
const (
testNet = "https://test.ipdb.io"
basePath = "/api/v1"
ErrNilTx = bcError("nil transaction provided")
ErrNoKeyPairs = bcError("no key pairs provided")
ModeAsync = txMode(models.TransactionModeAsync)
ModeSync = txMode(models.TransactionModeSync)
ModeCommit = txMode(models.TransactionModeCommit)
OpCreate = txOp(models.TransactionOperationCREATE)
OpTransfer = txOp(models.TransactionOperationTRANSFER)
)
func (e bcError) Error() string {
return string(e)
}
var DefaultSchemes = []string{"http"}
func NewRESTClientV1(ctx context.Context, host string, ownerKeyPair *KeyPair) (*RESTClientV1, error) {
if ownerKeyPair == nil {
return nil, ErrNoKeyPairs
}
strings.TrimRight(host, "/")
_, err := ping(host)
if err != nil {
return nil, errors.Wrap(err, "ping")
}
transport := httptransport.New(host, basePath, DefaultSchemes)
cli := client.New(transport, nil)
return &RESTClientV1{ctx, cli, ownerKeyPair}, err
}
var defaultOpt = func(op *runtime.ClientOperation) {}
type CreateParams struct {
Mode txMode
Amount float64
TxData, MetaData any
}
// CreateTx : all key names (e.g. anywhere in the JSON documents stored in asset.data or metadata):
// - must not begin with $
// - must not contain .
// - must not contain the null character (Unicode code point U+0000)
func (c *RESTClientV1) CreateTx(params CreateParams) (*Transaction, error) {
tx := c.prepareCreateTx(
strconv.FormatFloat(params.Amount, 'g', -1, 32), params.TxData, params.MetaData,
)
err := SignTx(tx, []*KeyPair{c.pair})
if err != nil {
return nil, err
}
resp, err := c.client.Operations.PostTransactions(&operations.PostTransactionsParams{
Mode: func(m txMode) *string { s := string(m); return &s }(params.Mode),
Context: c.ctx,
PostBody: tx,
}, defaultOpt)
if err != nil {
return nil, err
}
if !resp.IsSuccess() {
return nil, responseError(resp.Error(), "creation")
}
return resp.Payload, nil
}
func (c *RESTClientV1) prepareCreateTx(amount string, td, md any) *Transaction {
if amount == "0" {
amount = "1"
}
tp := models.TransactionOutputConditionDetailsTypeEd25519DashShaDash256
tx := models.Transaction{
Asset: &models.Asset{
Data: td,
},
Metadata: md,
Operation: string(OpCreate),
Outputs: []*models.TransactionOutput{
{
Amount: amount,
Condition: models.TransactionOutputCondition{
Details: models.TransactionOutputConditionDetails{
PublicKey: base58.Encode(c.pair.PublicKey),
Type: tp,
},
URI: NewURIfromKey(c.pair.PublicKey),
},
PublicKeys: []string{base58.Encode(c.pair.PublicKey)},
},
},
Version: models.TransactionVersionNr2Dot0,
}
tx.Inputs = append(tx.Inputs,
&models.TransactionInput{
Fulfillment: nil,
Fulfills: nil,
OwnersBefore: []string{base58.Encode(c.pair.PublicKey)},
},
)
return &tx
}
type TransferParams struct {
Mode txMode
Amount float64
From Owner
To ed25519.PublicKey
MetaData any
}
type Owner struct {
TxID string
Pair *KeyPair
}
func (c *RESTClientV1) TransferOneToOne(params TransferParams) (*Transaction, error) {
if params.From.TxID == "" {
return nil, ErrNilTx
}
if params.To == nil {
return nil, errors.New("empty destination public key")
}
tx := c.prepareTransferTx(
strconv.FormatFloat(params.Amount, 'g', -1, 32), params.From, params.To, params.MetaData,
)
err := SignTx(tx, []*KeyPair{params.From.Pair})
if err != nil {
return nil, err
}
resp, err := c.client.Operations.PostTransactions(&operations.PostTransactionsParams{
Mode: func(m txMode) *string { s := string(m); return &s }(params.Mode),
Context: c.ctx,
PostBody: tx,
}, defaultOpt)
if err != nil {
return nil, err
}
if !resp.IsSuccess() {
return nil, responseError(resp.Error(), "transfer")
}
return resp.Payload, nil
}
func (c *RESTClientV1) prepareTransferTx(
amount string,
owner Owner,
dest ed25519.PublicKey,
md any,
) *Transaction {
if amount == "0" {
amount = "1"
}
tp := models.TransactionOutputConditionDetailsTypeEd25519DashShaDash256
tx := models.Transaction{
Asset: &models.Asset{
ID: owner.TxID,
},
Metadata: md,
Operation: string(OpTransfer),
Outputs: []*models.TransactionOutput{
{
Amount: amount,
Condition: models.TransactionOutputCondition{
Details: models.TransactionOutputConditionDetails{
PublicKey: base58.Encode(dest),
Type: tp,
},
URI: NewURIfromKey(dest),
},
PublicKeys: []string{base58.Encode(dest)},
},
},
Version: models.TransactionVersionNr2Dot0,
}
tx.Inputs = append(tx.Inputs,
&models.TransactionInput{
Fulfillment: nil,
Fulfills: &models.Fulfills{
OutputIndex: 0,
TransactionID: owner.TxID,
},
OwnersBefore: []string{base58.Encode(owner.Pair.PublicKey)},
},
)
return &tx
}
// TransferManyToMany TODO
func (c *RESTClientV1) TransferManyToMany(
mode txMode,
amount float64,
prevTx []*Transaction,
destPubKeys []string,
metaData any,
) error {
panic("not implemented")
return nil
}
func (c *RESTClientV1) GetBlockHeight(blockHeight int64) (*Block, error) {
resp, err := c.client.Operations.GetBlocksBlockHeight(&operations.GetBlocksBlockHeightParams{
BlockHeight: blockHeight,
Context: c.ctx,
})
if err != nil {
return nil, err
}
if !resp.IsSuccess() {
return nil, responseError(resp.Error(), "block height")
}
return resp.Payload, nil
}
func (c *RESTClientV1) GetTransaction(txID string) (*Transaction, error) {
resp, err := c.client.Operations.GetTransactionsTransactionID(&operations.GetTransactionsTransactionIDParams{
TransactionID: txID,
Context: c.ctx,
})
if err != nil {
return nil, err
}
if !resp.IsSuccess() {
return nil, responseError(resp.Error(), "single tx")
}
return resp.Payload, nil
}
func (c *RESTClientV1) ListBlocks(txID string) ([]int64, error) {
resp, err := c.client.Operations.GetBlocks(&operations.GetBlocksParams{
TransactionID: txID,
Context: c.ctx,
})
if err != nil {
return nil, err
}
if !resp.IsSuccess() {
return nil, responseError(resp.Error(), "blocks list")
}
return resp.Payload, nil
}
func (c *RESTClientV1) ListOutputs(pubKey string, spent bool) ([]*Fulfills, error) {
resp, err := c.client.Operations.GetOutputs(&operations.GetOutputsParams{
PublicKey: pubKey,
Spent: &spent,
Context: c.ctx,
})
if err != nil {
return nil, err
}
if !resp.IsSuccess() {
return nil, responseError(resp.Error(), "outputs list")
}
return resp.Payload, nil
}
func (c *RESTClientV1) ListTransactions(assetID string, operation txOp, onlyLast bool) ([]*Transaction, error) {
resp, err := c.client.Operations.GetTransactions(&operations.GetTransactionsParams{
AssetID: &assetID,
LastTx: &onlyLast,
Operation: func(op txOp) *string { s := string(op); return &s }(operation),
Context: c.ctx,
})
if err != nil {
return nil, err
}
if !resp.IsSuccess() {
return nil, responseError(resp.Error(), "tx list")
}
return resp.Payload, nil
}
func (c *RESTClientV1) SearchAsset(search string, limit int64) ([]*Asset, error) {
var reqLimit *int64
if limit > 0 {
reqLimit = &limit
}
resp, err := c.client.Operations.GetAssets(&operations.GetAssetsParams{
Limit: reqLimit,
Search: search,
Context: c.ctx,
})
if err != nil {
return nil, err
}
if !resp.IsSuccess() {
return nil, responseError(resp.Error(), "search asset")
}
return resp.Payload, nil
}
func (c *RESTClientV1) SearchMetadata(search string, limit int64) ([]Metadata, error) {
var reqLimit *int64
if limit > 0 {
reqLimit = &limit
}
resp, err := c.client.Operations.GetMetadata(&operations.GetMetadataParams{
Limit: reqLimit,
Search: search,
Context: c.ctx,
})
if err != nil {
return nil, err
}
if !resp.IsSuccess() {
return nil, errors.New(resp.Error())
}
return resp.Payload, nil
}
func responseError(resp, msg string) error {
return fmt.Errorf("%s: %s", msg, resp)
}
// ============================================WEBSOCKET=================================================
type WSClient struct {
url string
ctx context.Context
logf func(format string, v ...any)
stub *stubborn.Client
}
type BigChainDBDialer = stubborn.DuplexConnector
func NewWSClient(ctx context.Context, host string, logf func(format string, v ...any)) (*WSClient, error) {
strings.TrimRight(host, "/")
return &WSClient{
url: "ws://" + host + basePath + "/streams/valid_transactions",
ctx: ctx,
logf: logf,
}, nil
}
func (ws *WSClient) SubscribeStream(stream chan ValidTransaction) error {
if ws == nil {
return errors.New("not connected")
}
ws.stub = stubborn.NewStubborn(stubborn.Config{
IsReconnectable: true,
MessageType: stubborn.TextMessage,
Dialerf: func(ctx context.Context) (BigChainDBDialer, error) {
conn, _, err := websocket.DefaultDialer.DialContext(
ctx,
ws.url,
nil,
)
conn.SetReadDeadline(time.Now().Add(time.Minute))
conn.WriteMessage(stubborn.TextMessage, []byte("ping"))
return conn, err
},
UnimportantErrs: []error{io.EOF},
})
ws.stub.SetErrorHandler(func(err error) {
if ws.logf != nil {
ws.logf("websocket connection failure: %v", err)
}
})
ws.stub.SetMessageHandler(func(resp []byte) {
if ws.logf != nil {
ws.logf("websocket message: %s", resp)
}
var validTx ValidTransaction
err := json.Unmarshal(resp, &validTx)
if err != nil {
if ws.logf != nil {
ws.logf("websocket message handling failure: %v %s", err, resp)
}
return
}
stream <- validTx
})
return ws.stub.Connect(ws.ctx)
}
func (ws *WSClient) Close() {
ws.stub.Close()
}
func ping(host string) ([]byte, error) {
url := "http://" + host + basePath
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
bt, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, errors.New(string(bt))
}
return bt, nil
}