Skip to content

Commit 2867ef9

Browse files
Test invalid mnemonic sentence
Throw error if mnemonic sentence is less than 12 words or greater than 24 words or number of words is not a multiple of six or the contains a word not in wordlist or has invalid checksum.
1 parent c12ac39 commit 2867ef9

1 file changed

Lines changed: 49 additions & 3 deletions

File tree

src/keys/bip39/mod.rs

Lines changed: 49 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ impl Mnemonic {
122122
indices.push(idx);
123123

124124
for j in 0..11 {
125-
mnemonic_bits[i * 11 + j] = (idx & (1 << 10 - j)) != 0;
125+
mnemonic_bits[i * 11 + j] = (idx & (1 << (10 - j))) != 0;
126126
}
127127
}
128128

@@ -133,7 +133,7 @@ impl Mnemonic {
133133
for i in 0..entropy_bytes_len {
134134
for j in 0..8 {
135135
if mnemonic_bits[i * 8 + j] {
136-
entropy[i] += 1 << 7 - j;
136+
entropy[i] += 1 << (7 - j);
137137
}
138138
}
139139
}
@@ -145,7 +145,7 @@ impl Mnemonic {
145145
//verify checksum calculated from entropy
146146
let entropy_bits_len = (words.len() * 32) / 3;
147147
for (i, &bit) in mnemonic_bits[entropy_bits_len..].iter().enumerate() {
148-
if (checksum_byte & (1 << 7 - i) != 0) != bit {
148+
if (checksum_byte & (1 << (7 - i)) != 0) != bit {
149149
return Err(Error::InvalidChecksum(checksum_byte as usize));
150150
}
151151
}
@@ -843,4 +843,50 @@ mod test {
843843
Err(Error::InvalidEntropyLength(248))
844844
);
845845
}
846+
847+
#[test]
848+
fn test_invalid_mnemonic() {
849+
//less than 12 words
850+
assert_eq!(
851+
Mnemonic::parse_in(
852+
Language::English,
853+
"join fossil bulk soft easily give section spoon divorce ice pilot"
854+
),
855+
Err(Error::InvalidWordCount(11))
856+
);
857+
858+
//more than 24 words
859+
assert_eq!(Mnemonic::parse_in(Language::English, "area secret six clutch run reject tape
860+
ritual soldier mad eagle win impulse found tattoo door culture reject movie grocery resource
861+
thought please conduct gorilla"), Err(Error::InvalidWordCount(25)));
862+
863+
//not a multiple of six
864+
assert_eq!(
865+
Mnemonic::parse_in(
866+
Language::English,
867+
"gorilla convince minor amateur labor advance hungry
868+
treat ripple bracket draft wrong found"
869+
),
870+
Err(Error::InvalidWordCount(13))
871+
);
872+
873+
//invalid word
874+
assert_eq!(
875+
Mnemonic::parse_in(
876+
Language::English,
877+
"here convince minor amateur labor advance hungry treat ripple bracket draft wrong"
878+
),
879+
Err(Error::InvalidWord(String::from("here")))
880+
);
881+
882+
//invalid checksum
883+
assert_eq!(
884+
Mnemonic::parse_in(
885+
Language::English,
886+
"gorilla convince minor amateur labor advance
887+
hungry treat ripple bracket draft gorilla"
888+
),
889+
Err(Error::InvalidChecksum(175))
890+
);
891+
}
846892
}

0 commit comments

Comments
 (0)