Hash the solution, add basic unit tests
In the previous section, we stored the crossword solution as plain text as a String type on the smart contract. If we're trying to hide the solution from the users, this isn't a great approach as it'll be public to anyone looking at the state. Let's instead hash our crossword solution and store that instead. There are different ways to hash data, but let's use sha256 which is one of the hashing algorithms available in the Rust SDK.
Without getting into much detail, hashing is a "one-way" function that will output a result from a given input. If you have input (in our case, the crossword puzzle solution) you can get a hash, but if you have a hash you cannot get the input. This basic idea is foundational to information theory and security.
Later on in this tutorial, we'll switch from using sha256 to using cryptographic key pairs to illustrate additional NEAR concepts.
Learn more about hashing from Evgeny Kapun's presentation on the subject. You may find other NEAR-related videos from the channel linked in the screenshot below.
Helper unit test during rapid iteration
As mentioned in the first section of this Basics chapter, our smart contract is technically a library as defined in the manifest file. For our purposes, a consequence of writing a library in Rust is not having a "main" function that runs. You may find many online tutorials where the command cargo run is used during development. We don't have this luxury, but we can use unit tests to interact with our smart contract. This is likely more convenient than building the contract, deploying to a blockchain network, and calling a method.
We'll add a dependency to the hex crate to make things easier. As you may remember, dependencies live in the manifest file.
Loading...
Let's write a unit test that acts as a helper during development. This unit test will sha256 hash the input "near nomicon ref finance" and print it in a human-readable, hex format. (We'll typically put unit tests at the bottom of the lib.rs file.)
Loading...
{:?} thing?Take a look at different formatting traits that are covered in the std Rust docs regarding this. This is a Debug formatting trait and can prove to be useful during development.
Run the unit tests with the command:
cargo test -- --nocapture
You'll see this output:
…
running 1 test
Let's debug: "69c2feb084439956193f4c21936025f14a5a5a78979d67ae34762e18a7206a0f"
test tests::debug_get_hash ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
This means when you sha256 the input "near nomicon ref finance" it produces the hash:
69c2feb084439956193f4c21936025f14a5a5a78979d67ae34762e18a7206a0f
You may also run tests using:
cargo test
