-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathconformance_test.go
More file actions
3334 lines (3110 loc) · 101 KB
/
conformance_test.go
File metadata and controls
3334 lines (3110 loc) · 101 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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package conformance
import (
"archive/tar"
"compress/gzip"
"encoding/hex"
"fmt"
"io"
"io/fs"
"maps"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"testing"
"github.com/blinklabs-io/gouroboros/cbor"
test_ledger "github.com/blinklabs-io/gouroboros/internal/test/ledger"
"github.com/blinklabs-io/gouroboros/ledger"
"github.com/blinklabs-io/gouroboros/ledger/babbage"
"github.com/blinklabs-io/gouroboros/ledger/common"
"github.com/blinklabs-io/gouroboros/ledger/conway"
"github.com/blinklabs-io/gouroboros/ledger/shelley"
"github.com/blinklabs-io/gouroboros/protocol/localstatequery"
)
// rulesConformanceTarball is the path to the conformance test vectors.
// Sourced from Amaru commit 930c14b6bdf8197bc7d9397d872949e108b28eb4
// (pragma-org/amaru crates/amaru-ledger/tests/data/rules-conformance.tar.gz)
var rulesConformanceTarball = "rules-conformance.tar.gz"
type eventType int
const (
eventTypeTransaction eventType = 0
eventTypePassTick eventType = 1
eventTypePassEpoch eventType = 2
)
type vectorEvent struct {
eventType eventType
// Transaction event fields
tx []byte
success bool
slot uint64
// PassTick/PassEpoch event fields
tickSlot uint64
epoch uint64
}
// stakeCredential is used for parsing CBOR credentials in governance state
type stakeCredential struct {
cbor.StructAsArray
Type uint64
Hash common.Blake2b224
}
// proposalsRoots tracks the last enacted proposal for each governance purpose
// A "root" is the GovActionId that new proposals of that type must reference as parent
type proposalsRoots struct {
ProtocolParameters *string // GovActionId key for last enacted ParameterChange
HardFork *string // GovActionId key for last enacted HardFork
ConstitutionalCommittee *string // GovActionId key for last enacted NoConfidence/UpdateCommittee
Constitution *string // GovActionId key for last enacted NewConstitution
}
// govActionInfo holds information about a governance action
type govActionInfo struct {
ActionType common.GovActionType // GovActionTypeNoConfidence = 3, GovActionTypeUpdateCommittee = 4, etc.
ExpiresAfter uint64 // Epoch after which this action expires
ProposedMembers map[common.Blake2b224]uint64 // For UpdateCommittee: credentials being added -> expiry epoch
// For HardFork proposals: the proposed protocol version
ProtocolVersionMajor uint
ProtocolVersionMinor uint
// For NewConstitution proposals: the new constitution's guardrails policy hash
NewConstitutionPolicyHash []byte
// ParentActionId is the parent (PrevGovId) reference, nil for root proposals
ParentActionId *string
// SubmittedEpoch is the epoch when the proposal was submitted
SubmittedEpoch uint64
// RatifiedEpoch is the epoch when the proposal was ratified (nil if not yet ratified)
// Enactment happens in the epoch AFTER ratification
RatifiedEpoch *uint64
// Votes tracks votes on this proposal: voter key -> vote (Yes=0, No=1, Abstain=2)
Votes map[string]uint8
// ParameterUpdate holds the proposed changes for ParameterChange proposals
ParameterUpdate *conway.ConwayProtocolParameterUpdate
}
// parsedGovState holds governance state extracted from test vectors
type parsedGovState struct {
CommitteeMembers []common.CommitteeMember
DRepRegistrations []common.DRepRegistration
HotKeyAuthorizations map[common.Blake2b224]common.Blake2b224 // cold -> hot
CurrentEpoch uint64
// Proposals tracks known governance proposals by their GovActionId
// Key is the string representation of GovActionId (txHash#index)
Proposals map[string]govActionInfo
// EnactedProposals tracks proposals that have been enacted (for vote validation)
EnactedProposals map[string]bool
// StakeRegistrations tracks registered stake credentials
StakeRegistrations map[common.Blake2b224]bool
// PoolRegistrations tracks registered pool key hashes
PoolRegistrations map[common.Blake2b224]bool
// RewardAccounts tracks reward account balances (credential -> balance)
RewardAccounts map[common.Blake2b224]uint64
// ConstitutionPolicyHash is the guardrails script hash from the constitution
ConstitutionPolicyHash []byte
// ConstitutionExists is true if a constitution document exists (anchor is present)
ConstitutionExists bool
// Roots tracks the last enacted proposal for each governance purpose
Roots proposalsRoots
}
type testVector struct {
title string
initialState cbor.RawMessage
finalState cbor.RawMessage
events []vectorEvent
pparamsHash []byte
}
// utxosMatch compares two transaction inputs to see if they refer to the same UTxO
func utxosMatch(a, b common.TransactionInput) bool {
// Get the underlying ShelleyTransactionInput, handling both value and pointer types
var aShelley, bShelley shelley.ShelleyTransactionInput
var aOk, bOk bool
// Handle 'a': could be value, pointer, or neither
if aVal, ok := a.(shelley.ShelleyTransactionInput); ok {
aShelley = aVal
aOk = true
} else if aPtr, ok := a.(*shelley.ShelleyTransactionInput); ok {
aShelley = *aPtr
aOk = true
}
// Handle 'b': could be value, pointer, or neither
if bVal, ok := b.(shelley.ShelleyTransactionInput); ok {
bShelley = bVal
bOk = true
} else if bPtr, ok := b.(*shelley.ShelleyTransactionInput); ok {
bShelley = *bPtr
bOk = true
}
// If both successfully converted to ShelleyTransactionInput, compare them
if aOk && bOk {
return aShelley.TxId == bShelley.TxId &&
aShelley.OutputIndex == bShelley.OutputIndex
}
// Fallback: compare as generic inputs (may not work for all types)
return false
}
func TestRulesConformanceVectors(t *testing.T) {
tmpDir := t.TempDir()
extractRulesConformance(t, tmpDir)
conwayDumpRoot := filepath.Join(
tmpDir,
"eras",
"conway",
"impl",
"dump",
"Conway",
)
vectorFiles := collectVectorFiles(t, conwayDumpRoot)
t.Logf("Found %d conformance vectors", len(vectorFiles))
if len(vectorFiles) == 0 {
t.Fatalf("no conformance vectors found")
}
for i, vectorPath := range vectorFiles {
t.Run(filepath.Base(vectorPath), func(t *testing.T) {
if i < 5 { // Log first few
t.Logf("Processing vector %d: %s", i, filepath.Base(vectorPath))
}
vector := decodeTestVector(t, vectorPath)
if i < 5 {
t.Logf("Vector title: %s", vector.title)
}
if strings.Contains(vector.title, "InvalidMetadata") {
t.Logf(
"Found InvalidMetadata vector with title: %s",
vector.title,
)
}
if len(vector.events) == 0 {
t.Fatalf("vector %s has no transaction events", vector.title)
}
// Decode initial_state to extract current pparams hash and UTxOs
pph := decodeInitialStatePParamsHash(t, vector.initialState)
vector.pparamsHash = pph
if len(pph) == 0 {
t.Fatalf(
"vector %s missing protocol parameters hash",
vector.title,
)
}
// Extract UTxOs from initial_state (map[utxoId]bytes format)
utxos := decodeInitialStateUtxos(t, vector.initialState)
// Extract governance state (committee, DReps, etc.)
govState := decodeInitialStateGovState(t, vector.initialState)
// Merge reward balances from final_state (these are balances AFTER all TXs)
mergeRewardBalancesFromFinalState(t, &govState, vector.finalState)
// Pre-compute future withdrawals for each event index
// This allows us to compute balance at TX i as: final_state + futureWithdrawals[i]
futureWithdrawals := computeFutureWithdrawals(t, vector.events)
// Verify the corresponding pparams file exists under pparams-by-hash
pparamsFile := findPParamsByHash(t, conwayDumpRoot, pph)
if pparamsFile == "" {
t.Fatalf(
"pparams file not found for hash %s",
hex.EncodeToString(pph),
)
}
// Load protocol parameters
pp := loadProtocolParameters(t, pparamsFile)
// Handle "No cost model" tests: The Haskell test suite modifies pparams
// in memory via `modifyPParams $ ppCostModelsL .~ mempty`, but the test
// vector export stores the original pparams hash. We need to simulate
// this by clearing the cost models for these specific tests.
if strings.Contains(vector.title, "No cost model") {
if cpp, ok := pp.(*conway.ConwayProtocolParameters); ok {
cpp.CostModels = make(
map[uint][]int64,
) // Clear to empty map
}
}
// Track pool registrations and retirements across transactions
var poolRegistrations []common.PoolRegistrationCertificate
poolRetirements := make(
map[common.PoolKeyHash]uint64,
) // pool -> retirement epoch
// Epoch length for testnet (slots per epoch) - used for retirement timing
// This is a typical testnet value; mainnet uses 432000
const slotsPerEpoch uint64 = 4320
// Track current slot across events
var currentSlot uint64
for txIdx, event := range vector.events {
switch event.eventType {
case eventTypePassTick:
// PassTick advances the slot
currentSlot = event.tickSlot
continue
case eventTypePassEpoch:
// PassEpoch advances to a new epoch (event.epoch is a delta)
govState.CurrentEpoch += event.epoch
// Process pool retirements at epoch boundary
for poolKey, retireEpoch := range poolRetirements {
if event.epoch >= retireEpoch {
// Pool retirement has taken effect, remove from registrations
for i, reg := range poolRegistrations {
if reg.Operator == poolKey {
poolRegistrations[i] = poolRegistrations[len(poolRegistrations)-1]
poolRegistrations = poolRegistrations[:len(poolRegistrations)-1]
break
}
}
delete(poolRetirements, poolKey)
delete(govState.PoolRegistrations, poolKey)
}
}
// Perform simplified ratification at epoch boundary
// Only enact proposals that match the current root chain
ratifyProposals(t, &govState, pp)
continue
case eventTypeTransaction:
// Continue with transaction processing below
}
tx := decodeTransaction(t, event.tx)
currentSlot = event.slot
// Calculate current epoch from slot (approximate, ignoring Byron era)
currentEpoch := event.slot / slotsPerEpoch
// Remove pools that have retired (retirement epoch has passed)
for poolKey, retireEpoch := range poolRetirements {
if currentEpoch >= retireEpoch {
// Pool retirement has taken effect, remove from registrations
for i, reg := range poolRegistrations {
if reg.Operator == poolKey {
poolRegistrations[i] = poolRegistrations[len(poolRegistrations)-1]
poolRegistrations = poolRegistrations[:len(poolRegistrations)-1]
break
}
}
delete(poolRetirements, poolKey)
}
}
// Compute adjusted reward balances for this TX:
// balance_at_txIdx = final_state_balance + futureWithdrawals[txIdx+1]
// We use txIdx+1 because we need balance BEFORE this TX executes
// (futureWithdrawals[txIdx] includes this TX's withdrawal)
txGovState := govState
txGovState.RewardAccounts = make(map[common.Blake2b224]uint64)
for k, v := range govState.RewardAccounts {
txGovState.RewardAccounts[k] = v + futureWithdrawals[txIdx+1][k]
}
result, err := executeTransaction(
t,
tx,
currentSlot,
currentEpoch,
pp,
utxos,
poolRegistrations,
txGovState,
)
if result && !event.success {
// Debug: show proposal and redeemer info
proposals := tx.ProposalProcedures()
t.Logf("DEBUG tx %d: %d proposals", txIdx, len(proposals))
for i, p := range proposals {
ga := p.GovAction()
if ga != nil {
if gap, ok := ga.(common.GovActionWithPolicy); ok {
t.Logf(
" proposal %d: type=%T policyHash=%x",
i,
ga,
gap.GetPolicyHash(),
)
} else {
t.Logf(" proposal %d: type=%T (no policy interface)", i, ga)
}
}
}
redeemerCount := 0
if tx.Witnesses() != nil &&
tx.Witnesses().Redeemers() != nil {
for k, v := range tx.Witnesses().Redeemers().Iter() {
t.Logf(
" redeemer: tag=%d index=%d exunits=%+v",
k.Tag,
k.Index,
v.ExUnits,
)
redeemerCount++
}
}
t.Logf(" total redeemers: %d", redeemerCount)
if tx.Witnesses() != nil {
t.Logf(" witness scripts: native=%d v1=%d v2=%d v3=%d",
len(tx.Witnesses().NativeScripts()),
len(tx.Witnesses().PlutusV1Scripts()),
len(tx.Witnesses().PlutusV2Scripts()),
len(tx.Witnesses().PlutusV3Scripts()))
}
t.Logf(" reference inputs: %d", len(tx.ReferenceInputs()))
for i, ri := range tx.ReferenceInputs() {
t.Logf(" ref input %d: %s", i, ri.String())
}
t.Errorf(
"expected failure but got success (tx %d, IsValid=%v, has redeemers=%v)",
txIdx,
tx.IsValid(),
tx.Witnesses() != nil &&
tx.Witnesses().Redeemers() != nil,
)
}
if !result && event.success {
t.Errorf(
"expected success but got failure (tx %d, IsValid=%v): %v",
txIdx,
tx.IsValid(),
err,
)
}
// Update UTxO set only for transactions that should be accepted into a block
// event.success indicates the transaction should be included (even with IsValid=false)
// Failed phase-1 transactions (event.success=false) should NOT update UTxOs
// Successful transactions or phase-2 failures (event.success=true) SHOULD update UTxOs
// Use Consumed() and Produced() methods which properly handle:
// - Regular inputs vs collateral (consumed based on IsValid flag)
// - Reference inputs (never consumed)
// - Output creation with correct UTxO IDs
if event.success {
// Remove consumed inputs
consumed := tx.Consumed()
for _, consumedInput := range consumed {
for i, utxo := range utxos {
if utxosMatch(consumedInput, utxo.Id) {
// Remove this UTxO by replacing it with the last element
// and truncating the slice (avoids shifting all elements)
utxos[i] = utxos[len(utxos)-1]
utxos = utxos[:len(utxos)-1]
break
}
}
}
// Add produced outputs
produced := tx.Produced()
utxos = append(utxos, produced...)
// Track pool registrations and retirements for value conservation calculations
// Also track DRep registrations and CC hot key authorizations for voter validation
for _, cert := range tx.Certificates() {
switch c := cert.(type) {
case *common.PoolRegistrationCertificate:
// Registration cancels any pending retirement for this pool
delete(poolRetirements, c.Operator)
// Check if pool already registered, update if so
found := false
for i, existing := range poolRegistrations {
if existing.Operator == c.Operator {
poolRegistrations[i] = *c
found = true
break
}
}
if !found {
poolRegistrations = append(poolRegistrations, *c)
}
// Track pool registration for delegation validation
govState.PoolRegistrations[c.Operator] = true
case *common.PoolRetirementCertificate:
// Schedule retirement - will take effect at epoch boundary
poolRetirements[c.PoolKeyHash] = c.Epoch
case *common.RegistrationCertificate:
// Register stake credential (Conway-era with explicit deposit)
credHash := c.StakeCredential.Credential
govState.StakeRegistrations[credHash] = true
case *common.StakeRegistrationCertificate:
// Register stake credential (Shelley-era, implicit deposit from pparams)
credHash := c.StakeCredential.Credential
govState.StakeRegistrations[credHash] = true
case *common.StakeRegistrationDelegationCertificate:
// Register stake credential (and delegate in same cert)
credHash := c.StakeCredential.Credential
govState.StakeRegistrations[credHash] = true
case *common.StakeVoteRegistrationDelegationCertificate:
// Register stake credential (and delegate stake+vote in same cert)
credHash := c.StakeCredential.Credential
govState.StakeRegistrations[credHash] = true
case *common.VoteRegistrationDelegationCertificate:
// Register stake credential (and delegate vote in same cert)
credHash := c.StakeCredential.Credential
govState.StakeRegistrations[credHash] = true
case *common.DeregistrationCertificate:
// Deregister stake credential (Conway-era with explicit refund)
credHash := c.StakeCredential.Credential
delete(govState.StakeRegistrations, credHash)
delete(govState.RewardAccounts, credHash)
case *common.StakeDeregistrationCertificate:
// Deregister stake credential (Shelley-era)
credHash := c.StakeCredential.Credential
delete(govState.StakeRegistrations, credHash)
delete(govState.RewardAccounts, credHash)
case *common.RegistrationDrepCertificate:
// Register DRep - use Credential directly (it's already a hash)
credHash := c.DrepCredential.Credential
found := false
for _, existing := range govState.DRepRegistrations {
if existing.Credential == credHash {
found = true
break
}
}
if !found {
govState.DRepRegistrations = append(govState.DRepRegistrations, common.DRepRegistration{
Credential: credHash,
})
}
case *common.DeregistrationDrepCertificate:
// Unregister DRep - use Credential directly
credHash := c.DrepCredential.Credential
for i, existing := range govState.DRepRegistrations {
if existing.Credential == credHash {
govState.DRepRegistrations = append(
govState.DRepRegistrations[:i],
govState.DRepRegistrations[i+1:]...,
)
break
}
}
case *common.AuthCommitteeHotCertificate:
// Authorize CC hot key - use Credential directly
coldHash := c.ColdCredential.Credential
hotHash := c.HotCredential.Credential
govState.HotKeyAuthorizations[coldHash] = hotHash
// Also update the committee member's hot key if they exist
for i, member := range govState.CommitteeMembers {
if member.ColdKey == coldHash {
govState.CommitteeMembers[i].HotKey = &hotHash
break
}
}
case *common.ResignCommitteeColdCertificate:
// Mark CC member as resigned - use Credential directly
coldHash := c.ColdCredential.Credential
for i, member := range govState.CommitteeMembers {
if member.ColdKey == coldHash {
govState.CommitteeMembers[i].Resigned = true
// Remove hot key authorization
govState.CommitteeMembers[i].HotKey = nil
delete(govState.HotKeyAuthorizations, coldHash)
break
}
}
}
}
// Track proposals created by this transaction
txHash := tx.Hash()
// Get govActionLifetime from protocol parameters for expiration calculation
var govActionLifetime uint64
if conwayPP, ok := pp.(*conway.ConwayProtocolParameters); ok {
govActionLifetime = conwayPP.GovActionValidityPeriod
}
for idx, proposal := range tx.ProposalProcedures() {
govAction := proposal.GovAction()
if govAction == nil {
continue
}
// Get action type, proposed members, and parent from the concrete type
var actionType common.GovActionType
var proposedMembers map[common.Blake2b224]uint64
var protoMajor, protoMinor uint
var newConstitutionPolicyHash []byte
var parentActionId *string
var paramUpdate *conway.ConwayProtocolParameterUpdate
switch ga := govAction.(type) {
case *common.NoConfidenceGovAction:
actionType = common.GovActionType(ga.Type)
if ga.ActionId != nil {
key := fmt.Sprintf("%x#%d", ga.ActionId.TransactionId[:], ga.ActionId.GovActionIdx)
parentActionId = &key
}
case *common.UpdateCommitteeGovAction:
actionType = common.GovActionType(ga.Type)
if ga.ActionId != nil {
key := fmt.Sprintf("%x#%d", ga.ActionId.TransactionId[:], ga.ActionId.GovActionIdx)
parentActionId = &key
}
// Track the credentials being added by this proposal with their expiry epochs
if len(ga.CredEpochs) > 0 {
proposedMembers = make(map[common.Blake2b224]uint64)
for cred, epoch := range ga.CredEpochs {
proposedMembers[cred.Credential] = uint64(epoch)
}
}
case *common.HardForkInitiationGovAction:
actionType = common.GovActionType(ga.Type)
if ga.ActionId != nil {
key := fmt.Sprintf("%x#%d", ga.ActionId.TransactionId[:], ga.ActionId.GovActionIdx)
parentActionId = &key
}
// Track the proposed protocol version for HardFork proposals
protoMajor = ga.ProtocolVersion.Major
protoMinor = ga.ProtocolVersion.Minor
case *common.TreasuryWithdrawalGovAction:
actionType = common.GovActionType(ga.Type)
case *common.NewConstitutionGovAction:
actionType = common.GovActionType(ga.Type)
if ga.ActionId != nil {
key := fmt.Sprintf("%x#%d", ga.ActionId.TransactionId[:], ga.ActionId.GovActionIdx)
parentActionId = &key
}
// Track the proposed constitution's guardrails policy hash
if len(ga.Constitution.ScriptHash) > 0 {
newConstitutionPolicyHash = make([]byte, len(ga.Constitution.ScriptHash))
copy(newConstitutionPolicyHash, ga.Constitution.ScriptHash)
}
case *conway.ConwayParameterChangeGovAction:
actionType = common.GovActionTypeParameterChange
if ga.ActionId != nil {
key := fmt.Sprintf("%x#%d", ga.ActionId.TransactionId[:], ga.ActionId.GovActionIdx)
parentActionId = &key
}
// Store the parameter update for enactment
paramUpdate = &ga.ParamUpdate
case *common.InfoGovAction:
actionType = common.GovActionType(ga.Type)
}
// Create GovActionId string key
govActionKey := fmt.Sprintf("%x#%d", txHash[:], idx)
t.Logf(
"DEBUG proposal added: tx %d, key=%s, type=%d (%T), parent=%v",
txIdx,
govActionKey,
actionType,
govAction,
parentActionId,
)
govState.Proposals[govActionKey] = govActionInfo{
ActionType: actionType,
ExpiresAfter: currentEpoch + govActionLifetime,
ProposedMembers: proposedMembers,
ProtocolVersionMajor: protoMajor,
ProtocolVersionMinor: protoMinor,
NewConstitutionPolicyHash: newConstitutionPolicyHash,
ParentActionId: parentActionId,
SubmittedEpoch: currentEpoch,
Votes: make(map[string]uint8),
ParameterUpdate: paramUpdate,
}
}
// Track votes from VotingProcedures
votingProcs := tx.VotingProcedures()
if votingProcs != nil {
for voter, votes := range votingProcs {
voterKey := fmt.Sprintf(
"%d:%x",
voter.Type,
voter.Hash[:],
)
for govActionId, votingProcedure := range votes {
actionKey := fmt.Sprintf(
"%x#%d",
govActionId.TransactionId[:],
govActionId.GovActionIdx,
)
if info, exists := govState.Proposals[actionKey]; exists {
if info.Votes == nil {
info.Votes = make(map[string]uint8)
}
info.Votes[voterKey] = votingProcedure.Vote
govState.Proposals[actionKey] = info
}
}
}
}
}
}
})
}
t.Logf("Processed %d vectors", len(vectorFiles))
// Summary will be calculated from the logs
}
func extractRulesConformance(t testing.TB, dest string) {
tarball, err := os.Open(rulesConformanceTarball)
if err != nil {
t.Fatalf("failed to open rules conformance tarball: %v", err)
}
defer tarball.Close()
gzipReader, err := gzip.NewReader(tarball)
if err != nil {
t.Fatalf("failed to decompress tarball: %v", err)
}
defer gzipReader.Close()
tr := tar.NewReader(gzipReader)
for {
header, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
t.Fatalf("error reading tarball: %v", err)
}
target := filepath.Join(dest, header.Name)
switch header.Typeflag {
case tar.TypeDir:
if err := os.MkdirAll(target, 0o755); err != nil {
t.Fatalf("failed to create directory %s: %v", target, err)
}
case tar.TypeReg:
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
t.Fatalf(
"failed to create directory %s: %v",
filepath.Dir(target),
err,
)
}
out, err := os.Create(target)
if err != nil {
t.Fatalf("failed to create file %s: %v", target, err)
}
if _, err := io.Copy(out, tr); err != nil {
out.Close()
t.Fatalf("failed to write %s: %v", target, err)
}
out.Close()
}
}
}
func collectVectorFiles(t testing.TB, root string) []string {
var vectors []string
err := filepath.WalkDir(
root,
func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
if entry.IsDir() {
if strings.Contains(path, "pparams-by-hash") {
return filepath.SkipDir
}
return nil
}
if strings.Contains(path, "pparams-by-hash") ||
strings.Contains(path, "scripts/") {
return nil
}
// Filter obvious non-vector files: we expect leaf files under the spec trees
// Keep everything else (no strict extension filtering — Amaru vectors lack .cbor)
if !strings.HasSuffix(path, "/README") &&
!strings.HasSuffix(path, ".md") {
vectors = append(vectors, path)
}
return nil
},
)
if err != nil {
t.Fatalf("failed to walk extracted conformance data: %v", err)
}
sort.Strings(vectors)
return vectors
}
func decodeTestVector(t testing.TB, vectorPath string) testVector {
data, err := os.ReadFile(vectorPath)
if err != nil {
t.Fatalf("failed to read vector %s: %v", vectorPath, err)
}
var items []cbor.RawMessage
if _, err := cbor.Decode(data, &items); err != nil {
t.Fatalf("failed to decode vector %s: %v", vectorPath, err)
}
if len(items) < 5 {
t.Fatalf("unexpected vector structure %s", vectorPath)
}
var title string
if _, err := cbor.Decode(items[4], &title); err != nil {
t.Fatalf("failed to decode vector title %s: %v", vectorPath, err)
}
events := decodeEvents(t, items[3])
return testVector{
title: title,
initialState: items[1],
finalState: items[2],
events: events,
}
}
func decodeEvents(t testing.TB, raw cbor.RawMessage) []vectorEvent {
var encodedEvents []cbor.RawMessage
if _, err := cbor.Decode(raw, &encodedEvents); err != nil {
t.Fatalf("failed to decode events list: %v", err)
}
var events []vectorEvent
for _, rawEvent := range encodedEvents {
var payload []any
if _, err := cbor.Decode(rawEvent, &payload); err != nil {
t.Fatalf("failed to decode event: %v", err)
}
if len(payload) == 0 {
continue
}
variant, ok := payload[0].(uint64)
if !ok {
t.Fatalf("unexpected variant type: %T", payload[0])
}
switch eventType(variant) {
case eventTypeTransaction:
if len(payload) < 4 {
t.Fatalf("transaction event missing fields")
}
txBytes, ok := payload[1].([]byte)
if !ok {
t.Fatalf("unexpected tx bytes type: %T", payload[1])
}
success, ok := payload[2].(bool)
if !ok {
t.Fatalf("unexpected success flag type: %T", payload[2])
}
slot, ok := payload[3].(uint64)
if !ok {
t.Fatalf("unexpected slot type: %T", payload[3])
}
events = append(
events,
vectorEvent{
eventType: eventTypeTransaction,
tx: txBytes,
success: success,
slot: slot,
},
)
case eventTypePassTick:
if len(payload) < 2 {
t.Fatalf("PassTick event missing slot field")
}
tickSlot, ok := payload[1].(uint64)
if !ok {
t.Fatalf("unexpected PassTick slot type: %T", payload[1])
}
events = append(
events,
vectorEvent{eventType: eventTypePassTick, tickSlot: tickSlot},
)
case eventTypePassEpoch:
if len(payload) < 2 {
t.Fatalf("PassEpoch event missing epoch field")
}
epoch, ok := payload[1].(uint64)
if !ok {
t.Fatalf("unexpected PassEpoch epoch type: %T", payload[1])
}
events = append(
events,
vectorEvent{eventType: eventTypePassEpoch, epoch: epoch},
)
default:
t.Fatalf("unknown event variant: %d", variant)
}
}
return events
}
// decodeInitialStatePParamsHash navigates the initial_state structure (mirroring
// the Rust decode_ledger_state) and extracts current_pparams_hash. It decodes into
// cbor.Value so byte-string map keys do not explode Go's map typing.
func decodeInitialStatePParamsHash(t testing.TB, raw cbor.RawMessage) []byte {
var v cbor.Value
if _, err := cbor.Decode(raw, &v); err != nil {
t.Fatalf("failed to decode initial_state: %v", err)
}
top := v.Value()
arr, ok := top.([]any)
if !ok || len(arr) < 4 {
t.Fatalf("unexpected initial_state shape: %T len=%d", top, len(arr))
}
bes, ok := arr[3].([]any)
if !ok || len(bes) < 2 {
t.Fatalf(
"unexpected begin_epoch_state: %T len=%d types=%T",
arr[3],
len(bes),
bes,
)
}
ls, ok := bes[1].([]any)
if !ok || len(ls) < 1 {
t.Fatalf("unexpected ledger_state: %T", bes[1])
}
// gov_state is [proposals, committee, constitution, current_pparams_hash, ...]
// current_pparams_hash is an array: [key, status, ..., current_pparams_hash_bytes, ...]
for idx, item := range ls {
sub, ok := item.([]any)
if !ok || len(sub) <= 3 {
continue
}
switch v := sub[3].(type) {
case []byte:
if len(v) > 0 {
return v
}
case cbor.ByteString:
b := v.Bytes()
if len(b) > 0 {
return b
}
case []any:
// sub[3] is an array whose [3] element contains the hash
if len(v) > 3 {
switch hashv := v[3].(type) {
case []byte:
if len(hashv) > 0 {
return hashv
}
case cbor.ByteString:
b := hashv.Bytes()
if len(b) > 0 {
return b
}
}
}
}
_ = idx
}
// Help debugging: log the ledger_state shape to understand where pparams hash sits
typeNames := make([]string, len(ls))
subLens := make([]int, len(ls))
for i, item := range ls {
typeNames[i] = fmt.Sprintf("%T", item)
if s, ok := item.([]any); ok {
subLens[i] = len(s)
}
}
t.Fatalf("failed to locate protocol parameters hash in initial_state")
return nil
}
// decodeEmbeddedCostModels extracts cost models from the UTxO state's embedded pparams.
// In test vectors, the UTxO state pparams is an array of 4 maps representing:
// [currentEpochPParams, prevEpochPParams, futurePParams, proposedUpdates]
// Each map is sparse: {field_index -> value}. If the map is empty or lacks key 15 (CostModels),
// it means no cost models are set for that epoch.
// Returns nil if no cost models are found (meaning validation should fail for Plutus scripts),
// or the cost models map if present.
func decodeEmbeddedCostModels(
t testing.TB,
raw cbor.RawMessage,
) map[uint][]int64 {
var v cbor.Value
if _, err := cbor.Decode(raw, &v); err != nil {
return nil // Can't decode, assume no cost models
}
arr, ok := v.Value().([]any)
if !ok || len(arr) < 4 {
return nil
}
bes, ok := arr[3].([]any)
if !ok || len(bes) < 2 {
return nil
}
ls, ok := bes[1].([]any)
if !ok || len(ls) < 1 {
return nil
}
// ls[0] is UTxO state, ls[0][1] is embedded pparams
utxoState, ok := ls[0].([]any)
if !ok || len(utxoState) < 2 {
return nil
}
pparams, ok := utxoState[1].([]any)
if !ok || len(pparams) < 1 {
return nil
}
// pparams[0] is current epoch pparams (sparse map)
currentPParams, ok := pparams[0].(map[any]any)
if !ok || len(currentPParams) == 0 {
// Empty map means no fields set, including no cost models
return nil
}
// Look for key 15 (CostModels field index in ConwayProtocolParameters)
for k, v := range currentPParams {
var keyUint uint64
switch kTyped := k.(type) {
case uint64:
keyUint = kTyped
case int64:
keyUint = uint64(kTyped)
case int:
keyUint = uint64(kTyped)
default:
continue
}
if keyUint == 15 {
// Found CostModels - decode it
costModelsMap, ok := v.(map[any]any)
if !ok {
return nil
}
result := make(map[uint][]int64)
for version, model := range costModelsMap {
var versionUint uint
switch vTyped := version.(type) {
case uint64:
versionUint = uint(vTyped)
case int64:
versionUint = uint(vTyped)
case int:
versionUint = uint(vTyped)
default:
continue
}
modelArr, ok := model.([]any)
if !ok {
continue
}
costs := make([]int64, len(modelArr))
for i, cost := range modelArr {
switch cTyped := cost.(type) {
case int64:
costs[i] = cTyped