-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathcardano.go
More file actions
510 lines (452 loc) · 13.9 KB
/
cardano.go
File metadata and controls
510 lines (452 loc) · 13.9 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
// Copyright 2025 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 cardano
import (
"bytes"
"encoding/hex"
"sync"
"github.com/blinklabs-io/adder/event"
"github.com/blinklabs-io/adder/plugin"
"github.com/blinklabs-io/gouroboros/ledger"
"github.com/blinklabs-io/gouroboros/ledger/common"
)
type Cardano struct {
errorChan chan error
inputChan chan event.Event
outputChan chan event.Event
doneChan chan struct{}
wg sync.WaitGroup
stopOnce sync.Once
logger plugin.Logger
filterSet filterSet
}
// New returns a new Cardano object with the specified options applied
func New(options ...CardanoOptionFunc) *Cardano {
c := &Cardano{}
for _, option := range options {
option(c)
}
return c
}
// Start the cardano filter
func (c *Cardano) Start() error {
c.errorChan = make(chan error)
c.inputChan = make(chan event.Event, 10)
c.outputChan = make(chan event.Event, 10)
c.doneChan = make(chan struct{})
c.stopOnce = sync.Once{}
c.wg.Add(1)
go c.processEvents()
return nil
}
// processEvents handles incoming events and applies filters
func (c *Cardano) processEvents() {
defer c.wg.Done()
for {
select {
case <-c.doneChan:
return
case evt, ok := <-c.inputChan:
// Channel has been closed, which means we're shutting down
if !ok {
return
}
if c.filterEvent(evt) {
// Send event along, but check for shutdown
select {
case <-c.doneChan:
return
case c.outputChan <- evt:
}
}
}
}
}
// filterEvent returns true if the event should be passed through
func (c *Cardano) filterEvent(evt event.Event) bool {
switch v := evt.Payload.(type) {
case event.BlockEvent:
return c.filterBlockEvent(v)
case event.TransactionEvent:
return c.filterTransactionEvent(v)
case event.GovernanceEvent:
return c.filterGovernanceEvent(v)
case event.DRepCertificateEvent:
return c.filterDRepCertificateEvent(v)
default:
// Pass through events we don't filter
return true
}
}
// filterBlockEvent checks pool filter for block events using O(1) lookup
func (c *Cardano) filterBlockEvent(be event.BlockEvent) bool {
if !c.filterSet.hasPoolFilter {
return true
}
// O(1) lookup using pre-computed hexToBech32 map
// Check if the issuer vkey (hex) maps to a filtered pool
if _, exists := c.filterSet.pools.hexToBech32[be.IssuerVkey]; exists {
return true
}
// Also check direct hex match in hexPoolIds
if _, exists := c.filterSet.pools.hexPoolIds[be.IssuerVkey]; exists {
return true
}
// Also check direct match in bech32PoolIds for bech32 format pool IDs
if _, exists := c.filterSet.pools.bech32PoolIds[be.IssuerVkey]; exists {
return true
}
return false
}
// filterTransactionEvent checks all applicable filters with early exit on match
func (c *Cardano) filterTransactionEvent(te event.TransactionEvent) bool {
// Check address filter
if c.filterSet.hasAddressFilter {
if !c.matchAddressFilter(te) {
return false
}
}
// Check policy ID filter
if c.filterSet.hasPolicyFilter {
if !c.matchPolicyFilter(te) {
return false
}
}
// Check asset fingerprint filter
if c.filterSet.hasAssetFilter {
if !c.matchAssetFilter(te) {
return false
}
}
// Check pool filter
if c.filterSet.hasPoolFilter {
if !c.matchPoolFilterTx(te) {
return false
}
}
// Check DRep filter
if c.filterSet.hasDRepFilter {
if !c.matchDRepFilterTx(te) {
return false
}
}
return true
}
// filterDRepCertificateEvent checks DRep filter for DRep certificate events
func (c *Cardano) filterDRepCertificateEvent(de event.DRepCertificateEvent) bool {
if !c.filterSet.hasDRepFilter {
return true
}
if _, exists := c.filterSet.dreps.hexDRepIds[de.Certificate.DRepHash]; exists {
return true
}
if _, exists := c.filterSet.dreps.bech32DRepIds[de.Certificate.DRepId]; exists {
return true
}
return false
}
// matchAddressFilter checks if transaction matches address filters
func (c *Cardano) matchAddressFilter(te event.TransactionEvent) bool {
// Include resolved inputs as outputs for matching
allOutputs := append(te.Outputs, te.ResolvedInputs...)
// Check outputs against payment and stake addresses
for _, output := range allOutputs {
addrStr := output.Address().String()
// O(1) lookup in payment addresses
if _, exists := c.filterSet.addresses.paymentAddresses[addrStr]; exists {
return true
}
// Check stake address if we have stake filters
if len(c.filterSet.addresses.stakeAddresses) > 0 {
stakeAddr := output.Address().StakeAddress()
if stakeAddr != nil {
// O(1) lookup in stake addresses
if _, exists := c.filterSet.addresses.stakeAddresses[stakeAddr.String()]; exists {
return true
}
}
}
}
// Check certificates for stake address matches
if len(c.filterSet.addresses.stakeAddresses) > 0 {
if c.matchStakeCertificates(te.Certificates) {
return true
}
}
return false
}
// matchAddressFilterGovernance checks if governance event matches address filters
func (c *Cardano) matchAddressFilterGovernance(ge event.GovernanceEvent) bool {
// Check proposal procedures for reward account matches
for _, prop := range ge.ProposalProcedures {
// RewardAccount is a stake/reward address string
if _, exists := c.filterSet.addresses.stakeAddresses[prop.RewardAccount]; exists {
return true
}
// Check treasury withdrawal addresses if this is a treasury withdrawal action
if prop.ActionData.TreasuryWithdrawal != nil {
for _, withdrawal := range prop.ActionData.TreasuryWithdrawal.Withdrawals {
// Check against payment addresses
if _, exists := c.filterSet.addresses.paymentAddresses[withdrawal.Address]; exists {
return true
}
// Also check against stake addresses (some withdrawals may use stake addresses)
if _, exists := c.filterSet.addresses.stakeAddresses[withdrawal.Address]; exists {
return true
}
}
}
}
// Check vote delegation certificates for stake credential matches
if len(c.filterSet.addresses.stakeCredentialHashes) > 0 {
for _, cert := range ge.VoteDelegationCertificates {
// StakeCredential is a hex string of the credential hash (28 bytes)
credBytes, err := hex.DecodeString(cert.StakeCredential)
if err != nil {
continue
}
for _, filterHash := range c.filterSet.addresses.stakeCredentialHashes {
// filterHash may include header byte from bech32 decoding
// Compare against last 28 bytes (the actual credential hash)
var hashToCompare []byte
if len(filterHash) > 28 {
hashToCompare = filterHash[len(filterHash)-28:]
} else {
hashToCompare = filterHash
}
if bytes.Equal(credBytes, hashToCompare) {
return true
}
}
}
}
return false
}
// matchStakeCertificates checks certificates against stake credential hashes
func (c *Cardano) matchStakeCertificates(certificates []ledger.Certificate) bool {
for _, certificate := range certificates {
var credBytes []byte
switch cert := certificate.(type) {
case *common.StakeDelegationCertificate:
hash := cert.StakeCredential.Hash()
credBytes = hash[:]
case *common.StakeDeregistrationCertificate:
hash := cert.StakeCredential.Hash()
credBytes = hash[:]
default:
continue
}
// Use pre-decoded stake credential hashes with bytes.Equal comparison
for _, filterHash := range c.filterSet.addresses.stakeCredentialHashes {
// filterHash may include header byte from bech32 decoding
// Compare against last 28 bytes (the actual credential hash)
var hashToCompare []byte
if len(filterHash) > 28 {
hashToCompare = filterHash[len(filterHash)-28:]
} else {
hashToCompare = filterHash
}
if bytes.Equal(credBytes, hashToCompare) {
return true
}
}
}
return false
}
// matchPolicyFilter checks if transaction matches policy ID filters
func (c *Cardano) matchPolicyFilter(te event.TransactionEvent) bool {
// Include resolved inputs as outputs for matching
allOutputs := append(te.Outputs, te.ResolvedInputs...)
for _, output := range allOutputs {
if output.Assets() != nil {
for _, policyId := range output.Assets().Policies() {
// O(1) lookup in policy IDs
if _, exists := c.filterSet.policies.policyIds[policyId.String()]; exists {
return true
}
}
}
}
return false
}
// matchAssetFilter checks if transaction matches asset fingerprint filters
func (c *Cardano) matchAssetFilter(te event.TransactionEvent) bool {
// Include resolved inputs as outputs for matching
allOutputs := append(te.Outputs, te.ResolvedInputs...)
for _, output := range allOutputs {
if output.Assets() != nil {
for _, policyId := range output.Assets().Policies() {
for _, assetName := range output.Assets().Assets(policyId) {
assetFp := ledger.NewAssetFingerprint(policyId.Bytes(), assetName)
// O(1) lookup in asset fingerprints
if _, exists := c.filterSet.assets.fingerprints[assetFp.String()]; exists {
return true
}
}
}
}
}
return false
}
// filterGovernanceEvent checks all applicable filters for governance events
func (c *Cardano) filterGovernanceEvent(ge event.GovernanceEvent) bool {
// Check address filter
if c.filterSet.hasAddressFilter {
if !c.matchAddressFilterGovernance(ge) {
return false
}
}
// Check DRep filter
if c.filterSet.hasDRepFilter {
if !c.matchDRepFilterGovernance(ge) {
return false
}
}
return true
}
// matchDRepFilterGovernance checks if governance event contains matching DRep IDs
func (c *Cardano) matchDRepFilterGovernance(ge event.GovernanceEvent) bool {
// Check DRep certificates (registrations, updates, retirements)
for _, cert := range ge.DRepCertificates {
if _, exists := c.filterSet.dreps.hexDRepIds[cert.DRepHash]; exists {
return true
}
}
// Check vote delegation certificates (delegations TO a DRep)
for _, cert := range ge.VoteDelegationCertificates {
if cert.DRepHash != "" {
if _, exists := c.filterSet.dreps.hexDRepIds[cert.DRepHash]; exists {
return true
}
}
}
// Check voting procedures (votes cast BY a DRep)
for _, vote := range ge.VotingProcedures {
if vote.VoterType == "DRep" {
if _, exists := c.filterSet.dreps.hexDRepIds[vote.VoterHash]; exists {
return true
}
}
}
return false
}
// matchDRepFilterTx checks transaction certificates against DRep filters
func (c *Cardano) matchDRepFilterTx(te event.TransactionEvent) bool {
for _, certificate := range te.Certificates {
var drepHash []byte
switch cert := certificate.(type) {
case *common.RegistrationDrepCertificate:
drepHash = cert.DrepCredential.Credential[:]
case *common.DeregistrationDrepCertificate:
drepHash = cert.DrepCredential.Credential[:]
case *common.UpdateDrepCertificate:
drepHash = cert.DrepCredential.Credential[:]
case *common.VoteDelegationCertificate:
if cert.Drep.Type == common.DrepTypeAddrKeyHash ||
cert.Drep.Type == common.DrepTypeScriptHash {
drepHash = cert.Drep.Credential
}
case *common.StakeVoteDelegationCertificate:
if cert.Drep.Type == common.DrepTypeAddrKeyHash ||
cert.Drep.Type == common.DrepTypeScriptHash {
drepHash = cert.Drep.Credential
}
case *common.VoteRegistrationDelegationCertificate:
if cert.Drep.Type == common.DrepTypeAddrKeyHash ||
cert.Drep.Type == common.DrepTypeScriptHash {
drepHash = cert.Drep.Credential
}
case *common.StakeVoteRegistrationDelegationCertificate:
if cert.Drep.Type == common.DrepTypeAddrKeyHash ||
cert.Drep.Type == common.DrepTypeScriptHash {
drepHash = cert.Drep.Credential
}
default:
continue
}
if drepHash != nil {
// O(1) lookup using byte string key (no encoding needed)
if _, exists := c.filterSet.dreps.bytesLookup[string(drepHash)]; exists {
return true
}
}
}
// Also check VotingProcedures from raw transaction if available
if te.Transaction != nil {
for voter := range te.Transaction.VotingProcedures() {
if voter.Type == common.VoterTypeDRepKeyHash ||
voter.Type == common.VoterTypeDRepScriptHash {
voterHash := voter.Hash[:]
// O(1) lookup using byte string key (no encoding needed)
if _, exists := c.filterSet.dreps.bytesLookup[string(voterHash)]; exists {
return true
}
}
}
}
return false
}
// matchPoolFilterTx checks transaction certificates against pool filters
func (c *Cardano) matchPoolFilterTx(te event.TransactionEvent) bool {
for _, certificate := range te.Certificates {
var poolKeyHash []byte
switch cert := certificate.(type) {
case *ledger.StakeDelegationCertificate:
poolKeyHash = cert.PoolKeyHash[:]
case *ledger.PoolRetirementCertificate:
poolKeyHash = cert.PoolKeyHash[:]
case *ledger.PoolRegistrationCertificate:
poolKeyHash = cert.Operator[:]
default:
continue
}
// O(1) lookup using byte string key (no encoding needed)
if _, exists := c.filterSet.pools.bytesLookup[string(poolKeyHash)]; exists {
return true
}
}
return false
}
// Stop the cardano filter
func (c *Cardano) Stop() error {
c.stopOnce.Do(func() {
if c.doneChan != nil {
close(c.doneChan)
}
// Wait for goroutine to exit before closing channels
c.wg.Wait()
if c.inputChan != nil {
close(c.inputChan)
}
if c.outputChan != nil {
close(c.outputChan)
}
if c.errorChan != nil {
close(c.errorChan)
}
})
return nil
}
// ErrorChan returns the plugin's error channel
func (c *Cardano) ErrorChan() <-chan error {
return c.errorChan
}
// InputChan returns the input event channel
func (c *Cardano) InputChan() chan<- event.Event {
return c.inputChan
}
// OutputChan returns the output event channel
func (c *Cardano) OutputChan() <-chan event.Event {
return c.outputChan
}