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