|
| 1 | +using CardanoSharp.Wallet; |
| 2 | +using CardanoSharp.Wallet.Encoding; |
| 3 | +using CardanoSharp.Wallet.Enums; |
| 4 | +using CardanoSharp.Wallet.Extensions.Models; |
| 5 | +using System.Text.Json; |
| 6 | +using static Cscli.ConsoleTool.Constants; |
| 7 | + |
| 8 | +namespace Cscli.ConsoleTool.Commands; |
| 9 | + |
| 10 | +// See https://cips.cardano.org/cips/cip1855/ |
| 11 | +public class DerivePolicyKeyCommand : ICommand |
| 12 | +{ |
| 13 | + public string? Mnemonic { get; init; } |
| 14 | + public string Language { get; init; } = DefaultMnemonicLanguage; |
| 15 | + public string Passphrase { get; init; } = string.Empty; |
| 16 | + public int PolicyIndex { get; init; } = 0; |
| 17 | + public string? VerificationKeyFile { get; init; } = null; |
| 18 | + public string? SigningKeyFile { get; init; } = null; |
| 19 | + |
| 20 | + public async ValueTask<CommandResult> ExecuteAsync(CancellationToken ct) |
| 21 | + { |
| 22 | + var (isValid, wordList, validationErrors) = Validate(); |
| 23 | + if (!isValid) |
| 24 | + { |
| 25 | + return CommandResult.FailureInvalidOptions( |
| 26 | + string.Join(Environment.NewLine, validationErrors)); |
| 27 | + } |
| 28 | + |
| 29 | + var mnemonicService = new MnemonicService(); |
| 30 | + try |
| 31 | + { |
| 32 | + var rootKey = mnemonicService.Restore(Mnemonic, wordList) |
| 33 | + .GetRootKey(Passphrase); |
| 34 | + var policySkey = rootKey.Derive($"m/1855'/1815'/{PolicyIndex}'"); |
| 35 | + var policyVkey = policySkey.GetPublicKey(false); |
| 36 | + var bech32PolicyKey = Bech32.Encode(policySkey.Key, PolicySigningKeyBech32Prefix); |
| 37 | + var result = CommandResult.Success(bech32PolicyKey); |
| 38 | + // Write output to CBOR JSON file outputs if optional file paths are supplied |
| 39 | + if (!string.IsNullOrWhiteSpace(SigningKeyFile)) |
| 40 | + { |
| 41 | + var skeyCbor = new TextEnvelope( |
| 42 | + PaymentExtendedSKeyJsonTypeField, // required for cardano-cli compatibility |
| 43 | + PaymentSKeyJsonDescriptionField, |
| 44 | + KeyUtils.BuildCborHexPayload(policySkey.BuildExtendedSkeyWithVerificationKeyBytes())); |
| 45 | + await File.WriteAllTextAsync(SigningKeyFile, JsonSerializer.Serialize(skeyCbor, SerialiserOptions), ct).ConfigureAwait(false); |
| 46 | + } |
| 47 | + if (!string.IsNullOrWhiteSpace(VerificationKeyFile)) |
| 48 | + { |
| 49 | + var vkeyCbor = new TextEnvelope( |
| 50 | + PaymentExtendedVKeyJsonTypeField, // required for cardano-cli compatibility |
| 51 | + PaymentVKeyJsonDescriptionField, |
| 52 | + KeyUtils.BuildCborHexPayload(policyVkey.BuildExtendedVkeyBytes())); |
| 53 | + await File.WriteAllTextAsync(VerificationKeyFile, JsonSerializer.Serialize(vkeyCbor, SerialiserOptions), ct).ConfigureAwait(false); |
| 54 | + } |
| 55 | + return result; |
| 56 | + } |
| 57 | + catch (ArgumentException ex) |
| 58 | + { |
| 59 | + return CommandResult.FailureInvalidOptions(ex.Message); |
| 60 | + } |
| 61 | + catch (Exception ex) |
| 62 | + { |
| 63 | + return CommandResult.FailureUnhandledException("Unexpected error", ex); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + private ( |
| 68 | + bool isValid, |
| 69 | + WordLists wordList, |
| 70 | + IReadOnlyCollection<string> validationErrors) Validate() |
| 71 | + { |
| 72 | + var validationErrors = new List<string>(); |
| 73 | + if (string.IsNullOrWhiteSpace(Mnemonic)) |
| 74 | + { |
| 75 | + validationErrors.Add( |
| 76 | + $"Invalid option --recovery-phrase is required"); |
| 77 | + } |
| 78 | + if (PolicyIndex < 0 || PolicyIndex > MaxDerivationPathIndex) |
| 79 | + { |
| 80 | + validationErrors.Add( |
| 81 | + $"Invalid option --policy-index must be between 0 and {MaxDerivationPathIndex}"); |
| 82 | + } |
| 83 | + if (!string.IsNullOrWhiteSpace(SigningKeyFile) |
| 84 | + && Path.IsPathFullyQualified(SigningKeyFile) |
| 85 | + && !Directory.Exists(Path.GetDirectoryName(SigningKeyFile))) |
| 86 | + { |
| 87 | + validationErrors.Add( |
| 88 | + $"Invalid option --signing-key-file path {SigningKeyFile} does not exist"); |
| 89 | + } |
| 90 | + if (!string.IsNullOrWhiteSpace(VerificationKeyFile) |
| 91 | + && Path.IsPathFullyQualified(VerificationKeyFile) |
| 92 | + && !Directory.Exists(Path.GetDirectoryName(VerificationKeyFile))) |
| 93 | + { |
| 94 | + validationErrors.Add( |
| 95 | + $"Invalid option --verification-key-file path {VerificationKeyFile} does not exist"); |
| 96 | + } |
| 97 | + if (!Enum.TryParse<WordLists>(Language, ignoreCase: true, out var wordlist)) |
| 98 | + { |
| 99 | + validationErrors.Add( |
| 100 | + $"Invalid option --language {Language} is not supported"); |
| 101 | + } |
| 102 | + var wordCount = Mnemonic?.Split(' ', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries).Length; |
| 103 | + if (wordCount.HasValue && wordCount > 0 && !ValidMnemonicSizes.Contains(wordCount.Value)) |
| 104 | + { |
| 105 | + validationErrors.Add( |
| 106 | + $"Invalid option --recovery-phrase must have the following word count ({string.Join(", ", ValidMnemonicSizes)})"); |
| 107 | + } |
| 108 | + |
| 109 | + return (!validationErrors.Any(), wordlist, validationErrors); |
| 110 | + } |
| 111 | +} |
0 commit comments