정답 해시 & 기본 단위 테스트 추가
이전 섹션에서는 십자말 풀이 정답을 스마트 컨트랙트의 String
자료형을 사용해 일반 텍스트로 저장했습니다. 사용자에게 정답을 숨기려는 경우, 이는 상태를 보는 모든 사람에게 공개되므로 좋은 접근 방식이 아닙니다. 대신 십자말 풀이 정답을 해시하고 저장해 보겠습니다. 데이터를 해시하는 방법은 여러 가지가 있지만 Rust SDK에서 사용할 수 있는 해시 알고리즘 중 하나인 sha256
을 사용합시다.
이 튜토리얼의 뒷부분에서 추가 NEAR 개념을 설명하기 위해 sha256
를 사용하는 것에서, 암호화 키 쌍 사용으로 바꿀 것입니다.
해당 주제에 대한 Evgeny Kapun의 프레젠테이션에서 해싱에 대해 자세히 알아보세요. 아래 스크린샷에 링크된 채널에서 다른 NEAR 관련 동영상을 찾을 수 있습니다.
빠른 반복 과정을 도와주는 단위 테스트(Unit Test)
이 기초 챕터의 첫 번째 섹션에서 언급했듯이, 스마트 컨트랙트는 기술적으로 매니페스트 파일에 정의된 라이브러리입니다. 우리의 목적을 위해, Rust로 라이브러리를 작성한 결과에는 "main" 함수가 없습니다. 개발 중에 cargo run
명령이 사용되는 많은 온라인 튜토리얼을 찾을 수 있겠지만, 우리에게는 이러한 사치가 없습니다. 그러나, 단위 테스트를 사용하여 스마트 컨트랙트와 상호 작용할 수 있습니다. 이는 컨트랙트를 작성하고 블록체인 네트워크에 배포하며 메서드를 호출하는 것보다 더 편리할 것입니다.
일을 더 쉽게 하기 위해 hex 크레이트에 의존성(dependency)을 추가할 것입니다. 기억하시겠지만 의존성은 매니페스트 파일에 있습니다.
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.)
#[cfg(test)]
mod tests {
use super::*;
use near_sdk::test_utils::{get_logs, VMContextBuilder};
use near_sdk::{testing_env, AccountId};
#[test]
fn debug_get_hash() {
// Basic set up for a unit test
testing_env!(VMContextBuilder::new().build());
// Using a unit test to rapidly debug and iterate
let debug_solution = "near nomicon ref finance";
let debug_hash_bytes = env::sha256(debug_solution.as_bytes());
let debug_hash_string = hex::encode(debug_hash_bytes);
println!("Let's debug: {:?}", debug_hash_string);
}
}
{:?}
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
cargo test
Note that the test command we ran had additional flags. Those flags told Rust not to hide the output from the tests. You can read more about this in the cargo docs. Go ahead and try running the tests using the command above, without the additional flags, and note that we won't see the debug message. :::
The unit test above is meant for debugging and quickly running snippets of code. Some may find this a useful technique when getting familiar with Rust and writing smart contracts. Next we'll write a real unit test that applies to this early version of our crossword puzzle contract.