fix: increase multihash size to 256 bytes

feat/type-attributes
Tomáš Mládek 2023-05-20 19:24:19 +02:00
parent f2a764d84e
commit 51ba6f8772
1 changed files with 13 additions and 7 deletions

View File

@ -1,6 +1,5 @@
use crate::util::hash::{b58_decode, b58_encode, Hash, Hashable};
use anyhow::{anyhow, Result};
use multihash::{Code, Multihash, MultihashDigest};
use serde::de::Visitor;
use serde::{de, ser, Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
@ -21,18 +20,25 @@ const SHA2_256: u64 = 0x12;
// multihash identity
const IDENTITY: u64 = 0x00;
type LargeMultihash = multihash::MultihashGeneric<256>;
impl Address {
pub fn encode(&self) -> Result<Vec<u8>> {
let hash = match self {
Self::Hash(hash) => Multihash::wrap(SHA2_256, &hash.0).map_err(|err| anyhow!(err))?,
Self::Hash(hash) => {
LargeMultihash::wrap(SHA2_256, &hash.0).map_err(|err| anyhow!(err))?
}
Self::Uuid(uuid) => {
Code::Identity.digest(&[vec![b'U'], uuid.as_bytes().to_vec()].concat())
LargeMultihash::wrap(IDENTITY, &[vec![b'U'], uuid.as_bytes().to_vec()].concat())
.map_err(|err| anyhow!(err))?
}
Self::Attribute(attribute) => {
Code::Identity.digest(&[&[b'A'], attribute.as_bytes()].concat())
LargeMultihash::wrap(IDENTITY, &[&[b'A'], attribute.as_bytes()].concat())
.map_err(|err| anyhow!(err))?
}
Self::Url(url) => {
Code::Identity.digest(&[&[b'X'], url.to_string().as_bytes()].concat())
LargeMultihash::wrap(IDENTITY, &[&[b'X'], url.to_string().as_bytes()].concat())
.map_err(|err| anyhow!(err))?
}
};
@ -40,7 +46,7 @@ impl Address {
}
pub fn decode(buffer: &[u8]) -> Result<Self> {
let multihash = Multihash::from_bytes(buffer)
let multihash = LargeMultihash::from_bytes(buffer)
.map_err(|err| anyhow!("Error decoding address: {}", err))?;
match multihash.code() {
@ -184,7 +190,7 @@ mod tests {
#[test]
fn test_url_codec() -> Result<()> {
let addr = Address::Url(Url::parse("https://upend.dev").unwrap());
let addr = Address::Url(Url::parse("https://upend.dev/an/url/that/is/particularly/long/because/multihash/used/to/have/a/small/limit").unwrap());
let encoded = addr.encode()?;
let decoded = Address::decode(&encoded)?;
assert_eq!(addr, decoded);