Skip to main content

add_content_hash_to_event

Function add_content_hash_to_event 

Source
pub fn add_content_hash_to_event(
    object: &mut CanonicalJsonObject,
) -> Result<(), JsonError>
Expand description

Compute and add the content hash to the given event.

This adds or overwrites the sha256 key in the hashes object of the event.

This should only be called when creating a new event.

§Parameters

  • object: A JSON object to be hashed according to the Matrix specification.

§Errors

Returns an error if the hashes key is present and is not an object.

§Examples

use ruma_common::CanonicalJsonObject;
use ruma_signatures::add_content_hash_to_event;

// Deserialize an event from JSON.
let mut event = serde_json::from_str(
    r#"{
        "room_id": "!x:domain",
        "sender": "@a:domain",
        "origin": "domain",
        "origin_server_ts": 1000000,
        "type": "X",
        "content": {},
        "prev_events": [],
        "auth_events": [],
        "depth": 3
    }"#,
)?;

// Hash the JSON.
add_content_hash_to_event(&mut event)?;

// The hash was added.
assert_eq!(
    event,
    serde_json::from_str::<CanonicalJsonObject>(
        r#"{
            "room_id": "!x:domain",
            "sender": "@a:domain",
            "origin": "domain",
            "origin_server_ts": 1000000,
            "type": "X",
            "content": {},
            "prev_events": [],
            "auth_events": [],
            "depth": 3,
            "hashes": {
                "sha256": "5jM4wQpv6lnBo7CLIghJuHdW+s2CMBJPUOGOC89ncos"
            }
        }"#,
    )?
);