Skip to content

Replace hardcoded _get_tag() with data-driven TAG_TABLE generated from CSV #40

Description

@sumanjeet0012

The _get_tag() function in code.py is ~260 lines of hardcoded if/elif pattern matching. It should be replaced with a simple dict lookup using a TAG_TABLE that is generated from the upstream CSV's tag column, matching how go-multicodec generates its Tag() method.

Problem

Current implementation in multicodec/code.py (lines 178–438):

def _get_tag(code: int) -> str:
    name = CODE_TABLE.get(code, "")

    # CID
    if name in ("cidv1", "cidv2", "cidv3"):
        return "cid"

    # Encryption
    if name in ("aes-gcm-256",):
        return "encryption"

    # ... 200+ more lines of if/elif pattern matching ...

    # Multihash — substring matching (fragile!)
    if any(h in name for h in ("sha2-", "sha3-", "blake2b-", ...)):
        return "multihash"

    return "<unknown>"

Problems with this approach:

  • Drift risk: When new codecs are added to the CSV, they may not match existing patterns and silently return "<unknown>"
  • Already missing 6 tags: multikey, multisig, nonce, shelter, softhash, vlad (see related issue)
  • 260 lines of code that should be ~5 lines with a generated lookup table
  • No connection to the authoritative CSV tag column

In contrast, go-multicodec generates its Tag() method directly from the CSV:

// Generated from table.csv — always in sync
func (c Code) Tag() string {
    switch c {
    case Identity, Sha1, Sha2_256, ...:
        return "multihash"
    case Ip4, Tcp, Udp, ...:
        return "multiaddr"
    // ...
    }
}

Proposed Solution

  1. Generate a TAG_TABLE dict in constants.py (or a new tags.py) that maps every codec code to its tag, sourced from the CSV:

    TAG_TABLE = {
        0x12: "multihash",     # sha2-256
        0x04: "multiaddr",     # ip4
        0x70: "ipld",          # dag-pb
        # ... all 603 entries ...
    }
  2. Replace _get_tag() in code.py with a one-line lookup:

    def _get_tag(code: int) -> str:
        return TAG_TABLE.get(code, "<unknown>")
  3. Update tools/update-table.py (or tools/gen_code_table.py) to generate TAG_TABLE from the CSV data.

  4. Remove the ~260 lines of hardcoded pattern matching from code.py.

  5. Add tests that verify every codec's tag matches the CSV.

Related

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions