paritytech / paritytech/parity-scale-codec

Bug: incorrect index assignment with `#[codec(index = ...)]`

Open
#724 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Rust
Stars
287
Forks
103
Avg merge
6d 13h
Merged PRs (30d)
1

Description

Hey! I recently encountered a bug with both the Encode and Decode derive macros, which causes incorrect discriminant values (indexes) to be assigned to enum variants.

Here’s a minimal reproducible example:

use parity_scale_codec::{Decode, Encode};

#[derive(Decode, Encode)]
enum MyEnum {
    #[codec(index = 1)]
    A, // will have index 1
    B, // will also get index 1, incorrectly
}

This results in a compile-time error:

error[E0080]: evaluation of constant value failed
 --> src/lib.rs:3:10
  |
3 | #[derive(Decode, Encode)]
  |          ^^^^^^ the evaluated program panicked at 'Found variants that have duplicate indexes. Both `A` and `B` have the index `1`. Use different indexes for each variant.', src/lib.rs:3:10
  |
  = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `::core::panic` (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0080]: evaluation of constant value failed
 --> src/lib.rs:3:18
  |
3 | #[derive(Decode, Encode)]
  |                  ^^^^^^ the evaluated program panicked at 'Found variants that have duplicate indexes. Both `A` and `B` have the index `1`. Use different indexes for each variant.', src/lib.rs:3:18
  |
  = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `::core::panic` (in Nightly builds, run with -Z macro-backtrace for more info)

If we change the index to 3, the code compiles, but B is still incorrectly assigned index 1, instead of the expected next available index (which should be 4 in this case).

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the Encode and Decode derive macros and reproduce the enum examples from the issue. Trace how an explicit codec index affects the following variant, then verify that duplicate indexes are rejected and that the next implicit index follows the highest assigned index.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
data
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.