#How to encode `BytesN` or `[u8; 15]`

16 messages · Page 1 of 1 (latest)

tardy carbon
#

Hello!

I am trying to generate an encoded random identifier from a Soroban smart contract.

I managed to generate random bytes [u8; 15].
For what it's worth, you can also take this to a BytesN -> BytesN::from_array(&e, &raw_bytes).

But now I want to encode these bytes (either from [u8; 15] or BytesN) to Base 32.

Would anyone know how to achieve this? Thanks.

karmic roost
#

Theres a crate called base32 can you import it?

tardy carbon
#

Yeah I already solved it.
The main problem was that the encode function returns an alloc::string::String. But I already noticed I can add extern crate alloc; to the contract and it works.

Thank you!

karmic roost
#

Hmm there is an alloc like in rs soroban sdk im not sure the normal alloc will work but maybe

tardy carbon
karmic roost
#

Ah yes perfect sorry got confused

tardy carbon
#

np, thank you!

paper gulch
#

The base32 and 64 crates in the Rust ecosystem seem to be dependent on alloc.

#

But, the algorithms are very suitable to be written in a way that doesn't require alloc.

#

For a contract I wrote I ported the base64url encoder from the Go stdlib:
https://github.com/leighmcculloch/soroban-webauthn/blob/main/contract-ed25519/src/base64_url.rs

The logic in the Go stdlib is simpler to follow than other references I looked at. You could port the base32 encoding logic into your contract. It's here for reference:
https://github.com/golang/go/blob/26b5783b72376acd0386f78295e678b9a6bff30e/src/encoding/base32/base32.go

GitHub

soroban-passkey. Contribute to leighmcculloch/soroban-webauthn development by creating an account on GitHub.

GitHub

The Go programming language. Contribute to golang/go development by creating an account on GitHub.

tardy carbon
#

@paper gulch thanks for the response!
Some questions:

  1. Would the contract have any problems if base32 is used depending on alloc?
  2. What you did was basically look at Go code and pass it to Rust, right? That's what you mean by "I ported"?
paper gulch
#

I looked at the Go code and rewrote it in Rust.

#

Contracts can depend on alloc, but the allocator in the Rust SDK is quite experimental. Unclear how much cost it'll consume and if it'll fit under the limits

#

I'd expect the alloc version to be more expensive.

tardy carbon
#

Yeah I got it, thank you so much!!

karmic roost
#

I have a short rust base32 implementation i made a few months ago.