-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathocean.go
373 lines (334 loc) · 8.8 KB
/
ocean.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
package main
import (
"context"
"encoding/hex"
"fmt"
"github.com/vulpemventures/go-elements/address"
"github.com/vulpemventures/go-elements/elementsutil"
"github.com/vulpemventures/go-elements/transaction"
pb "github.com/vulpemventures/ocean/api-spec/protobuf/gen/go/ocean/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
const MSATS_PER_BYTE = 110
type service struct {
addr string
accountName string
conn *grpc.ClientConn
walletClient pb.WalletServiceClient
accountClient pb.AccountServiceClient
txClient pb.TransactionServiceClient
notifyClient pb.NotificationServiceClient
}
type WalletService interface {
Status(ctx context.Context) (WalletStatus, error)
GetAddress(ctx context.Context, isChange bool) (string, []byte, error)
Balance(ctx context.Context, assetHash string) (Balance, error)
SelectUtxos(ctx context.Context, asset string, amount uint64) ([]UTXO, uint64, error)
SignPset(
ctx context.Context, pset string, extractRawTx bool,
) (string, error)
Transfer(ctx context.Context, outs []TxOutput) (string, error)
BroadcastTransaction(ctx context.Context, txHex string) (string, error)
TransactionNotifications(ctx context.Context) (<-chan *TransactionNotification, error)
WatchScript(ctx context.Context, script string) error
Close()
}
type WalletStatus interface {
IsInitialized() bool
IsUnlocked() bool
IsSynced() bool
}
type TxInput interface {
GetTxid() string
GetIndex() uint32
GetScript() string
GetScriptSigSize() int
GetWitnessSize() int
}
type TxOutput interface {
GetAmount() uint64
GetAsset() string
GetScript() string
}
type Utxo interface {
GetTxid() string
GetIndex() uint32
GetAsset() string
GetValue() uint64
GetScript() string
GetAssetBlinder() string
GetValueBlinder() string
GetAccountName() string
GetSpentStatus() *pb.UtxoStatus
GetConfirmedStatus() *pb.UtxoStatus
GetRedeemScript() string
}
type walletStatus struct {
*pb.StatusResponse
}
type getIn struct {
*pb.StatusResponse
}
func (w walletStatus) IsInitialized() bool {
return w.StatusResponse.GetInitialized()
}
func (w walletStatus) IsUnlocked() bool {
return w.StatusResponse.GetUnlocked()
}
func (w walletStatus) IsSynced() bool {
return w.StatusResponse.GetSynced()
}
type UTXO struct {
Txid string `json:"txid"`
Index int `json:"index"`
Value uint64 `json:"value"`
Prevout *transaction.TxOutput
Status struct {
Confirmed bool `json:"confirmed"`
} `json:"status"`
}
func NewWalletService(addr, accountName string) (WalletService, error) {
conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return nil, err
}
walletClient := pb.NewWalletServiceClient(conn)
accountClient := pb.NewAccountServiceClient(conn)
txClient := pb.NewTransactionServiceClient(conn)
notifyClient := pb.NewNotificationServiceClient(conn)
svc := &service{
addr: addr,
accountName: accountName,
conn: conn,
walletClient: walletClient,
accountClient: accountClient,
txClient: txClient,
notifyClient: notifyClient,
}
ctx := context.Background()
status, err := svc.Status(ctx)
if err != nil {
return nil, err
}
if !(status.IsInitialized() && status.IsUnlocked()) {
return nil, fmt.Errorf("wallet must be already initialized and unlocked")
}
// Create ark account at startup if needed.
info, err := walletClient.GetInfo(ctx, &pb.GetInfoRequest{})
if err != nil {
return nil, err
}
found := false
for _, account := range info.GetAccounts() {
if account.GetLabel() == svc.accountName {
found = true
break
}
}
if !found {
if _, err := accountClient.CreateAccountBIP44(ctx, &pb.CreateAccountBIP44Request{
Label: svc.accountName,
Unconfidential: true,
}); err != nil {
return nil, err
}
}
return svc, nil
}
func (s *service) Close() {
s.conn.Close()
}
func (s *service) Status(
ctx context.Context,
) (WalletStatus, error) {
res, err := s.walletClient.Status(ctx, &pb.StatusRequest{})
if err != nil {
return nil, err
}
return walletStatus{res}, nil
}
type Balance struct {
AvailableBalance uint64
PendingBalance uint64
}
func (s *service) Balance(ctx context.Context, assetHash string) (Balance, error) {
balanceResponse, err := s.accountClient.Balance(ctx, &pb.BalanceRequest{
AccountName: s.accountName,
})
if err != nil {
return Balance{}, err
}
balanceByAsset := balanceResponse.GetBalance()
balanceInfo, ok := balanceByAsset[assetHash]
if !ok {
return Balance{}, fmt.Errorf("asset not found")
}
return Balance{
AvailableBalance: balanceInfo.GetConfirmedBalance(),
PendingBalance: balanceInfo.GetUnconfirmedBalance(),
}, nil
}
func (s *service) GetAddress(
ctx context.Context, isChange bool,
) (string, []byte, error) {
var addr string
if isChange {
res, err := s.accountClient.DeriveChangeAddresses(ctx, &pb.DeriveChangeAddressesRequest{
AccountName: s.accountName,
NumOfAddresses: uint64(1),
})
if err != nil {
return "", nil, err
}
if len(res.GetAddresses()) == 0 {
return "", nil, err
}
addr = res.GetAddresses()[0]
} else {
res, err := s.accountClient.DeriveAddresses(ctx, &pb.DeriveAddressesRequest{
AccountName: s.accountName,
NumOfAddresses: uint64(1),
})
if err != nil {
return "", nil, err
}
if len(res.GetAddresses()) == 0 {
return "", nil, err
}
addr = res.GetAddresses()[0]
}
script, err := address.ToOutputScript(addr)
if err != nil {
return "", nil, err
}
return addr, script, nil
}
type TransactionNotification struct {
TxId string
Confirmed bool
Timestamp int64
}
func (s *service) TransactionNotifications(ctx context.Context) (<-chan *TransactionNotification, error) {
//
// Create a channel to receive notifications
notifChan := make(chan *TransactionNotification)
// Start the TransactionNotifications RPC
notifStream, err := s.notifyClient.TransactionNotifications(
ctx, &pb.TransactionNotificationsRequest{},
)
if err != nil {
return nil, fmt.Errorf("failed to start TransactionNotifications RPC: %w", err)
}
// Start a goroutine to receive notifications from the Notification RPC and send them to the channel
go func() {
for {
resp, err := notifStream.Recv()
if err != nil {
// Handle error...
break
}
notif := &TransactionNotification{
TxId: resp.GetTxid(),
Confirmed: false,
Timestamp: 0,
}
blockDetails := resp.GetBlockDetails()
if blockDetails != nil {
notif.Confirmed = true
notif.Timestamp = blockDetails.GetTimestamp()
}
notifChan <- notif
}
}()
return notifChan, nil
}
func (s *service) WatchScript(ctx context.Context, script string) error {
// Start the Watch RPC
_, err := s.notifyClient.WatchExternalScript(ctx, &pb.WatchExternalScriptRequest{Script: script})
if err != nil {
return fmt.Errorf("failed to start Watch RPC: %w", err)
}
return nil
}
func (s *service) SelectUtxos(
ctx context.Context, asset string, value uint64,
) ([]UTXO, uint64, error) {
res, err := s.txClient.SelectUtxos(ctx, &pb.SelectUtxosRequest{
AccountName: s.accountName,
TargetAsset: asset,
TargetAmount: value,
})
if err != nil {
return nil, 0, err
}
utxos := make([]UTXO, len(res.GetUtxos()))
for i, utxo := range res.GetUtxos() {
assetBytes, _ := elementsutil.AssetHashToBytes(utxo.Asset)
valueBytes, _ := elementsutil.ValueToBytes(utxo.Value)
scritpBytes, _ := hex.DecodeString(utxo.Script)
prevout := transaction.NewTxOutput(assetBytes, valueBytes, scritpBytes)
utxos[i] = UTXO{
Txid: utxo.GetTxid(),
Index: int(utxo.GetIndex()),
Value: utxo.GetValue(),
Prevout: prevout,
Status: struct {
Confirmed bool `json:"confirmed"`
}{
Confirmed: true,
},
}
}
return utxos, res.GetChange(), nil
}
func (s *service) SignPset(
ctx context.Context, pset string, extractRawTx bool,
) (string, error) {
res, err := s.txClient.SignPset(ctx, &pb.SignPsetRequest{
Pset: pset,
})
if err != nil {
return "", err
}
signedPset := res.GetPset()
return signedPset, nil
}
func (s *service) Transfer(
ctx context.Context, outs []TxOutput,
) (string, error) {
res, err := s.txClient.Transfer(ctx, &pb.TransferRequest{
AccountName: s.accountName,
Receivers: outputList(outs).toProto(),
MillisatsPerByte: MSATS_PER_BYTE,
})
if err != nil {
return "", err
}
return res.GetTxHex(), nil
}
func (s *service) BroadcastTransaction(
ctx context.Context, txHex string,
) (string, error) {
res, err := s.txClient.BroadcastTransaction(
ctx, &pb.BroadcastTransactionRequest{
TxHex: txHex,
},
)
if err != nil {
return "", err
}
return res.GetTxid(), nil
}
type outputList []TxOutput
func (l outputList) toProto() []*pb.Output {
list := make([]*pb.Output, 0, len(l))
for _, out := range l {
list = append(list, &pb.Output{
Amount: out.GetAmount(),
Script: out.GetScript(),
Asset: out.GetAsset(),
})
}
return list
}