-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
636 lines (550 loc) · 18 KB
/
client.go
File metadata and controls
636 lines (550 loc) · 18 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
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
package hcs2
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"regexp"
"strings"
"sync"
"time"
"github.com/hashgraph-online/standards-sdk-go/pkg/inscriber"
"github.com/hashgraph-online/standards-sdk-go/pkg/mirror"
"github.com/hashgraph-online/standards-sdk-go/pkg/shared"
hedera "github.com/hashgraph/hedera-sdk-go/v2"
)
// maxPayloadBytes is the maximum HCS message payload size before overflow.
const maxPayloadBytes = 1024
// inscriberWaitMaxAttempts is the max number of polling attempts while waiting
// for an overflow inscription to complete.
const inscriberWaitMaxAttempts = 120
// inscriberWaitInterval is the polling interval between inscription status checks.
const inscriberWaitInterval = 2 * time.Second
// hcs1ReferencePattern matches an HCS-1 HRL like "hcs://1/0.0.12345".
var hcs1ReferencePattern = regexp.MustCompile(`^hcs://1/(\d+\.\d+\.\d+)$`)
// errNoPublicKey is returned when no public key is provided and the operator key is not used.
var errNoPublicKey = errors.New("no public key provided")
// Client is the HCS-2 SDK client.
type Client struct {
hederaClient *hedera.Client
mirrorClient *mirror.Client
operatorID hedera.AccountID
operatorPublicKey hedera.PublicKey
operatorKey hedera.PrivateKey
operatorKeyRaw string
network string
inscriberAuthURL string
inscriberAPIURL string
registryTypeMap map[string]RegistryType
mutex sync.RWMutex
}
// NewClient creates a new Client.
func NewClient(config ClientConfig) (*Client, error) {
network, err := shared.NormalizeNetwork(config.Network)
if err != nil {
return nil, err
}
hederaClient, operator, err := shared.ResolveHederaClientAndOperator(
network,
config.HederaClient,
config.OperatorAccountID,
config.OperatorPrivateKey,
)
if err != nil {
return nil, err
}
mirrorClient, err := mirror.NewClient(mirror.Config{
Network: network,
BaseURL: config.MirrorBaseURL,
APIKey: config.MirrorAPIKey,
})
if err != nil {
return nil, err
}
return &Client{
hederaClient: hederaClient,
mirrorClient: mirrorClient,
operatorID: operator.AccountID,
operatorPublicKey: operator.PublicKey,
operatorKey: operator.PrivateKey,
operatorKeyRaw: operator.PrivateKeyRaw,
network: network,
inscriberAuthURL: strings.TrimSpace(config.InscriberAuthURL),
inscriberAPIURL: strings.TrimSpace(config.InscriberAPIURL),
registryTypeMap: map[string]RegistryType{},
}, nil
}
// MirrorClient returns the configured mirror node client.
func (c *Client) MirrorClient() *mirror.Client {
return c.mirrorClient
}
// CreateRegistry creates the requested resource.
func (c *Client) CreateRegistry(
ctx context.Context,
options CreateRegistryOptions,
) (CreateRegistryResult, error) {
registryType := options.RegistryType
if registryType != RegistryTypeIndexed && registryType != RegistryTypeNonIndexed {
registryType = RegistryTypeIndexed
}
ttl := options.TTL
if ttl <= 0 {
ttl = 86400
}
transaction := hedera.NewTopicCreateTransaction().SetTopicMemo(BuildTopicMemo(registryType, ttl))
adminKey, err := c.resolvePublicKey(options.AdminKey, options.UseOperatorAsAdmin)
if err != nil && !errors.Is(err, errNoPublicKey) {
return CreateRegistryResult{}, err
}
if adminKey != nil {
transaction.SetAdminKey(*adminKey)
}
submitKey, err := c.resolvePublicKey(options.SubmitKey, options.UseOperatorAsSubmit)
if err != nil && !errors.Is(err, errNoPublicKey) {
return CreateRegistryResult{}, err
}
if submitKey != nil {
transaction.SetSubmitKey(*submitKey)
}
response, err := transaction.Execute(c.hederaClient)
if err != nil {
return CreateRegistryResult{}, fmt.Errorf("failed to execute create topic transaction: %w", err)
}
receipt, err := response.GetReceipt(c.hederaClient)
if err != nil {
return CreateRegistryResult{}, fmt.Errorf("failed to get create topic receipt: %w", err)
}
if receipt.TopicID == nil {
return CreateRegistryResult{}, fmt.Errorf("topic ID missing in create topic receipt")
}
topicID := receipt.TopicID.String()
c.mutex.Lock()
c.registryTypeMap[topicID] = registryType
c.mutex.Unlock()
return CreateRegistryResult{
Success: true,
TopicID: topicID,
TransactionID: response.TransactionID.String(),
}, nil
}
// RegisterEntry registers the requested resource.
func (c *Client) RegisterEntry(
ctx context.Context,
registryTopicID string,
options RegisterEntryOptions,
protocol string,
) (OperationResult, error) {
if protocol == "" {
protocol = defaultProtocol
}
message := Message{
P: protocol,
Op: OperationRegister,
TopicID: options.TargetTopicID,
Metadata: options.Metadata,
Memo: options.Memo,
}
if err := ValidateMessage(message); err != nil {
return OperationResult{}, err
}
registryType, err := c.resolveRegistryType(ctx, registryTopicID, options.RegistryType)
if err != nil {
return OperationResult{}, err
}
analyticsMemo := options.AnalyticsMemo
if analyticsMemo == "" {
analyticsMemo = BuildTransactionMemo(OperationRegister, registryType)
}
return c.submitMessage(ctx, registryTopicID, message, analyticsMemo)
}
// UpdateEntry updates the requested resource.
func (c *Client) UpdateEntry(
ctx context.Context,
registryTopicID string,
options UpdateEntryOptions,
) (OperationResult, error) {
registryType, err := c.resolveRegistryType(ctx, registryTopicID, options.RegistryType)
if err != nil {
return OperationResult{}, err
}
if registryType != RegistryTypeIndexed {
return OperationResult{}, fmt.Errorf("update is only valid for indexed registries")
}
message := Message{
P: defaultProtocol,
Op: OperationUpdate,
TopicID: options.TargetTopicID,
UID: options.UID,
Metadata: options.Metadata,
Memo: options.Memo,
}
if err := ValidateMessage(message); err != nil {
return OperationResult{}, err
}
analyticsMemo := options.AnalyticsMemo
if analyticsMemo == "" {
analyticsMemo = BuildTransactionMemo(OperationUpdate, registryType)
}
return c.submitMessage(ctx, registryTopicID, message, analyticsMemo)
}
// DeleteEntry deletes the requested resource.
func (c *Client) DeleteEntry(
ctx context.Context,
registryTopicID string,
options DeleteEntryOptions,
) (OperationResult, error) {
registryType, err := c.resolveRegistryType(ctx, registryTopicID, options.RegistryType)
if err != nil {
return OperationResult{}, err
}
if registryType != RegistryTypeIndexed {
return OperationResult{}, fmt.Errorf("delete is only valid for indexed registries")
}
message := Message{
P: defaultProtocol,
Op: OperationDelete,
UID: options.UID,
Memo: options.Memo,
}
if err := ValidateMessage(message); err != nil {
return OperationResult{}, err
}
analyticsMemo := options.AnalyticsMemo
if analyticsMemo == "" {
analyticsMemo = BuildTransactionMemo(OperationDelete, registryType)
}
return c.submitMessage(ctx, registryTopicID, message, analyticsMemo)
}
// MigrateRegistry performs the requested operation.
func (c *Client) MigrateRegistry(
ctx context.Context,
registryTopicID string,
options MigrateRegistryOptions,
) (OperationResult, error) {
registryType, err := c.resolveRegistryType(ctx, registryTopicID, options.RegistryType)
if err != nil {
return OperationResult{}, err
}
message := Message{
P: defaultProtocol,
Op: OperationMigrate,
TopicID: options.TargetTopicID,
Metadata: options.Metadata,
Memo: options.Memo,
}
if err := ValidateMessage(message); err != nil {
return OperationResult{}, err
}
analyticsMemo := options.AnalyticsMemo
if analyticsMemo == "" {
analyticsMemo = BuildTransactionMemo(OperationMigrate, registryType)
}
return c.submitMessage(ctx, registryTopicID, message, analyticsMemo)
}
// GetRegistry returns the requested value.
func (c *Client) GetRegistry(
ctx context.Context,
topicID string,
options QueryRegistryOptions,
) (TopicRegistry, error) {
topicInfo, err := c.mirrorClient.GetTopicInfo(ctx, topicID)
if err != nil {
return TopicRegistry{}, err
}
memoInfo, ok := ParseTopicMemo(topicInfo.Memo)
if !ok {
return TopicRegistry{}, fmt.Errorf("topic %s is not an HCS-2 registry", topicID)
}
order := options.Order
if order == "" {
order = "asc"
}
sequenceNumber := ""
if options.Skip > 0 {
sequenceNumber = fmt.Sprintf("gt:%d", options.Skip)
}
messages, err := c.mirrorClient.GetTopicMessages(ctx, topicID, mirror.MessageQueryOptions{
SequenceNumber: sequenceNumber,
Limit: options.Limit,
Order: order,
})
if err != nil {
return TopicRegistry{}, err
}
entries := make([]RegistryEntry, 0, len(messages))
var latestEntry *RegistryEntry
for _, item := range messages {
message, decodeErr := c.decodeRegistryMessage(ctx, item, options.ResolveOverflow)
if decodeErr != nil {
continue
}
if err := ValidateMessage(message); err != nil {
continue
}
entry := RegistryEntry{
TopicID: topicID,
Sequence: item.SequenceNumber,
Timestamp: item.ConsensusTimestamp,
Payer: item.PayerAccountID,
Message: message,
ConsensusTimestamp: item.ConsensusTimestamp,
RegistryType: memoInfo.RegistryType,
}
entries = append(entries, entry)
if latestEntry == nil || entry.Timestamp > latestEntry.Timestamp {
copyEntry := entry
latestEntry = ©Entry
}
}
if memoInfo.RegistryType == RegistryTypeNonIndexed {
if latestEntry == nil {
entries = []RegistryEntry{}
} else {
entries = []RegistryEntry{*latestEntry}
}
}
c.mutex.Lock()
c.registryTypeMap[topicID] = memoInfo.RegistryType
c.mutex.Unlock()
return TopicRegistry{
TopicID: topicID,
RegistryType: memoInfo.RegistryType,
TTL: memoInfo.TTL,
Entries: entries,
LatestEntry: latestEntry,
}, nil
}
// GetTopicInfo returns the requested value.
func (c *Client) GetTopicInfo(ctx context.Context, topicID string) (mirror.TopicInfo, error) {
return c.mirrorClient.GetTopicInfo(ctx, topicID)
}
// SubmitMessage submits the requested message payload.
func (c *Client) SubmitMessage(
ctx context.Context,
registryTopicID string,
payload Message,
transactionMemo string,
) (OperationResult, error) {
return c.submitMessage(ctx, registryTopicID, payload, transactionMemo)
}
// decodeRegistryMessage decodes a mirror node message into an HCS-2 Message.
// If the message metadata is an HCS-1 HRL (overflow), it optionally resolves
// the reference when resolveOverflow is true.
func (c *Client) decodeRegistryMessage(
ctx context.Context,
item mirror.TopicMessage,
resolveOverflow bool,
) (Message, error) {
var message Message
if err := mirror.DecodeMessageJSON(item, &message); err != nil {
return Message{}, fmt.Errorf("unable to decode message: %w", err)
}
// Check if metadata is an HCS-1 HRL (overflow reference).
if resolveOverflow && hcs1ReferencePattern.MatchString(message.Metadata) {
resolvedBytes, err := c.ResolveHCS1Reference(ctx, message.Metadata)
if err != nil {
return Message{}, fmt.Errorf("failed to resolve overflow: %w", err)
}
var resolved Message
if err := json.Unmarshal(resolvedBytes, &resolved); err != nil {
return Message{}, fmt.Errorf("failed to unmarshal resolved overflow: %w", err)
}
return resolved, nil
}
return message, nil
}
func (c *Client) submitMessage(
ctx context.Context,
registryTopicID string,
message Message,
transactionMemo string,
) (OperationResult, error) {
topicID, err := hedera.TopicIDFromString(strings.TrimSpace(registryTopicID))
if err != nil {
return OperationResult{}, fmt.Errorf("invalid registry topic ID: %w", err)
}
payload, err := json.Marshal(message)
if err != nil {
return OperationResult{}, fmt.Errorf("failed to marshal HCS-2 message: %w", err)
}
// If payload exceeds maxPayloadBytes, inscribe via HCS-1 and submit a reference.
if len(payload) > maxPayloadBytes {
hrl, inscribeErr := c.inscribeOverflow(ctx, payload)
if inscribeErr != nil {
return OperationResult{}, fmt.Errorf("failed to inscribe overflow payload via HCS-1: %w", inscribeErr)
}
// Build a standard HCS-2 message with metadata set to the HRL.
overflowMsg := message
overflowMsg.Metadata = hrl
payload, err = json.Marshal(overflowMsg)
if err != nil {
return OperationResult{}, fmt.Errorf("failed to marshal overflow message: %w", err)
}
}
transaction := hedera.NewTopicMessageSubmitTransaction().
SetTopicID(topicID).
SetMessage(payload)
if strings.TrimSpace(transactionMemo) != "" {
transaction.SetTransactionMemo(transactionMemo)
}
response, err := transaction.Execute(c.hederaClient)
if err != nil {
return OperationResult{}, fmt.Errorf("failed to execute message submit transaction: %w", err)
}
receipt, err := response.GetReceipt(c.hederaClient)
if err != nil {
return OperationResult{}, fmt.Errorf("failed to get message submit receipt: %w", err)
}
return OperationResult{
Success: true,
TransactionID: response.TransactionID.String(),
SequenceNumber: int64(receipt.TopicSequenceNumber), //nolint:gosec // overflow won't occur in practice
}, nil
}
// inscribeOverflow inscribes the payload via the inscriber API and
// returns an HRL reference (e.g. "hcs://1/0.0.12345").
func (c *Client) inscribeOverflow(ctx context.Context, payload []byte) (string, error) {
network := inscriber.NetworkTestnet
if strings.EqualFold(c.network, shared.NetworkMainnet) {
network = inscriber.NetworkMainnet
}
authClient := inscriber.NewAuthClient(c.inscriberAuthURL)
if strings.TrimSpace(c.operatorKeyRaw) == "" {
return "", fmt.Errorf("operator private key is required for inscriber-backed overflow handling")
}
authResult, authErr := authClient.Authenticate(
ctx,
c.operatorID.String(),
c.operatorKeyRaw,
network,
)
if authErr != nil {
return "", fmt.Errorf("failed to authenticate inscriber client: %w", authErr)
}
inscriberClient, clientErr := inscriber.NewClient(inscriber.Config{
APIKey: authResult.APIKey,
Network: network,
BaseURL: c.inscriberAPIURL,
})
if clientErr != nil {
return "", fmt.Errorf("failed to create inscriber client: %w", clientErr)
}
job, startErr := inscriberClient.StartInscription(ctx, inscriber.StartInscriptionRequest{
HolderID: c.operatorID.String(),
Mode: inscriber.ModeFile,
Network: network,
FileStandard: "hcs-1",
File: inscriber.FileInput{
Type: "base64",
Base64: base64.StdEncoding.EncodeToString(payload),
FileName: fmt.Sprintf("hcs2-overflow-%d.json", time.Now().UnixNano()),
MimeType: "application/json",
},
})
if startErr != nil {
return "", fmt.Errorf("failed to start HCS-1 overflow inscription: %w", startErr)
}
if strings.TrimSpace(job.TransactionBytes) == "" {
return "", fmt.Errorf("inscriber response did not include transaction bytes")
}
executedTxID, execErr := inscriber.ExecuteTransaction(
ctx,
job.TransactionBytes,
inscriber.HederaClientConfig{
AccountID: c.operatorID.String(),
PrivateKey: c.operatorKeyRaw,
Network: network,
},
)
if execErr != nil {
return "", fmt.Errorf("failed to execute overflow inscription transaction: %w", execErr)
}
waited, waitErr := inscriberClient.WaitForInscription(ctx, executedTxID, inscriber.WaitOptions{
MaxAttempts: inscriberWaitMaxAttempts,
Interval: inscriberWaitInterval,
})
if waitErr != nil {
return "", fmt.Errorf("failed to wait for overflow inscription: %w", waitErr)
}
if !waited.Completed && !strings.EqualFold(waited.Status, "completed") {
return "", fmt.Errorf("overflow inscription did not complete successfully")
}
inscribedTopicID := strings.TrimSpace(waited.TopicID)
if inscribedTopicID == "" {
inscribedTopicID = strings.TrimSpace(job.TopicID)
}
if inscribedTopicID == "" {
return "", fmt.Errorf("overflow inscription did not return a topic ID")
}
return fmt.Sprintf("hcs://1/%s", inscribedTopicID), nil
}
// ResolveHCS1Reference resolves an HCS-1 HRL (e.g. "hcs://1/0.0.12345") to the
// raw payload bytes stored on that topic.
func (c *Client) ResolveHCS1Reference(ctx context.Context, hcs1Reference string) ([]byte, error) {
matches := hcs1ReferencePattern.FindStringSubmatch(strings.TrimSpace(hcs1Reference))
if len(matches) != 2 { //nolint:mnd // regex capture group count
return nil, fmt.Errorf("invalid HCS-1 reference %q", hcs1Reference)
}
topicID := matches[1]
messages, err := c.mirrorClient.GetTopicMessages(ctx, topicID, mirror.MessageQueryOptions{
Order: "asc",
})
if err != nil {
return nil, fmt.Errorf("failed to fetch HCS-1 payload from %s: %w", hcs1Reference, err)
}
if len(messages) == 0 {
return nil, fmt.Errorf("no HCS-1 payload found at %s", hcs1Reference)
}
// HCS-1 stores the payload as the message content of the first message.
return base64.StdEncoding.DecodeString(messages[0].Message)
}
func (c *Client) resolveRegistryType(
ctx context.Context,
topicID string,
override *RegistryType,
) (RegistryType, error) {
if override != nil {
return *override, nil
}
c.mutex.RLock()
cachedType, ok := c.registryTypeMap[topicID]
c.mutex.RUnlock()
if ok {
return cachedType, nil
}
topicInfo, err := c.mirrorClient.GetTopicInfo(ctx, topicID)
if err != nil {
return RegistryTypeIndexed, err
}
memoInfo, parsed := ParseTopicMemo(topicInfo.Memo)
if !parsed {
return RegistryTypeIndexed, fmt.Errorf("topic %s is not an HCS-2 registry", topicID)
}
c.mutex.Lock()
c.registryTypeMap[topicID] = memoInfo.RegistryType
c.mutex.Unlock()
return memoInfo.RegistryType, nil
}
func (c *Client) resolvePublicKey(rawKey string, useOperator bool) (*hedera.PublicKey, error) {
if useOperator {
if strings.TrimSpace(c.operatorPublicKey.String()) == "" {
return nil, fmt.Errorf("operator public key is not configured")
}
publicKey := c.operatorPublicKey
return &publicKey, nil
}
if strings.TrimSpace(rawKey) == "" {
return nil, errNoPublicKey
}
publicKey, pubErr := hedera.PublicKeyFromString(rawKey)
if pubErr == nil {
return &publicKey, nil
}
privateKey, prvErr := shared.ParsePrivateKey(rawKey)
if prvErr != nil {
return nil, fmt.Errorf("failed to parse key as public (%w) or private (%w)", pubErr, prvErr)
}
derivedPublicKey := privateKey.PublicKey()
return &derivedPublicKey, nil
}