blvm-protocol 0.1.4

Bitcoin Commons BLVM: Bitcoin protocol abstraction layer for multiple variants and evolution
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
name: CI

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]
  release:
    types: [published]
  repository_dispatch:
    types: [build-chain, upstream-changed]
  workflow_dispatch:
    inputs:
      skip_tests:
        description: 'Skip test execution and coverage steps'
        required: false
        type: boolean
        default: false

permissions:
  contents: read
  actions: write

env:
  CARGO_TERM_COLOR: always
  RUST_BACKTRACE: '1'
  CARGO_INCREMENTAL: '1'

jobs:
  setup:
    name: Setup
    runs-on: [self-hosted, Linux, X64, builds]
    if: |
      (github.event_name != 'push' || github.event.head_commit == null || 
       (!contains(github.event.head_commit.message, '[skip ci]') &&
        !contains(github.event.head_commit.message, '[ci skip]') &&
        !contains(github.event.head_commit.message, '[no ci]')))
    outputs:
      cache-key: ${{ steps.setup-cache.outputs.cache-key }}
      consensus-cache-key: ${{ steps.setup-cache.outputs.consensus-cache-key }}
    steps:
      - name: Disk check
        uses: BTCDecoded/rust-ci/runner-disk-guard@main

      - uses: actions/checkout@v4
      

      - name: Strip [patch.crates-io] for crates.io-only CI
        uses: BTCDecoded/rust-ci/strip-patch-crates-io@main
      - name: Checkout consensus
        uses: actions/checkout@v4
        with:
          repository: BTCDecoded/blvm-consensus
          path: _temp-blvm-consensus
      
      - name: Move consensus
        run: |
          if [ -d "../blvm-consensus" ]; then rm -rf ../blvm-consensus; fi
          mv _temp-blvm-consensus ../blvm-consensus
      
      - name: Setup local dependencies for build
        run: |
          mkdir -p .cargo
          cat > .cargo/config.toml << EOF
          [patch.crates-io]
          blvm-consensus = { path = "../blvm-consensus" }
          EOF
          echo "✅ Created .cargo/config.toml for local dependency builds"
      
      - name: Cache
        id: setup-cache
        run: |
          CACHE_ROOT="/tmp/runner-cache"
          
          # Generate cache keys from Cargo.toml (sibling libraries do not commit Cargo.lock)
          DEPS_KEY=$(sha256sum Cargo.toml | cut -d' ' -f1)
          CONSENSUS_DEPS_KEY=$(sha256sum ../blvm-consensus/Cargo.toml | cut -d' ' -f1)
          
          # Include toolchain version in cache key
          TOOLCHAIN=$(grep -E '^channel|rust-version' rust-toolchain.toml Cargo.toml 2>/dev/null | head -1 | sha256sum | cut -d' ' -f1 || echo "1.88.0")
          
          CACHE_KEY="${DEPS_KEY}-${TOOLCHAIN}"
          CONSENSUS_CACHE_KEY="${CONSENSUS_DEPS_KEY}-${TOOLCHAIN}"
          
          # Set up cache directories
          CARGO_CACHE_DIR="$CACHE_ROOT/cargo/$CACHE_KEY"
          TARGET_CACHE_DIR="$CACHE_ROOT/target/$CACHE_KEY"
          CONSENSUS_TARGET_DIR="$CACHE_ROOT/blvm-consensus-target/$CONSENSUS_CACHE_KEY"
          
          echo "CARGO_CACHE_DIR=$CARGO_CACHE_DIR" >> $GITHUB_ENV
          echo "TARGET_CACHE_DIR=$TARGET_CACHE_DIR" >> $GITHUB_ENV
          echo "CONSENSUS_TARGET_DIR=$CONSENSUS_TARGET_DIR" >> $GITHUB_ENV
          
          echo "cache-key=$CACHE_KEY" >> $GITHUB_OUTPUT
          echo "consensus-cache-key=$CONSENSUS_CACHE_KEY" >> $GITHUB_OUTPUT
          
          mkdir -p "$CARGO_CACHE_DIR"/{registry,git} "$TARGET_CACHE_DIR" "$CONSENSUS_TARGET_DIR"
          

      - name: Install Rust
        uses: BTCDecoded/rust-ci/install-rust-toolchain@main

  test:
    name: Test
    needs: setup
    runs-on: [self-hosted, Linux, X64, builds]
    if: |
      (github.event_name != 'push' || github.event.head_commit == null || 
       (!contains(github.event.head_commit.message, '[skip ci]') &&
        !contains(github.event.head_commit.message, '[ci skip]') &&
        !contains(github.event.head_commit.message, '[no ci]'))) &&
      (github.event_name != 'workflow_dispatch' || github.event.inputs.skip_tests != 'true')
    steps:
      - uses: actions/checkout@v4
      

      - name: Strip [patch.crates-io] for crates.io-only CI
        uses: BTCDecoded/rust-ci/strip-patch-crates-io@main
      - name: Checkout consensus
        uses: actions/checkout@v4
        with:
          repository: BTCDecoded/blvm-consensus
          path: _temp-blvm-consensus
      
      - name: Move consensus
        run: |
          if [ -d "../blvm-consensus" ]; then rm -rf ../blvm-consensus; fi
          mv _temp-blvm-consensus ../blvm-consensus
      
      - name: Cache
        run: |
          CACHE_ROOT="/tmp/runner-cache"
          CACHE_KEY="${{ needs.setup.outputs.cache-key }}"
          CONSENSUS_CACHE_KEY="${{ needs.setup.outputs.consensus-cache-key }}"
          
          echo "CARGO_CACHE_DIR=$CACHE_ROOT/cargo/$CACHE_KEY" >> $GITHUB_ENV
          echo "TARGET_CACHE_DIR=$CACHE_ROOT/target/$CACHE_KEY" >> $GITHUB_ENV
          echo "CONSENSUS_TARGET_DIR=$CACHE_ROOT/blvm-consensus-target/$CONSENSUS_CACHE_KEY" >> $GITHUB_ENV
      
      - name: Restore Cargo cache
        uses: BTCDecoded/rust-ci/runner-cargo-cache@main
        with:
          operation: restore

      - name: Install Rust
        uses: BTCDecoded/rust-ci/install-rust-toolchain@main
      
      - name: Run tests with coverage
        run: |
          # Install tarpaulin
          cargo install cargo-tarpaulin --version 0.27.0
          
          # Run tests with coverage in one step
          # Use --lib --bins --tests to ensure all test types run
          # Use --skip-clean to reuse cached build artifacts, --timeout to prevent hangs
          cargo tarpaulin --lib --bins --tests --out xml --output-dir coverage --skip-clean --timeout 120
      
      - name: Upload coverage to Codecov
        uses: codecov/codecov-action@v3
        with:
          file: coverage/cobertura.xml
      
      - name: Save Cargo cache
        if: always()
        uses: BTCDecoded/rust-ci/runner-cargo-cache@main
        with:
          operation: save

      - name: Prune old runner caches
        if: always()
        uses: BTCDecoded/rust-ci/runner-cargo-cache@main
        with:
          operation: prune

  clippy:
    name: Clippy
    needs: setup
    runs-on: [self-hosted, Linux, X64, builds]
    if: |
      (github.event_name != 'push' || github.event.head_commit == null || 
       (!contains(github.event.head_commit.message, '[skip ci]') &&
        !contains(github.event.head_commit.message, '[ci skip]') &&
        !contains(github.event.head_commit.message, '[no ci]'))) &&
      (github.event_name != 'workflow_dispatch' || github.event.inputs.skip_tests != 'true')
    steps:
      - uses: actions/checkout@v4
      

      - name: Strip [patch.crates-io] for crates.io-only CI
        uses: BTCDecoded/rust-ci/strip-patch-crates-io@main
      - name: Checkout consensus
        uses: actions/checkout@v4
        with:
          repository: BTCDecoded/blvm-consensus
          path: _temp-blvm-consensus
      
      - name: Move consensus
        run: |
          if [ -d "../blvm-consensus" ]; then rm -rf ../blvm-consensus; fi
          mv _temp-blvm-consensus ../blvm-consensus
      
      - name: Setup local dependencies for build
        run: |
          mkdir -p .cargo
          cat > .cargo/config.toml << EOF
          [patch.crates-io]
          blvm-consensus = { path = "../blvm-consensus" }
          EOF
          echo "✅ Created .cargo/config.toml for local dependency builds"
      
      - name: Cache
        uses: BTCDecoded/rust-ci/runner-cargo-cache@main
        with:
          operation: bind-env
          cache-key: ${{ needs.setup.outputs.cache-key }}
          include-target: false

      - name: Restore Cargo cache
        uses: BTCDecoded/rust-ci/runner-cargo-cache@main
        with:
          operation: restore

      - name: Install Rust
        uses: BTCDecoded/rust-ci/install-rust-toolchain@main
      
      - name: Run clippy
        run: |
          if ! cargo clippy --version >/dev/null 2>&1; then
            echo "Skipping Clippy (cargo-clippy not installed for the active toolchain)"
            exit 0
          fi
          cargo clippy --lib --bins -- -D warnings

  fmt:
    name: Format
    needs: setup
    runs-on: [self-hosted, Linux, X64, builds]
    if: |
      (github.event_name != 'push' || github.event.head_commit == null || 
       (!contains(github.event.head_commit.message, '[skip ci]') &&
        !contains(github.event.head_commit.message, '[ci skip]') &&
        !contains(github.event.head_commit.message, '[no ci]'))) &&
      (github.event_name != 'workflow_dispatch' || github.event.inputs.skip_tests != 'true')
    steps:
      - uses: actions/checkout@v4
      

      - name: Strip [patch.crates-io] for crates.io-only CI
        uses: BTCDecoded/rust-ci/strip-patch-crates-io@main
      - name: Install Rust
        uses: BTCDecoded/rust-ci/install-rust-toolchain@main
      
      - name: Check formatting
        run: |
          if ! cargo fmt --version >/dev/null 2>&1; then
            echo "Skipping rustfmt (not installed for the active toolchain)"
            exit 0
          fi
          cargo fmt -- --check

  docs:
    name: Docs
    needs: setup
    runs-on: [self-hosted, Linux, X64, builds]
    if: |
      (github.event_name != 'push' || github.event.head_commit == null || 
       (!contains(github.event.head_commit.message, '[skip ci]') &&
        !contains(github.event.head_commit.message, '[ci skip]') &&
        !contains(github.event.head_commit.message, '[no ci]'))) &&
      (github.event_name != 'workflow_dispatch' || github.event.inputs.skip_tests != 'true')
    steps:
      - uses: actions/checkout@v4
      

      - name: Strip [patch.crates-io] for crates.io-only CI
        uses: BTCDecoded/rust-ci/strip-patch-crates-io@main
      - name: Cache
        uses: BTCDecoded/rust-ci/runner-cargo-cache@main
        with:
          operation: bind-env
          cache-key: ${{ needs.setup.outputs.cache-key }}
          include-target: false

      - name: Restore Cargo cache
        uses: BTCDecoded/rust-ci/runner-cargo-cache@main
        with:
          operation: restore

      - name: Install Rust
        uses: BTCDecoded/rust-ci/install-rust-toolchain@main
      
      - name: Build docs
        run: cargo doc --no-deps
      
      - name: Check docs
        run: cargo doc --no-deps --document-private-items

  security:
    name: Security
    needs: setup
    runs-on: [self-hosted, Linux, X64, builds]
    if: |
      (github.event_name != 'push' || github.event.head_commit == null ||
       (!contains(github.event.head_commit.message, '[skip ci]') &&
        !contains(github.event.head_commit.message, '[ci skip]') &&
        !contains(github.event.head_commit.message, '[no ci]'))) &&
      (github.event_name != 'workflow_dispatch' || github.event.inputs.skip_tests != 'true')
    steps:
      - uses: actions/checkout@v4
      

      - name: Strip [patch.crates-io] for crates.io-only CI
        uses: BTCDecoded/rust-ci/strip-patch-crates-io@main
      - name: Install Rust
        uses: BTCDecoded/rust-ci/install-rust-toolchain@main
      
      # 0.22+ parses CVSS 4.0 in advisory-db; 0.21 fails loading the DB (e.g. cap-primitives RUSTSEC-2024-0445).
      # --force + PATH: self-hosted runners may have an older system cargo-audit earlier on PATH than ~/.cargo/bin.
      - name: Install cargo-audit
        run: cargo install cargo-audit --version 0.22.1 --locked --force
      
      - name: Run security audit
        run: |
          export PATH="${HOME}/.cargo/bin:${PATH}"
          command -v cargo-audit
          cargo-audit --version
          cargo audit

  build:
    name: Build
    needs: 
      - setup
      - test
      - clippy
      - fmt
      - docs
      - security
    runs-on: [self-hosted, Linux, X64, builds]
    if: |
      always() &&
      needs.setup.result == 'success' &&
      (github.event_name == 'push' || github.event_name == 'release' || github.event_name == 'repository_dispatch' || github.event_name == 'workflow_dispatch') &&
      (github.event_name != 'push' || github.event.head_commit == null || 
       (!contains(github.event.head_commit.message, '[skip ci]') &&
        !contains(github.event.head_commit.message, '[ci skip]') &&
        !contains(github.event.head_commit.message, '[no ci]'))) &&
      ((github.event_name == 'workflow_dispatch' && github.event.inputs.skip_tests == 'true') ||
       (needs.test.result == 'success' && needs.clippy.result == 'success' && 
        needs.fmt.result == 'success' && needs.docs.result == 'success' && 
        needs.security.result == 'success'))
    steps:
      - uses: actions/checkout@v4
      

      - name: Strip [patch.crates-io] for crates.io-only CI
        uses: BTCDecoded/rust-ci/strip-patch-crates-io@main
      - name: Checkout consensus
        uses: actions/checkout@v4
        with:
          repository: BTCDecoded/blvm-consensus
          path: _temp-blvm-consensus
      
      - name: Move consensus
        run: |
          if [ -d "../blvm-consensus" ]; then rm -rf ../blvm-consensus; fi
          mv _temp-blvm-consensus ../blvm-consensus
      
      - name: Setup local dependencies for build
        run: |
          mkdir -p .cargo
          cat > .cargo/config.toml << EOF
          [patch.crates-io]
          blvm-consensus = { path = "../blvm-consensus" }
          EOF
          echo "✅ Created .cargo/config.toml for local dependency builds"
      
      - name: Cache
        run: |
          CACHE_ROOT="/tmp/runner-cache"
          CACHE_KEY="${{ needs.setup.outputs.cache-key }}"
          CONSENSUS_CACHE_KEY="${{ needs.setup.outputs.consensus-cache-key }}"
          
          echo "CARGO_CACHE_DIR=$CACHE_ROOT/cargo/$CACHE_KEY" >> $GITHUB_ENV
          echo "TARGET_CACHE_DIR=$CACHE_ROOT/target/$CACHE_KEY" >> $GITHUB_ENV
          echo "CONSENSUS_TARGET_DIR=$CACHE_ROOT/blvm-consensus-target/$CONSENSUS_CACHE_KEY" >> $GITHUB_ENV
      
      - name: Restore Cargo cache
        uses: BTCDecoded/rust-ci/runner-cargo-cache@main
        with:
          operation: restore

      - name: Install Rust
        uses: BTCDecoded/rust-ci/install-rust-toolchain@main
      
      - name: Build
        run: cargo build --release
      
      - name: Save Cargo cache
        if: always()
        uses: BTCDecoded/rust-ci/runner-cargo-cache@main
        with:
          operation: save

  release:
    name: Release
    needs: [build, test, clippy, fmt, docs, security]
    runs-on: [self-hosted, Linux, X64, builds]
    if: |
      always() &&
      needs.build.result == 'success' &&
      (github.event_name == 'push' || github.event_name == 'workflow_dispatch') &&
      (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/master') &&
      (github.event_name != 'push' || github.event.head_commit == null || 
       (!contains(github.event.head_commit.message, '[skip ci]') &&
        !contains(github.event.head_commit.message, '[ci skip]') &&
        !contains(github.event.head_commit.message, '[no ci]') &&
        !contains(github.event.head_commit.message, '[skip release]'))) &&
      ((github.event_name == 'workflow_dispatch' && github.event.inputs.skip_tests == 'true') ||
       (needs.test.result == 'success' && needs.clippy.result == 'success' && 
        needs.fmt.result == 'success' && needs.docs.result == 'success' && 
        needs.security.result == 'success'))
    permissions:
      contents: write
      id-token: write
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      

      - name: Strip [patch.crates-io] for crates.io-only CI
        uses: BTCDecoded/rust-ci/strip-patch-crates-io@main
      - name: Install Rust
        uses: BTCDecoded/rust-ci/install-rust-toolchain@main
      
      - name: Determine version
        id: version
        run: |
          # Auto-increment patch version from Cargo.toml
          # Extract only the package version (first version = after [package])
          CURRENT=$(grep -A 10 '^\[package\]' Cargo.toml | grep '^version = ' | head -1 | sed -E 's/^version = "([^"]+)".*/\1/')
          if [ -z "$CURRENT" ]; then
            echo "❌ Could not determine current version from Cargo.toml"
            echo "Debug: Looking for version in [package] section"
            grep -A 10 '^\[package\]' Cargo.toml | head -10
            exit 1
          fi
          
          echo "Current version: ${CURRENT}"
          
          # Validate version format (should be X.Y.Z)
          if ! echo "$CURRENT" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then
            echo "❌ Invalid version format: ${CURRENT} (expected X.Y.Z)"
            exit 1
          fi
          
          # Increment patch version (X.Y.Z -> X.Y.(Z+1))
          MAJOR=$(echo "$CURRENT" | cut -d. -f1)
          MINOR=$(echo "$CURRENT" | cut -d. -f2)
          PATCH=$(echo "$CURRENT" | cut -d. -f3)
          
          # Validate components are numeric
          if ! [[ "$MAJOR" =~ ^[0-9]+$ ]] || ! [[ "$MINOR" =~ ^[0-9]+$ ]] || ! [[ "$PATCH" =~ ^[0-9]+$ ]]; then
            echo "❌ Version components must be numeric: ${MAJOR}.${MINOR}.${PATCH}"
            exit 1
          fi
          
          PATCH=$((PATCH + 1))
          VERSION="${MAJOR}.${MINOR}.${PATCH}"
          
          # Check if version already exists and increment until we find a free one
          CRATE_NAME=$(grep -E '^name = ' Cargo.toml | sed -E 's/^name = "([^"]+)".*/\1/')
          MAX_ATTEMPTS=10
          ATTEMPT=0
          
          while [ $ATTEMPT -lt $MAX_ATTEMPTS ]; do
            echo "Checking if ${CRATE_NAME} v${VERSION} already exists on crates.io..."
            
            # Update cargo index first to ensure we have latest data
            cargo update --dry-run 2>/dev/null || true
            
            VERSION_EXISTS="false"
            
            # Method 1: Check using cargo search with updated index (most reliable for cargo's view)
            CARGO_SEARCH_OUTPUT=$(cargo search "$CRATE_NAME" --limit 100 2>/dev/null || echo "")
            if echo "$CARGO_SEARCH_OUTPUT" | grep -qE "\"${CRATE_NAME}\".*\"${VERSION}\""; then
              VERSION_EXISTS="true"
              echo "Found via cargo search (with updated index)"
            else
              # Method 2: Check using crates.io API
              API_RESPONSE=$(curl -s --max-time 10 "https://crates.io/api/v1/crates/${CRATE_NAME}/versions" 2>/dev/null || echo "")
              
              if [ -n "$API_RESPONSE" ] && ! echo "$API_RESPONSE" | grep -q '"detail"'; then
                # Parse JSON to check if version exists
                if command -v jq &> /dev/null; then
                  EXISTS_CHECK=$(echo "$API_RESPONSE" | jq -r ".versions[] | select(.num == \"${VERSION}\") | .num" | head -1)
                  if [ "$EXISTS_CHECK" = "$VERSION" ]; then
                    VERSION_EXISTS="true"
                    echo "Found via crates.io API"
                  fi
                else
                  # Fallback: grep for version in JSON
                  if echo "$API_RESPONSE" | grep -q "\"num\":\"${VERSION}\""; then
                    VERSION_EXISTS="true"
                    echo "Found via crates.io API (grep)"
                  fi
                fi
              fi
              
              # Method 3: If still not found, try a temporary Cargo.toml update and dry-run check
              # This uses cargo's index directly (same as cargo publish)
              if [ "$VERSION_EXISTS" = "false" ]; then
                # Save original Cargo.toml
                cp Cargo.toml Cargo.toml.bak
                # Temporarily update [package] version only (same as blvm-consensus: do not sed every
                # top-level `version =` line — that corrupts e.g. [dependencies.smallvec] version pins).
                awk -v ver="$VERSION" '
                  /^\[package\]/ { in_package = 1; print; next }
                  /^\[/ { in_package = 0 }
                  in_package && /^version = / {
                    print "version = \"" ver "\""
                    next
                  }
                  { print }
                ' Cargo.toml > Cargo.toml.tmp && mv Cargo.toml.tmp Cargo.toml
                DRY_RUN_OUTPUT=$(cargo publish --dry-run --allow-dirty 2>&1 || true)
                # Restore original Cargo.toml
                mv Cargo.toml.bak Cargo.toml
                
                if echo "$DRY_RUN_OUTPUT" | grep -qiE "(already exists|already been uploaded|already exists on crates.io)"; then
                  VERSION_EXISTS="true"
                  echo "Found via cargo publish dry-run (cargo index check)"
                fi
              fi
            fi
            
            if [ "$VERSION_EXISTS" = "true" ]; then
              echo "⚠️  Version ${VERSION} already exists, incrementing..."
              MAJOR=$(echo "$VERSION" | cut -d. -f1)
              MINOR=$(echo "$VERSION" | cut -d. -f2)
              PATCH=$(echo "$VERSION" | cut -d. -f3)
              PATCH=$((PATCH + 1))
              VERSION="${MAJOR}.${MINOR}.${PATCH}"
              ATTEMPT=$((ATTEMPT + 1))
            else
              echo "✅ Version ${VERSION} is available"
              break
            fi
          done
          
          if [ $ATTEMPT -eq $MAX_ATTEMPTS ]; then
            echo "❌ Failed to find available version after ${MAX_ATTEMPTS} attempts"
            exit 1
          fi
          
          VERSION_TAG="v${VERSION}"
          
          echo "version=${VERSION}" >> $GITHUB_OUTPUT
          echo "version_tag=${VERSION_TAG}" >> $GITHUB_OUTPUT
          echo "✅ Releasing version: ${VERSION_TAG}"
      
      - name: Get latest blvm-consensus version from crates.io
        id: consensus-version
        run: |
          CONSENSUS_VER=$(cargo search blvm-consensus --limit 1 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1 || echo "")
          if [ -z "$CONSENSUS_VER" ]; then
            echo "ERROR: blvm-consensus not found on crates.io. It must be published first."
            exit 1
          fi
          echo "version=${CONSENSUS_VER}" >> $GITHUB_OUTPUT
          echo "Using blvm-consensus version: ${CONSENSUS_VER}"
      
      - name: Update Cargo.toml to use crates.io dependencies
        run: |
          VERSION="${{ steps.version.outputs.version }}"
          CONSENSUS_VER="${{ steps.consensus-version.outputs.version }}"
          
          # Update [package] version only (see blvm-consensus release job; naive sed breaks optional dep pins).
          awk -v ver="$VERSION" '
            /^\[package\]/ { in_package = 1; print; next }
            /^\[/ { in_package = 0 }
            in_package && /^version = / {
              print "version = \"" ver "\""
              next
            }
            { print }
          ' Cargo.toml > Cargo.toml.tmp && mv Cargo.toml.tmp Cargo.toml
          
          # Update blvm-consensus dependency to use crates.io version
          sed -i 's|blvm-consensus = {[^}]*}|blvm-consensus = "'"${CONSENSUS_VER}"'"|g' Cargo.toml
          
          echo "Updated Cargo.toml:"
          echo "  package version: ${VERSION}"
          echo "  blvm-consensus: ${CONSENSUS_VER}"
          grep -A 12 '^\[package\]' Cargo.toml | grep '^version = ' | head -1
          grep '^blvm-consensus = ' Cargo.toml | head -1
      
      - name: Check for crates.io token
        run: |
          if [ -z "${CARGO_REGISTRY_TOKEN:-}" ]; then
            echo "⚠️  CARGO_REGISTRY_TOKEN not set, skipping crate publication"
            echo "   Set CARGO_REGISTRY_TOKEN secret to enable crate publishing"
            exit 0
          fi
      
      - name: Configure cargo for crates.io
        if: env.CARGO_REGISTRY_TOKEN != ''
        run: |
          cargo login "${CARGO_REGISTRY_TOKEN}"
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
      
      - name: Verify package
        if: env.CARGO_REGISTRY_TOKEN != ''
        run: |
          cargo package --list
      
      - name: Dry-run publish
        if: env.CARGO_REGISTRY_TOKEN != ''
        run: |
          cargo publish --dry-run --allow-dirty
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
      
      - name: Check if version already exists
        if: env.CARGO_REGISTRY_TOKEN != ''
        id: check-version
        run: |
          VERSION="${{ steps.version.outputs.version }}"
          CRATE_NAME=$(grep -E '^name = ' Cargo.toml | sed -E 's/^name = "([^"]+)".*/\1/')
          
          echo "🔍 Checking if ${CRATE_NAME} v${VERSION} already exists on crates.io..."
          
          # Update cargo index first to ensure we have latest data
          cargo update --dry-run 2>/dev/null || true
          
          # Use crates.io API to check if version exists (more reliable than cargo search)
          # The API returns versions in the "versions" array
          API_RESPONSE=$(curl -s "https://crates.io/api/v1/crates/${CRATE_NAME}/versions" 2>/dev/null || echo "")
          
          if [ -z "$API_RESPONSE" ] || echo "$API_RESPONSE" | grep -q '"detail"'; then
            echo "⚠️  Could not check crates.io API (crate may not exist yet), using cargo search as fallback"
            # Fallback to cargo search - check all versions
            SEARCH_OUTPUT=$(cargo search "$CRATE_NAME" --limit 100 2>/dev/null || echo "")
            if echo "$SEARCH_OUTPUT" | grep -qE "\"${CRATE_NAME}\".*\"${VERSION}\""; then
              echo "exists=true" >> $GITHUB_OUTPUT
              echo "⚠️  Version ${VERSION} already published for ${CRATE_NAME} (found via cargo search)"
            else
              echo "exists=false" >> $GITHUB_OUTPUT
              echo "✅ Version ${VERSION} not yet published for ${CRATE_NAME} (cargo search)"
            fi
          else
            # Show existing versions for debugging
            echo "📋 Existing versions on crates.io:"
            if command -v jq &> /dev/null; then
              echo "$API_RESPONSE" | jq -r ".versions[].num" | head -5
            else
              echo "$API_RESPONSE" | grep -o '"num":"[^"]*"' | sed 's/"num":"\(.*\)"/\1/' | head -5
            fi
            echo ""
            
            # Parse JSON to check if version exists (using jq if available, or grep as fallback)
            if command -v jq &> /dev/null; then
              VERSION_EXISTS=$(echo "$API_RESPONSE" | jq -r ".versions[] | select(.num == \"${VERSION}\") | .num" | head -1)
              if [ "$VERSION_EXISTS" = "$VERSION" ]; then
                echo "exists=true" >> $GITHUB_OUTPUT
                echo "⚠️  Version ${VERSION} already published for ${CRATE_NAME} (found via API)"
              else
                echo "exists=false" >> $GITHUB_OUTPUT
                echo "✅ Version ${VERSION} not yet published for ${CRATE_NAME} (API check)"
              fi
            else
              # Fallback: grep for version in JSON
              if echo "$API_RESPONSE" | grep -q "\"num\":\"${VERSION}\""; then
                echo "exists=true" >> $GITHUB_OUTPUT
                echo "⚠️  Version ${VERSION} already published for ${CRATE_NAME} (found via grep)"
              else
                echo "exists=false" >> $GITHUB_OUTPUT
                echo "✅ Version ${VERSION} not yet published for ${CRATE_NAME} (grep check)"
              fi
            fi
          fi
          
          echo ""
          echo "📊 Version check result: ${{ steps.check-version.outputs.exists }}"
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
      
      - name: Publish to crates.io
        if: env.CARGO_REGISTRY_TOKEN != ''
        id: publish
        run: |
          set +e
          VERSION="${{ steps.version.outputs.version }}"
          CRATE_NAME=$(grep -E '^name = ' Cargo.toml | sed -E 's/^name = "([^"]+)".*/\1/')
          
          echo "🔍 Publish Debug Info:"
          echo "  Version: ${VERSION}"
          echo "  Crate: ${CRATE_NAME}"
          echo "  Version exists check: ${{ steps.check-version.outputs.exists }}"
          
          # Skip if version already exists
          if [ "${{ steps.check-version.outputs.exists }}" = "true" ]; then
            echo "⚠️  Version ${VERSION} already exists on crates.io, skipping publish"
            echo "published=false" >> $GITHUB_OUTPUT
            exit 0
          fi
          
          echo ""
          echo "📦 Publishing ${CRATE_NAME} v${VERSION} to crates.io..."
          echo "Running: cargo publish --token [REDACTED] --allow-dirty"
          
          # Update cargo index before publishing to ensure we have latest data
          cargo update --dry-run 2>/dev/null || true
          
          PUBLISH_OUTPUT=$(cargo publish --token "${CARGO_REGISTRY_TOKEN}" --allow-dirty 2>&1)
          PUBLISH_EXIT_CODE=$?
          
          echo ""
          echo "📋 Publish Output:"
          echo "$PUBLISH_OUTPUT"
          echo ""
          
          if [ $PUBLISH_EXIT_CODE -eq 0 ]; then
            echo "✅ Successfully published ${CRATE_NAME} v${VERSION}"
            echo "published=true" >> $GITHUB_OUTPUT
            echo "Waiting 30 seconds for crates.io to index..."
            sleep 30
            echo "✅ Publish complete - version should be available on crates.io"
          else
            # Check if error is due to version already existing
            if echo "$PUBLISH_OUTPUT" | grep -qiE "(already exists|already been uploaded|already exists on crates.io)"; then
              echo "⚠️  Version ${VERSION} already exists on crates.io (detected during publish)"
              echo "published=false" >> $GITHUB_OUTPUT
              exit 0
            else
              echo "❌ Failed to publish ${CRATE_NAME} v${VERSION}"
              echo "Exit code: $PUBLISH_EXIT_CODE"
              echo "Error output:"
              echo "$PUBLISH_OUTPUT"
              echo ""
              echo "::error::cargo publish failed — job must fail until this is fixed"
              echo "published=false" >> $GITHUB_OUTPUT
              exit 1
            fi
          fi
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
      
      - name: Verify published crate is available
        if: |
          env.CARGO_REGISTRY_TOKEN != '' &&
          steps.publish.outputs.published == 'true'
        run: |
          VERSION="${{ steps.version.outputs.version }}"
          CRATE_NAME=$(grep -E '^name = ' Cargo.toml | sed -E 's/^name = "([^"]+)".*/\1/')
          echo "Verifying ${CRATE_NAME} v${VERSION} is available on crates.io..."
          
          # Try to fetch the crate info
          MAX_RETRIES=5
          RETRY_COUNT=0
          while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
            if cargo search "$CRATE_NAME" --limit 1 2>/dev/null | grep -q "v${VERSION}"; then
              echo "✅ ${CRATE_NAME} v${VERSION} is now available on crates.io"
              echo "📦 Crate page: https://crates.io/crates/${CRATE_NAME}/${VERSION}"
              break
            else
              RETRY_COUNT=$((RETRY_COUNT + 1))
              if [ $RETRY_COUNT -lt $MAX_RETRIES ]; then
                echo "⏳ Waiting for crates.io to index (attempt $RETRY_COUNT/$MAX_RETRIES)..."
                sleep 10
              else
                echo "⚠️  ${CRATE_NAME} v${VERSION} not yet visible on crates.io (may take a few minutes)"
              fi
            fi
          done
      
      - name: Create git tag
        run: |
          VERSION_TAG="${{ steps.version.outputs.version_tag }}"
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          
          # Check if tag already exists
          if git rev-parse "$VERSION_TAG" >/dev/null 2>&1; then
            echo "⚠️  Tag ${VERSION_TAG} already exists, skipping tag creation"
          else
            git tag -a "$VERSION_TAG" -m "Release ${VERSION_TAG}"
            git push origin "$VERSION_TAG"
            echo "✅ Created and pushed tag ${VERSION_TAG}"
          fi
      
      - name: Generate release notes
        id: release_notes
        run: |
          VERSION="${{ steps.version.outputs.version }}"
          VERSION_TAG="${{ steps.version.outputs.version_tag }}"
          CRATE_NAME=$(grep -E '^name = ' Cargo.toml | sed -E 's/^name = "([^"]+)".*/\1/')
          DESCRIPTION=$(grep -E '^description = ' Cargo.toml | sed -E 's/^description = "([^"]+)".*/\1/' || echo "Bitcoin protocol abstraction layer")
          
          # Get commit range for this release
          if [ -n "${{ github.event.before }}" ] && [ "${{ github.event.before }}" != "0000000000000000000000000000000000000000" ]; then
            COMMIT_RANGE="${{ github.event.before }}..${{ github.sha }}"
            COMMIT_COUNT=$(git rev-list --count "$COMMIT_RANGE" 2>/dev/null || echo "?")
          else
            COMMIT_RANGE="HEAD~10..HEAD"
            COMMIT_COUNT="?"
          fi
          
          cat > /tmp/release_notes.md << EOF
          ## $VERSION_TAG
          
          **$DESCRIPTION**
          
          ### 📦 Installation
          
          Add to your \`Cargo.toml\`:
          
          \`\`\`toml
          [dependencies]
          $CRATE_NAME = "$VERSION"
          \`\`\`
          
          Or install via cargo:
          
          \`\`\`bash
          cargo add $CRATE_NAME@$VERSION
          \`\`\`
          
          ### 🔗 Links
          
          - **Crates.io**: [${CRATE_NAME} v${VERSION}](https://crates.io/crates/${CRATE_NAME}/${VERSION})
          - **Documentation**: [docs.rs/${CRATE_NAME}/${VERSION}](https://docs.rs/${CRATE_NAME}/${VERSION})
          - **Repository**: [GitHub](https://github.com/${{ github.repository }})
          
          ### 📝 Changes
          
          This release includes $COMMIT_COUNT commits since the last release.
          
          **Published to crates.io**: ${{ steps.publish.outputs.published == 'true' && '✅ Yes' || '⚠️  Already exists or skipped' }}
          
          See [full commit history](https://github.com/${{ github.repository }}/compare/$COMMIT_RANGE) for details.
          EOF
          
          echo "notes<<EOF" >> $GITHUB_OUTPUT
          cat /tmp/release_notes.md >> $GITHUB_OUTPUT
          echo "EOF" >> $GITHUB_OUTPUT
      
      - name: Create GitHub Release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: ${{ steps.version.outputs.version_tag }}
          name: Release ${{ steps.version.outputs.version_tag }}
          body: ${{ steps.release_notes.outputs.notes }}
          draft: false
          prerelease: false
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}