You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
For example, we want a custom integer type can only old number less than 100:
#[derive(Encode,Decode)]structUIntLessThan100(u8);implUIntLessThan100{pub new(val:u8) -> Option<Self> {if val < 100{Some(Self(val))}else{None}
pub add(self, other:Self) -> u8{self.0 + other.0}// this can never overflow because we know 100 + 100 < 255}
But this will result an invalid struct and break the invariant and causing panics.
let bad:UIntLessThan100 = Decode::decode(&mut&[255u8]).unwrap();
BoundedVec have similar issue and the solution is write a custom decode implementation. But it is tedious for large struct.
The text was updated successfully, but these errors were encountered:
You could make a PR to add a trait parity_scale_codec::Validated and then have a new #[codec(validated)] annotation which applies to a struct which is #[derive(Decode)]
Add a CodecError::ValidationFailed
Then in the autogenerated Decode impl, if the codec(validated) is present, it adds the extra check
#[codec(validate_with = "fn_path")] would avoid the need for a new trait
#[derive(Decode)]#[codec(validate_with = "check_trit")]structTrit(u8);// Probably some more concrete error type in practicefncheck_trit(trit:&Trit) -> Result<(),String>{match trit.0{0 | 1 | 2 => Ok(()),
_ => Err("byte-pattern out of range for trit".into()),}}
If the "validation function" fails, that would manifest as a CodecError at a higher level.
For example, we want a custom integer type can only old number less than 100:
But this will result an invalid struct and break the invariant and causing panics.
BoundedVec
have similar issue and the solution is write a custom decode implementation. But it is tedious for large struct.The text was updated successfully, but these errors were encountered: