| | | 1 | | using System.Runtime.InteropServices; |
| | | 2 | | using System.Runtime.Serialization; |
| | | 3 | | using System.Text; |
| | | 4 | | using System.Text.Json; |
| | | 5 | | using NBitcoin; |
| | | 6 | | |
| | | 7 | | namespace NLightning.Infrastructure.Bitcoin.Managers; |
| | | 8 | | |
| | | 9 | | using Domain.Bitcoin.ValueObjects; |
| | | 10 | | using Domain.Crypto.Constants; |
| | | 11 | | using Domain.Crypto.ValueObjects; |
| | | 12 | | using Domain.Protocol.Interfaces; |
| | | 13 | | using Domain.Protocol.ValueObjects; |
| | | 14 | | using Infrastructure.Crypto.Ciphers; |
| | | 15 | | using Infrastructure.Crypto.Factories; |
| | | 16 | | using Infrastructure.Crypto.Hashes; |
| | | 17 | | using Node.Models; |
| | | 18 | | |
| | | 19 | | /// <summary> |
| | | 20 | | /// Manages a securely stored private key using protected memory allocation. |
| | | 21 | | /// This class ensures that the private key remains inaccessible from regular memory |
| | | 22 | | /// and is securely wiped when no longer needed. |
| | | 23 | | /// </summary> |
| | | 24 | | public class SecureKeyManager : ISecureKeyManager, IDisposable |
| | | 25 | | { |
| | 0 | 26 | | private static readonly byte[] s_salt = |
| | 0 | 27 | | [ |
| | 0 | 28 | | 0xFF, 0x1D, 0x3B, 0xF5, 0x24, 0xA2, 0xB7, 0xA9, |
| | 0 | 29 | | 0xC3, 0x1B, 0x1F, 0x58, 0xE9, 0x48, 0xB5, 0x69 |
| | 0 | 30 | | ]; |
| | | 31 | | |
| | | 32 | | private readonly string _filePath; |
| | 0 | 33 | | private readonly object _lastUsedIndexLock = new(); |
| | | 34 | | private readonly Network _network; |
| | 0 | 35 | | private readonly KeyPath _keyPath = new("m/6425'/0'/0'/0"); |
| | | 36 | | |
| | | 37 | | private uint _lastUsedIndex; |
| | | 38 | | private ulong _privateKeyLength; |
| | | 39 | | private IntPtr _securePrivateKeyPtr; |
| | | 40 | | |
| | 0 | 41 | | public BitcoinKeyPath KeyPath => _keyPath.ToBytes(); |
| | | 42 | | |
| | 0 | 43 | | public string OutputDescriptor { get; init; } |
| | | 44 | | |
| | 0 | 45 | | public uint HeightOfBirth { get; init; } |
| | | 46 | | |
| | | 47 | | /// <summary> |
| | | 48 | | /// Manages secure key operations for generating and managing cryptographic keys. |
| | | 49 | | /// Provides functionality to safely store, load, and derive secure keys protected in memory. |
| | | 50 | | /// </summary> |
| | | 51 | | /// <param name="privateKey">The private key to be managed.</param> |
| | | 52 | | /// <param name="network">The network associated with the private key.</param> |
| | | 53 | | /// <param name="filePath">The file path for storing the key data.</param> |
| | | 54 | | /// <param name="heightOfBirth">Block Height when the wallet was created</param> |
| | 0 | 55 | | public SecureKeyManager(byte[] privateKey, BitcoinNetwork network, string filePath, uint heightOfBirth) |
| | | 56 | | { |
| | 0 | 57 | | _privateKeyLength = (ulong)privateKey.Length; |
| | | 58 | | |
| | 0 | 59 | | using var cryptoProvider = CryptoFactory.GetCryptoProvider(); |
| | | 60 | | |
| | | 61 | | // Allocate secure memory |
| | 0 | 62 | | _securePrivateKeyPtr = cryptoProvider.MemoryAlloc(_privateKeyLength); |
| | | 63 | | |
| | | 64 | | // Lock the memory to prevent swapping |
| | 0 | 65 | | if (cryptoProvider.MemoryLock(_securePrivateKeyPtr, _privateKeyLength) == -1) |
| | 0 | 66 | | throw new InvalidOperationException("Failed to lock memory."); |
| | | 67 | | |
| | | 68 | | // Copy the private key to secure memory |
| | 0 | 69 | | Marshal.Copy(privateKey, 0, _securePrivateKeyPtr, (int)_privateKeyLength); |
| | | 70 | | |
| | | 71 | | // Get Output Descriptor |
| | 0 | 72 | | _network = Network.GetNetwork(network) |
| | 0 | 73 | | ?? throw new ArgumentException("Invalid network specified.", nameof(network)); |
| | 0 | 74 | | var extKey = new ExtKey(new Key(privateKey), network.ChainHash); |
| | 0 | 75 | | var xpub = extKey.Neuter().ToString(_network); |
| | 0 | 76 | | var fingerprint = extKey.GetPublicKey().GetHDFingerPrint(); |
| | | 77 | | |
| | 0 | 78 | | OutputDescriptor = $"wpkh([{fingerprint}/{KeyPath}/*]{xpub}/0/*)"; |
| | | 79 | | |
| | | 80 | | // Securely wipe the original key from regular memory |
| | 0 | 81 | | cryptoProvider.MemoryZero(Marshal.UnsafeAddrOfPinnedArrayElement(privateKey, 0), _privateKeyLength); |
| | | 82 | | |
| | 0 | 83 | | _filePath = filePath; |
| | 0 | 84 | | HeightOfBirth = heightOfBirth; |
| | 0 | 85 | | } |
| | | 86 | | |
| | | 87 | | public ExtPrivKey GetNextKey(out uint index) |
| | | 88 | | { |
| | 0 | 89 | | lock (_lastUsedIndexLock) |
| | | 90 | | { |
| | 0 | 91 | | _lastUsedIndex++; |
| | 0 | 92 | | index = _lastUsedIndex; |
| | 0 | 93 | | } |
| | | 94 | | |
| | | 95 | | // Derive the key at m/6425'/0'/0'/0/index |
| | 0 | 96 | | var masterKey = GetMasterKey(); |
| | 0 | 97 | | var derivedKey = masterKey.Derive(_keyPath.Derive(index)); |
| | | 98 | | |
| | 0 | 99 | | _ = UpdateLastUsedIndexOnFile().ContinueWith(task => |
| | 0 | 100 | | { |
| | 0 | 101 | | if (task.IsFaulted) |
| | 0 | 102 | | Console.Error.WriteLine($"Failed to update last used index on file: {task.Exception.Message}"); |
| | 0 | 103 | | }, TaskContinuationOptions.OnlyOnFaulted); |
| | | 104 | | |
| | 0 | 105 | | return derivedKey.ToBytes(); |
| | | 106 | | } |
| | | 107 | | |
| | | 108 | | public ExtPrivKey GetKeyAtIndex(uint index) |
| | | 109 | | { |
| | 0 | 110 | | var masterKey = GetMasterKey(); |
| | 0 | 111 | | return masterKey.Derive(_keyPath.Derive(index)).ToBytes(); |
| | | 112 | | } |
| | | 113 | | |
| | | 114 | | public CryptoKeyPair GetNodeKeyPair() |
| | | 115 | | { |
| | 0 | 116 | | var masterKey = GetMasterKey(); |
| | 0 | 117 | | return new CryptoKeyPair(masterKey.PrivateKey.ToBytes(), masterKey.PrivateKey.PubKey.ToBytes()); |
| | | 118 | | } |
| | | 119 | | |
| | | 120 | | public CompactPubKey GetNodePubKey() |
| | | 121 | | { |
| | 0 | 122 | | var masterKey = GetMasterKey(); |
| | 0 | 123 | | return masterKey.PrivateKey.PubKey.ToBytes(); |
| | | 124 | | } |
| | | 125 | | |
| | | 126 | | public async Task UpdateLastUsedIndexOnFile() |
| | | 127 | | { |
| | 0 | 128 | | var jsonString = await File.ReadAllTextAsync(_filePath); |
| | 0 | 129 | | var data = JsonSerializer.Deserialize<KeyFileData>(jsonString) |
| | 0 | 130 | | ?? throw new SerializationException("Invalid key file"); |
| | | 131 | | |
| | 0 | 132 | | lock (_lastUsedIndexLock) |
| | | 133 | | { |
| | 0 | 134 | | data.LastUsedIndex = _lastUsedIndex; |
| | 0 | 135 | | } |
| | | 136 | | |
| | 0 | 137 | | jsonString = JsonSerializer.Serialize(data); |
| | | 138 | | |
| | 0 | 139 | | await File.WriteAllTextAsync(_filePath, jsonString); |
| | 0 | 140 | | } |
| | | 141 | | |
| | | 142 | | public void SaveToFile(string password) |
| | | 143 | | { |
| | 0 | 144 | | lock (_lastUsedIndexLock) |
| | | 145 | | { |
| | 0 | 146 | | var extKey = GetMasterKey(); |
| | 0 | 147 | | var extKeyBytes = Encoding.UTF8.GetBytes(extKey.ToString(_network)); |
| | | 148 | | |
| | 0 | 149 | | Span<byte> key = stackalloc byte[CryptoConstants.PrivkeyLen]; |
| | 0 | 150 | | Span<byte> nonce = stackalloc byte[CryptoConstants.Xchacha20Poly1305NonceLen]; |
| | 0 | 151 | | Span<byte> cipherText = stackalloc byte[extKeyBytes.Length + CryptoConstants.Xchacha20Poly1305TagLen]; |
| | | 152 | | |
| | 0 | 153 | | using var argon2Id = new Argon2Id(); |
| | 0 | 154 | | argon2Id.DeriveKeyFromPasswordAndSalt(password, s_salt, key); |
| | | 155 | | |
| | 0 | 156 | | using var xChaCha20Poly1305 = new XChaCha20Poly1305(); |
| | 0 | 157 | | xChaCha20Poly1305.Encrypt(key, nonce, ReadOnlySpan<byte>.Empty, extKeyBytes, cipherText); |
| | | 158 | | |
| | 0 | 159 | | var data = new KeyFileData |
| | 0 | 160 | | { |
| | 0 | 161 | | Network = _network.ToString(), |
| | 0 | 162 | | LastUsedIndex = _lastUsedIndex, |
| | 0 | 163 | | Descriptor = OutputDescriptor, |
| | 0 | 164 | | EncryptedExtKey = Convert.ToBase64String(cipherText), |
| | 0 | 165 | | HeightOfBirth = HeightOfBirth |
| | 0 | 166 | | }; |
| | 0 | 167 | | var json = JsonSerializer.Serialize(data); |
| | 0 | 168 | | File.WriteAllText(_filePath, json); |
| | | 169 | | } |
| | 0 | 170 | | } |
| | | 171 | | |
| | | 172 | | public static SecureKeyManager FromMnemonic(string mnemonic, string passphrase, BitcoinNetwork network, |
| | | 173 | | string? filePath = null, uint currentHeight = 0) |
| | | 174 | | { |
| | 0 | 175 | | if (string.IsNullOrWhiteSpace(filePath)) |
| | 0 | 176 | | filePath = GetKeyFilePath(network); |
| | | 177 | | |
| | 0 | 178 | | var mnemonicObj = new Mnemonic(mnemonic, Wordlist.English); |
| | 0 | 179 | | var extKey = mnemonicObj.DeriveExtKey(passphrase); |
| | 0 | 180 | | return new SecureKeyManager(extKey.PrivateKey.ToBytes(), network, filePath, currentHeight); |
| | | 181 | | } |
| | | 182 | | |
| | | 183 | | public static SecureKeyManager FromFilePath(string filePath, BitcoinNetwork expectedNetwork, string password) |
| | | 184 | | { |
| | 0 | 185 | | var jsonString = File.ReadAllText(filePath); |
| | 0 | 186 | | var data = JsonSerializer.Deserialize<KeyFileData>(jsonString) |
| | 0 | 187 | | ?? throw new SerializationException("Invalid key file"); |
| | | 188 | | |
| | 0 | 189 | | if (expectedNetwork != data.Network.ToLowerInvariant()) |
| | 0 | 190 | | throw new Exception($"Invalid network. Expected {expectedNetwork}, but got {data.Network}"); |
| | | 191 | | |
| | 0 | 192 | | var network = Network.GetNetwork(expectedNetwork) |
| | 0 | 193 | | ?? throw new ArgumentException("Invalid network specified.", nameof(expectedNetwork)); |
| | | 194 | | |
| | 0 | 195 | | var encryptedExtKey = Convert.FromBase64String(data.EncryptedExtKey); |
| | 0 | 196 | | Span<byte> nonce = stackalloc byte[CryptoConstants.Xchacha20Poly1305NonceLen]; |
| | | 197 | | |
| | 0 | 198 | | Span<byte> key = stackalloc byte[CryptoConstants.PrivkeyLen]; |
| | 0 | 199 | | using var argon2Id = new Argon2Id(); |
| | 0 | 200 | | argon2Id.DeriveKeyFromPasswordAndSalt(password, s_salt, key); |
| | | 201 | | |
| | 0 | 202 | | Span<byte> extKeyBytes = stackalloc byte[encryptedExtKey.Length - CryptoConstants.Xchacha20Poly1305TagLen]; |
| | 0 | 203 | | using var xChaCha20Poly1305 = new XChaCha20Poly1305(); |
| | 0 | 204 | | xChaCha20Poly1305.Decrypt(key, nonce, ReadOnlySpan<byte>.Empty, encryptedExtKey, extKeyBytes); |
| | | 205 | | |
| | 0 | 206 | | var extKeyStr = Encoding.UTF8.GetString(extKeyBytes); |
| | 0 | 207 | | var extKey = ExtKey.Parse(extKeyStr, network); |
| | | 208 | | |
| | 0 | 209 | | return new SecureKeyManager(extKey.PrivateKey.ToBytes(), expectedNetwork, filePath, data.HeightOfBirth) |
| | 0 | 210 | | { |
| | 0 | 211 | | _lastUsedIndex = data.LastUsedIndex, |
| | 0 | 212 | | OutputDescriptor = data.Descriptor |
| | 0 | 213 | | }; |
| | 0 | 214 | | } |
| | | 215 | | |
| | | 216 | | /// <summary> |
| | | 217 | | /// Gets the path for the Key file |
| | | 218 | | /// </summary> |
| | | 219 | | public static string GetKeyFilePath(string network) |
| | | 220 | | { |
| | 0 | 221 | | var homeDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); |
| | 0 | 222 | | var networkDir = Path.Combine(homeDir, ".nltg", network); |
| | 0 | 223 | | Directory.CreateDirectory(networkDir); // Ensure directory exists |
| | 0 | 224 | | return Path.Combine(networkDir, "nltg.key.json"); //DaemonConstants.KeyFile); |
| | | 225 | | } |
| | | 226 | | |
| | | 227 | | private ExtKey GetMasterKey() |
| | | 228 | | { |
| | 0 | 229 | | return new ExtKey(new Key(GetPrivateKeyBytes()), _network.GenesisHash.ToBytes()); |
| | | 230 | | } |
| | | 231 | | |
| | | 232 | | private void ReleaseUnmanagedResources() |
| | | 233 | | { |
| | 0 | 234 | | if (_securePrivateKeyPtr == IntPtr.Zero) |
| | 0 | 235 | | return; |
| | | 236 | | |
| | 0 | 237 | | using var cryptoProvider = CryptoFactory.GetCryptoProvider(); |
| | | 238 | | |
| | | 239 | | // Securely wipe the memory before freeing it |
| | 0 | 240 | | cryptoProvider.MemoryZero(_securePrivateKeyPtr, _privateKeyLength); |
| | | 241 | | |
| | | 242 | | // Unlock the memory |
| | 0 | 243 | | cryptoProvider.MemoryUnlock(_securePrivateKeyPtr, _privateKeyLength); |
| | | 244 | | |
| | | 245 | | // MemoryFree the memory |
| | 0 | 246 | | cryptoProvider.MemoryFree(_securePrivateKeyPtr); |
| | | 247 | | |
| | 0 | 248 | | _privateKeyLength = 0; |
| | 0 | 249 | | _securePrivateKeyPtr = IntPtr.Zero; |
| | 0 | 250 | | } |
| | | 251 | | |
| | | 252 | | /// <summary> |
| | | 253 | | /// Retrieves the private key stored in secure memory. |
| | | 254 | | /// </summary> |
| | | 255 | | /// <returns>The private key as a byte array.</returns> |
| | | 256 | | /// <exception cref="InvalidOperationException">Thrown if the key is not initialized.</exception> |
| | | 257 | | private byte[] GetPrivateKeyBytes() |
| | | 258 | | { |
| | 0 | 259 | | if (_securePrivateKeyPtr == IntPtr.Zero) |
| | 0 | 260 | | throw new InvalidOperationException("Secure key is not initialized."); |
| | | 261 | | |
| | 0 | 262 | | var privateKey = new byte[_privateKeyLength]; |
| | 0 | 263 | | Marshal.Copy(_securePrivateKeyPtr, privateKey, 0, (int)_privateKeyLength); |
| | | 264 | | |
| | 0 | 265 | | return privateKey; |
| | | 266 | | } |
| | | 267 | | |
| | | 268 | | public void Dispose() |
| | | 269 | | { |
| | 0 | 270 | | ReleaseUnmanagedResources(); |
| | 0 | 271 | | GC.SuppressFinalize(this); |
| | 0 | 272 | | } |
| | | 273 | | |
| | | 274 | | ~SecureKeyManager() |
| | | 275 | | { |
| | 0 | 276 | | ReleaseUnmanagedResources(); |
| | 0 | 277 | | } |
| | | 278 | | } |