| | | 1 | | using NBitcoin; |
| | | 2 | | |
| | | 3 | | namespace EF.Blockchain.Domain; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Represents a wallet with a public and private key used to sign and verify blockchain transactions. |
| | | 7 | | /// </summary> |
| | | 8 | | public class Wallet |
| | | 9 | | { |
| | | 10 | | /// <summary> |
| | | 11 | | /// The private key in hexadecimal format. Used to sign transactions. |
| | | 12 | | /// </summary> |
| | 1400 | 13 | | public string PrivateKey { get; private set; } |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// The public key in hexadecimal format. Used to verify ownership and generate the wallet address. |
| | | 17 | | /// </summary> |
| | 2008 | 18 | | public string PublicKey { get; private set; } |
| | | 19 | | |
| | | 20 | | /// <summary> |
| | | 21 | | /// Initializes a new wallet. |
| | | 22 | | /// Can use a raw private key (64 hex chars), a WIF string, or generate a new key if none is provided. |
| | | 23 | | /// </summary> |
| | | 24 | | /// <param name="wifOrPrivateKey"> |
| | | 25 | | /// Optional string representing a raw private key (64 hex characters) or a WIF-encoded private key. |
| | | 26 | | /// If null, a new random key is generated. |
| | | 27 | | /// </param> |
| | 1160 | 28 | | public Wallet(string? wifOrPrivateKey = null) |
| | 1160 | 29 | | { |
| | | 30 | | Key key; |
| | | 31 | | |
| | 1160 | 32 | | if (!string.IsNullOrEmpty(wifOrPrivateKey)) |
| | 128 | 33 | | { |
| | 128 | 34 | | if (wifOrPrivateKey.Length == 64) |
| | 120 | 35 | | { |
| | | 36 | | // From raw private key hex |
| | 120 | 37 | | var bytes = Convert.FromHexString(wifOrPrivateKey); |
| | 120 | 38 | | key = new Key(bytes); |
| | 120 | 39 | | } |
| | | 40 | | else |
| | 8 | 41 | | { |
| | | 42 | | // From WIF |
| | 8 | 43 | | key = Key.Parse(wifOrPrivateKey, Network.Main); |
| | 8 | 44 | | } |
| | 128 | 45 | | } |
| | | 46 | | else |
| | 1032 | 47 | | { |
| | | 48 | | // Random new key |
| | 1032 | 49 | | key = new Key(); |
| | 1032 | 50 | | } |
| | | 51 | | |
| | 1160 | 52 | | PrivateKey = key.ToHex(); |
| | 1160 | 53 | | PublicKey = key.PubKey.ToHex(); |
| | 1160 | 54 | | } |
| | | 55 | | } |