-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUtils.cs
69 lines (61 loc) · 1.95 KB
/
Utils.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using ProtoBuf;
using Secp256k1Net;
using Shared.models;
namespace Shared
{
public static class Utils
{
/// <summary>
/// Re-calculates the hash of a transaction.
/// </summary>
/// <returns>A hash of the transaction.</returns>
public static byte[] CalculateHash(object obj)
{
using (SHA256 hash = SHA256.Create())
{
var encodedBlock = JsonConvert.SerializeObject(obj);
var byteHash = hash.ComputeHash(Encoding.UTF8.GetBytes(encodedBlock));
return byteHash;
}
}
public static bool ValidateTransaction(Transaction transaction)
{
if (transaction.FromAddress == null)
{
return true;
}
if (transaction.Signature == null)
{
return false;
}
using (var secp256k1 = new Secp256k1())
{
return secp256k1.Verify(
Convert.FromHexString(transaction.Signature),
System.Security.Cryptography.SHA256.Create().ComputeHash(Utils.CalculateHash(transaction)),
Convert.FromHexString(transaction.FromAddress)
);
}
}
public static T DeserializeProtobuf<T>(string base64)
{
byte[] payloadByteArray = Convert.FromBase64String(base64);
using (var stream = new MemoryStream(payloadByteArray))
{
return Serializer.Deserialize<T>(stream);
}
}
public static string SerializeProtobuf<T>(T o)
{
using (var stream = new MemoryStream())
{
Serializer.Serialize<T>(stream, o);
return Convert.ToBase64String(stream.ToArray());
}
}
}
}