文字列の繰り返しは repeat() を使用する
fn main() { let mut difficulty = 4; let str: String = "0".to_string(); let target = str.repeat(difficulty); println!("{}", target); }
$ cargo run
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.29s
Running `target/debug/crypt`
0000
リファクタリングする。
fn main() { let now = time::Instant::now(); let previous_hash = "b9b9ee9ffc95fa4956b63b6043a99d0a8f04e0e52e687fc1958d3c6dff885f01"; let mut num = rand::thread_rng().gen_range(0..1000000); let mut hash_num = format!("{}{}", previous_hash, num.to_string()); let mut header = Sha256::digest(hash_num); let mut target: String = (&hex::encode(header)[..4]).to_string(); let mut cnt = 1; println!("count: {} {:x}", cnt, header); let mut difficulty = 4; let str: String = "0".to_string(); let difficulty_str = str.repeat(difficulty); while target != difficulty_str { println!("count: {} {:x}", cnt, header); num = rand::thread_rng().gen_range(0..1000000); hash_num = format!("{}{}", previous_hash, num.to_string()); header = Sha256::digest(hash_num); target = (&hex::encode(header)[..4]).to_string(); cnt += 1; } println!("count: {} {:x}", cnt, header); println!("{:?}", now.elapsed()); }
$ cargo run
…
count: 60678 0000b49915dc1fbb5fc8660d285674dbbe9e8d06f31fc5040b6044b4fb3da86a
2.082390487s
問題ありません。なるほどね。これで、difficultyの値を自動調整できるようになりました。