-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery.go
More file actions
314 lines (278 loc) · 7.93 KB
/
query.go
File metadata and controls
314 lines (278 loc) · 7.93 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
// Copyright 2024 Blink Labs Software
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utxorpc
import (
"bytes"
"context"
"encoding/hex"
"fmt"
"log"
connect "connectrpc.com/connect"
"github.com/blinklabs-io/gouroboros/ledger"
"github.com/blinklabs-io/gouroboros/ledger/common"
// ocommon "github.com/blinklabs-io/gouroboros/protocol/common"
query "github.com/utxorpc/go-codegen/utxorpc/v1alpha/query"
"github.com/utxorpc/go-codegen/utxorpc/v1alpha/query/queryconnect"
"github.com/blinklabs-io/cardano-node-api/internal/node"
)
// queryServiceServer implements the WatchService API
type queryServiceServer struct {
queryconnect.UnimplementedQueryServiceHandler
}
// ReadParams
func (s *queryServiceServer) ReadParams(
ctx context.Context,
req *connect.Request[query.ReadParamsRequest],
) (*connect.Response[query.ReadParamsResponse], error) {
fieldMask := req.Msg.GetFieldMask()
log.Printf("Got a ReadParams request with fieldMask %v", fieldMask)
resp := &query.ReadParamsResponse{}
// Connect to node
oConn, err := node.GetConnection(nil)
if err != nil {
return nil, err
}
defer func() {
// Close Ouroboros connection
oConn.Close()
}()
// Start client
oConn.LocalStateQuery().Client.Start()
// Get protoParams
protoParams, err := oConn.LocalStateQuery().Client.GetCurrentProtocolParams()
if err != nil {
return nil, err
}
// Get chain point (slot and hash)
point, err := oConn.LocalStateQuery().Client.GetChainPoint()
if err != nil {
return nil, err
}
// Set up response parameters
acpc := &query.AnyChainParams_Cardano{
Cardano: protoParams.Utxorpc(),
}
resp.LedgerTip = &query.ChainPoint{
Slot: point.Slot,
Hash: point.Hash,
}
resp.Values = &query.AnyChainParams{
Params: acpc,
}
return connect.NewResponse(resp), nil
}
// ReadUtxos
func (s *queryServiceServer) ReadUtxos(
ctx context.Context,
req *connect.Request[query.ReadUtxosRequest],
) (*connect.Response[query.ReadUtxosResponse], error) {
keys := req.Msg.GetKeys() // []*TxoRef
log.Printf("Got a ReadUtxos request with keys %v", keys)
resp := &query.ReadUtxosResponse{}
// Connect to node
oConn, err := node.GetConnection(nil)
if err != nil {
return nil, err
}
defer func() {
// Close Ouroboros connection
oConn.Close()
}()
// Start client
oConn.LocalStateQuery().Client.Start()
// Setup our query input
tmpTxIns := []ledger.TransactionInput{}
for _, txo := range keys {
// txo.Hash, txo.Index
tmpTxIn := ledger.ShelleyTransactionInput{
TxId: ledger.Blake2b256(txo.GetHash()),
OutputIndex: uint32(txo.GetIndex()),
}
tmpTxIns = append(tmpTxIns, tmpTxIn)
}
// Get UTxOs
utxos, err := oConn.LocalStateQuery().Client.GetUTxOByTxIn(tmpTxIns)
if err != nil {
return nil, err
}
// Get chain point (slot and hash)
point, err := oConn.LocalStateQuery().Client.GetChainPoint()
if err != nil {
return nil, err
}
for _, txo := range keys {
for utxoId, utxo := range utxos.Results {
var aud query.AnyUtxoData
var audc query.AnyUtxoData_Cardano
aud.TxoRef = txo
txHash := hex.EncodeToString(txo.GetHash())
if utxoId.Hash.String() == txHash &&
// #nosec G115
uint32(utxoId.Idx) == txo.GetIndex() {
aud.NativeBytes = utxo.Cbor()
audc.Cardano = utxo.Utxorpc()
if audc.Cardano.GetDatum() != nil {
// Check if Datum.Hash is all zeroes
isAllZeroes := true
for _, b := range audc.Cardano.GetDatum().GetHash() {
if b != 0 {
isAllZeroes = false
break
}
}
if isAllZeroes {
// No actual datum; set Datum to nil to omit it
audc.Cardano.Datum = nil
log.Print(
"Datum Hash is all zeroes; setting Datum to nil",
)
} else {
log.Printf("Datum Hash present: %x", audc.Cardano.GetDatum().GetHash())
}
}
aud.ParsedState = &audc
}
resp.Items = append(resp.Items, &aud)
}
}
resp.LedgerTip = &query.ChainPoint{
Slot: point.Slot,
Hash: point.Hash,
}
log.Printf(
"Prepared response with LedgerTip: Slot=%v, Hash=%v",
resp.GetLedgerTip().GetSlot(),
resp.GetLedgerTip().GetHash(),
)
log.Printf("Final response: %v", resp)
return connect.NewResponse(resp), nil
}
// SearchUtxos
func (s *queryServiceServer) SearchUtxos(
ctx context.Context,
req *connect.Request[query.SearchUtxosRequest],
) (*connect.Response[query.SearchUtxosResponse], error) {
predicate := req.Msg.GetPredicate() // UtxoPredicate
log.Printf("Got a SearchUtxos request with predicate %v", predicate)
resp := &query.SearchUtxosResponse{}
if predicate == nil {
return nil, fmt.Errorf("ERROR: empty predicate: %v", predicate)
}
addressPattern := predicate.GetMatch().GetCardano().GetAddress()
assetPattern := predicate.GetMatch().GetCardano().GetAsset()
var addresses []common.Address
if addressPattern != nil {
// Handle Exact Address
exactAddressBytes := addressPattern.GetExactAddress()
if exactAddressBytes != nil {
var addr common.Address
err := addr.UnmarshalCBOR(exactAddressBytes)
if err != nil {
return nil, fmt.Errorf(
"failed to decode exact address: %w",
err,
)
}
addresses = append(addresses, addr)
}
// Handle Payment Part
paymentPart := addressPattern.GetPaymentPart()
if paymentPart != nil {
log.Printf("PaymentPart is present, decoding...")
var paymentAddr common.Address
err := paymentAddr.UnmarshalCBOR(paymentPart)
if err != nil {
return nil, fmt.Errorf("failed to decode payment part: %w", err)
}
addresses = append(addresses, paymentAddr)
}
// Handle Delegation Part
delegationPart := addressPattern.GetDelegationPart()
if delegationPart != nil {
log.Printf("DelegationPart is present, decoding...")
var delegationAddr common.Address
err := delegationAddr.UnmarshalCBOR(delegationPart)
if err != nil {
return nil, fmt.Errorf(
"failed to decode delegation part: %w",
err,
)
}
addresses = append(addresses, delegationAddr)
}
}
// Connect to node
oConn, err := node.GetConnection(nil)
if err != nil {
return nil, err
}
defer func() {
// Close Ouroboros connection
oConn.Close()
}()
// Start client
oConn.LocalStateQuery().Client.Start()
// Get UTxOs
utxos, err := oConn.LocalStateQuery().Client.GetUTxOByAddress(addresses)
if err != nil {
log.Printf("ERROR: %s", err)
return nil, err
}
// Get chain point (slot and hash)
point, err := oConn.LocalStateQuery().Client.GetChainPoint()
if err != nil {
log.Printf("ERROR: %s", err)
return nil, err
}
// Proceed to include the UTxO in the response
for utxoId, utxo := range utxos.Results {
var aud query.AnyUtxoData
var audc query.AnyUtxoData_Cardano
aud.TxoRef = &query.TxoRef{
Hash: utxoId.Hash.Bytes(),
Index: uint32(utxoId.Idx), // #nosec G115
}
aud.NativeBytes = utxo.Cbor()
audc.Cardano = utxo.Utxorpc()
aud.ParsedState = &audc
// If AssetPattern is specified, filter based on it
if assetPattern != nil {
assetFound := false
for _, multiasset := range audc.Cardano.GetAssets() {
if bytes.Equal(multiasset.GetPolicyId(), assetPattern.GetPolicyId()) {
for _, asset := range multiasset.GetAssets() {
if bytes.Equal(asset.GetName(), assetPattern.GetAssetName()) {
assetFound = true
break
}
}
}
if assetFound {
break
}
}
// Asset not found; skip this UTxO
if !assetFound {
continue
}
}
resp.Items = append(resp.Items, &aud)
}
resp.LedgerTip = &query.ChainPoint{
Slot: point.Slot,
Hash: point.Hash,
}
return connect.NewResponse(resp), nil
}
// StreamUtxos