I am making use of c# to consume the data from my chia node. I have used the following function to get the coin_id, however the actual response doesnt match with the expected value. Can you please provide me with a solution in c# for the same?
private static String sha256_hash(string value)
{
using var hash = SHA256.Create();
var byteArray = hash.ComputeHash(Encoding.UTF8.GetBytes(value));
return Convert.ToHexString(byteArray).ToLower();
}
string coin_id = sha256_hash(parent_coin_id + puzzle_hash + amount.ToString());
The issue is how you get bytes
from parent_coin_id
, puzzle_hash
, and amount
.
It’s been a while since I wrote any C# code, but, hopefully, the code below will give you some idea:
using System.Security.Cryptography;
var parent_id = "0101a581331ee609668229b75a08fb6f3bb32abf15349acc11c17c2072643a8d";
var puzzle_hash = "eff07522495060c066f66f32acc2a77e3a3e737aca8baea4d1a64ea4cdc13da9";
var amount = 1023; // in mojos
// convert values to bytes
byte[] parent_id_bytes = Convert.FromHexString(parent_id);
byte[] puzzle_hash_bytes = Convert.FromHexString(puzzle_hash);
var amount_hex_string = amount.ToString("X");
// add leading zero if needed
amount_hex_string = (amount_hex_string.Length % 2 == 0 ? "" : "0") + amount_hex_string;
byte[] amount_bytes = Convert.FromHexString(amount_hex_string);
// concat all to one bytes array
byte[] bytes = parent_id_bytes.Concat(puzzle_hash_bytes).Concat(amount_bytes).ToArray();
var hash = SHA256.Create();
byte[] coin_id_bytes = hash.ComputeHash(bytes);
string coin_id = Convert.ToHexString(coin_id_bytes);
Console.WriteLine(coin_id);
// 2DEFA04144FEF9C90598CBA104F36E2922C1B0C99220223780D6DA561B874A7A
You can double check with run
:
run '(sha256 0x0101a581331ee609668229b75a08fb6f3bb32abf15349acc11c17c2072643a8d 0xeff07522495060c066f66f32acc2a77e3a3e737aca8baea4d1a64ea4cdc13da9 1023)'
# 0x2defa04144fef9c90598cba104f36e2922c1b0c99220223780d6da561b874a7a