refactor: Always include encoding tag for KeyPackage and Welcome events#32
refactor: Always include encoding tag for KeyPackage and Welcome events#32mubarakcoded merged 2 commits intomasterfrom
Conversation
WalkthroughEncoding tags are now always included in welcome rumors and key-package events; Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Possibly related PRs
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
❌ Coverage: 87.03% → 86.98% (-0.05%) |
25ff536 to
58210e8
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
crates/mdk-core/src/key_packages.rs (1)
24-41: Update doc comment to describe[Tag; 7]array instead of "Vec of tags"; fix.into()string conversionsThe doc comment at lines 24-41 still describes the return as "A Vec of tags" but the function signature returns
[Tag; 7]. Update the doc to specify the fixed array of 7 tags and document the guaranteed presence and order of theencodingtag at index 6.All call sites (README.md, examples, tests, and test_util.rs) properly handle the
[Tag; 7]return type.Additionally, the encoding tag construction uses
"encoding".into()at lines 94, 672, and 897. Per coding guidelines, prefer.to_string()or.to_owned()for&strtoStringconversion instead of.into().
🧹 Nitpick comments (2)
crates/mdk-core/src/welcomes.rs (1)
371-377: Update MIP‑02 test docs to reflect 4‑tag welcome structureThe tests now correctly assert 4 tags on welcome rumors (relays, event reference, client, encoding), but the
test_welcome_event_structure_mip02_compliancedoc comment still claims “exactly 3 tags”. Consider updating that comment (and any similar references) to avoid confusion between spec text and the enforced structure.Also applies to: 425-430, 599-603, 695-696, 940-941
crates/mdk-core/src/key_packages.rs (1)
93-96: Minor style nit: prefer.to_string()over.into()for&str→StringPer the Rust guidelines you’re following, consider switching
"encoding".into()to"encoding".to_string()in theTagKind::Custom("encoding".into())construction here (and the similar pattern ingroups.rs) to keep&str→Stringconversions consistent:- Tag::custom( - TagKind::Custom("encoding".into()), - [encoding.as_tag_value()], - ), + Tag::custom( + TagKind::Custom("encoding".to_string()), + [encoding.as_tag_value()], + ),This is purely stylistic and doesn’t affect behavior.
Also applies to: 2109-2117, 2143-2151
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
crates/mdk-core/src/groups.rs(1 hunks)crates/mdk-core/src/key_packages.rs(10 hunks)crates/mdk-core/src/welcomes.rs(5 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs
📄 CodeRabbit inference engine (.cursor/rules/rust.mdc)
**/*.rs: All trait bounds should be written inwhereclauses rather than inline with type parameters in Rust
UseSelfinstead of the explicit type name when referring to the type in impl blocks
DeriveDebug,Clone,Copy,PartialEq,Eq, andHashfor public types when possible, in that order
DeriveDefaultfor public types when there is a reasonable default value
Always use full paths for logging withtracing::<op>!(...)instead of importing and using<op>!(...)
Prefer.to_string()or.to_owned()for&strtoStringconversion instead of.into()orString::from()
Order imports in the following sequence: (1) core/alloc/std, (2) external crates, (3) current sub-modules with mod declarations, (4) internal crate modules
Import thefmtmodule rather than using full paths when implementing traits fromcore::fmtorstd::fmt
Use relativeself::imports for sub-modules rather than bare module names
Place allusestatements at the top of the file following the specified import order, never inside functions, methods, or other blocks
Avoidif let ... { } else { }constructs; usematchinstead when both branches are non-empty
Useif let ... { }without an else clause when a match arm would be intentionally empty
Define sub-modules using separate files (e.g.,x.rs) withmod x;declaration rather than inlinemod x { .. }blocks, except fortestsandbenchesmodules
Use inlinemod tests { #[cfg(test)] ... }for test modules rather than creating separatetests.rsfiles
Use inlinemod benches { #[cfg(bench)] ... }for benchmark modules rather than creating separatebenches.rsfiles
Files:
crates/mdk-core/src/groups.rscrates/mdk-core/src/key_packages.rscrates/mdk-core/src/welcomes.rs
🧬 Code graph analysis (2)
crates/mdk-core/src/groups.rs (1)
crates/mdk-core/src/util.rs (1)
as_tag_value(62-67)
crates/mdk-core/src/welcomes.rs (1)
crates/mdk-core/src/util.rs (1)
decode_content(142-156)
🔇 Additional comments (2)
crates/mdk-core/src/groups.rs (1)
1291-1299: Welcome rumors now consistently carry anencodingtagThe added custom
encodingtag, keyed offContentEncodingand applied to every welcome rumor, is consistent with the new decoding flow and looks correct; no functional issues from this change.crates/mdk-core/src/welcomes.rs (1)
294-301: Shareddecode_contentusage inpreview_welcomelooks correctSwitching to
decode_contentwith explicitContentEncodingand logging the decoded format integrates cleanly with the new encoding tag and preserves the existing error-path behavior (failed decodes recorded asProcessedWelcome::Failed), so this change looks solid.
❌ Coverage: 87.03% → 86.98% (-0.05%) |
58210e8 to
bf3276f
Compare
❌ Coverage: 87.03% → 86.98% (-0.05%) |
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (3)
crates/mdk-core/src/welcomes.rs (1)
291-325: Centralized welcome decoding and format logging look solidUsing
decode_contenthere with the extra debug log on the actual decoded format keeps welcome handling consistent with key-package decoding and makes failures persistently tracked viaProcessedWelcome::Failed. The duplicated failure-handling block shared with the later parse error path is fine, but could be factored into a small helper in the future if this pattern appears more often.crates/mdk-core/src/key_packages.rs (2)
122-141: Unified key‑package decoding viadecode_contentis correct
parse_serialized_key_packagenow delegates todecode_content(key_package_str, encoding, "key package")and logs the decoded format, which matches the util contract and keeps base64/hex behavior centralized. Error mapping toError::KeyPackageplus the updated tests for invalid encodings/inputs (test_invalid_key_package_parsing) ensure both formats fail fast with the right variant.You might consider renaming the local
formatbinding in the match to something likedecoded_formatto avoid shadowing theformat!macro name and improve readability, but it’s not functionally problematic.Also applies to: 950-971
2087-2117: Encoding‑tag tests for base64 and hex cover the new behavior wellThe base64 and hex encoding tests now both ensure:
- Content decodes under the expected encoding.
- An
"encoding"tag is present.- The second element of that tag is exactly
"base64"or"hex".Combined with the cross‑format compatibility test, this gives good coverage of the new always-present encoding tag behavior for key packages.
If you want slightly clearer intent, matching on
tag.kind() == TagKind::Custom("encoding".into())(like other tests do) instead of peeking atas_slice().first()would reduce reliance on the underlying slice layout, but the current assertions are still robust.Also applies to: 2125-2151, 2153-2156, 2159-2212
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
crates/mdk-core/src/groups.rs(1 hunks)crates/mdk-core/src/key_packages.rs(10 hunks)crates/mdk-core/src/welcomes.rs(5 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs
📄 CodeRabbit inference engine (.cursor/rules/rust.mdc)
**/*.rs: All trait bounds should be written inwhereclauses rather than inline with type parameters in Rust
UseSelfinstead of the explicit type name when referring to the type in impl blocks
DeriveDebug,Clone,Copy,PartialEq,Eq, andHashfor public types when possible, in that order
DeriveDefaultfor public types when there is a reasonable default value
Always use full paths for logging withtracing::<op>!(...)instead of importing and using<op>!(...)
Prefer.to_string()or.to_owned()for&strtoStringconversion instead of.into()orString::from()
Order imports in the following sequence: (1) core/alloc/std, (2) external crates, (3) current sub-modules with mod declarations, (4) internal crate modules
Import thefmtmodule rather than using full paths when implementing traits fromcore::fmtorstd::fmt
Use relativeself::imports for sub-modules rather than bare module names
Place allusestatements at the top of the file following the specified import order, never inside functions, methods, or other blocks
Avoidif let ... { } else { }constructs; usematchinstead when both branches are non-empty
Useif let ... { }without an else clause when a match arm would be intentionally empty
Define sub-modules using separate files (e.g.,x.rs) withmod x;declaration rather than inlinemod x { .. }blocks, except fortestsandbenchesmodules
Use inlinemod tests { #[cfg(test)] ... }for test modules rather than creating separatetests.rsfiles
Use inlinemod benches { #[cfg(bench)] ... }for benchmark modules rather than creating separatebenches.rsfiles
Files:
crates/mdk-core/src/groups.rscrates/mdk-core/src/welcomes.rscrates/mdk-core/src/key_packages.rs
🧬 Code graph analysis (3)
crates/mdk-core/src/groups.rs (1)
crates/mdk-core/src/util.rs (1)
as_tag_value(62-67)
crates/mdk-core/src/welcomes.rs (1)
crates/mdk-core/src/util.rs (1)
decode_content(142-156)
crates/mdk-core/src/key_packages.rs (1)
crates/mdk-core/src/util.rs (1)
decode_content(142-156)
🔇 Additional comments (2)
crates/mdk-core/src/key_packages.rs (1)
20-41: Fixed 7‑tag key‑package API and encoding tag ordering are consistentThe switch to
Result<(String, [Tag; 7]), Error>plus the literal 7‑element array makes the tag schema explicit and compile‑time enforced. The documented tag order matches the array construction, and the updated tests (test_key_package_creation_and_parsing,test_complete_tag_structure_mip00_compliance) correctly assert both the total length and that the 7th tag is the custom"encoding"tag. This aligns nicely with the always-present encoding tag requirement across the codebase.Also applies to: 48-53, 86-99, 665-673, 861-863, 895-899
crates/mdk-core/src/groups.rs (1)
1272-1299: Always including the welcome encoding tag is correct and consistentBuilding welcome rumors with a fixed 4‑tag structure (relays, event ref, client, encoding) aligns welcomes with key‑package events and with the updated tests/spec expectations. Using the same
"encoding"custom tag populated fromContentEncoding::as_tag_value()ensuresContentEncoding::from_tagscan reliably recover the format for both legacy (no tag) and new events.
❌ Coverage: 87.03% → 87.02% (-0.01%) |
7800ad4 to
9dc8f16
Compare
|
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
crates/mdk-core/src/welcomes.rs (1)
371-377: Update comment to reflect 4-tag welcome structureThe test assertion at line 425 correctly checks
welcome_rumor.tags.len() == 4, but the comment at line 371 states "exactly 3 tags (relays + event reference + client)". Update this comment to "exactly 4 tags (relays + event reference + client + encoding)" to match the actual test requirements.
🧹 Nitpick comments (4)
crates/mdk-core/src/util.rs (1)
212-228: Movenostr::Tagimport out of the test function
use nostr::Tag;insidetest_from_tags_returns_encodingviolates the “no inneruse” guideline; please move this import to the top of thetestsmodule instead.As per coding guidelines, all
usestatements should live at the top of the file/module.crates/mdk-core/src/welcomes.rs (1)
291-324: Centralized welcome decoding viadecode_contentlooks correct; consider simplifying error formattingUsing
ContentEncoding::from_tagsanddecode_contentto drive decoding (with a hex default) is consistent with the new encoding‑tag design, and logging the decoded format is helpful. In the error branch, you can drop the debug formatter and just use{}foreto avoid quoting the already‑formatted error string:- let error_string = format!( - "Error decoding welcome event content ({}): {:?}", - encoding.as_tag_value(), - e - ); + let error_string = format!( + "Error decoding welcome event content ({}): {}", + encoding.as_tag_value(), + e + );crates/mdk-core/src/key_packages.rs (2)
24-41: Encoding/tag handling in key‑package creation/parsing looks correct; align"encoding"conversions with style guideThe refactored
create_key_package_for_eventcorrectly:
- Picks
ContentEncodingfromuse_base64_encoding,- Uses shared
encode_content,- Returns a fixed
[Tag; 7]including a trailingencodingtag, and- Leaves
parse_key_packagefree to derive the format viaContentEncoding::from_tags.
parse_serialized_key_package’s use ofdecode_content(..., "key package")and the format debug log are also consistent with the new util API and error expectations.To match the “prefer
.to_string()over.into()” guideline for&str → String, consider updating the custom kind construction (and matching test) like this:- Tag::custom( - TagKind::Custom("encoding".into()), - [encoding.as_tag_value()], - ), + Tag::custom( + TagKind::Custom("encoding".to_string()), + [encoding.as_tag_value()], + ),and
- assert_eq!(tags[6].kind(), TagKind::Custom("encoding".into())); + assert_eq!(tags[6].kind(), TagKind::Custom("encoding".to_string()));As per coding guidelines,
.to_string()is preferred here.Also applies to: 48-52, 72-85, 86-97, 127-133
2087-2117: Base64 and hex encoding tests validate both content and encoding tag; minor optional cleanupThe new
test_key_package_base64_encodingandtest_key_package_hex_encodingcorrectly:
- Exercise both encoding modes via
MdkConfig::use_base64_encoding,- Verify that content decodes as base64/hex, and
- Assert that the
["encoding", "..."]tag is present with the expected value.If you want to trim a tiny allocation in the tag lookup, you could compare against
"encoding"as&strinstead of constructing aStringeach time:- .find(|t| t.as_slice().first() == Some(&"encoding".to_string())); + .find(|t| t.as_slice().first().map(String::as_str) == Some("encoding"));Also applies to: 2125-2151
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
crates/mdk-core/src/groups.rs(1 hunks)crates/mdk-core/src/key_packages.rs(10 hunks)crates/mdk-core/src/util.rs(1 hunks)crates/mdk-core/src/welcomes.rs(5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- crates/mdk-core/src/groups.rs
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs
📄 CodeRabbit inference engine (.cursor/rules/rust.mdc)
**/*.rs: All trait bounds should be written inwhereclauses rather than inline with type parameters in Rust
UseSelfinstead of the explicit type name when referring to the type in impl blocks
DeriveDebug,Clone,Copy,PartialEq,Eq, andHashfor public types when possible, in that order
DeriveDefaultfor public types when there is a reasonable default value
Always use full paths for logging withtracing::<op>!(...)instead of importing and using<op>!(...)
Prefer.to_string()or.to_owned()for&strtoStringconversion instead of.into()orString::from()
Order imports in the following sequence: (1) core/alloc/std, (2) external crates, (3) current sub-modules with mod declarations, (4) internal crate modules
Import thefmtmodule rather than using full paths when implementing traits fromcore::fmtorstd::fmt
Use relativeself::imports for sub-modules rather than bare module names
Place allusestatements at the top of the file following the specified import order, never inside functions, methods, or other blocks
Avoidif let ... { } else { }constructs; usematchinstead when both branches are non-empty
Useif let ... { }without an else clause when a match arm would be intentionally empty
Define sub-modules using separate files (e.g.,x.rs) withmod x;declaration rather than inlinemod x { .. }blocks, except fortestsandbenchesmodules
Use inlinemod tests { #[cfg(test)] ... }for test modules rather than creating separatetests.rsfiles
Use inlinemod benches { #[cfg(bench)] ... }for benchmark modules rather than creating separatebenches.rsfiles
Files:
crates/mdk-core/src/util.rscrates/mdk-core/src/key_packages.rscrates/mdk-core/src/welcomes.rs
🧠 Learnings (1)
📚 Learning: 2025-12-03T10:18:10.432Z
Learnt from: CR
Repo: marmot-protocol/mdk PR: 0
File: .cursor/rules/rust.mdc:0-0
Timestamp: 2025-12-03T10:18:10.432Z
Learning: Applies to **/*.rs : Use inline `mod tests { #[cfg(test)] ... }` for test modules rather than creating separate `tests.rs` files
Applied to files:
crates/mdk-core/src/util.rs
🧬 Code graph analysis (2)
crates/mdk-core/src/key_packages.rs (1)
crates/mdk-core/src/util.rs (1)
decode_content(142-156)
crates/mdk-core/src/welcomes.rs (1)
crates/mdk-core/src/util.rs (1)
decode_content(142-156)
🔇 Additional comments (2)
crates/mdk-core/src/util.rs (1)
162-210: ContentEncoding tests provide good coverage of new behaviorThe new tests exercise hex/base64 round‑trips, invalid input handling, ambiguous strings, and tag value round‑trip, which aligns well with the new
decode_contentAPI and tag‑based encoding selection.crates/mdk-core/src/key_packages.rs (1)
642-666: Tests correctly enforce 7‑tag structure including encodingThe updated tests (
test_key_package_creation_and_parsingandtest_complete_tag_structure_mip00_compliance) now assert a 7‑tag structure and explicitly check that the last tag is the customencodingtag, which matches the newcreate_key_package_for_eventcontract and spec text in the comments.Also applies to: 861-863, 895-899
- Always include ["encoding", "hex"] or ["encoding", "base64"] tag - Revert to fixed-size [Tag; 7] array instead of Vec<Tag> - Remove wrapper methods, inline decode_content calls - Add test for ContentEncoding::from_tags
9dc8f16 to
7427a6d
Compare
|
jgmontoya
left a comment
There was a problem hiding this comment.
Looks good, leaving just a very minor comment but approved so you can merge after addressing
✅ Coverage: 87.03% → 87.04% (+0.01%) |
Summary by CodeRabbit
Improvements
Breaking Changes
Tests
✏️ Tip: You can customize this high-level summary in your review settings.