tsk
June 7, 2023, 8:52am
1
How do I encode a struct imported from Sway into bytes using Rust SDK?
For example I have a struct defined in Sway
struct TransferParams {
to: Identity,
asset_id: ContractId,
amount: u64,
}
I need to sha256 this struct using Rust so I need the struct encoded as bytes.
Any help? Thanks
tsk
June 12, 2023, 12:44am
2
I found out that for a simple struct fuels::core::calldata!
macro will encode it into bytes.
Care must be taken if the struct contains Bytes
and you need to hash it. The hash might be inconsistent between the code you write in Rust SDK and Sway.
opened 02:06PM - 18 Jan 23 UTC
closed 11:01AM - 20 Jan 23 UTC
lib: std
The `Bytes` type was recently introduced as a way to tightly pack bytes. A commo… n use case for this is hashing as a way to avoid padding of types such as `u8` to a full word. This is explicitly done in the [Merkle Proof library](https://github.com/FuelLabs/sway-libs/blob/27215d1829d2fd03d78d31a7d00cd70675cbc8fc/sway_libs/src/merkle_proof/binary_merkle_proof.sw#L22) where the concatenation of a single `u8` to the front of a `b256` is needed to follow the RFC-6962 specification.
However, the current [`sha256()`](https://github.com/FuelLabs/sway/blob/f18197f0c040d1223968ca046edf12e053a3568a/sway-lib-std/src/hash.sw#L4) function in the hash library does not allow for hashing of the tightly packed bytes. The `Bytes` type stores a length along with the `RawBytes` type which contains a pointer to the bytes.
For example, when calling `sha256(my_bytes)` where `my_bytes` is a `Bytes` struct, the `sha256()` method will call `__size_of` upon the struct. As a result, I did not just hash the tightly packed bytes but instead hashed the struct itself.
To avoid developers having to create their own asm blocks, there should be an easy method to hash these bytes.
I believe the best way to handle this would be to add a hashing function to the `Bytes` type. A developer would then call the function in the same manor that `.join()` and `.push()` are called.
cc @nfurfaro