├── .github └── workflows │ ├── build.yaml │ └── release.yaml ├── .gitignore ├── CONTRIBUTING.md ├── Cscli.sln ├── README.md ├── Src └── ConsoleTool │ ├── BackendGateway.cs │ ├── CommandParser.cs │ ├── CommandResult.cs │ ├── Constants.cs │ ├── Crypto │ ├── DecodeBech32Command.cs │ ├── EncodeBech32Command.cs │ └── HashBlake2bCommand.cs │ ├── Cscli.ConsoleTool.csproj │ ├── DomainTypes.cs │ ├── ICommand.cs │ ├── KeyUtils.cs │ ├── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── Query │ ├── QueryAccountAssetCommand.cs │ ├── QueryAccountInfoCommand.cs │ ├── QueryAddressInfoCommand.cs │ ├── QueryProtocolParametersCommand.cs │ ├── QueryTipCommand.cs │ └── QueryTransactionInfoCommand.cs │ ├── ShowBaseHelpCommand.cs │ ├── ShowInvalidArgumentCommand.cs │ ├── ShowVersionCommand.cs │ ├── Transaction │ ├── BuildSimplePaymentTransactionCommand.cs │ ├── SignTransactionCommand.cs │ ├── SubmitTransactionCommand.cs │ ├── TxUtils.cs │ └── ViewTransactionCommand.cs │ └── Wallet │ ├── ConvertVerificationKeyCommand.cs │ ├── DeriveAccountKeyCommand.cs │ ├── DeriveChangeAddressCommand.cs │ ├── DeriveChangeKeyCommand.cs │ ├── DerivePaymentAddressCommand.cs │ ├── DerivePaymentKeyCommand.cs │ ├── DerivePolicyKeyCommand.cs │ ├── DeriveRootKeyCommand.cs │ ├── DeriveStakeAddressCommand.cs │ ├── DeriveStakeKeyCommand.cs │ └── GenerateMnemonicCommand.cs ├── Tests └── ConsoleTool.UnitTests │ ├── BuildSimplePaymentTransactionCommandShould.cs │ ├── CommandParserShould.cs │ ├── ConvertVerificationKeyCommandShould.cs │ ├── Cscli.ConsoleTool.UnitTests.csproj │ ├── DecodeBech32CommandShould.cs │ ├── DeriveAccountKeyCommandShould.cs │ ├── DeriveChangeAddressCommandShould.cs │ ├── DeriveChangeKeyCommandShould.cs │ ├── DerivePaymentAddressCommandShould.cs │ ├── DerivePaymentKeyCommandShould.cs │ ├── DerivePolicyKeyCommandShould.cs │ ├── DeriveRootKeyCommandShould.cs │ ├── DeriveStakeAddressCommandShould.cs │ ├── DeriveStakeKeyCommandShould.cs │ ├── EncodeBech32CommandShould.cs │ ├── GenerateMnemonicCommandShould.cs │ ├── HashBlake2bCommandShould.cs │ ├── QueryAccountAssetCommandShould.cs │ ├── QueryAccountInfoCommandShould.cs │ ├── QueryAddressInfoCommandShould.cs │ ├── QueryProtocolParametersCommandShould.cs │ ├── QueryTipCommandShould.cs │ ├── QueryTransactionInfoCommandShould.cs │ ├── SignTransactionCommandShould.cs │ ├── SubmitTransactionCommandShould.cs │ └── ViewTransactionCommandShould.cs └── build.ps1 /.github/workflows/build.yaml: -------------------------------------------------------------------------------- 1 | name: Build, Test and Publish Package 2 | 3 | on: 4 | push: 5 | tags: 6 | - v* 7 | branches: 8 | - main 9 | - feature/* 10 | 11 | jobs: 12 | build: 13 | runs-on: ubuntu-latest 14 | env: 15 | DOTNET_VERSION: '6.0.x' 16 | DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true 17 | DOTNET_CLI_TELEMETRY_OPTOUT: true 18 | DOTNET_NOLOGO: true 19 | NUGET_TOKEN: ${{ secrets.NUGET_TOKEN }} 20 | steps: 21 | - name: Checkout 22 | uses: actions/checkout@v3 23 | with: 24 | fetch-depth: 0 25 | 26 | - name: Setup dotnet 27 | uses: actions/setup-dotnet@v1 28 | with: 29 | dotnet-version: ${{ env.DOTNET_VERSION }} 30 | 31 | - name: Restore dependencies 32 | shell: bash 33 | run: dotnet restore 34 | 35 | - name: Build 36 | shell: bash 37 | run: dotnet build --no-restore -c Release 38 | 39 | - name: Test 40 | shell: bash 41 | run: dotnet test --no-build --verbosity normal -c Release 42 | 43 | - name: Pack Tool 44 | shell: bash 45 | run: dotnet pack --no-build Src/ConsoleTool/Cscli.ConsoleTool.csproj -o nupkg -c Release 46 | 47 | - name: Publish To nuget.org 48 | shell: bash 49 | run: dotnet nuget push nupkg/*.nupkg -k $NUGET_TOKEN -s https://api.nuget.org/v3/index.json -------------------------------------------------------------------------------- /.github/workflows/release.yaml: -------------------------------------------------------------------------------- 1 | name: Publish GitHub Release and Artifacts 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | jobs: 8 | release: 9 | name: Release 10 | env: 11 | DOTNET_VERSION: '6.0.x' 12 | DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true 13 | DOTNET_CLI_TELEMETRY_OPTOUT: true 14 | DOTNET_NOLOGO: true 15 | strategy: 16 | matrix: 17 | kind: ['linux', 'windows', 'macOS'] 18 | include: 19 | - kind: linux 20 | os: ubuntu-latest 21 | target: linux-x64 22 | - kind: windows 23 | os: windows-latest 24 | target: win-x64 25 | - kind: macOS 26 | os: macos-latest 27 | target: osx-x64 28 | runs-on: ${{ matrix.os }} 29 | steps: 30 | - name: Checkout 31 | uses: actions/checkout@v3 32 | with: 33 | fetch-depth: 0 34 | 35 | - name: Setup dotnet 36 | uses: actions/setup-dotnet@v1 37 | with: 38 | dotnet-version: ${{ env.DOTNET_VERSION }} 39 | 40 | - name: Set release params 41 | id: release-params 42 | run: | 43 | echo "::set-output name=release_name::cscli-$(git describe --tags --abbrev=0)-${{ matrix.target }}" 44 | 45 | - name: Build 46 | shell: bash 47 | run: | 48 | dotnet publish Src/ConsoleTool/Cscli.ConsoleTool.csproj -r "${{ matrix.target }}" -c Release -o "${{steps.release-params.outputs.release_name}}" "-p:PublishSingleFile=true" "-p:PublishTrimmed=true" "-p:AssemblyName=cscli.${{ matrix.target }}" --self-contained true 49 | 50 | - name: Upload Build Artifact 51 | uses: actions/upload-artifact@v2 52 | with: 53 | name: Application_Artifact 54 | path: "${{steps.release-params.outputs.release_name}}/*" 55 | 56 | - name: Publish to GitHub Release 57 | uses: softprops/action-gh-release@v1 58 | with: 59 | files: "${{steps.release-params.outputs.release_name}}/*" 60 | env: 61 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # Tye 66 | .tye/ 67 | 68 | # ASP.NET Scaffolding 69 | ScaffoldingReadMe.txt 70 | 71 | # StyleCop 72 | StyleCopReport.xml 73 | 74 | # Files built by Visual Studio 75 | *_i.c 76 | *_p.c 77 | *_h.h 78 | *.ilk 79 | *.meta 80 | *.obj 81 | *.iobj 82 | *.pch 83 | *.pdb 84 | *.ipdb 85 | *.pgc 86 | *.pgd 87 | *.rsp 88 | *.sbr 89 | *.tlb 90 | *.tli 91 | *.tlh 92 | *.tmp 93 | *.tmp_proj 94 | *_wpftmp.csproj 95 | *.log 96 | *.vspscc 97 | *.vssscc 98 | .builds 99 | *.pidb 100 | *.svclog 101 | *.scc 102 | 103 | # Chutzpah Test files 104 | _Chutzpah* 105 | 106 | # Visual C++ cache files 107 | ipch/ 108 | *.aps 109 | *.ncb 110 | *.opendb 111 | *.opensdf 112 | *.sdf 113 | *.cachefile 114 | *.VC.db 115 | *.VC.VC.opendb 116 | 117 | # Visual Studio profiler 118 | *.psess 119 | *.vsp 120 | *.vspx 121 | *.sap 122 | 123 | # Visual Studio Trace Files 124 | *.e2e 125 | 126 | # TFS 2012 Local Workspace 127 | $tf/ 128 | 129 | # Guidance Automation Toolkit 130 | *.gpState 131 | 132 | # ReSharper is a .NET coding add-in 133 | _ReSharper*/ 134 | *.[Rr]e[Ss]harper 135 | *.DotSettings.user 136 | 137 | # TeamCity is a build add-in 138 | _TeamCity* 139 | 140 | # DotCover is a Code Coverage Tool 141 | *.dotCover 142 | 143 | # AxoCover is a Code Coverage Tool 144 | .axoCover/* 145 | !.axoCover/settings.json 146 | 147 | # Coverlet is a free, cross platform Code Coverage Tool 148 | coverage*.json 149 | coverage*.xml 150 | coverage*.info 151 | 152 | # Visual Studio code coverage results 153 | *.coverage 154 | *.coveragexml 155 | 156 | # NCrunch 157 | _NCrunch_* 158 | .*crunch*.local.xml 159 | nCrunchTemp_* 160 | 161 | # MightyMoose 162 | *.mm.* 163 | AutoTest.Net/ 164 | 165 | # Web workbench (sass) 166 | .sass-cache/ 167 | 168 | # Installshield output folder 169 | [Ee]xpress/ 170 | 171 | # DocProject is a documentation generator add-in 172 | DocProject/buildhelp/ 173 | DocProject/Help/*.HxT 174 | DocProject/Help/*.HxC 175 | DocProject/Help/*.hhc 176 | DocProject/Help/*.hhk 177 | DocProject/Help/*.hhp 178 | DocProject/Help/Html2 179 | DocProject/Help/html 180 | 181 | # Click-Once directory 182 | publish/ 183 | 184 | # Publish Web Output 185 | *.[Pp]ublish.xml 186 | *.azurePubxml 187 | # Note: Comment the next line if you want to checkin your web deploy settings, 188 | # but database connection strings (with potential passwords) will be unencrypted 189 | *.pubxml 190 | *.publishproj 191 | 192 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 193 | # checkin your Azure Web App publish settings, but sensitive information contained 194 | # in these scripts will be unencrypted 195 | PublishScripts/ 196 | 197 | # NuGet Packages 198 | *.nupkg 199 | # NuGet Symbol Packages 200 | *.snupkg 201 | # The packages folder can be ignored because of Package Restore 202 | **/[Pp]ackages/* 203 | # except build/, which is used as an MSBuild target. 204 | !**/[Pp]ackages/build/ 205 | # Uncomment if necessary however generally it will be regenerated when needed 206 | #!**/[Pp]ackages/repositories.config 207 | # NuGet v3's project.json files produces more ignorable files 208 | *.nuget.props 209 | *.nuget.targets 210 | 211 | # Microsoft Azure Build Output 212 | csx/ 213 | *.build.csdef 214 | 215 | # Microsoft Azure Emulator 216 | ecf/ 217 | rcf/ 218 | 219 | # Windows Store app package directories and files 220 | AppPackages/ 221 | BundleArtifacts/ 222 | Package.StoreAssociation.xml 223 | _pkginfo.txt 224 | *.appx 225 | *.appxbundle 226 | *.appxupload 227 | 228 | # Visual Studio cache files 229 | # files ending in .cache can be ignored 230 | *.[Cc]ache 231 | # but keep track of directories ending in .cache 232 | !?*.[Cc]ache/ 233 | 234 | # Others 235 | ClientBin/ 236 | ~$* 237 | *~ 238 | *.dbmdl 239 | *.dbproj.schemaview 240 | *.jfm 241 | *.pfx 242 | *.publishsettings 243 | orleans.codegen.cs 244 | 245 | # Including strong name files can present a security risk 246 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 247 | #*.snk 248 | 249 | # Since there are multiple workflows, uncomment next line to ignore bower_components 250 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 251 | #bower_components/ 252 | 253 | # RIA/Silverlight projects 254 | Generated_Code/ 255 | 256 | # Backup & report files from converting an old project file 257 | # to a newer Visual Studio version. Backup files are not needed, 258 | # because we have git ;-) 259 | _UpgradeReport_Files/ 260 | Backup*/ 261 | UpgradeLog*.XML 262 | UpgradeLog*.htm 263 | ServiceFabricBackup/ 264 | *.rptproj.bak 265 | 266 | # SQL Server files 267 | *.mdf 268 | *.ldf 269 | *.ndf 270 | 271 | # Business Intelligence projects 272 | *.rdl.data 273 | *.bim.layout 274 | *.bim_*.settings 275 | *.rptproj.rsuser 276 | *- [Bb]ackup.rdl 277 | *- [Bb]ackup ([0-9]).rdl 278 | *- [Bb]ackup ([0-9][0-9]).rdl 279 | 280 | # Microsoft Fakes 281 | FakesAssemblies/ 282 | 283 | # GhostDoc plugin setting file 284 | *.GhostDoc.xml 285 | 286 | # Node.js Tools for Visual Studio 287 | .ntvs_analysis.dat 288 | node_modules/ 289 | 290 | # Visual Studio 6 build log 291 | *.plg 292 | 293 | # Visual Studio 6 workspace options file 294 | *.opt 295 | 296 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 297 | *.vbw 298 | 299 | # Visual Studio LightSwitch build output 300 | **/*.HTMLClient/GeneratedArtifacts 301 | **/*.DesktopClient/GeneratedArtifacts 302 | **/*.DesktopClient/ModelManifest.xml 303 | **/*.Server/GeneratedArtifacts 304 | **/*.Server/ModelManifest.xml 305 | _Pvt_Extensions 306 | 307 | # Paket dependency manager 308 | .paket/paket.exe 309 | paket-files/ 310 | 311 | # FAKE - F# Make 312 | .fake/ 313 | 314 | # CodeRush personal settings 315 | .cr/personal 316 | 317 | # Python Tools for Visual Studio (PTVS) 318 | __pycache__/ 319 | *.pyc 320 | 321 | # Cake - Uncomment if you are using it 322 | # tools/** 323 | # !tools/packages.config 324 | 325 | # Tabs Studio 326 | *.tss 327 | 328 | # Telerik's JustMock configuration file 329 | *.jmconfig 330 | 331 | # BizTalk build output 332 | *.btp.cs 333 | *.btm.cs 334 | *.odx.cs 335 | *.xsd.cs 336 | 337 | # OpenCover UI analysis results 338 | OpenCover/ 339 | 340 | # Azure Stream Analytics local run output 341 | ASALocalRun/ 342 | 343 | # MSBuild Binary and Structured Log 344 | *.binlog 345 | 346 | # NVidia Nsight GPU debugger configuration file 347 | *.nvuser 348 | 349 | # MFractors (Xamarin productivity tool) working folder 350 | .mfractor/ 351 | 352 | # Local History for Visual Studio 353 | .localhistory/ 354 | 355 | # BeatPulse healthcheck temp database 356 | healthchecksdb 357 | 358 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 359 | MigrationBackup/ 360 | 361 | # Ionide (cross platform F# VS Code tools) working folder 362 | .ionide/ 363 | 364 | # Fody - auto-generated XML schema 365 | FodyWeavers.xsd 366 | 367 | ## 368 | ## Visual studio for Mac 369 | ## 370 | 371 | 372 | # globs 373 | Makefile.in 374 | *.userprefs 375 | *.usertasks 376 | config.make 377 | config.status 378 | aclocal.m4 379 | install-sh 380 | autom4te.cache/ 381 | *.tar.gz 382 | tarballs/ 383 | test-results/ 384 | 385 | # Mac bundle stuff 386 | *.dmg 387 | *.app 388 | 389 | # content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore 390 | # General 391 | .DS_Store 392 | .AppleDouble 393 | .LSOverride 394 | 395 | # Icon must end with two \r 396 | Icon 397 | 398 | 399 | # Thumbnails 400 | ._* 401 | 402 | # Files that might appear in the root of a volume 403 | .DocumentRevisions-V100 404 | .fseventsd 405 | .Spotlight-V100 406 | .TemporaryItems 407 | .Trashes 408 | .VolumeIcon.icns 409 | .com.apple.timemachine.donotpresent 410 | 411 | # Directories potentially created on remote AFP share 412 | .AppleDB 413 | .AppleDesktop 414 | Network Trash Folder 415 | Temporary Items 416 | .apdisk 417 | 418 | # content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore 419 | # Windows thumbnail cache files 420 | Thumbs.db 421 | ehthumbs.db 422 | ehthumbs_vista.db 423 | 424 | # Dump file 425 | *.stackdump 426 | 427 | # Folder config file 428 | [Dd]esktop.ini 429 | 430 | # Recycle Bin used on file shares 431 | $RECYCLE.BIN/ 432 | 433 | # Windows Installer files 434 | *.cab 435 | *.msi 436 | *.msix 437 | *.msm 438 | *.msp 439 | 440 | # Windows shortcuts 441 | *.lnk 442 | 443 | # JetBrains Rider 444 | .idea/ 445 | *.sln.iml 446 | 447 | ## 448 | ## Visual Studio Code 449 | ## 450 | .vscode/* 451 | !.vscode/settings.json 452 | !.vscode/tasks.json 453 | !.vscode/launch.json 454 | !.vscode/extensions.json 455 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CardanoSharp/cscli/fc9171147e40726a86083294f9b940f72c9a8b0d/CONTRIBUTING.md -------------------------------------------------------------------------------- /Cscli.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.31903.59 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Src", "Src", "{959CFE41-F8AB-410D-872A-D471FA0445CF}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Cscli.ConsoleTool", "Src\ConsoleTool\Cscli.ConsoleTool.csproj", "{981A72C6-AF08-4CDC-8498-AAA21274A5DA}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{145F7D38-B287-4D62-B3C6-D38713EF9210}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Cscli.ConsoleTool.UnitTests", "Tests\ConsoleTool.UnitTests\Cscli.ConsoleTool.UnitTests.csproj", "{E9FD7B17-AADF-4037-ABFB-5F6C66201A0D}" 13 | EndProject 14 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{40C32857-89C3-405A-B941-0BA4777F81B6}" 15 | ProjectSection(SolutionItems) = preProject 16 | build.ps1 = build.ps1 17 | .github\workflows\build.yaml = .github\workflows\build.yaml 18 | CONTRIBUTING.md = CONTRIBUTING.md 19 | README.md = README.md 20 | .github\workflows\release.yaml = .github\workflows\release.yaml 21 | EndProjectSection 22 | EndProject 23 | Global 24 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 25 | Debug|Any CPU = Debug|Any CPU 26 | Debug|x64 = Debug|x64 27 | Debug|x86 = Debug|x86 28 | Release|Any CPU = Release|Any CPU 29 | Release|x64 = Release|x64 30 | Release|x86 = Release|x86 31 | EndGlobalSection 32 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 33 | {981A72C6-AF08-4CDC-8498-AAA21274A5DA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 34 | {981A72C6-AF08-4CDC-8498-AAA21274A5DA}.Debug|Any CPU.Build.0 = Debug|Any CPU 35 | {981A72C6-AF08-4CDC-8498-AAA21274A5DA}.Debug|x64.ActiveCfg = Debug|Any CPU 36 | {981A72C6-AF08-4CDC-8498-AAA21274A5DA}.Debug|x64.Build.0 = Debug|Any CPU 37 | {981A72C6-AF08-4CDC-8498-AAA21274A5DA}.Debug|x86.ActiveCfg = Debug|Any CPU 38 | {981A72C6-AF08-4CDC-8498-AAA21274A5DA}.Debug|x86.Build.0 = Debug|Any CPU 39 | {981A72C6-AF08-4CDC-8498-AAA21274A5DA}.Release|Any CPU.ActiveCfg = Release|Any CPU 40 | {981A72C6-AF08-4CDC-8498-AAA21274A5DA}.Release|Any CPU.Build.0 = Release|Any CPU 41 | {981A72C6-AF08-4CDC-8498-AAA21274A5DA}.Release|x64.ActiveCfg = Release|Any CPU 42 | {981A72C6-AF08-4CDC-8498-AAA21274A5DA}.Release|x64.Build.0 = Release|Any CPU 43 | {981A72C6-AF08-4CDC-8498-AAA21274A5DA}.Release|x86.ActiveCfg = Release|Any CPU 44 | {981A72C6-AF08-4CDC-8498-AAA21274A5DA}.Release|x86.Build.0 = Release|Any CPU 45 | {E9FD7B17-AADF-4037-ABFB-5F6C66201A0D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 46 | {E9FD7B17-AADF-4037-ABFB-5F6C66201A0D}.Debug|Any CPU.Build.0 = Debug|Any CPU 47 | {E9FD7B17-AADF-4037-ABFB-5F6C66201A0D}.Debug|x64.ActiveCfg = Debug|Any CPU 48 | {E9FD7B17-AADF-4037-ABFB-5F6C66201A0D}.Debug|x64.Build.0 = Debug|Any CPU 49 | {E9FD7B17-AADF-4037-ABFB-5F6C66201A0D}.Debug|x86.ActiveCfg = Debug|Any CPU 50 | {E9FD7B17-AADF-4037-ABFB-5F6C66201A0D}.Debug|x86.Build.0 = Debug|Any CPU 51 | {E9FD7B17-AADF-4037-ABFB-5F6C66201A0D}.Release|Any CPU.ActiveCfg = Release|Any CPU 52 | {E9FD7B17-AADF-4037-ABFB-5F6C66201A0D}.Release|Any CPU.Build.0 = Release|Any CPU 53 | {E9FD7B17-AADF-4037-ABFB-5F6C66201A0D}.Release|x64.ActiveCfg = Release|Any CPU 54 | {E9FD7B17-AADF-4037-ABFB-5F6C66201A0D}.Release|x64.Build.0 = Release|Any CPU 55 | {E9FD7B17-AADF-4037-ABFB-5F6C66201A0D}.Release|x86.ActiveCfg = Release|Any CPU 56 | {E9FD7B17-AADF-4037-ABFB-5F6C66201A0D}.Release|x86.Build.0 = Release|Any CPU 57 | EndGlobalSection 58 | GlobalSection(SolutionProperties) = preSolution 59 | HideSolutionNode = FALSE 60 | EndGlobalSection 61 | GlobalSection(NestedProjects) = preSolution 62 | {981A72C6-AF08-4CDC-8498-AAA21274A5DA} = {959CFE41-F8AB-410D-872A-D471FA0445CF} 63 | {E9FD7B17-AADF-4037-ABFB-5F6C66201A0D} = {145F7D38-B287-4D62-B3C6-D38713EF9210} 64 | EndGlobalSection 65 | GlobalSection(ExtensibilityGlobals) = postSolution 66 | SolutionGuid = {F7774616-7E41-477E-8DB4-8892DDF67047} 67 | EndGlobalSection 68 | EndGlobal 69 | -------------------------------------------------------------------------------- /Src/ConsoleTool/BackendGateway.cs: -------------------------------------------------------------------------------- 1 | using CardanoSharp.Wallet.Enums; 2 | using Refit; 3 | 4 | namespace Cscli.ConsoleTool.Koios; 5 | 6 | public static class BackendGateway 7 | { 8 | public static T GetBackendClient(NetworkType networkType) => 9 | RestService.For(GetBaseUrlForNetwork(networkType)); 10 | 11 | private static string GetBaseUrlForNetwork(NetworkType networkType) => networkType switch 12 | { 13 | NetworkType.Mainnet => "https://api.koios.rest/api/v0", 14 | NetworkType.Testnet => "https://testnet.koios.rest/api/v0", 15 | _ => throw new ArgumentException($"{nameof(networkType)} {networkType} is invalid", nameof(networkType)) 16 | }; 17 | } 18 | -------------------------------------------------------------------------------- /Src/ConsoleTool/CommandParser.cs: -------------------------------------------------------------------------------- 1 | using Cscli.ConsoleTool.Crypto; 2 | using Cscli.ConsoleTool.Query; 3 | using Cscli.ConsoleTool.Transaction; 4 | using Cscli.ConsoleTool.Wallet; 5 | using Microsoft.Extensions.Configuration; 6 | using System.Text; 7 | 8 | namespace Cscli.ConsoleTool; 9 | 10 | public static class CommandParser 11 | { 12 | public static ICommand ParseArgsToCommand(string[] args) 13 | { 14 | if (args.Length == 0 || IsHelpOption(args[0])) 15 | { 16 | return new ShowBaseHelpCommand(); 17 | } 18 | if (IsVersionOption(args[0])) 19 | { 20 | return new ShowVersionCommand(); 21 | } 22 | var intent = DeriveIntent(args); 23 | var command = ParseCommands(intent, args); 24 | return command; 25 | } 26 | 27 | private static string DeriveIntent(string[] args) 28 | { 29 | // Intent comprises of the first few cli args that are not command arguments 30 | static bool IsCommandArgument(string arg) => 31 | arg.StartsWith("-") || arg.StartsWith("/"); 32 | 33 | var intent = new StringBuilder(); 34 | foreach (var arg in args) 35 | { 36 | if (IsCommandArgument(arg)) 37 | break; 38 | intent.Append($"{arg} "); 39 | } 40 | return intent.ToString().TrimEnd(); 41 | } 42 | 43 | private static ICommand ParseCommands(string intent, string[] args) => 44 | args[0] switch 45 | { 46 | "wallet" => ParseWalletCommands(intent, args), 47 | "query" => ParseQueryCommands(intent, args), 48 | "transaction" => ParseTransactionCommands(intent, args), 49 | "bech32" or "blake2b" => ParseCryptoCommands(intent, args), 50 | _ => new ShowInvalidArgumentCommand(intent) 51 | }; 52 | 53 | private static ICommand ParseWalletCommands(string intent, string[] args) => 54 | intent switch 55 | { 56 | "wallet recovery-phrase generate" => BuildCommand(args), 57 | "wallet key root derive" => BuildCommand(args), 58 | "wallet key account derive" => BuildCommand(args), 59 | "wallet key payment derive" => BuildCommand(args), 60 | "wallet key change derive" => BuildCommand(args), 61 | "wallet key stake derive" => BuildCommand(args), 62 | "wallet key policy derive" => BuildCommand(args), 63 | "wallet address payment derive" => BuildCommand(args), 64 | "wallet address change derive" => BuildCommand(args), 65 | "wallet address stake derive" => BuildCommand(args), 66 | "wallet key verification convert" or "wallet key public convert" => BuildCommand(args), 67 | _ => new ShowInvalidArgumentCommand(intent) 68 | }; 69 | 70 | private static ICommand ParseQueryCommands(string intent, string[] args) => 71 | intent switch 72 | { 73 | "query tip" => BuildCommand(args), 74 | "query protocol-parameters" => BuildCommand(args), 75 | "query info account" => BuildCommand(args), 76 | "query asset account" => BuildCommand(args), 77 | "query info address" => BuildCommand(args), 78 | "query info transaction" => BuildCommand(args), 79 | _ => new ShowInvalidArgumentCommand(intent) 80 | }; 81 | 82 | private static ICommand ParseTransactionCommands(string intent, string[] args) => 83 | intent switch 84 | { 85 | "transaction simple-payment build" => BuildCommand(args), 86 | "transaction submit" => BuildCommand(args), 87 | "transaction view" => BuildCommand(args), 88 | "transaction sign" => BuildCommand(args), 89 | _ => new ShowInvalidArgumentCommand(intent) 90 | }; 91 | 92 | private static ICommand ParseCryptoCommands(string intent, string[] args) => 93 | intent switch 94 | { 95 | "bech32 encode" => BuildCommand(args), 96 | "bech32 decode" => BuildCommand(args), 97 | "blake2b hash" => BuildCommand(args), 98 | _ => new ShowInvalidArgumentCommand(intent) 99 | }; 100 | 101 | private static ICommand BuildCommand( 102 | string[] args) 103 | where T : ICommand 104 | { 105 | var command = new ConfigurationBuilder() 106 | .AddEnvironmentVariables() 107 | .AddCommandLine(args, Constants.SwitchMappings) 108 | .Build() 109 | .Get(); 110 | 111 | return command; 112 | } 113 | 114 | private static bool IsHelpOption(string arg) 115 | { 116 | return arg == "help" || arg == "-h" || arg == "--help"; 117 | } 118 | 119 | private static bool IsVersionOption(string arg) 120 | { 121 | return arg == "version" || arg == "-v" || arg == "--version"; 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /Src/ConsoleTool/CommandResult.cs: -------------------------------------------------------------------------------- 1 | namespace Cscli.ConsoleTool; 2 | 3 | public enum CommandOutcome 4 | { 5 | Success = 0, 6 | FailureInvalidOptions, 7 | FailureTimedOut, 8 | FailureCancelled, 9 | FailureBackend, 10 | FailureUnhandledException, 11 | } 12 | 13 | public class CommandResult 14 | { 15 | public CommandOutcome Outcome { get; } 16 | 17 | public string Result { get; } 18 | 19 | public Exception? Exception { get; } 20 | 21 | public CommandResult(CommandOutcome outcome, string result, Exception? exception = null) 22 | { 23 | Outcome = outcome; 24 | Result = result; 25 | Exception = exception; 26 | } 27 | 28 | public static CommandResult Success(string result) => 29 | new(CommandOutcome.Success, result); 30 | 31 | public static CommandResult FailureInvalidOptions(string result) => 32 | new(CommandOutcome.FailureInvalidOptions, result); 33 | 34 | public static CommandResult FailureTimedOut(string result) => 35 | new(CommandOutcome.FailureTimedOut, result); 36 | 37 | public static CommandResult FailureCancelled(string result) => 38 | new(CommandOutcome.FailureCancelled, result); 39 | 40 | public static CommandResult FailureBackend(string result) => 41 | new(CommandOutcome.FailureBackend, result); 42 | 43 | public static CommandResult FailureUnhandledException(string result, Exception ex) => 44 | new(CommandOutcome.FailureUnhandledException, result, ex); 45 | } 46 | 47 | -------------------------------------------------------------------------------- /Src/ConsoleTool/Constants.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Encodings.Web; 2 | using System.Text.Json; 3 | 4 | namespace Cscli.ConsoleTool; 5 | 6 | public static class Constants 7 | { 8 | public const int MessageStandardKey = 674; 9 | public const int NftStandardKey = 721; 10 | public const int NftRoyaltyStandardKey = 777; 11 | public const int MaxMetadataStringLength = 64; 12 | public const string DefaultMnemonicLanguage = "English"; 13 | public const int DefaultMnemonicCount = 24; 14 | public const int MaxDerivationPathIndex = Int32.MaxValue; // 2^31 - 1 15 | // Bech32 Prefixes https://cips.cardano.org/cips/cip5/ 16 | public const string RootExtendedSigningKeyBech32Prefix = "root_xsk"; 17 | public const string RootSigningKeyBech32Prefix = "root_sk"; 18 | public const string AccountExtendedSigningKeyBech32Prefix = "acct_xsk"; 19 | public const string AccountSigningKeyBech32Prefix = "acct_sk"; 20 | public const string PaymentExtendedSigningKeyBech32Prefix = "addr_xsk"; 21 | public const string PaymentSigningKeyBech32Prefix = "addr_sk"; 22 | public const string PaymentSharedSigningKeyBech32Prefix = "addr_shared_sk"; 23 | public const string StakeExtendedSigningKeyBech32Prefix = "stake_xsk"; 24 | public const string StakeSigningKeyBech32Prefix = "stake_sk"; 25 | public const string PolicySigningKeyBech32Prefix = "policy_sk"; 26 | public const string AddressMainnetBech32Prefix = "addr"; 27 | public const string AddressTestnetBech32Prefix = "addr_test"; 28 | // JSON CBOR text envelopes from cardano-cli 29 | public const string PaymentSKeyJsonTypeField = "PaymentSigningKeyShelley_ed25519"; 30 | public const string PaymentExtendedSKeyJsonTypeField = "PaymentExtendedSigningKeyShelley_ed25519_bip32"; 31 | public const string PaymentSKeyJsonDescriptionField = "Payment Signing Key"; 32 | public const string PaymentVKeyJsonTypeField = "PaymentVerificationKeyShelley_ed25519"; 33 | public const string PaymentExtendedVKeyJsonTypeField = "PaymentExtendedVerificationKeyShelley_ed25519_bip32"; 34 | public const string PaymentVKeyJsonDescriptionField = "Payment Verification Key"; 35 | public const string StakeSKeyJsonTypeField = "StakeSigningKeyShelley_ed25519"; 36 | public const string StakeExtendedSKeyJsonTypeField = "StakeExtendedSigningKeyShelley_ed25519_bip32"; 37 | public const string StakeSKeyJsonDescriptionField = "Stake Signing Key"; 38 | public const string StakeVKeyJsonTypeField = "StakeVerificationKeyShelley_ed25519"; 39 | public const string StakeExtendedVKeyJsonTypeField = "StakeExtendedVerificationKeyShelley_ed25519_bip32"; 40 | public const string StakeVKeyJsonDescriptionField = "Stake Verification Key"; 41 | public const string TxAlonzoJsonTypeField = "Tx AlonzoEra"; 42 | // Transaction Building constants 43 | public const uint TtlTipOffsetSlots = 7200; // 2 hours 44 | 45 | // Validation constraints 46 | public static readonly int[] ValidMnemonicSizes = { 9, 12, 15, 18, 21, 24 }; 47 | // Default JSON Serialiser settings 48 | public static readonly JsonSerializerOptions SerialiserOptions = new() 49 | { 50 | PropertyNamingPolicy = JsonNamingPolicy.CamelCase, 51 | WriteIndented = true, 52 | Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping 53 | }; 54 | // Commandline args switch mappings 55 | public static Dictionary SwitchMappings => new() 56 | { 57 | { "--recovery-phrase", "mnemonic" }, 58 | { "--verification-key-file", "verificationKeyFile" }, 59 | { "--signing-key-file", "signingKeyFile" }, 60 | { "--account-index", "accountIndex" }, 61 | { "--address-index", "addressIndex" }, 62 | { "--policy-index", "policyIndex" }, 63 | { "--stake-account-index", "stakeAccountIndex" }, 64 | { "--stake-address-index", "stakeAddressIndex" }, 65 | { "--payment-address-type", "paymentAddressType" }, 66 | { "--stake-address", "stakeAddress" }, 67 | { "--cbor-hex", "cborHex" }, 68 | { "--tx-id", "txId" }, 69 | { "--signing-key", "signingKey" }, 70 | { "--signing-keys", "signingKeys" }, 71 | { "--send-all", "sendAll" }, 72 | { "--out-file", "outFile" }, 73 | { "--mock-witness-count", "mockWitnessCount"} 74 | //{ "--output-format", "outputFormat" }, 75 | }; 76 | } -------------------------------------------------------------------------------- /Src/ConsoleTool/Crypto/DecodeBech32Command.cs: -------------------------------------------------------------------------------- 1 | using CardanoSharp.Wallet.Encoding; 2 | using CardanoSharp.Wallet.Extensions; 3 | 4 | namespace Cscli.ConsoleTool.Crypto; 5 | 6 | public class DecodeBech32Command : ICommand 7 | { 8 | public string Value { get; init; } = string.Empty; 9 | 10 | public ValueTask ExecuteAsync(CancellationToken ct) 11 | { 12 | if (string.IsNullOrEmpty(Value)) 13 | { 14 | return ValueTask.FromResult(CommandResult.FailureInvalidOptions( 15 | $"Invalid option --value is required.")); 16 | } 17 | if (!Bech32.IsValid(Value)) 18 | { 19 | return ValueTask.FromResult(CommandResult.FailureInvalidOptions( 20 | $"Invalid option --value {Value} is not a valid bech32 encoding.")); 21 | } 22 | 23 | try 24 | { 25 | var hex = Bech32 26 | .Decode(Value, out _, out _) 27 | .ToStringHex(); 28 | var result = CommandResult.Success(hex); 29 | return ValueTask.FromResult(result); 30 | } 31 | catch (Exception ex) 32 | { 33 | return ValueTask.FromResult( 34 | CommandResult.FailureUnhandledException("Unexpected error", ex)); 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /Src/ConsoleTool/Crypto/EncodeBech32Command.cs: -------------------------------------------------------------------------------- 1 | using CardanoSharp.Wallet.Encoding; 2 | 3 | namespace Cscli.ConsoleTool.Crypto; 4 | 5 | public class EncodeBech32Command : ICommand 6 | { 7 | public string Prefix { get; init; } = string.Empty; 8 | public string Value { get; init; } = string.Empty; 9 | 10 | public ValueTask ExecuteAsync(CancellationToken ct) 11 | { 12 | if (string.IsNullOrEmpty(Value)) 13 | { 14 | return ValueTask.FromResult(CommandResult.FailureInvalidOptions( 15 | $"Invalid option --value is required")); 16 | } 17 | 18 | try 19 | { 20 | var rawBytesValue = Convert.FromHexString(Value); 21 | var bech32Value = Bech32.Encode(rawBytesValue, Prefix); 22 | var result = CommandResult.Success(bech32Value); 23 | return ValueTask.FromResult(result); 24 | } 25 | catch (FormatException ex) 26 | { 27 | return ValueTask.FromResult( 28 | CommandResult.FailureInvalidOptions($"Invalid option --value {ex.Message}")); 29 | } 30 | catch (Exception ex) 31 | { 32 | return ValueTask.FromResult( 33 | CommandResult.FailureUnhandledException("Unexpected error", ex)); 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /Src/ConsoleTool/Crypto/HashBlake2bCommand.cs: -------------------------------------------------------------------------------- 1 | using Blake2Fast; 2 | using CardanoSharp.Wallet.Extensions; 3 | using System.Collections.Immutable; 4 | 5 | namespace Cscli.ConsoleTool.Crypto; 6 | 7 | public class HashBlake2bCommand : ICommand 8 | { 9 | private static readonly ImmutableArray HashAlgorithmLengths = ImmutableArray.Create(new[] 10 | { 11 | 160, // Assets 12 | 224, // Keys/Addresses/SimpleScript/PlutusScript 13 | 256, // Transactions 14 | 512 // Wallet checksums 15 | }); 16 | 17 | public int Length { get; init; } = 224; 18 | public string Value { get; init; } = string.Empty; 19 | 20 | public ValueTask ExecuteAsync(CancellationToken ct) 21 | { 22 | if (string.IsNullOrEmpty(Value)) 23 | { 24 | return ValueTask.FromResult(CommandResult.FailureInvalidOptions( 25 | $"Invalid option --value is required")); 26 | } 27 | if (!HashAlgorithmLengths.Contains(Length)) 28 | { 29 | return ValueTask.FromResult(CommandResult.FailureInvalidOptions( 30 | $"Invalid option --length {Length} is not supported")); 31 | } 32 | 33 | try 34 | { 35 | var digestLengthInBytes = Length / 8; 36 | var rawBytesValue = Convert.FromHexString(Value); 37 | var digest = Blake2b.ComputeHash(digestLengthInBytes, rawBytesValue); 38 | var digestHex = digest.ToStringHex(); 39 | var result = CommandResult.Success(digestHex); 40 | return ValueTask.FromResult(result); 41 | } 42 | catch (FormatException ex) 43 | { 44 | return ValueTask.FromResult( 45 | CommandResult.FailureInvalidOptions($"Invalid option --value {ex.Message}")); 46 | } 47 | catch (Exception ex) 48 | { 49 | return ValueTask.FromResult( 50 | CommandResult.FailureUnhandledException("Unexpected error", ex)); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Src/ConsoleTool/Cscli.ConsoleTool.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | enable 8 | 0.0.0.0-populated-by-NetRevisionTask 9 | true 10 | cscli 11 | false 12 | cscli 13 | nupkg 14 | README.md 15 | false 16 | Keith 17 | Lovelace Academy 18 | Cross Platform Global Tool / Console App for generating Cardano keys, addresses and transactions 19 | 20 | 21 | {semvertag:main}+{chash:7}{!:-mod} 22 | true 23 | true 24 | true 25 | v[0-9]* 26 | true 27 | git 28 | true 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | all 42 | runtime; build; native; contentfiles; analyzers; buildtransitive 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /Src/ConsoleTool/DomainTypes.cs: -------------------------------------------------------------------------------- 1 | namespace Cscli.ConsoleTool; 2 | 3 | public record struct NativeAssetValue(string PolicyId, string AssetName, long Quantity); 4 | 5 | public record struct Balance(ulong Lovelaces, NativeAssetValue[] NativeAssets); 6 | 7 | public record struct PendingTransactionOutput(string Address, Balance Value); 8 | 9 | public record UnspentTransactionOutput(string TxHash, uint OutputIndex, Balance Value) 10 | { 11 | public override int GetHashCode() => ToString().GetHashCode(); 12 | public override string ToString() => $"{TxHash}_{OutputIndex}"; 13 | bool IEquatable.Equals(UnspentTransactionOutput? other) 14 | => other is not null && TxHash == other.TxHash && OutputIndex == other.OutputIndex; 15 | public ulong Lovelaces => Value.Lovelaces; 16 | } 17 | 18 | public record TextEnvelope(string? Type, string? Description, string? CborHex); 19 | 20 | public record Tx( 21 | string Id, 22 | bool IsValid, 23 | TxBody TransactionBody, 24 | TxWitnessSet? TransactionWitnessSet, 25 | TxAuxData AuxiliaryData); 26 | 27 | public record TxBody( 28 | IEnumerable Inputs, 29 | IEnumerable Outputs, 30 | IEnumerable Mint, 31 | ulong Fee, 32 | uint? Ttl, 33 | string? AuxiliaryDataHash, 34 | uint? TransactionStartInterval); 35 | 36 | public record TxIn( 37 | string TransactionId, 38 | uint TransactionIndex); 39 | 40 | public record TxOut( 41 | string Address, 42 | Balance Value); 43 | 44 | public record TxWitnessSet( 45 | IEnumerable VKeyWitnesses, 46 | IEnumerable NativeScripts); 47 | 48 | public record TxVKeyWitness(string Verificationkey, string Signature); 49 | 50 | public record TxNativeScript(string Type); 51 | 52 | public record TxAuxData(Dictionary Metadata); 53 | 54 | -------------------------------------------------------------------------------- /Src/ConsoleTool/ICommand.cs: -------------------------------------------------------------------------------- 1 | namespace Cscli.ConsoleTool; 2 | 3 | public interface ICommand 4 | { 5 | ValueTask ExecuteAsync(CancellationToken ct); 6 | } 7 | -------------------------------------------------------------------------------- /Src/ConsoleTool/KeyUtils.cs: -------------------------------------------------------------------------------- 1 | using CardanoSharp.Wallet.Extensions.Models; 2 | using CardanoSharp.Wallet.Models.Keys; 3 | 4 | namespace Cscli.ConsoleTool; 5 | 6 | public static class KeyUtils 7 | { 8 | public static byte[] BuildNonExtendedSkeyWithVerificationKeyBytes(this PrivateKey prvKey) 9 | { 10 | var pubKey = prvKey.GetPublicKey(false); 11 | var skeyBytes = new byte[prvKey.Key.Length + pubKey.Key.Length]; 12 | Buffer.BlockCopy(prvKey.Key, 0, skeyBytes, 0, prvKey.Key.Length); 13 | Buffer.BlockCopy(pubKey.Key, 0, skeyBytes, prvKey.Key.Length, pubKey.Key.Length); 14 | return skeyBytes; 15 | } 16 | 17 | public static byte[] BuildExtendedSkeyBytes(this PrivateKey prvKey) 18 | { 19 | var extendedKeyBytes = new byte[prvKey.Key.Length + prvKey.Chaincode.Length]; 20 | Buffer.BlockCopy(prvKey.Key, 0, extendedKeyBytes, 0, prvKey.Key.Length); 21 | Buffer.BlockCopy(prvKey.Chaincode, 0, extendedKeyBytes, prvKey.Key.Length, prvKey.Chaincode.Length); 22 | return extendedKeyBytes; 23 | } 24 | 25 | public static byte[] BuildExtendedSkeyWithVerificationKeyBytes(this PrivateKey prvKey) 26 | { 27 | var pubKey = prvKey.GetPublicKey(false); 28 | var extendedKeyBytes = new byte[prvKey.Key.Length + pubKey.Key.Length + prvKey.Chaincode.Length]; 29 | Buffer.BlockCopy(prvKey.Key, 0, extendedKeyBytes, 0, prvKey.Key.Length); 30 | Buffer.BlockCopy(pubKey.Key, 0, extendedKeyBytes, prvKey.Key.Length, pubKey.Key.Length); 31 | Buffer.BlockCopy(prvKey.Chaincode, 0, extendedKeyBytes, prvKey.Key.Length + pubKey.Key.Length, prvKey.Chaincode.Length); 32 | return extendedKeyBytes; 33 | } 34 | 35 | public static byte[] BuildExtendedVkeyBytes(this PublicKey pubKey) 36 | { 37 | var extendedKeyBytes = new byte[pubKey.Key.Length + pubKey.Chaincode.Length]; 38 | Buffer.BlockCopy(pubKey.Key, 0, extendedKeyBytes, 0, pubKey.Key.Length); 39 | Buffer.BlockCopy(pubKey.Chaincode, 0, extendedKeyBytes, pubKey.Key.Length, pubKey.Chaincode.Length); 40 | return extendedKeyBytes; 41 | } 42 | 43 | public static string BuildCborHexPayload(byte[] keyPayload) 44 | => $"58{keyPayload.Length:x2}{Convert.ToHexString(keyPayload).ToLower()}"; 45 | } 46 | -------------------------------------------------------------------------------- /Src/ConsoleTool/Program.cs: -------------------------------------------------------------------------------- 1 | namespace Cscli.ConsoleTool; 2 | 3 | class Program 4 | { 5 | static async Task Main(string[] args) 6 | { 7 | Console.OutputEncoding = System.Text.Encoding.UTF8; 8 | var cts = SetupUserInputCancellationTokenSource(); 9 | var command = CommandParser.ParseArgsToCommand(args); 10 | var commandResult = await command.ExecuteAsync(cts.Token).ConfigureAwait(false); 11 | if (commandResult.Outcome == CommandOutcome.Success) 12 | { 13 | Console.Out.WriteLine(commandResult.Result); 14 | return 0; 15 | } 16 | Console.Error.WriteLine(commandResult.Result); 17 | return (int)commandResult.Outcome; 18 | } 19 | 20 | private static CancellationTokenSource SetupUserInputCancellationTokenSource() 21 | { 22 | var cts = new CancellationTokenSource(); 23 | Console.CancelKeyPress += (s, e) => 24 | { 25 | e.Cancel = true; 26 | cts.Cancel(); 27 | }; 28 | return cts; 29 | } 30 | } -------------------------------------------------------------------------------- /Src/ConsoleTool/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "Cscli.ConsoleTool": { 4 | "commandName": "Project", 5 | "commandLineArgs": " query info account --network testnet --address addr_test1qq4qw3s2p5q0ttfucewkttnz795ujue9jd7ruxrpsa05f47cq54ahxv48q2ja88q22f3t9s3gd3napuy9ausj7wdantsvjsd9s" 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /Src/ConsoleTool/Query/QueryAccountAssetCommand.cs: -------------------------------------------------------------------------------- 1 | using CardanoSharp.Koios.Client; 2 | using CardanoSharp.Wallet; 3 | using CardanoSharp.Wallet.Encoding; 4 | using CardanoSharp.Wallet.Enums; 5 | using CardanoSharp.Wallet.Models.Addresses; 6 | using Cscli.ConsoleTool.Koios; 7 | using System.Text.Json; 8 | using static Cscli.ConsoleTool.Constants; 9 | 10 | namespace Cscli.ConsoleTool.Query; 11 | 12 | public class QueryAccountAssetCommand : ICommand 13 | { 14 | public string StakeAddress { get; init; } = string.Empty; 15 | public string Address { get; init; } = string.Empty; 16 | public string? Network { get; init; } 17 | 18 | public async ValueTask ExecuteAsync(CancellationToken ct) 19 | { 20 | var (isValid, networkType, stakeAddress, errors) = Validate(); 21 | if (!isValid || stakeAddress is null) 22 | { 23 | return CommandResult.FailureInvalidOptions( 24 | string.Join(Environment.NewLine, errors)); 25 | } 26 | 27 | var accountClient = BackendGateway.GetBackendClient(networkType); 28 | try 29 | { 30 | var assets = await accountClient 31 | .GetAccountAssets(new AccountBulkRequest() { StakeAddresses = new []{ stakeAddress.ToString() }}) 32 | .ConfigureAwait(false); 33 | if (!assets.IsSuccessStatusCode || assets.Content is null) 34 | return CommandResult.FailureBackend($"Koios backend response was unsuccessful"); 35 | 36 | var json = JsonSerializer.Serialize(assets.Content, SerialiserOptions); 37 | return CommandResult.Success(json); 38 | } 39 | catch (Exception ex) 40 | { 41 | return CommandResult.FailureUnhandledException("Unexpected error", ex); 42 | } 43 | } 44 | 45 | private ( 46 | bool isValid, 47 | NetworkType derivedNetworkType, 48 | Address? derivedStakeAddress, 49 | IReadOnlyCollection validationErrors) Validate() 50 | { 51 | var validationErrors = new List(); 52 | if (!Enum.TryParse(Network, ignoreCase: true, out var networkType)) 53 | { 54 | validationErrors.Add( 55 | $"Invalid option --network must be either testnet or mainnet"); 56 | } 57 | var stakeAddressArgumentExists = !string.IsNullOrWhiteSpace(StakeAddress); 58 | var paymentAddressArgumentExists = !string.IsNullOrWhiteSpace(Address); 59 | if (!stakeAddressArgumentExists && !paymentAddressArgumentExists 60 | || stakeAddressArgumentExists && paymentAddressArgumentExists) 61 | { 62 | validationErrors.Add( 63 | "Invalid option, one of either --stake-address or --address is required"); 64 | return (!validationErrors.Any(), networkType, null, validationErrors); 65 | } 66 | if (stakeAddressArgumentExists) 67 | { 68 | if (!Bech32.IsValid(StakeAddress)) 69 | { 70 | validationErrors.Add( 71 | $"Invalid option --stake-address {StakeAddress} is invalid"); 72 | } 73 | else 74 | { 75 | var stakeAddress = new Address(StakeAddress); 76 | if (stakeAddress.AddressType != AddressType.Reward || stakeAddress.NetworkType != networkType) 77 | { 78 | validationErrors.Add( 79 | $"Invalid option --stake-address {StakeAddress} is invalid for {Network}"); 80 | } 81 | else 82 | { 83 | return (!validationErrors.Any(), networkType, stakeAddress, validationErrors); 84 | } 85 | } 86 | } 87 | if (paymentAddressArgumentExists) 88 | { 89 | if (!Bech32.IsValid(Address)) 90 | { 91 | validationErrors.Add( 92 | $"Invalid option --address {Address} is not a base address with attached staking credentials"); 93 | } 94 | else 95 | { 96 | var addressService = new AddressService(); 97 | var address = new Address(Address); 98 | if (address.AddressType != AddressType.Base || address.NetworkType != networkType) 99 | { 100 | validationErrors.Add( 101 | $"Invalid option --address {Address} is not a base address with attached staking credentials for {Network}"); 102 | } 103 | else 104 | { 105 | var stakeAddress = addressService.ExtractRewardAddress(address); 106 | return (!validationErrors.Any(), networkType, stakeAddress, validationErrors); 107 | } 108 | } 109 | } 110 | return (!validationErrors.Any(), networkType, null, validationErrors); 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /Src/ConsoleTool/Query/QueryAccountInfoCommand.cs: -------------------------------------------------------------------------------- 1 | using CardanoSharp.Koios.Client; 2 | using CardanoSharp.Wallet; 3 | using CardanoSharp.Wallet.Encoding; 4 | using CardanoSharp.Wallet.Enums; 5 | using CardanoSharp.Wallet.Models.Addresses; 6 | using Cscli.ConsoleTool.Koios; 7 | using System.Text.Json; 8 | using static Cscli.ConsoleTool.Constants; 9 | 10 | namespace Cscli.ConsoleTool.Query; 11 | 12 | public class QueryAccountInfoCommand : ICommand 13 | { 14 | public string StakeAddress { get; init; } = string.Empty; 15 | public string Address { get; init; } = string.Empty; 16 | public string? Network { get; init; } 17 | 18 | public async ValueTask ExecuteAsync(CancellationToken ct) 19 | { 20 | var (isValid, networkType, stakeAddress, errors) = Validate(); 21 | if (!isValid || stakeAddress is null) 22 | { 23 | return CommandResult.FailureInvalidOptions( 24 | string.Join(Environment.NewLine, errors)); 25 | } 26 | 27 | var accountClient = BackendGateway.GetBackendClient(networkType); 28 | try 29 | { 30 | var accountInfo = await accountClient 31 | .GetAccountInformation( 32 | new AccountBulkRequest() 33 | { 34 | StakeAddresses = new string[] { stakeAddress.ToString() } 35 | }).ConfigureAwait(false); 36 | if (!accountInfo.IsSuccessStatusCode || accountInfo.Content is null) 37 | return CommandResult.FailureBackend($"Koios backend response was unsuccessful"); 38 | 39 | var json = JsonSerializer.Serialize(accountInfo.Content, SerialiserOptions); 40 | return CommandResult.Success(json); 41 | } 42 | catch (Exception ex) 43 | { 44 | return CommandResult.FailureUnhandledException("Unexpected error", ex); 45 | } 46 | } 47 | 48 | private ( 49 | bool isValid, 50 | NetworkType derivedNetworkType, 51 | Address? derivedStakeAddress, 52 | IReadOnlyCollection validationErrors) Validate() 53 | { 54 | var validationErrors = new List(); 55 | if (!Enum.TryParse(Network, ignoreCase: true, out var networkType)) 56 | { 57 | validationErrors.Add( 58 | $"Invalid option --network must be either testnet or mainnet"); 59 | } 60 | var stakeAddressArgumentExists = !string.IsNullOrWhiteSpace(StakeAddress); 61 | var paymentAddressArgumentExists = !string.IsNullOrWhiteSpace(Address); 62 | if (!stakeAddressArgumentExists && !paymentAddressArgumentExists 63 | || stakeAddressArgumentExists && paymentAddressArgumentExists) 64 | { 65 | validationErrors.Add( 66 | "Invalid option, one of either --stake-address or --address is required"); 67 | return (!validationErrors.Any(), networkType, null, validationErrors); 68 | } 69 | if (stakeAddressArgumentExists) 70 | { 71 | if (!Bech32.IsValid(StakeAddress)) 72 | { 73 | validationErrors.Add( 74 | $"Invalid option --stake-address {StakeAddress} is invalid"); 75 | } 76 | else 77 | { 78 | var stakeAddress = new Address(StakeAddress); 79 | if (stakeAddress.AddressType != AddressType.Reward || stakeAddress.NetworkType != networkType) 80 | { 81 | validationErrors.Add( 82 | $"Invalid option --stake-address {StakeAddress} is invalid for {Network}"); 83 | } 84 | else 85 | { 86 | return (!validationErrors.Any(), networkType, stakeAddress, validationErrors); 87 | } 88 | } 89 | } 90 | if (paymentAddressArgumentExists) 91 | { 92 | if (!Bech32.IsValid(Address)) 93 | { 94 | validationErrors.Add( 95 | $"Invalid option --address {Address} is not a base address with attached staking credentials"); 96 | } 97 | else 98 | { 99 | var addressService = new AddressService(); 100 | var address = new Address(Address); 101 | if (address.AddressType != AddressType.Base || address.NetworkType != networkType) 102 | { 103 | validationErrors.Add( 104 | $"Invalid option --address {Address} is not a base address with attached staking credentials for {Network}"); 105 | } 106 | else 107 | { 108 | var stakeAddress = addressService.ExtractRewardAddress(address); 109 | return (!validationErrors.Any(), networkType, stakeAddress, validationErrors); 110 | } 111 | } 112 | } 113 | return (!validationErrors.Any(), networkType, null, validationErrors); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /Src/ConsoleTool/Query/QueryAddressInfoCommand.cs: -------------------------------------------------------------------------------- 1 | using CardanoSharp.Koios.Client; 2 | using CardanoSharp.Wallet.Encoding; 3 | using CardanoSharp.Wallet.Enums; 4 | using CardanoSharp.Wallet.Models.Addresses; 5 | using Cscli.ConsoleTool.Koios; 6 | using System.Text.Json; 7 | using static Cscli.ConsoleTool.Constants; 8 | 9 | namespace Cscli.ConsoleTool.Query; 10 | 11 | public class QueryAddressInfoCommand : ICommand 12 | { 13 | public string? Address { get; init; } 14 | public string? Network { get; init; } 15 | 16 | public async ValueTask ExecuteAsync(CancellationToken ct) 17 | { 18 | var (isValid, networkType, address, errors) = Validate(); 19 | if (!isValid) 20 | { 21 | return CommandResult.FailureInvalidOptions( 22 | string.Join(Environment.NewLine, errors)); 23 | } 24 | 25 | var addressClient = BackendGateway.GetBackendClient(networkType); 26 | try 27 | { 28 | var addressInfo = (await addressClient 29 | .GetAddressInformation(new AddressBulkRequest() 30 | { Addresses = new List(){ address.ToString() }}) 31 | .ConfigureAwait(false)); 32 | if (!addressInfo.IsSuccessStatusCode || addressInfo.Content is null) 33 | return CommandResult.FailureBackend($"Koios backend response was unsuccessful"); 34 | 35 | var json = JsonSerializer.Serialize(addressInfo.Content, SerialiserOptions); 36 | return CommandResult.Success(json); 37 | } 38 | catch (Exception ex) 39 | { 40 | return CommandResult.FailureUnhandledException("Unexpected error", ex); 41 | } 42 | } 43 | 44 | private ( 45 | bool isValid, 46 | NetworkType derivedNetworkType, 47 | Address address, 48 | IReadOnlyCollection validationErrors) Validate() 49 | { 50 | var validationErrors = new List(); 51 | if (!Enum.TryParse(Network, ignoreCase: true, out var networkType)) 52 | { 53 | validationErrors.Add( 54 | $"Invalid option --network must be either testnet or mainnet"); 55 | } 56 | if (string.IsNullOrWhiteSpace(Address)) 57 | { 58 | validationErrors.Add( 59 | $"Invalid option --address is required"); 60 | } 61 | var address = new Address(Address); 62 | if (!Bech32.IsValid(Address) || address.NetworkType != networkType) 63 | { 64 | validationErrors.Add( 65 | $"Invalid option --address {Address} is invalid for {Network}"); 66 | } 67 | return (!validationErrors.Any(), networkType, address, validationErrors); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /Src/ConsoleTool/Query/QueryProtocolParametersCommand.cs: -------------------------------------------------------------------------------- 1 | using CardanoSharp.Koios.Client; 2 | using CardanoSharp.Wallet.Enums; 3 | using Cscli.ConsoleTool.Koios; 4 | using System.Text.Json; 5 | using static Cscli.ConsoleTool.Constants; 6 | 7 | namespace Cscli.ConsoleTool.Query; 8 | 9 | public class QueryProtocolParametersCommand : ICommand 10 | { 11 | public string? Network { get; init; } 12 | 13 | public async ValueTask ExecuteAsync(CancellationToken ct) 14 | { 15 | if (!Enum.TryParse(Network, ignoreCase: true, out var networkType)) 16 | { 17 | return CommandResult.FailureInvalidOptions( 18 | $"Invalid option --network must be either testnet or mainnet"); 19 | } 20 | 21 | var epochClient = BackendGateway.GetBackendClient(networkType); 22 | try 23 | { 24 | var protocolParams = await epochClient.GetProtocolParameters(null, limit:1).ConfigureAwait(false); 25 | if (!protocolParams.IsSuccessStatusCode || protocolParams.Content is null) 26 | return CommandResult.FailureBackend($"Koios backend response was unsuccessful"); 27 | 28 | var json = JsonSerializer.Serialize(protocolParams.Content.First(), SerialiserOptions); 29 | return CommandResult.Success(json); 30 | } 31 | catch (Exception ex) 32 | { 33 | return CommandResult.FailureUnhandledException("Unexpected error", ex); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Src/ConsoleTool/Query/QueryTipCommand.cs: -------------------------------------------------------------------------------- 1 | using CardanoSharp.Koios.Client; 2 | using CardanoSharp.Wallet.Enums; 3 | using Cscli.ConsoleTool.Koios; 4 | using System.Text.Json; 5 | using static Cscli.ConsoleTool.Constants; 6 | 7 | namespace Cscli.ConsoleTool.Query; 8 | 9 | public class QueryTipCommand : ICommand 10 | { 11 | public string? Network { get; init; } 12 | 13 | public async ValueTask ExecuteAsync(CancellationToken ct) 14 | { 15 | if (!Enum.TryParse(Network, ignoreCase: true, out var networkType)) 16 | { 17 | return CommandResult.FailureInvalidOptions( 18 | $"Invalid option --network must be either testnet or mainnet"); 19 | } 20 | 21 | var networkClient = BackendGateway.GetBackendClient(networkType); 22 | try 23 | { 24 | var chainTip = await networkClient.GetChainTip().ConfigureAwait(false); 25 | if (!chainTip.IsSuccessStatusCode || chainTip.Content is null) 26 | return CommandResult.FailureBackend($"Koios backend response was unsuccessful"); 27 | 28 | var json = JsonSerializer.Serialize(chainTip.Content.First(), SerialiserOptions); 29 | return CommandResult.Success(json); 30 | } 31 | catch (Exception ex) 32 | { 33 | return CommandResult.FailureUnhandledException("Unexpected error", ex); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Src/ConsoleTool/Query/QueryTransactionInfoCommand.cs: -------------------------------------------------------------------------------- 1 | using CardanoSharp.Koios.Client; 2 | using CardanoSharp.Wallet.Enums; 3 | using Cscli.ConsoleTool.Koios; 4 | using System.Text.Json; 5 | using static Cscli.ConsoleTool.Constants; 6 | 7 | namespace Cscli.ConsoleTool.Query; 8 | 9 | public class QueryTransactionInfoCommand : ICommand 10 | { 11 | public string? TxId { get; init; } 12 | public string? Network { get; init; } 13 | 14 | public async ValueTask ExecuteAsync(CancellationToken ct) 15 | { 16 | var (isValid, networkType, txId, errors) = Validate(); 17 | if (!isValid) 18 | { 19 | return CommandResult.FailureInvalidOptions( 20 | string.Join(Environment.NewLine, errors)); 21 | } 22 | 23 | var transactionClient = BackendGateway.GetBackendClient(networkType); 24 | try 25 | { 26 | var txInfo = await transactionClient.GetTransactionInformation( 27 | new GetTransactionRequest { TxHashes = new List{ txId } }).ConfigureAwait(false); 28 | if (!txInfo.IsSuccessStatusCode || txInfo.Content is null) 29 | return CommandResult.FailureBackend($"Koios backend response was unsuccessful"); 30 | 31 | var json = JsonSerializer.Serialize(txInfo.Content, SerialiserOptions); 32 | return CommandResult.Success(json); 33 | } 34 | catch (Exception ex) 35 | { 36 | return CommandResult.FailureUnhandledException("Unexpected error", ex); 37 | } 38 | } 39 | 40 | private ( 41 | bool isValid, 42 | NetworkType derivedNetworkType, 43 | string txId, 44 | IReadOnlyCollection validationErrors) Validate() 45 | { 46 | var validationErrors = new List(); 47 | if (!Enum.TryParse(Network, ignoreCase: true, out var networkType)) 48 | { 49 | validationErrors.Add( 50 | $"Invalid option --network must be either testnet or mainnet"); 51 | } 52 | if (string.IsNullOrWhiteSpace(TxId)) 53 | { 54 | validationErrors.Add( 55 | $"Invalid option --tx-id is required"); 56 | } 57 | return (!validationErrors.Any(), networkType, TxId ?? "", validationErrors); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Src/ConsoleTool/ShowBaseHelpCommand.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | namespace Cscli.ConsoleTool; 4 | 5 | public class ShowBaseHelpCommand : ICommand 6 | { 7 | public ValueTask ExecuteAsync(CancellationToken ct) 8 | { 9 | var versionString = (Assembly.GetEntryAssembly() ?? throw new InvalidOperationException()) 10 | .GetCustomAttribute()? 11 | .Version; 12 | var helpText = $@"cscli v{versionString} 13 | A lightweight cross-platform tool for generating/serialising Cardano wallet primitives (i.e. recovery-phrases, keys, addresses and transactions), querying the chain and submitting transactions to the testnet or mainnet networks. Please refer to https://github.com/CardanoSharp/cscli for further documentation. 14 | 15 | USAGE: cscli (OPTION | COMMAND) 16 | 17 | Options: 18 | -v, --version Show the cscli version 19 | -h, --help Show this help text 20 | 21 | Wallet Commands: 22 | wallet recovery-phrase generate --size [--language ] 23 | wallet key root derive --recovery-phrase """" [--language ] [--passphrase """"] 24 | wallet key account derive --recovery-phrase """" [--language ] [--passphrase """"] [--account-index ] 25 | wallet key stake derive --recovery-phrase """" [--language ] [--passphrase """"] [--account-index ] [--address-index ] [--verification-key-file ] [--signing-key-file ] 26 | wallet key payment derive --recovery-phrase """" [--language ] [--passphrase """"] [--account-index ] [--address-index ] [--verification-key-file ] [--signing-key-file ] 27 | wallet key change derive --recovery-phrase """" [--language ] [--passphrase """"] [--account-index ] [--address-index ] [--verification-key-file ] [--signing-key-file ] 28 | wallet key policy derive --recovery-phrase """" [--language ] [--passphrase """"] [--policy-index ] [--verification-key-file ] [--signing-key-file ] 29 | wallet key verification convert --signing-key """" [--verification-key-file ] 30 | wallet address stake derive --recovery-phrase """" --network [--language ] [--passphrase """"] [--account-index ] [--address-index ] 31 | wallet address change derive --recovery-phrase """" --network --payment-address-type [--language ] [--passphrase """"] [--account-index ] [--address-index ] [--stake-account-index ] [--stake-address-index ] 32 | wallet address payment derive --recovery-phrase """" --network --payment-address-type [--language ] [--passphrase """"] [--account-index ] [--address-index ] [--stake-account-index ] [--stake-address-index ] 33 | 34 | Query Commands: 35 | query tip --network 36 | query protocol-parameters --network 37 | query info account --network (--stake-address | --address ) 38 | query asset account --network --stake-address 39 | query info address --network --address 40 | query info transaction --network --tx-id 41 | 42 | Transaction Commands: 43 | BETA: transaction simple-payment build --network --from
--to
(--ada | --lovelaces | --send-all true) [--ttl ] [--mock-witness-count ] [--signing-key ] [--submit true] [--message """"] [--out-file ] 44 | transaction view --network --cbor-hex 45 | transaction sign --cbor-hex --signing-keys [--out-file ] 46 | transaction submit --network --cbor-hex 47 | 48 | Encoding/Crypto Commands: 49 | bech32 encode --value --prefix 50 | bech32 decode --value 51 | blake2b hash --value --length 52 | 53 | Arguments: 54 | ::= 9 | 12 | 15 | 18 | 21 | 24(default) 55 | ::= english(default)|chinesesimplified|chinesetraditional|french|italian|japanese|korean|spanish|czech|portuguese 56 | ::= 0(default) | 1 | .. | 2147483647 57 | ::= testnet | mainnet 58 | ::= enterprise | base 59 | ::= 160 | 224 | 256 | 512 60 | "; 61 | return ValueTask.FromResult(CommandResult.Success(helpText)); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Src/ConsoleTool/ShowInvalidArgumentCommand.cs: -------------------------------------------------------------------------------- 1 | namespace Cscli.ConsoleTool; 2 | 3 | public class ShowInvalidArgumentCommand : ICommand 4 | { 5 | public ShowInvalidArgumentCommand(string invalidArg) 6 | { 7 | InvalidArg = invalidArg; 8 | } 9 | 10 | public string InvalidArg { get; } 11 | 12 | public ValueTask ExecuteAsync(CancellationToken ct) 13 | { 14 | var helpText = $"Invalid argument(s) {InvalidArg}"; 15 | var result = CommandResult.Success(helpText); 16 | return ValueTask.FromResult(result); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Src/ConsoleTool/ShowVersionCommand.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | namespace Cscli.ConsoleTool; 4 | 5 | public class ShowVersionCommand : ICommand 6 | { 7 | public ValueTask ExecuteAsync(CancellationToken ct) 8 | { 9 | var cardanoSharpVersion = Assembly.GetAssembly(typeof(CardanoSharp.Wallet.MnemonicService))?.GetName().Version?.ToString(); 10 | var cscliVersionString = (Assembly.GetEntryAssembly() ?? throw new InvalidOperationException()) 11 | .GetCustomAttribute()? 12 | .InformationalVersion; 13 | var versionText = $"cscli {cscliVersionString} | CardanoSharp.Wallet {cardanoSharpVersion}"; 14 | return ValueTask.FromResult(CommandResult.Success(versionText)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Src/ConsoleTool/Transaction/SignTransactionCommand.cs: -------------------------------------------------------------------------------- 1 | using CardanoSharp.Wallet.Encoding; 2 | using CardanoSharp.Wallet.Extensions; 3 | using CardanoSharp.Wallet.Extensions.Models; 4 | using CardanoSharp.Wallet.Extensions.Models.Transactions; 5 | using CardanoSharp.Wallet.Models.Keys; 6 | using CardanoSharp.Wallet.Models.Transactions; 7 | using System.Text.Json; 8 | using static Cscli.ConsoleTool.Constants; 9 | 10 | namespace Cscli.ConsoleTool.Transaction; 11 | 12 | public class SignTransactionCommand : ICommand 13 | { 14 | public string? CborHex { get; init; } 15 | public string? SigningKeys { get; init; } 16 | public string? OutFile { get; init; } 17 | 18 | public async ValueTask ExecuteAsync(CancellationToken ct) 19 | { 20 | var (isValid, txCborBytes, signingKeys, errors) = Validate(); 21 | if (!isValid) 22 | { 23 | return CommandResult.FailureInvalidOptions( 24 | string.Join(Environment.NewLine, errors)); 25 | } 26 | 27 | var tx = txCborBytes.DeserializeTransaction(); 28 | if (tx.TransactionWitnessSet is null) 29 | { 30 | tx.TransactionWitnessSet = new TransactionWitnessSet 31 | { 32 | VKeyWitnesses = new List(), 33 | }; 34 | } 35 | 36 | foreach (var signingKey in signingKeys) 37 | { 38 | var vKey = signingKey.GetPublicKey(false); 39 | var keyExistsInWitnessSet = tx.TransactionWitnessSet.VKeyWitnesses.Any(kw => kw.VKey.Key.SequenceEqual(vKey.Key)); 40 | if (!keyExistsInWitnessSet) 41 | { 42 | tx.TransactionWitnessSet.VKeyWitnesses.Add(new VKeyWitness { SKey = signingKey, VKey = vKey }); 43 | } 44 | } 45 | txCborBytes = tx.Serialize(); // CardanoSharp signs all vkey witnesses upon Serialize() 46 | if (!string.IsNullOrWhiteSpace(OutFile)) 47 | { 48 | var txTextEnvelope = new TextEnvelope(TxAlonzoJsonTypeField, "", txCborBytes.ToStringHex()); 49 | await File.WriteAllTextAsync(OutFile, JsonSerializer.Serialize(txTextEnvelope, SerialiserOptions), ct); 50 | } 51 | return CommandResult.Success(txCborBytes.ToStringHex()); 52 | } 53 | 54 | private ( 55 | bool isValid, 56 | byte[] txCborBytes, 57 | PrivateKey[] signingKeys, 58 | IReadOnlyCollection validationErrors) Validate() 59 | { 60 | var txCborBytes = Array.Empty(); 61 | var validationErrors = new List(); 62 | if (string.IsNullOrWhiteSpace(CborHex)) 63 | { 64 | validationErrors.Add( 65 | $"Invalid option --cbor-hex is required"); 66 | } 67 | else 68 | { 69 | try 70 | { 71 | txCborBytes = Convert.FromHexString(CborHex); 72 | } 73 | catch (FormatException) 74 | { 75 | validationErrors.Add( 76 | $"Invalid option --cbor-hex {CborHex} is not in hexadecimal format"); 77 | } 78 | } 79 | var bech32SigningKeys = SigningKeys?.Split(',') ?? Array.Empty(); 80 | var signingKeys = new PrivateKey[bech32SigningKeys.Length]; 81 | if (string.IsNullOrWhiteSpace(SigningKeys)) 82 | { 83 | validationErrors.Add("Invalid option --signing-keys is required"); 84 | return (isValid: false, txCborBytes, signingKeys, validationErrors); 85 | } 86 | for (int i = 0; i < bech32SigningKeys.Length; i++) 87 | { 88 | if (string.IsNullOrWhiteSpace(bech32SigningKeys[i])) 89 | { 90 | validationErrors.Add($"Invalid option --signing-keys[{i}] is empty or whitespace"); 91 | continue; 92 | } 93 | if (!Bech32.IsValid(bech32SigningKeys[i])) 94 | { 95 | validationErrors.Add($"Invalid option --signing-keys[{i}] is not a valid Bech32-encoded key"); 96 | continue; 97 | } 98 | signingKeys[i] = TxUtils.GetPrivateKeyFromBech32SigningKey(bech32SigningKeys[i]); 99 | } 100 | if (!string.IsNullOrWhiteSpace(OutFile) 101 | && Path.IsPathFullyQualified(OutFile) 102 | && !Directory.Exists(Path.GetDirectoryName(OutFile))) 103 | { 104 | validationErrors.Add( 105 | $"Invalid option --out-file path {OutFile} does not exist"); 106 | } 107 | return (!validationErrors.Any(), txCborBytes, signingKeys, validationErrors); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /Src/ConsoleTool/Transaction/SubmitTransactionCommand.cs: -------------------------------------------------------------------------------- 1 | using CardanoSharp.Koios.Client; 2 | using CardanoSharp.Wallet.Enums; 3 | using Cscli.ConsoleTool.Koios; 4 | 5 | namespace Cscli.ConsoleTool.Transaction; 6 | 7 | public class SubmitTransactionCommand : ICommand 8 | { 9 | public string? CborHex { get; init; } 10 | public string? Network { get; init; } 11 | 12 | public async ValueTask ExecuteAsync(CancellationToken ct) 13 | { 14 | var (isValid, networkType, txCborBytes, errors) = Validate(); 15 | if (!isValid) 16 | { 17 | return CommandResult.FailureInvalidOptions( 18 | string.Join(Environment.NewLine, errors)); 19 | } 20 | 21 | var txClient = BackendGateway.GetBackendClient(networkType); 22 | try 23 | { 24 | using var stream = new MemoryStream(txCborBytes); 25 | var txSubmissionResponse = await txClient.Submit(stream).ConfigureAwait(false); 26 | if (!txSubmissionResponse.IsSuccessStatusCode) 27 | { 28 | if (txSubmissionResponse.Error is null || string.IsNullOrWhiteSpace(txSubmissionResponse.Error.Content)) 29 | return CommandResult.FailureBackend($"Koios backend response was unsuccessful"); 30 | return CommandResult.FailureBackend(txSubmissionResponse.Error.Content); 31 | } 32 | if (txSubmissionResponse.Content is null) 33 | { 34 | return CommandResult.FailureBackend("Koios transaction submission response did not return a valid transaction ID"); 35 | } 36 | return CommandResult.Success(txSubmissionResponse.Content.TrimStart('"').TrimEnd('"')); 37 | } 38 | catch (Exception ex) 39 | { 40 | return CommandResult.FailureUnhandledException("Unexpected error", ex); 41 | } 42 | } 43 | 44 | private ( 45 | bool isValid, 46 | NetworkType derivedNetworkType, 47 | byte[] txCborBytes, 48 | IReadOnlyCollection validationErrors) Validate() 49 | { 50 | var validationErrors = new List(); 51 | if (!Enum.TryParse(Network, ignoreCase: true, out var networkType)) 52 | { 53 | validationErrors.Add( 54 | $"Invalid option --network must be either testnet or mainnet"); 55 | } 56 | if (string.IsNullOrWhiteSpace(CborHex)) 57 | { 58 | validationErrors.Add( 59 | $"Invalid option --cbor-hex is required"); 60 | } 61 | else 62 | { 63 | try 64 | { 65 | var txCborBytes = Convert.FromHexString(CborHex); 66 | return (!validationErrors.Any(), networkType, txCborBytes, validationErrors); 67 | } 68 | catch (FormatException) 69 | { 70 | validationErrors.Add( 71 | $"Invalid option --cbor-hex {CborHex} is not in hexadecimal format"); 72 | } 73 | } 74 | return (!validationErrors.Any(), networkType, Array.Empty(), validationErrors); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /Src/ConsoleTool/Transaction/TxUtils.cs: -------------------------------------------------------------------------------- 1 | using CardanoSharp.Wallet.Encoding; 2 | using CardanoSharp.Wallet.Models.Keys; 3 | 4 | namespace Cscli.ConsoleTool.Transaction; 5 | 6 | public static class TxUtils 7 | { 8 | public static bool IsZero(this Balance value) 9 | { 10 | return value.Lovelaces == 0 && value.NativeAssets.Length == 0; 11 | } 12 | 13 | public static Balance Sum(this IEnumerable values) 14 | { 15 | var lovelaces = 0UL; 16 | var nativeAssets = new Dictionary<(string PolicyId, string AssetNameHex), long>(); 17 | foreach (var value in values) 18 | { 19 | lovelaces += value.Lovelaces; 20 | foreach (var nativeAsset in value.NativeAssets) 21 | { 22 | if (nativeAssets.ContainsKey((nativeAsset.PolicyId, nativeAsset.AssetName))) 23 | { 24 | nativeAssets[(nativeAsset.PolicyId, nativeAsset.AssetName)] += nativeAsset.Quantity; 25 | continue; 26 | } 27 | nativeAssets.Add((nativeAsset.PolicyId, nativeAsset.AssetName), nativeAsset.Quantity); 28 | } 29 | } 30 | return new Balance( 31 | lovelaces, 32 | nativeAssets.Select(nav => new NativeAssetValue(nav.Key.PolicyId, nav.Key.AssetNameHex, nav.Value)).ToArray()); 33 | } 34 | 35 | public static Balance Subtract(this Balance lhsValue, Balance rhsValue) 36 | { 37 | static NativeAssetValue SubtractSingleValue(NativeAssetValue lhsValue, NativeAssetValue rhsValue) 38 | { 39 | return rhsValue == default 40 | ? lhsValue 41 | : new NativeAssetValue(lhsValue.PolicyId, lhsValue.AssetName, lhsValue.Quantity - rhsValue.Quantity); 42 | }; 43 | 44 | if (rhsValue.NativeAssets.Length == 0) 45 | return new Balance(lhsValue.Lovelaces - rhsValue.Lovelaces, lhsValue.NativeAssets); 46 | 47 | var missingLhsValues = rhsValue.NativeAssets 48 | .Where(rna => !lhsValue.NativeAssets 49 | .Any(lna => lna.PolicyId == rna.PolicyId && lna.AssetName == rna.AssetName)) 50 | .ToArray(); 51 | if (missingLhsValues.Any()) 52 | throw new ArgumentException("lhsValue is missing Native Assets found on rhsValue", nameof(rhsValue)); 53 | 54 | var nativeAssets = lhsValue.NativeAssets 55 | .Select(lv => SubtractSingleValue( 56 | lv, 57 | rhsValue.NativeAssets.FirstOrDefault( 58 | rv => rv.PolicyId == lv.PolicyId && rv.AssetName == lv.AssetName))) 59 | .Where(na => na.Quantity != 0) 60 | .ToArray(); 61 | return new Balance(lhsValue.Lovelaces - rhsValue.Lovelaces, nativeAssets); 62 | } 63 | 64 | public static ulong CalculateMinUtxoLovelace( 65 | NativeAssetValue[] tokenBundle, 66 | int lovelacePerUtxoWord = 34482, // utxoCostPerWord in protocol params (could change in the future) 67 | int policyIdSizeBytes = 28, // 224 bit policyID (won't in forseeable future) 68 | bool hasDataHash = false) // for UTxOs with smart contract datum 69 | { 70 | // https://docs.cardano.org/native-tokens/minimum-ada-value-requirement#min-ada-valuecalculation 71 | const int fixedUtxoPrefixWords = 6; 72 | const int fixedUtxoEntryWithoutValueSizeWords = 27; // The static parts of a UTxO: 6 + 7 + 14 words 73 | const int coinSizeWords = 2; // since updated from 0 in docs.cardano.org/native-tokens/minimum-ada-value-requirement 74 | const int adaOnlyUtxoSizeWords = fixedUtxoEntryWithoutValueSizeWords + coinSizeWords; 75 | const int fixedPerTokenCost = 12; 76 | const int byteRoundUpAddition = 7; 77 | const int bytesPerWord = 8; // One "word" is 8 bytes (64-bit) 78 | const int fixedDataHashSizeWords = 10; 79 | 80 | var isAdaOnly = tokenBundle.Length == 0; 81 | if (isAdaOnly) 82 | return (ulong)lovelacePerUtxoWord * adaOnlyUtxoSizeWords; // 999978 lovelaces or 0.999978 ADA 83 | 84 | // Get distinct policyIDs and assetNames 85 | var policyIds = new HashSet(); 86 | var assetNameHexadecimals = new HashSet(); 87 | foreach (var customToken in tokenBundle) 88 | { 89 | policyIds.Add(customToken.PolicyId); 90 | assetNameHexadecimals.Add(customToken.AssetName); 91 | } 92 | 93 | // Calculate (prefix + (numDistinctPids * 28(policyIdSizeBytes) + numTokens * 12(fixedPerTokenCost) + tokensNameLen + 7) ~/8) 94 | var tokensNameLen = assetNameHexadecimals.Sum(an => an.Length) / 2; // 2 hexadecimal chars = 1 Byte 95 | var valueSizeWords = fixedUtxoPrefixWords + ( 96 | (policyIds.Count * policyIdSizeBytes) 97 | + (tokenBundle.Length * fixedPerTokenCost) 98 | + tokensNameLen + byteRoundUpAddition) / bytesPerWord; 99 | var dataHashSizeWords = hasDataHash ? fixedDataHashSizeWords : 0; 100 | 101 | var minUtxoLovelace = lovelacePerUtxoWord 102 | * (fixedUtxoEntryWithoutValueSizeWords + valueSizeWords + dataHashSizeWords); 103 | 104 | return (ulong)minUtxoLovelace; 105 | } 106 | 107 | public static PrivateKey GetPrivateKeyFromBech32SigningKey(string bech32EncodedSigningKey) 108 | { 109 | var keyBytes = Bech32.Decode(bech32EncodedSigningKey, out _, out _); 110 | // Extended signing key "*_xsk" 64 bytes key + 32 bytes chain-code (optional) 111 | // or non-extended "*_sk" 32 bytes key 112 | return keyBytes.Length >= 64 113 | ? new PrivateKey(keyBytes[..64], keyBytes[64..]) 114 | : new PrivateKey(keyBytes[..32], Array.Empty()); 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /Src/ConsoleTool/Transaction/ViewTransactionCommand.cs: -------------------------------------------------------------------------------- 1 | using CardanoSharp.Wallet.Enums; 2 | using CardanoSharp.Wallet.Extensions; 3 | using CardanoSharp.Wallet.Extensions.Models.Transactions; 4 | using CardanoSharp.Wallet.Models.Addresses; 5 | using CardanoSharp.Wallet.Models.Transactions; 6 | using CardanoSharp.Wallet.Utilities; 7 | using System.Text.Json; 8 | using static Cscli.ConsoleTool.Constants; 9 | 10 | namespace Cscli.ConsoleTool.Transaction; 11 | 12 | public class ViewTransactionCommand : ICommand 13 | { 14 | public string? CborHex { get; init; } 15 | public string? Network { get; init; } 16 | 17 | public ValueTask ExecuteAsync(CancellationToken ct) 18 | { 19 | var (isValid, network, txCborBytes, errors) = Validate(); 20 | if (!isValid) 21 | { 22 | return ValueTask.FromResult(CommandResult.FailureInvalidOptions( 23 | string.Join(Environment.NewLine, errors))); 24 | } 25 | 26 | var deSerialisedTx = txCborBytes.DeserializeTransaction(); 27 | var txId = deSerialisedTx.TransactionWitnessSet is null 28 | ? "n/a" 29 | : HashUtility.Blake2b256(deSerialisedTx.TransactionBody.Serialize(deSerialisedTx.AuxiliaryData)).ToStringHex(); 30 | var tx = new Tx( 31 | Id: txId, 32 | IsValid: deSerialisedTx.IsValid, 33 | TransactionBody: new TxBody( 34 | deSerialisedTx.TransactionBody.TransactionInputs.Select( 35 | txI => new TxIn(txI.TransactionId.ToStringHex(), txI.TransactionIndex)).ToArray(), 36 | deSerialisedTx.TransactionBody.TransactionOutputs.Select( 37 | txO => MapTxOut(network, txO)).ToArray(), 38 | MapNativeAssets(deSerialisedTx.TransactionBody.Mint), 39 | deSerialisedTx.TransactionBody.Fee, 40 | deSerialisedTx.TransactionBody.Ttl, 41 | deSerialisedTx.AuxiliaryData is null ? null : HashUtility.Blake2b256(deSerialisedTx.AuxiliaryData.GetCBOR().EncodeToBytes()).ToStringHex(), 42 | deSerialisedTx.TransactionBody.TransactionStartInterval), 43 | TransactionWitnessSet: deSerialisedTx.TransactionWitnessSet is null 44 | ? null 45 | : new TxWitnessSet( 46 | deSerialisedTx.TransactionWitnessSet.VKeyWitnesses.Select( 47 | vw => new TxVKeyWitness(vw.VKey.Key.ToStringHex(), vw.Signature.ToStringHex())) 48 | .ToArray(), 49 | deSerialisedTx.TransactionWitnessSet.NativeScripts.Select(MapNativeScript).ToArray()), 50 | AuxiliaryData: new TxAuxData(deSerialisedTx.AuxiliaryData?.Metadata ?? new Dictionary())); 51 | var json = JsonSerializer.Serialize(tx, SerialiserOptions); 52 | return ValueTask.FromResult(CommandResult.Success(json)); 53 | } 54 | 55 | private ( 56 | bool isValid, 57 | NetworkType networkType, 58 | byte[] txCborBytes, 59 | IReadOnlyCollection validationErrors) Validate() 60 | { 61 | var validationErrors = new List(); 62 | var txCborBytes = Array.Empty(); 63 | if (!Enum.TryParse(Network, ignoreCase: true, out var networkType)) 64 | { 65 | validationErrors.Add("Invalid option --network must be either testnet or mainnet"); 66 | } 67 | if (string.IsNullOrWhiteSpace(CborHex)) 68 | { 69 | validationErrors.Add( 70 | $"Invalid option --cbor-hex is required"); 71 | } 72 | else 73 | { 74 | try 75 | { 76 | txCborBytes = Convert.FromHexString(CborHex); 77 | } 78 | catch (FormatException) 79 | { 80 | validationErrors.Add( 81 | $"Invalid option --cbor-hex {CborHex} is not in hexadecimal format"); 82 | } 83 | } 84 | return (!validationErrors.Any(), networkType, txCborBytes, validationErrors); 85 | } 86 | 87 | private static TxOut MapTxOut(NetworkType network, TransactionOutput txO) 88 | { 89 | var addrPrefix = network == NetworkType.Mainnet ? AddressMainnetBech32Prefix : AddressTestnetBech32Prefix; 90 | return new TxOut( 91 | new Address(addrPrefix, txO.Address).ToString(), 92 | new Balance(txO.Value.Coin, MapNativeAssets(txO.Value.MultiAsset).ToArray())); 93 | } 94 | 95 | private static NativeAssetValue[] MapNativeAssets(IDictionary multiAsset) 96 | { 97 | if (multiAsset is null) 98 | return Array.Empty(); 99 | 100 | return multiAsset.Keys.SelectMany( 101 | maKey => multiAsset[maKey].Token.Select( 102 | mat => new NativeAssetValue(maKey.ToStringHex(), mat.Key.ToStringHex(), mat.Value))) 103 | .ToArray(); 104 | } 105 | 106 | private static TxNativeScript MapNativeScript(NativeScript nativeScript) 107 | { 108 | if (nativeScript is null) 109 | return new TxNativeScript(""); 110 | 111 | return new TxNativeScript(BuildNativeScriptString(nativeScript)); 112 | 113 | static string BuildNativeScriptString(NativeScript ns) 114 | { 115 | if (ns.ScriptPubKey is not null) 116 | return $"PubKey({ns.ScriptPubKey.KeyHash.ToStringHex()})"; 117 | if (ns.InvalidAfter is not null) 118 | return $"InvalidAfter({ns.InvalidAfter.After})"; 119 | if (ns.InvalidBefore is not null) 120 | return $"InvalidBefore({ns.InvalidBefore.Before})"; 121 | if (ns.ScriptNofK is not null) 122 | return $"NofK({ns.ScriptNofK.N}of{ns.ScriptNofK.NativeScripts.Count}[{string.Join(',',ns.ScriptNofK.NativeScripts.Select(BuildNativeScriptString))}])"; 123 | if (ns.ScriptAny is not null) 124 | return $"Any([{string.Join(',', ns.ScriptAny.NativeScripts.Select(BuildNativeScriptString))}])"; 125 | if (ns.ScriptAll is not null) 126 | return $"All([{string.Join(',', ns.ScriptAll.NativeScripts.Select(BuildNativeScriptString))}])"; 127 | return ""; 128 | } 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /Src/ConsoleTool/Wallet/ConvertVerificationKeyCommand.cs: -------------------------------------------------------------------------------- 1 | using CardanoSharp.Wallet.Encoding; 2 | using CardanoSharp.Wallet.Extensions.Models; 3 | using CardanoSharp.Wallet.Models.Keys; 4 | using Cscli.ConsoleTool.Transaction; 5 | using System.Text.Json; 6 | using static Cscli.ConsoleTool.Constants; 7 | 8 | namespace Cscli.ConsoleTool.Wallet; 9 | 10 | public class ConvertVerificationKeyCommand : ICommand 11 | { 12 | private static readonly HashSet SupportedSigningKeyPrefixes = new() 13 | { 14 | RootExtendedSigningKeyBech32Prefix, RootSigningKeyBech32Prefix, 15 | AccountExtendedSigningKeyBech32Prefix, AccountSigningKeyBech32Prefix, 16 | PaymentExtendedSigningKeyBech32Prefix, PaymentSigningKeyBech32Prefix, 17 | StakeExtendedSigningKeyBech32Prefix, StakeSigningKeyBech32Prefix, 18 | PolicySigningKeyBech32Prefix 19 | }; 20 | 21 | public string? SigningKey { get; init; } 22 | public string? VerificationKeyFile { get; init; } = null; 23 | 24 | public async ValueTask ExecuteAsync(CancellationToken ct) 25 | { 26 | if (string.IsNullOrWhiteSpace(SigningKey)) 27 | return CommandResult.FailureInvalidOptions( 28 | "Invalid option --sigining-key is required"); 29 | 30 | if (!Bech32.IsValid(SigningKey)) 31 | return CommandResult.FailureInvalidOptions( 32 | "Invalid option --sigining-key is not in bech32 format - please see https://cips.cardano.org/cips/cip5/"); 33 | 34 | _ = Bech32.Decode(SigningKey, out _, out var sKeyPrefix); 35 | if (!SupportedSigningKeyPrefixes.Contains(sKeyPrefix)) 36 | return CommandResult.FailureInvalidOptions( 37 | $"Invalid option --sigining-key with prefix '{sKeyPrefix}' is not supported"); 38 | 39 | var signingKey = TxUtils.GetPrivateKeyFromBech32SigningKey(SigningKey); 40 | var verificationKey = signingKey.GetPublicKey(false); 41 | 42 | var vKeyPrefix = sKeyPrefix.Replace("sk", "vk"); 43 | var bech32VKey = verificationKey.Chaincode.Length == 0 44 | ? Bech32.Encode(verificationKey.Key, vKeyPrefix) 45 | : Bech32.Encode(verificationKey.BuildExtendedVkeyBytes(), vKeyPrefix); 46 | if (!string.IsNullOrWhiteSpace(VerificationKeyFile)) 47 | { 48 | var vkeyCborTextEnvelope = BuildTextEnvelope(sKeyPrefix, verificationKey); 49 | if (vkeyCborTextEnvelope is not null) 50 | await File.WriteAllTextAsync(VerificationKeyFile, JsonSerializer.Serialize(vkeyCborTextEnvelope, SerialiserOptions), ct).ConfigureAwait(false); 51 | } 52 | 53 | return CommandResult.Success(bech32VKey); 54 | } 55 | 56 | private static TextEnvelope? BuildTextEnvelope(string sKeyPrefix, PublicKey vKey) => sKeyPrefix switch 57 | { 58 | PaymentExtendedSigningKeyBech32Prefix => new TextEnvelope( 59 | PaymentExtendedVKeyJsonTypeField, 60 | PaymentVKeyJsonDescriptionField, 61 | KeyUtils.BuildCborHexPayload(vKey.BuildExtendedVkeyBytes())), 62 | PaymentSigningKeyBech32Prefix => new TextEnvelope( 63 | PaymentVKeyJsonTypeField, 64 | PaymentVKeyJsonDescriptionField, 65 | KeyUtils.BuildCborHexPayload(vKey.Key)), 66 | // cardano-cli compatibility requires us to use non-extended verification keys 67 | StakeExtendedSigningKeyBech32Prefix => new TextEnvelope( 68 | StakeVKeyJsonTypeField, 69 | StakeVKeyJsonDescriptionField, 70 | KeyUtils.BuildCborHexPayload(vKey.Key)), 71 | // cardano-cli compatibility requires us to use non-extended verification keys 72 | StakeSigningKeyBech32Prefix => new TextEnvelope( 73 | StakeVKeyJsonTypeField, 74 | StakeVKeyJsonDescriptionField, 75 | KeyUtils.BuildCborHexPayload(vKey.Key)), 76 | // cardano-cli compatibility requires us to use extended payment verification keys for policy keys 77 | PolicySigningKeyBech32Prefix => new TextEnvelope( 78 | PaymentExtendedVKeyJsonTypeField, 79 | PaymentVKeyJsonDescriptionField, 80 | KeyUtils.BuildCborHexPayload(vKey.BuildExtendedVkeyBytes())), 81 | _ => null 82 | }; 83 | } 84 | -------------------------------------------------------------------------------- /Src/ConsoleTool/Wallet/DeriveAccountKeyCommand.cs: -------------------------------------------------------------------------------- 1 | using CardanoSharp.Wallet; 2 | using CardanoSharp.Wallet.Encoding; 3 | using CardanoSharp.Wallet.Enums; 4 | using CardanoSharp.Wallet.Extensions.Models; 5 | using static Cscli.ConsoleTool.Constants; 6 | 7 | namespace Cscli.ConsoleTool.Wallet; 8 | 9 | public class DeriveAccountKeyCommand : ICommand 10 | { 11 | public string? Mnemonic { get; init; } 12 | public string Language { get; init; } = DefaultMnemonicLanguage; 13 | public string Passphrase { get; init; } = string.Empty; 14 | public int AccountIndex { get; init; } = 0; 15 | 16 | public ValueTask ExecuteAsync(CancellationToken ct) 17 | { 18 | if (string.IsNullOrWhiteSpace(Mnemonic)) 19 | { 20 | return ValueTask.FromResult(CommandResult.FailureInvalidOptions( 21 | $"Invalid option --recovery-phrase is required")); 22 | } 23 | if (!Enum.TryParse(Language, ignoreCase: true, out var wordlist)) 24 | { 25 | return ValueTask.FromResult(CommandResult.FailureInvalidOptions( 26 | $"Invalid option --language {Language} is not supported")); 27 | } 28 | var wordCount = Mnemonic.Split(' ', StringSplitOptions.TrimEntries).Length; 29 | if (!ValidMnemonicSizes.Contains(wordCount)) 30 | { 31 | return ValueTask.FromResult(CommandResult.FailureInvalidOptions( 32 | $"Invalid option --recovery-phrase must have the following word count ({string.Join(", ", ValidMnemonicSizes)})")); 33 | } 34 | if (AccountIndex < 0 || AccountIndex > MaxDerivationPathIndex) 35 | { 36 | return ValueTask.FromResult(CommandResult.FailureInvalidOptions( 37 | $"Invalid option --account-index must be between 0 and {MaxDerivationPathIndex}")); 38 | } 39 | 40 | var mnemonicService = new MnemonicService(); 41 | try 42 | { 43 | var rootPrvKey = mnemonicService.Restore(Mnemonic, wordlist) 44 | .GetRootKey(Passphrase); 45 | var accountSkey = rootPrvKey.Derive($"m/1852'/1815'/{AccountIndex}'"); 46 | var accountVkey = accountSkey.GetPublicKey(false); 47 | var accountSkeyExtendedBytes = accountSkey.BuildExtendedSkeyBytes(); 48 | var bech32AccountkeyExtended = Bech32.Encode(accountSkeyExtendedBytes, AccountExtendedSigningKeyBech32Prefix); 49 | var result = CommandResult.Success(bech32AccountkeyExtended); 50 | return ValueTask.FromResult(result); 51 | } 52 | catch (ArgumentException ex) 53 | { 54 | return ValueTask.FromResult( 55 | CommandResult.FailureInvalidOptions(ex.Message)); 56 | } 57 | catch (Exception ex) 58 | { 59 | return ValueTask.FromResult( 60 | CommandResult.FailureUnhandledException("Unexpected error", ex)); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Src/ConsoleTool/Wallet/DeriveChangeAddressCommand.cs: -------------------------------------------------------------------------------- 1 | using CardanoSharp.Wallet; 2 | using CardanoSharp.Wallet.Enums; 3 | using CardanoSharp.Wallet.Extensions.Models; 4 | using CardanoSharp.Wallet.Models.Addresses; 5 | using CardanoSharp.Wallet.Models.Keys; 6 | using static Cscli.ConsoleTool.Constants; 7 | 8 | namespace Cscli.ConsoleTool.Wallet; 9 | 10 | public class DeriveChangeAddressCommand : ICommand 11 | { 12 | public string? Mnemonic { get; init; } 13 | public string Language { get; init; } = DefaultMnemonicLanguage; 14 | public string Passphrase { get; init; } = string.Empty; 15 | public string? PaymentAddressType { get; init; } 16 | public int AccountIndex { get; init; } = 0; 17 | public int AddressIndex { get; init; } = 0; 18 | public int StakeAccountIndex { get; init; } = 0; 19 | public int StakeAddressIndex { get; init; } = 0; 20 | public string? Network { get; init; } 21 | 22 | public ValueTask ExecuteAsync(CancellationToken ct) 23 | { 24 | var (isValid, wordList, addressType, network, errors) = Validate(); 25 | if (!isValid) 26 | { 27 | return ValueTask.FromResult( 28 | CommandResult.FailureInvalidOptions(string.Join(Environment.NewLine, errors))); 29 | } 30 | 31 | var mnemonicService = new MnemonicService(); 32 | try 33 | { 34 | var rootKey = mnemonicService.Restore(Mnemonic, wordList) 35 | .GetRootKey(Passphrase); 36 | var address = GetPaymentAddress( 37 | addressType, rootKey, new AddressService(), network); 38 | return ValueTask.FromResult(CommandResult.Success(address.ToString())); 39 | } 40 | catch (ArgumentException ex) 41 | { 42 | return ValueTask.FromResult(CommandResult.FailureInvalidOptions(ex.Message)); 43 | } 44 | catch (Exception ex) 45 | { 46 | return ValueTask.FromResult( 47 | CommandResult.FailureUnhandledException("Unexpected error", ex)); 48 | } 49 | } 50 | 51 | private Address GetPaymentAddress( 52 | AddressType addressType, 53 | PrivateKey rootKey, 54 | IAddressService addressService, 55 | NetworkType networkType) => addressType switch 56 | { 57 | AddressType.Enterprise => addressService.GetEnterpriseAddress( 58 | rootKey.Derive($"m/1852'/1815'/{AccountIndex}'/1/{AddressIndex}").GetPublicKey(false), 59 | networkType), 60 | AddressType.Base => addressService.GetBaseAddress( 61 | rootKey.Derive($"m/1852'/1815'/{AccountIndex}'/1/{AddressIndex}").GetPublicKey(false), 62 | rootKey.Derive($"m/1852'/1815'/{StakeAccountIndex}'/2/{StakeAddressIndex}").GetPublicKey(false), 63 | networkType), 64 | _ => throw new NotImplementedException($"--payment-address-type not valid for {nameof(DerivePaymentAddressCommand)}") 65 | }; 66 | 67 | private ( 68 | bool isValid, 69 | WordLists derivedWordList, 70 | AddressType derivedAddressType, 71 | NetworkType derivedNetworkType, 72 | IReadOnlyCollection validationErrors) Validate() 73 | { 74 | var validationErrors = new List(); 75 | if (string.IsNullOrWhiteSpace(Mnemonic)) 76 | { 77 | validationErrors.Add( 78 | $"Invalid option --recovery-phrase is required"); 79 | } 80 | var wordCount = Mnemonic?.Split(' ', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries).Length; 81 | if (wordCount.HasValue && wordCount > 0 && !ValidMnemonicSizes.Contains(wordCount.Value)) 82 | { 83 | validationErrors.Add( 84 | $"Invalid option --recovery-phrase must have the following word count ({string.Join(", ", ValidMnemonicSizes)})"); 85 | } 86 | if (!Enum.TryParse(Language, ignoreCase: true, out var wordlist)) 87 | { 88 | validationErrors.Add( 89 | $"Invalid option --language {Language} is not supported"); 90 | } 91 | if (!Enum.TryParse(PaymentAddressType, ignoreCase: true, out var paymentAddressType) 92 | || paymentAddressType != AddressType.Base && paymentAddressType != AddressType.Enterprise) 93 | { 94 | validationErrors.Add( 95 | $"Invalid option --payment-address-type {PaymentAddressType} is not supported"); 96 | } 97 | if (AccountIndex < 0 || AccountIndex > MaxDerivationPathIndex) 98 | { 99 | validationErrors.Add( 100 | $"Invalid option --account-index must be between 0 and {MaxDerivationPathIndex}"); 101 | } 102 | if (AddressIndex < 0 || AddressIndex > MaxDerivationPathIndex) 103 | { 104 | validationErrors.Add( 105 | $"Invalid option --address-index must be between 0 and {MaxDerivationPathIndex}"); 106 | } 107 | if (StakeAccountIndex < 0 || StakeAccountIndex > MaxDerivationPathIndex) 108 | { 109 | validationErrors.Add( 110 | $"Invalid option --stake-account-index must be between 0 and {MaxDerivationPathIndex}"); 111 | } 112 | if (StakeAddressIndex < 0 || StakeAddressIndex > MaxDerivationPathIndex) 113 | { 114 | validationErrors.Add( 115 | $"Invalid option --stake-address-index must be between 0 and {MaxDerivationPathIndex}"); 116 | } 117 | if (!Enum.TryParse(Network, ignoreCase: true, out var networkType)) 118 | { 119 | validationErrors.Add( 120 | $"Invalid option --network must be either testnet or mainnet"); 121 | } 122 | return (!validationErrors.Any(), wordlist, paymentAddressType, networkType, validationErrors); 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /Src/ConsoleTool/Wallet/DeriveChangeKeyCommand.cs: -------------------------------------------------------------------------------- 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.Wallet; 9 | 10 | public class DeriveChangeKeyCommand : ICommand 11 | { 12 | public string? Mnemonic { get; init; } 13 | public string Language { get; init; } = DefaultMnemonicLanguage; 14 | public string Passphrase { get; init; } = string.Empty; 15 | public int AccountIndex { get; init; } = 0; 16 | public int AddressIndex { get; init; } = 0; 17 | public string? VerificationKeyFile { get; init; } = null; 18 | public string? SigningKeyFile { get; init; } = null; 19 | 20 | public async ValueTask 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 rootPrvKey = mnemonicService.Restore(Mnemonic, wordList) 33 | .GetRootKey(Passphrase); 34 | var changeSkey = rootPrvKey.Derive($"m/1852'/1815'/{AccountIndex}'/1/{AddressIndex}"); 35 | var changeVkey = changeSkey.GetPublicKey(false); 36 | var changeSkeyExtendedBytes = changeSkey.BuildExtendedSkeyBytes(); 37 | var bech32changeSkeyExtended = Bech32.Encode(changeSkeyExtendedBytes, PaymentExtendedSigningKeyBech32Prefix); 38 | var result = CommandResult.Success(bech32changeSkeyExtended); 39 | // Write output to CBOR JSON file outputs if optional file paths are supplied 40 | if (!string.IsNullOrWhiteSpace(SigningKeyFile)) 41 | { 42 | var skeyCbor = new TextEnvelope( 43 | PaymentExtendedSKeyJsonTypeField, 44 | PaymentSKeyJsonDescriptionField, 45 | KeyUtils.BuildCborHexPayload(changeSkey.BuildExtendedSkeyWithVerificationKeyBytes())); 46 | await File.WriteAllTextAsync(SigningKeyFile, JsonSerializer.Serialize(skeyCbor, SerialiserOptions), ct).ConfigureAwait(false); 47 | } 48 | if (!string.IsNullOrWhiteSpace(VerificationKeyFile)) 49 | { 50 | var vkeyCbor = new TextEnvelope( 51 | PaymentExtendedVKeyJsonTypeField, 52 | PaymentVKeyJsonDescriptionField, 53 | KeyUtils.BuildCborHexPayload(changeVkey.BuildExtendedVkeyBytes())); 54 | await File.WriteAllTextAsync(VerificationKeyFile, JsonSerializer.Serialize(vkeyCbor, SerialiserOptions), ct).ConfigureAwait(false); 55 | } 56 | return result; 57 | } 58 | catch (ArgumentException ex) 59 | { 60 | return CommandResult.FailureInvalidOptions(ex.Message); 61 | } 62 | catch (Exception ex) 63 | { 64 | return CommandResult.FailureUnhandledException("Unexpected error", ex); 65 | } 66 | } 67 | 68 | private ( 69 | bool isValid, 70 | WordLists wordList, 71 | IReadOnlyCollection validationErrors) Validate() 72 | { 73 | var validationErrors = new List(); 74 | if (string.IsNullOrWhiteSpace(Mnemonic)) 75 | { 76 | validationErrors.Add( 77 | $"Invalid option --recovery-phrase is required"); 78 | } 79 | if (AccountIndex < 0 || AccountIndex > MaxDerivationPathIndex) 80 | { 81 | validationErrors.Add( 82 | $"Invalid option --account-index must be between 0 and {MaxDerivationPathIndex}"); 83 | } 84 | if (AddressIndex < 0 || AddressIndex > MaxDerivationPathIndex) 85 | { 86 | validationErrors.Add( 87 | $"Invalid option --address-index must be between 0 and {MaxDerivationPathIndex}"); 88 | } 89 | if (!string.IsNullOrWhiteSpace(SigningKeyFile) 90 | && Path.IsPathFullyQualified(SigningKeyFile) 91 | && !Directory.Exists(Path.GetDirectoryName(SigningKeyFile))) 92 | { 93 | validationErrors.Add( 94 | $"Invalid option --signing-key-file path {SigningKeyFile} does not exist"); 95 | } 96 | if (!string.IsNullOrWhiteSpace(VerificationKeyFile) 97 | && Path.IsPathFullyQualified(VerificationKeyFile) 98 | && !Directory.Exists(Path.GetDirectoryName(VerificationKeyFile))) 99 | { 100 | validationErrors.Add( 101 | $"Invalid option --verification-key-file path {VerificationKeyFile} does not exist"); 102 | } 103 | if (!Enum.TryParse(Language, ignoreCase: true, out var wordlist)) 104 | { 105 | validationErrors.Add( 106 | $"Invalid option --language {Language} is not supported"); 107 | } 108 | var wordCount = Mnemonic?.Split(' ', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries).Length; 109 | if (wordCount.HasValue && wordCount > 0 && !ValidMnemonicSizes.Contains(wordCount.Value)) 110 | { 111 | validationErrors.Add( 112 | $"Invalid option --recovery-phrase must have the following word count ({string.Join(", ", ValidMnemonicSizes)})"); 113 | } 114 | 115 | return (!validationErrors.Any(), wordlist, validationErrors); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /Src/ConsoleTool/Wallet/DerivePaymentAddressCommand.cs: -------------------------------------------------------------------------------- 1 | using CardanoSharp.Wallet; 2 | using CardanoSharp.Wallet.Enums; 3 | using CardanoSharp.Wallet.Extensions.Models; 4 | using CardanoSharp.Wallet.Models.Addresses; 5 | using CardanoSharp.Wallet.Models.Keys; 6 | using static Cscli.ConsoleTool.Constants; 7 | 8 | namespace Cscli.ConsoleTool.Wallet; 9 | 10 | public class DerivePaymentAddressCommand : ICommand 11 | { 12 | public string? Mnemonic { get; init; } 13 | public string Language { get; init; } = DefaultMnemonicLanguage; 14 | public string Passphrase { get; init; } = string.Empty; 15 | public string? PaymentAddressType { get; init; } 16 | public int AccountIndex { get; init; } = 0; 17 | public int AddressIndex { get; init; } = 0; 18 | public int StakeAccountIndex { get; init; } = 0; 19 | public int StakeAddressIndex { get; init; } = 0; 20 | public string? Network { get; init; } 21 | 22 | public ValueTask ExecuteAsync(CancellationToken ct) 23 | { 24 | var (isValid, wordList, addressType, network, errors) = Validate(); 25 | if (!isValid) 26 | { 27 | return ValueTask.FromResult( 28 | CommandResult.FailureInvalidOptions(string.Join(Environment.NewLine, errors))); 29 | } 30 | 31 | var mnemonicService = new MnemonicService(); 32 | try 33 | { 34 | var rootKey = mnemonicService.Restore(Mnemonic, wordList) 35 | .GetRootKey(Passphrase); 36 | var address = GetPaymentAddress( 37 | addressType, rootKey, new AddressService(), network); 38 | return ValueTask.FromResult(CommandResult.Success(address.ToString())); 39 | } 40 | catch (ArgumentException ex) 41 | { 42 | return ValueTask.FromResult(CommandResult.FailureInvalidOptions(ex.Message)); 43 | } 44 | catch (Exception ex) 45 | { 46 | return ValueTask.FromResult( 47 | CommandResult.FailureUnhandledException("Unexpected error", ex)); 48 | } 49 | } 50 | 51 | private Address GetPaymentAddress( 52 | AddressType addressType, 53 | PrivateKey rootKey, 54 | IAddressService addressService, 55 | NetworkType networkType) => addressType switch 56 | { 57 | AddressType.Enterprise => addressService.GetEnterpriseAddress( 58 | rootKey.Derive($"m/1852'/1815'/{AccountIndex}'/0/{AddressIndex}").GetPublicKey(false), 59 | networkType), 60 | AddressType.Base => addressService.GetBaseAddress( 61 | rootKey.Derive($"m/1852'/1815'/{AccountIndex}'/0/{AddressIndex}").GetPublicKey(false), 62 | rootKey.Derive($"m/1852'/1815'/{StakeAccountIndex}'/2/{StakeAddressIndex}").GetPublicKey(false), 63 | networkType), 64 | _ => throw new NotImplementedException($"--payment-address-type not valid for {nameof(DerivePaymentAddressCommand)}") 65 | }; 66 | 67 | private ( 68 | bool isValid, 69 | WordLists derivedWordList, 70 | AddressType derivedAddressType, 71 | NetworkType derivedNetworkType, 72 | IReadOnlyCollection validationErrors) Validate() 73 | { 74 | var validationErrors = new List(); 75 | if (string.IsNullOrWhiteSpace(Mnemonic)) 76 | { 77 | validationErrors.Add( 78 | $"Invalid option --recovery-phrase is required"); 79 | } 80 | var wordCount = Mnemonic?.Split(' ', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries).Length; 81 | if (wordCount.HasValue && wordCount > 0 && !ValidMnemonicSizes.Contains(wordCount.Value)) 82 | { 83 | validationErrors.Add( 84 | $"Invalid option --recovery-phrase must have the following word count ({string.Join(", ", ValidMnemonicSizes)})"); 85 | } 86 | if (!Enum.TryParse(Language, ignoreCase: true, out var wordlist)) 87 | { 88 | validationErrors.Add( 89 | $"Invalid option --language {Language} is not supported"); 90 | } 91 | if (!Enum.TryParse(PaymentAddressType, ignoreCase: true, out var paymentAddressType) 92 | || paymentAddressType != AddressType.Base && paymentAddressType != AddressType.Enterprise) 93 | { 94 | validationErrors.Add( 95 | $"Invalid option --payment-address-type {PaymentAddressType} is not supported"); 96 | } 97 | if (AccountIndex < 0 || AccountIndex > MaxDerivationPathIndex) 98 | { 99 | validationErrors.Add( 100 | $"Invalid option --account-index must be between 0 and {MaxDerivationPathIndex}"); 101 | } 102 | if (AddressIndex < 0 || AddressIndex > MaxDerivationPathIndex) 103 | { 104 | validationErrors.Add( 105 | $"Invalid option --address-index must be between 0 and {MaxDerivationPathIndex}"); 106 | } 107 | if (StakeAccountIndex < 0 || StakeAccountIndex > MaxDerivationPathIndex) 108 | { 109 | validationErrors.Add( 110 | $"Invalid option --stake-account-index must be between 0 and {MaxDerivationPathIndex}"); 111 | } 112 | if (StakeAddressIndex < 0 || StakeAddressIndex > MaxDerivationPathIndex) 113 | { 114 | validationErrors.Add( 115 | $"Invalid option --stake-address-index must be between 0 and {MaxDerivationPathIndex}"); 116 | } 117 | if (!Enum.TryParse(Network, ignoreCase: true, out var networkType)) 118 | { 119 | validationErrors.Add( 120 | $"Invalid option --network must be either testnet or mainnet"); 121 | } 122 | return (!validationErrors.Any(), wordlist, paymentAddressType, networkType, validationErrors); 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /Src/ConsoleTool/Wallet/DerivePaymentKeyCommand.cs: -------------------------------------------------------------------------------- 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.Wallet; 9 | 10 | public class DerivePaymentKeyCommand : ICommand 11 | { 12 | public string? Mnemonic { get; init; } 13 | public string Language { get; init; } = DefaultMnemonicLanguage; 14 | public string Passphrase { get; init; } = string.Empty; 15 | public int AccountIndex { get; init; } = 0; 16 | public int AddressIndex { get; init; } = 0; 17 | public string? VerificationKeyFile { get; init; } = null; 18 | public string? SigningKeyFile { get; init; } = null; 19 | 20 | public async ValueTask 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 rootPrvKey = mnemonicService.Restore(Mnemonic, wordList) 33 | .GetRootKey(Passphrase); 34 | var paymentSkey = rootPrvKey.Derive($"m/1852'/1815'/{AccountIndex}'/0/{AddressIndex}"); 35 | var paymentVkey = paymentSkey.GetPublicKey(false); 36 | var paymentSkeyExtendedBytes = paymentSkey.BuildExtendedSkeyBytes(); 37 | var bech32PaymentSkeyExtended = Bech32.Encode(paymentSkeyExtendedBytes, PaymentExtendedSigningKeyBech32Prefix); 38 | var result = CommandResult.Success(bech32PaymentSkeyExtended); 39 | // Write output to CBOR JSON file outputs if optional file paths are supplied 40 | if (!string.IsNullOrWhiteSpace(SigningKeyFile)) 41 | { 42 | var skeyCbor = new TextEnvelope( 43 | PaymentExtendedSKeyJsonTypeField, 44 | PaymentSKeyJsonDescriptionField, 45 | KeyUtils.BuildCborHexPayload(paymentSkey.BuildExtendedSkeyWithVerificationKeyBytes())); 46 | await File.WriteAllTextAsync(SigningKeyFile, JsonSerializer.Serialize(skeyCbor, SerialiserOptions), ct).ConfigureAwait(false); 47 | } 48 | if (!string.IsNullOrWhiteSpace(VerificationKeyFile)) 49 | { 50 | var vkeyCbor = new TextEnvelope( 51 | PaymentExtendedVKeyJsonTypeField, 52 | PaymentVKeyJsonDescriptionField, 53 | KeyUtils.BuildCborHexPayload(paymentVkey.BuildExtendedVkeyBytes())); 54 | await File.WriteAllTextAsync(VerificationKeyFile, JsonSerializer.Serialize(vkeyCbor, SerialiserOptions), ct).ConfigureAwait(false); 55 | } 56 | return result; 57 | } 58 | catch (ArgumentException ex) 59 | { 60 | return CommandResult.FailureInvalidOptions(ex.Message); 61 | } 62 | catch (Exception ex) 63 | { 64 | return CommandResult.FailureUnhandledException("Unexpected error", ex); 65 | } 66 | } 67 | 68 | private ( 69 | bool isValid, 70 | WordLists wordList, 71 | IReadOnlyCollection validationErrors) Validate() 72 | { 73 | var validationErrors = new List(); 74 | if (string.IsNullOrWhiteSpace(Mnemonic)) 75 | { 76 | validationErrors.Add( 77 | $"Invalid option --recovery-phrase is required"); 78 | } 79 | if (AccountIndex < 0 || AccountIndex > MaxDerivationPathIndex) 80 | { 81 | validationErrors.Add( 82 | $"Invalid option --account-index must be between 0 and {MaxDerivationPathIndex}"); 83 | } 84 | if (AddressIndex < 0 || AddressIndex > MaxDerivationPathIndex) 85 | { 86 | validationErrors.Add( 87 | $"Invalid option --address-index must be between 0 and {MaxDerivationPathIndex}"); 88 | } 89 | if (!string.IsNullOrWhiteSpace(SigningKeyFile) 90 | && Path.IsPathFullyQualified(SigningKeyFile) 91 | && !Directory.Exists(Path.GetDirectoryName(SigningKeyFile))) 92 | { 93 | validationErrors.Add( 94 | $"Invalid option --signing-key-file path {SigningKeyFile} does not exist"); 95 | } 96 | if (!string.IsNullOrWhiteSpace(VerificationKeyFile) 97 | && Path.IsPathFullyQualified(VerificationKeyFile) 98 | && !Directory.Exists(Path.GetDirectoryName(VerificationKeyFile))) 99 | { 100 | validationErrors.Add( 101 | $"Invalid option --verification-key-file path {VerificationKeyFile} does not exist"); 102 | } 103 | if (!Enum.TryParse(Language, ignoreCase: true, out var wordlist)) 104 | { 105 | validationErrors.Add( 106 | $"Invalid option --language {Language} is not supported"); 107 | } 108 | var wordCount = Mnemonic?.Split(' ', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries).Length; 109 | if (wordCount.HasValue && wordCount > 0 && !ValidMnemonicSizes.Contains(wordCount.Value)) 110 | { 111 | validationErrors.Add( 112 | $"Invalid option --recovery-phrase must have the following word count ({string.Join(", ", ValidMnemonicSizes)})"); 113 | } 114 | 115 | return (!validationErrors.Any(), wordlist, validationErrors); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /Src/ConsoleTool/Wallet/DerivePolicyKeyCommand.cs: -------------------------------------------------------------------------------- 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.Wallet; 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 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 validationErrors) Validate() 71 | { 72 | var validationErrors = new List(); 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(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 | } 112 | -------------------------------------------------------------------------------- /Src/ConsoleTool/Wallet/DeriveRootKeyCommand.cs: -------------------------------------------------------------------------------- 1 | using CardanoSharp.Wallet; 2 | using CardanoSharp.Wallet.Encoding; 3 | using CardanoSharp.Wallet.Enums; 4 | using CardanoSharp.Wallet.Extensions.Models; 5 | using static Cscli.ConsoleTool.Constants; 6 | 7 | namespace Cscli.ConsoleTool.Wallet; 8 | 9 | public class DeriveRootKeyCommand : ICommand 10 | { 11 | public string? Mnemonic { get; init; } 12 | public string Language { get; init; } = DefaultMnemonicLanguage; 13 | public string Passphrase { get; init; } = string.Empty; 14 | 15 | public ValueTask ExecuteAsync(CancellationToken ct) 16 | { 17 | if (string.IsNullOrWhiteSpace(Mnemonic)) 18 | { 19 | return ValueTask.FromResult(CommandResult.FailureInvalidOptions( 20 | $"Invalid option --recovery-phrase is required")); 21 | } 22 | if (!Enum.TryParse(Language, ignoreCase: true, out var wordlist)) 23 | { 24 | return ValueTask.FromResult(CommandResult.FailureInvalidOptions( 25 | $"Invalid option --language {Language} is not supported")); 26 | } 27 | var wordCount = Mnemonic.Split(' ', StringSplitOptions.TrimEntries).Length; 28 | if (!ValidMnemonicSizes.Contains(wordCount)) 29 | { 30 | return ValueTask.FromResult(CommandResult.FailureInvalidOptions( 31 | $"Invalid option --recovery-phrase must have the following word count ({string.Join(", ", ValidMnemonicSizes)})")); 32 | } 33 | 34 | var mnemonicService = new MnemonicService(); 35 | try 36 | { 37 | var rootPrvKey = mnemonicService.Restore(Mnemonic, wordlist) 38 | .GetRootKey(Passphrase); 39 | var rootKeyExtendedBytes = rootPrvKey.BuildExtendedSkeyBytes(); 40 | var bech32ExtendedRootKey = Bech32.Encode(rootKeyExtendedBytes, RootExtendedSigningKeyBech32Prefix); 41 | return ValueTask.FromResult(CommandResult.Success(bech32ExtendedRootKey)); 42 | } 43 | catch (ArgumentException ex) 44 | { 45 | return ValueTask.FromResult( 46 | CommandResult.FailureInvalidOptions(ex.Message)); 47 | } 48 | catch (Exception ex) 49 | { 50 | return ValueTask.FromResult( 51 | CommandResult.FailureUnhandledException("Unexpected error", ex)); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Src/ConsoleTool/Wallet/DeriveStakeAddressCommand.cs: -------------------------------------------------------------------------------- 1 | using CardanoSharp.Wallet; 2 | using CardanoSharp.Wallet.Enums; 3 | using CardanoSharp.Wallet.Extensions.Models; 4 | using static Cscli.ConsoleTool.Constants; 5 | 6 | namespace Cscli.ConsoleTool.Wallet; 7 | 8 | public class DeriveStakeAddressCommand : ICommand 9 | { 10 | public string? Mnemonic { get; init; } 11 | public string Language { get; init; } = DefaultMnemonicLanguage; 12 | public string Passphrase { get; init; } = string.Empty; 13 | public int AccountIndex { get; init; } = 0; 14 | public int AddressIndex { get; init; } = 0; 15 | public string? Network { get; init; } 16 | 17 | public ValueTask ExecuteAsync(CancellationToken ct) 18 | { 19 | var (isValid, wordList, network, errors) = Validate(); 20 | if (!isValid) 21 | { 22 | return ValueTask.FromResult( 23 | CommandResult.FailureInvalidOptions(string.Join(Environment.NewLine, errors))); 24 | } 25 | 26 | var mnemonicService = new MnemonicService(); 27 | var addressService = new AddressService(); 28 | try 29 | { 30 | var rootPrvKey = mnemonicService.Restore(Mnemonic, wordList) 31 | .GetRootKey(Passphrase); 32 | var stakeVkey = rootPrvKey.Derive($"m/1852'/1815'/{AccountIndex}'/2/{AddressIndex}") 33 | .GetPublicKey(false); 34 | var stakeAddr = addressService.GetRewardAddress(stakeVkey, network); 35 | return ValueTask.FromResult(CommandResult.Success(stakeAddr.ToString())); 36 | } 37 | catch (ArgumentException ex) 38 | { 39 | return ValueTask.FromResult(CommandResult.FailureInvalidOptions(ex.Message)); 40 | } 41 | catch (Exception ex) 42 | { 43 | return ValueTask.FromResult( 44 | CommandResult.FailureUnhandledException("Unexpected error", ex)); 45 | } 46 | } 47 | 48 | private ( 49 | bool isValid, 50 | WordLists derivedWordList, 51 | NetworkType derivedNetworkType, 52 | IReadOnlyCollection validationErrors) Validate() 53 | { 54 | var validationErrors = new List(); 55 | if (string.IsNullOrWhiteSpace(Mnemonic)) 56 | { 57 | validationErrors.Add( 58 | $"Invalid option --recovery-phrase is required"); 59 | } 60 | var wordCount = Mnemonic?.Split(' ', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries).Length; 61 | if (wordCount.HasValue && wordCount > 0 && !ValidMnemonicSizes.Contains(wordCount.Value)) 62 | { 63 | validationErrors.Add( 64 | $"Invalid option --recovery-phrase must have the following word count ({string.Join(", ", ValidMnemonicSizes)})"); 65 | } 66 | if (!Enum.TryParse(Language, ignoreCase: true, out var wordlist)) 67 | { 68 | validationErrors.Add( 69 | $"Invalid option --language {Language} is not supported"); 70 | } 71 | if (AccountIndex < 0 || AccountIndex > MaxDerivationPathIndex) 72 | { 73 | validationErrors.Add( 74 | $"Invalid option --account-index must be between 0 and {MaxDerivationPathIndex}"); 75 | } 76 | if (AddressIndex < 0 || AddressIndex > MaxDerivationPathIndex) 77 | { 78 | validationErrors.Add( 79 | $"Invalid option --address-index must be between 0 and {MaxDerivationPathIndex}"); 80 | } 81 | if (!Enum.TryParse(Network, ignoreCase: true, out var networkType)) 82 | { 83 | validationErrors.Add( 84 | $"Invalid option --network must be either testnet or mainnet"); 85 | } 86 | return (!validationErrors.Any(), wordlist, networkType, validationErrors); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /Src/ConsoleTool/Wallet/DeriveStakeKeyCommand.cs: -------------------------------------------------------------------------------- 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.Wallet; 9 | 10 | public class DeriveStakeKeyCommand : ICommand 11 | { 12 | public string? Mnemonic { get; init; } 13 | public string Language { get; init; } = DefaultMnemonicLanguage; 14 | public string Passphrase { get; init; } = string.Empty; 15 | public int AccountIndex { get; init; } = 0; 16 | public int AddressIndex { get; init; } = 0; 17 | public string? VerificationKeyFile { get; init; } = null; 18 | public string? SigningKeyFile { get; init; } = null; 19 | 20 | public async ValueTask ExecuteAsync(CancellationToken ct) 21 | { 22 | var (isValid, derivedWorldList, 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, derivedWorldList) 33 | .GetRootKey(Passphrase); 34 | var stakeSkey = rootKey.Derive($"m/1852'/1815'/{AccountIndex}'/2/{AddressIndex}"); 35 | var stakeVkey = stakeSkey.GetPublicKey(false); 36 | var stakeSkeyExtendedBytes = stakeSkey.BuildExtendedSkeyBytes(); 37 | var bech32StakeSkeyExtended = Bech32.Encode(stakeSkeyExtendedBytes, StakeExtendedSigningKeyBech32Prefix); 38 | var result = CommandResult.Success(bech32StakeSkeyExtended); 39 | // Write output to CBOR JSON file outputs if optional file paths are supplied 40 | if (!string.IsNullOrWhiteSpace(SigningKeyFile)) 41 | { 42 | var skeyCbor = new TextEnvelope( 43 | StakeExtendedSKeyJsonTypeField, 44 | StakeSKeyJsonDescriptionField, 45 | KeyUtils.BuildCborHexPayload(stakeSkey.BuildExtendedSkeyWithVerificationKeyBytes())); 46 | await File.WriteAllTextAsync(SigningKeyFile, JsonSerializer.Serialize(skeyCbor, SerialiserOptions), ct).ConfigureAwait(false); 47 | } 48 | if (!string.IsNullOrWhiteSpace(VerificationKeyFile)) 49 | { 50 | // cardano-cli compatibility requires us to use non-extended verification keys 51 | var vkeyCbor = new TextEnvelope( 52 | StakeVKeyJsonTypeField, 53 | StakeVKeyJsonDescriptionField, 54 | KeyUtils.BuildCborHexPayload(stakeVkey.Key)); 55 | await File.WriteAllTextAsync(VerificationKeyFile, JsonSerializer.Serialize(vkeyCbor, SerialiserOptions), ct).ConfigureAwait(false); 56 | } 57 | return result; 58 | } 59 | catch (ArgumentException ex) 60 | { 61 | return CommandResult.FailureInvalidOptions(ex.Message); 62 | } 63 | catch (Exception ex) 64 | { 65 | return CommandResult.FailureUnhandledException("Unexpected error", ex); 66 | } 67 | } 68 | 69 | private ( 70 | bool isValid, 71 | WordLists derivedWordList, 72 | IReadOnlyCollection validationErrors) Validate() 73 | { 74 | var validationErrors = new List(); 75 | if (string.IsNullOrWhiteSpace(Mnemonic)) 76 | { 77 | validationErrors.Add( 78 | $"Invalid option --recovery-phrase is required"); 79 | } 80 | if (AccountIndex < 0 || AccountIndex > MaxDerivationPathIndex) 81 | { 82 | validationErrors.Add( 83 | $"Invalid option --account-index must be between 0 and {MaxDerivationPathIndex}"); 84 | } 85 | if (AddressIndex < 0 || AddressIndex > MaxDerivationPathIndex) 86 | { 87 | validationErrors.Add( 88 | $"Invalid option --address-index must be between 0 and {MaxDerivationPathIndex}"); 89 | } 90 | if (!string.IsNullOrWhiteSpace(SigningKeyFile) 91 | && Path.IsPathFullyQualified(SigningKeyFile) 92 | && !Directory.Exists(Path.GetDirectoryName(SigningKeyFile))) 93 | { 94 | validationErrors.Add( 95 | $"Invalid option --signing-key-file path {SigningKeyFile} does not exist"); 96 | } 97 | if (!string.IsNullOrWhiteSpace(VerificationKeyFile) 98 | && Path.IsPathFullyQualified(VerificationKeyFile) 99 | && !Directory.Exists(Path.GetDirectoryName(VerificationKeyFile))) 100 | { 101 | validationErrors.Add( 102 | $"Invalid option --verification-key-file path {VerificationKeyFile} does not exist"); 103 | } 104 | if (!Enum.TryParse(Language, ignoreCase: true, out var wordlist)) 105 | { 106 | validationErrors.Add( 107 | $"Invalid option --language {Language} is not supported"); 108 | } 109 | var wordCount = Mnemonic?.Split(' ', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries).Length; 110 | if (wordCount.HasValue && wordCount > 0 && !ValidMnemonicSizes.Contains(wordCount.Value)) 111 | { 112 | validationErrors.Add( 113 | $"Invalid option --recovery-phrase must have the following word count ({string.Join(", ", ValidMnemonicSizes)})"); 114 | } 115 | 116 | return (!validationErrors.Any(), wordlist, validationErrors); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /Src/ConsoleTool/Wallet/GenerateMnemonicCommand.cs: -------------------------------------------------------------------------------- 1 | using CardanoSharp.Wallet; 2 | using CardanoSharp.Wallet.Enums; 3 | using static Cscli.ConsoleTool.Constants; 4 | 5 | namespace Cscli.ConsoleTool.Wallet; 6 | 7 | public class GenerateMnemonicCommand : ICommand 8 | { 9 | public int Size { get; init; } = DefaultMnemonicCount; 10 | public string Language { get; init; } = DefaultMnemonicLanguage; 11 | 12 | public ValueTask ExecuteAsync(CancellationToken ct) 13 | { 14 | if (!ValidMnemonicSizes.Contains(Size)) 15 | { 16 | return ValueTask.FromResult(CommandResult.FailureInvalidOptions( 17 | $"Invalid option --size {Size} is not supported")); 18 | } 19 | if (!Enum.TryParse(Language, ignoreCase: true, out var wordlist)) 20 | { 21 | return ValueTask.FromResult(CommandResult.FailureInvalidOptions( 22 | $"Invalid option --language {Language} is not supported")); 23 | } 24 | 25 | var mnemonicService = new MnemonicService(); 26 | try 27 | { 28 | var mnemonic = mnemonicService.Generate(Size, wordlist); 29 | var wordsResult = CommandResult.Success(mnemonic.Words); 30 | return ValueTask.FromResult(wordsResult); 31 | } 32 | catch (Exception ex) 33 | { 34 | return ValueTask.FromResult( 35 | CommandResult.FailureUnhandledException("Unexpected error", ex)); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Tests/ConsoleTool.UnitTests/ConvertVerificationKeyCommandShould.cs: -------------------------------------------------------------------------------- 1 | using Cscli.ConsoleTool.Wallet; 2 | using FluentAssertions; 3 | using Xunit; 4 | 5 | namespace Cscli.ConsoleTool.UnitTests; 6 | 7 | public class ConvertVerificationKeyCommandShould 8 | { 9 | [Theory] 10 | [InlineData(null)] 11 | [InlineData("")] 12 | [InlineData(" ")] 13 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Mnemonic_Is_Not_Supplied( 14 | string invalidSigningKey) 15 | { 16 | var command = new ConvertVerificationKeyCommand() 17 | { 18 | SigningKey = invalidSigningKey 19 | }; 20 | 21 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 22 | 23 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 24 | executionResult.Result.Should().Be("Invalid option --sigining-key is required"); 25 | } 26 | 27 | [Theory] 28 | [InlineData("KxFC1jmwwCoACiCAWZ3eXa96mBM6tb3TYzGmf6YwgdGWZgawvrtJ")] 29 | [InlineData("1E99423A4ED27608A15A2616A2B0E9E52CED330AC530EDCC32C8FFC6A526AEDD")] 30 | [InlineData("0x983110309620D911731Ac0932219af06091b6744")] 31 | [InlineData("some_sk1aaa3shjrd4gy70q4m2ejgjgsdzwej4whc4r2trrcwedlpm6z4dglxl4nycrd8fptxrkye3tl3q29euxlqj7zndk9cfg4tskqlnp90uqwjqz02")] 32 | [InlineData("addr_xsk1fzw9r482t0ekua7rcqewg3k8ju5d9run4juuehm2p24jtuzz4dg4wpeulnqhualvtx9lyy7u0h9pdjvmyhxdhzsyy49szs6y8c9zwfp0eqyrqyl290e6dr0q3fvngmsjn4aask9jjr6q34juh25hczw3euust000")] 33 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_SigningKey_Is_Not_Valid_Bech32( 34 | string invalidSigningKey) 35 | { 36 | var command = new ConvertVerificationKeyCommand() 37 | { 38 | SigningKey = invalidSigningKey 39 | }; 40 | 41 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 42 | 43 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 44 | executionResult.Result.Should().Be("Invalid option --sigining-key is not in bech32 format - please see https://cips.cardano.org/cips/cip5/"); 45 | } 46 | 47 | [Theory] 48 | [InlineData("addr_test1qpvttg5263dnutj749k5dcr35yk5mr94fxx0q2zs2xeuxq5hvcrpf2ezgxucdwcjytcrww34j5y609ss4sfpptg3uvpsxmcdtf", "addr_test")] 49 | [InlineData("addr1vy5zuhh9685fup86syuzmu3e6eengzv8t46mfqxg086cvqqrukl6w", "addr")] 50 | [InlineData("stake_test1uztkvps54v3yrwvxhvfz9uph8g6e2zd8jcg2cyss45g7xqclj4scq", "stake_test")] 51 | [InlineData("stake1u9wqktpz964g6jaemt5wr5tspy9cqxpdkw98d022d85kxxc2n2yxj", "stake")] 52 | [InlineData("addr_xvk1m62sxsn8t8apscjx2l6mejfj7wpzpmy7e6ex9yru4uk3nzmwp74zljqgxqf752ln56x7pzjex3hp98tmmpvt9y85prt9ew4f0syarncveq5jl", "addr_xvk")] 53 | [InlineData("policy_vk17s29wgt93lj3m830qhlpx8rx5shwmtljhdswdjyjetprhu5yaahqwzt9lc", "policy_vk")] 54 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_SigningKey_Is_Not_Supported( 55 | string invalidSigningKey, string derivedPrefix) 56 | { 57 | var command = new ConvertVerificationKeyCommand() 58 | { 59 | SigningKey = invalidSigningKey 60 | }; 61 | 62 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 63 | 64 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 65 | executionResult.Result.Should().Be($"Invalid option --sigining-key with prefix '{derivedPrefix}' is not supported"); 66 | } 67 | 68 | [Theory] 69 | [InlineData("addr_xsk1fzw9r482t0ekua7rcqewg3k8ju5d9run4juuehm2p24jtuzz4dg4wpeulnqhualvtx9lyy7u0h9pdjvmyhxdhzsyy49szs6y8c9zwfp0eqyrqyl290e6dr0q3fvngmsjn4aask9jjr6q34juh25hczw3euust0dw", "addr_xvk1m62sxsn8t8apscjx2l6mejfj7wpzpmy7e6ex9yru4uk3nzmwp74zljqgxqf752ln56x7pzjex3hp98tmmpvt9y85prt9ew4f0syarncveq5jl")] 70 | [InlineData("stake_xsk1xr5c8423vymrfvrqz58wqqtpekg8cl2s7zvuedeass77emzz4dgs32nfp944ljxw86h7wkxcrut8gr8qmql8gvc9slc8nj9x47a6jtaqqxf9ywd4wfhrzv4c54vcjp827fytdzrxs3gdh5f0a0s7hcf8a5e4ay8g", "stake_xvk1r0v9a3ca9kxwqxqp8qcsnqa2llaytp2gdkc4w67rskc2udg9vtn2qqvj2gum2unwxyet3f2e3yzw4ujgk6yxdpzsm0gjl6lpa0sj0mg4tq9sj")] 71 | [InlineData("policy_sk1trt3shjrd4gy70q4m2ejgjgsdzwej4whc4r2trrcwedlpm6z4dglxl4nycrd8fptxrkye3tl3q29euxlqj7zndk9cfg4tskqlnp90uqwjqz02", "policy_vk17s29wgt93lj3m830qhlpx8rx5shwmtljhdswdjyjetprhu5yaahqwzt9lc")] 72 | public async Task Execute_Successfully_With_Correct_Public_Verification_Key_When_Signing_Key_Is_Supported( 73 | string signingKey, string expectedVerificationKey) 74 | { 75 | var command = new ConvertVerificationKeyCommand() 76 | { 77 | SigningKey = signingKey 78 | }; 79 | 80 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 81 | 82 | executionResult.Outcome.Should().Be(CommandOutcome.Success); 83 | executionResult.Result.Should().Be(expectedVerificationKey); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /Tests/ConsoleTool.UnitTests/Cscli.ConsoleTool.UnitTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | enable 8 | false 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | runtime; build; native; contentfiles; analyzers; buildtransitive 17 | all 18 | 19 | 20 | runtime; build; native; contentfiles; analyzers; buildtransitive 21 | all 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /Tests/ConsoleTool.UnitTests/DecodeBech32CommandShould.cs: -------------------------------------------------------------------------------- 1 | using Cscli.ConsoleTool.Crypto; 2 | using FluentAssertions; 3 | using Xunit; 4 | 5 | namespace Cscli.ConsoleTool.UnitTests; 6 | 7 | public class DecodeBech32CommandShould 8 | { 9 | [Theory] 10 | [InlineData( 11 | "addr1qx2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer3n0d3vllmyqwsx5wktcd8cc3sq835lu7drv2xwl2wywfgse35a3x", 12 | "019493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8e337b62cfff6403a06a3acbc34f8c46003c69fe79a3628cefa9c47251")] 13 | [InlineData( 14 | "addr1z8phkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gten0d3vllmyqwsx5wktcd8cc3sq835lu7drv2xwl2wywfgs9yc0hh", 15 | "11c37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f337b62cfff6403a06a3acbc34f8c46003c69fe79a3628cefa9c47251")] 16 | [InlineData( 17 | "addr1yx2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzerkr0vd4msrxnuwnccdxlhdjar77j6lg0wypcc9uar5d2shs2z78ve", 18 | "219493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8ec37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f")] 19 | [InlineData( 20 | "addr1x8phkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gt7r0vd4msrxnuwnccdxlhdjar77j6lg0wypcc9uar5d2shskhj42g", 21 | "31c37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542fc37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f")] 22 | [InlineData("addr1gx2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer5pnz75xxcrzqf96k", 23 | "419493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8e8198bd431b03")] 24 | [InlineData("addr128phkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtupnz75xxcrtw79hu", 25 | "51c37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f8198bd431b03")] 26 | [InlineData("addr1vx2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzers66hrl8", 27 | "619493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8e")] 28 | [InlineData("addr1w8phkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtcyjy7wx", 29 | "71c37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f")] 30 | [InlineData("stake1uyehkck0lajq8gr28t9uxnuvgcqrc6070x3k9r8048z8y5gh6ffgw", 31 | "e1337b62cfff6403a06a3acbc34f8c46003c69fe79a3628cefa9c47251")] 32 | [InlineData("stake178phkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtcccycj5", 33 | "f1c37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f")] 34 | [InlineData( 35 | "addr_test1qz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer3n0d3vllmyqwsx5wktcd8cc3sq835lu7drv2xwl2wywfgs68faae", 36 | "009493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8e337b62cfff6403a06a3acbc34f8c46003c69fe79a3628cefa9c47251")] 37 | [InlineData( 38 | "addr_test1zrphkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gten0d3vllmyqwsx5wktcd8cc3sq835lu7drv2xwl2wywfgsxj90mg", 39 | "10c37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f337b62cfff6403a06a3acbc34f8c46003c69fe79a3628cefa9c47251")] 40 | [InlineData( 41 | "addr_test1yz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzerkr0vd4msrxnuwnccdxlhdjar77j6lg0wypcc9uar5d2shsf5r8qx", 42 | "209493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8ec37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f")] 43 | [InlineData( 44 | "addr_test1xrphkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gt7r0vd4msrxnuwnccdxlhdjar77j6lg0wypcc9uar5d2shs4p04xh", 45 | "30c37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542fc37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f")] 46 | [InlineData("addr_test1gz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer5pnz75xxcrdw5vky", 47 | "409493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8e8198bd431b03")] 48 | [InlineData("addr_test12rphkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtupnz75xxcryqrvmw", 49 | "50c37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f8198bd431b03")] 50 | [InlineData("addr_test1vz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzerspjrlsz", 51 | "609493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8e")] 52 | [InlineData("addr_test1wrphkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtcl6szpr", 53 | "70c37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f")] 54 | [InlineData("stake_test1uqehkck0lajq8gr28t9uxnuvgcqrc6070x3k9r8048z8y5gssrtvn", 55 | "e0337b62cfff6403a06a3acbc34f8c46003c69fe79a3628cefa9c47251")] 56 | [InlineData("stake_test17rphkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtcljw6kf", 57 | "f0c37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f")] 58 | public async Task Execute_Successfully_With_Bech_Decoding_When_Properties_Are_Valid(string value, string expectedHex) 59 | { 60 | var command = new DecodeBech32Command() 61 | { 62 | Value = value 63 | }; 64 | 65 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 66 | 67 | executionResult.Outcome.Should().Be(CommandOutcome.Success); 68 | executionResult.Result.Should().Be(expectedHex); 69 | } 70 | 71 | [Theory] 72 | [InlineData( 73 | "root_xsk12qpr53a6r7dpjpu2mr6zh96vp4whx2td4zccmplq3am6ph6z4dga6td8nph4qpcnlkdcjkd96p83t23mplvh2w42n6yc3urav8qgph3d9az6lc0px7xq7sau4r4dsfp9h0syfkhge8e6muhd69vz9j6fggdhgd4e", 74 | "50023a47ba1f9a19078ad8f42b974c0d5d73296da8b18d87e08f77a0df42ab51dd2da7986f500713fd9b8959a5d04f15aa3b0fd9753aaa9e8988f07d61c080de2d2f45afe1e1378c0f43bca8ead82425bbe044dae8c9f3adf2edd15822cb4942")] 75 | [InlineData( 76 | "addr_xsk1fzw9r482t0ekua7rcqewg3k8ju5d9run4juuehm2p24jtuzz4dg4wpeulnqhualvtx9lyy7u0h9pdjvmyhxdhzsyy49szs6y8c9zwfp0eqyrqyl290e6dr0q3fvngmsjn4aask9jjr6q34juh25hczw3euust0dw", 77 | "489c51d4ea5bf36e77c3c032e446c79728d28f93acb9ccdf6a0aab25f042ab5157073cfcc17e77ec598bf213dc7dca16c99b25ccdb8a04254b0143443e0a27242fc8083013ea2bf3a68de08a59346e129d7bd858b290f408d65cbaa97c09d1cf")] 78 | [InlineData( 79 | "stake_xsk1xr5c8423vymrfvrqz58wqqtpekg8cl2s7zvuedeass77emzz4dgs32nfp944ljxw86h7wkxcrut8gr8qmql8gvc9slc8nj9x47a6jtaqqxf9ywd4wfhrzv4c54vcjp827fytdzrxs3gdh5f0a0s7hcf8a5e4ay8g", 80 | "30e983d551613634b060150ee00161cd907c7d50f099ccb73d843decec42ab5108aa69096b5fc8ce3eafe758d81f16740ce0d83e74330587f079c8a6afbba92fa001925239b5726e3132b8a5598904eaf248b688668450dbd12febe1ebe127ed")] 81 | public async Task Execute_Successfully_With_Bech32_Decoding_When_Properties_Are_Valid(string value, string expectedHex) 82 | { 83 | var command = new DecodeBech32Command() 84 | { 85 | Value = value 86 | }; 87 | 88 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 89 | 90 | executionResult.Outcome.Should().Be(CommandOutcome.Success); 91 | executionResult.Result.Should().Be(expectedHex); 92 | } 93 | 94 | [Theory] 95 | [InlineData("")] 96 | [InlineData(null)] 97 | [InlineData("this is not a valid address")] 98 | [InlineData("addr_fake1yz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzerkr0vd4msrxnuwnccdxlhdjar77j6lg0wypcc9uar5d2shsf5r8qx")] 99 | public async Task Fail_With_Bech_Decoding_When_Properities_Are_Invalid(string value) 100 | { 101 | var command = new DecodeBech32Command() 102 | { 103 | Value = value 104 | }; 105 | 106 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 107 | 108 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 109 | } 110 | } -------------------------------------------------------------------------------- /Tests/ConsoleTool.UnitTests/DeriveRootKeyCommandShould.cs: -------------------------------------------------------------------------------- 1 | using Cscli.ConsoleTool.Wallet; 2 | using FluentAssertions; 3 | using Xunit; 4 | 5 | namespace Cscli.ConsoleTool.UnitTests; 6 | 7 | public class DeriveRootKeyCommandShould 8 | { 9 | [Theory] 10 | [InlineData("English", null)] 11 | [InlineData("English", "")] 12 | [InlineData("Spanish", null)] 13 | [InlineData("Spanish", "")] 14 | [InlineData("Japanese", null)] 15 | [InlineData("Japanese", "")] 16 | [InlineData("ChineseSimplified", null)] 17 | [InlineData("ChineseSimplified", "")] 18 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Mnemonic_Is_Not_Supplied( 19 | string language, string mnemonic) 20 | { 21 | var command = new DeriveRootKeyCommand() 22 | { 23 | Mnemonic = mnemonic, 24 | Language = language, 25 | }; 26 | 27 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 28 | 29 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 30 | executionResult.Result.Should().Be("Invalid option --recovery-phrase is required"); 31 | } 32 | 33 | [Theory] 34 | [InlineData("English", "shoe")] 35 | [InlineData("English", "baby laundry")] 36 | [InlineData("English", "gloom fatigue little")] 37 | [InlineData("English", "learn venue harvest fossil")] 38 | [InlineData("English", "daring please route manual orphan")] 39 | [InlineData("English", "once phrase win hawk before observe")] 40 | [InlineData("English", "anchor elite rare young flash chaos loop")] 41 | [InlineData("English", "salon expand attack move drip amateur second machine")] 42 | [InlineData("English", "script scale minute dial radar tissue spray another bubble benefit")] 43 | [InlineData("English", "eternal coin garment topic flag waste arch hobby tube great laptop donate lottery chief parade junior surge fortune zebra runway obey physical unknown logic fence")] 44 | [InlineData("Spanish", "bello")] 45 | [InlineData("Japanese", "なれる")] 46 | [InlineData("Italian", "fuggente")] 47 | [InlineData("ChineseSimplified", "厉")] 48 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Mnemonic_Is_Not_Of_Valid_Length( 49 | string language, string mnemonic) 50 | { 51 | var command = new DeriveRootKeyCommand() 52 | { 53 | Mnemonic = mnemonic, 54 | Language = language, 55 | }; 56 | 57 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 58 | 59 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 60 | executionResult.Result.Should().Be("Invalid option --recovery-phrase must have the following word count (9, 12, 15, 18, 21, 24)"); 61 | } 62 | 63 | [Theory] 64 | [InlineData("invalid", "shoe follow blossom remain learn venue harvest fossil found")] 65 | [InlineData("Australian", "shoe follow blossom remain learn venue harvest fossil found")] 66 | [InlineData("en-GB", "shoe follow blossom remain learn venue harvest fossil found")] 67 | [InlineData("Klingon", "shoe follow blossom remain learn venue harvest fossil found")] 68 | [InlineData("aenglish", "rapid limit bicycle embrace speak column spoil casino become evolve unknown worry letter team laptop unknown false elbow bench analyst dilemma engage pulse plug")] 69 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Language_Is_Not_Supported( 70 | string language, string mnemonic) 71 | { 72 | var command = new DeriveRootKeyCommand() 73 | { 74 | Mnemonic = mnemonic, 75 | Language = language, 76 | }; 77 | 78 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 79 | 80 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 81 | executionResult.Result.Should().Be($"Invalid option --language {language} is not supported"); 82 | } 83 | 84 | [Theory] 85 | [InlineData("English", "dueño misil favor koala pudor aplicar guitarra fracaso talar")] 86 | [InlineData("Spanish", "rapid limit bicycle embrace speak column spoil casino become evolve unknown worry letter team laptop unknown false elbow bench analyst dilemma engage pulse plug")] 87 | [InlineData("Japanese", "exigente pioneiro garrafa tarja genial dominado aclive tradutor fretar")] 88 | [InlineData("Italian", "りけん ぞんび こんすい たまる めだつ すんぽう つまらない せつりつ けんない")] 89 | [InlineData("French", "趋 富 吸 献 树 吾 秒 举 火 侦 佛 疑 机 察 统")] 90 | [InlineData("ChineseSimplified", "danseur prouesse sauvage exquis cirque endosser saumon cintrer ratisser rompre pièce achat opinion cloporte orageux")] 91 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Words_Are_Invalid_For_Language_Word_List( 92 | string language, string mnemonic) 93 | { 94 | var command = new DeriveRootKeyCommand() 95 | { 96 | Mnemonic = mnemonic, 97 | Language = language, 98 | }; 99 | 100 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 101 | 102 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 103 | executionResult.Result.Should().Contain("invalid words"); 104 | } 105 | 106 | [Theory] 107 | [InlineData("fitness juice ankle box prepare gallery purse narrow miracle next soccer category", 108 | "root_xsk1lr3cx6gq4za83wzg86c6zkgtgneduls79q3jfvsxxt95qlnsl3fx50ze4squpnf765a7hpalypwmhayqdk75qzmcky3af23zttvrsedhjr79k4kzyawfd69780ndrf94m02t5rh90nl922a6h2652yxapuaec7du")] 109 | [InlineData("trap report remind insane change toy rotate suggest misery vault language mind bone hen mountain", 110 | "root_xsk1zz42r64vuyfg5fm29syvfrurcnzq3sqatsnrdqus0w92ss7j5dzkyu52ufx78revvjfvqh4s6yamvf2rd3fwkwpj3qdp9y3ywr0vceq7r08zh9292q2jqf6rs9lf2xpucnnamgr8tts5qw602tjuzzd6jspgpgt2")] 111 | [InlineData("since cook close prosper slush luggage observe neglect fit arm twelve grief evolve illegal seven destroy joke hand useless knee silent wasp protect purity", 112 | "root_xsk1mp5v07fpudmmwvvsqj38nn8l3hkeuhes53r5f2xpevdqe6pgy3v7a8tjtkmd677ge7n8w55gfyk974ee06a794nah2lwpuusln0hf82la4ec2e34jtqhk7pzprvwvtmn9uk5s2xvca8332guj6g4ku6djut4hs9r")] 113 | public async Task Derive_Correct_Bech32_Extended_Root_Signing_Key_Defaulting_To_English_When_Passphrase_And_Language_Are_Not_Supplied_And_Mnemonic_Is_Valid_English( 114 | string mnemonic, string expectedBech32Key) 115 | { 116 | var command = new DeriveRootKeyCommand() 117 | { 118 | Mnemonic = mnemonic 119 | }; 120 | var englishSpecificCommand = new DeriveRootKeyCommand() 121 | { 122 | Mnemonic = mnemonic, 123 | Language = "English" 124 | }; 125 | 126 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 127 | var englishSpecificCommandResult = await englishSpecificCommand.ExecuteAsync(CancellationToken.None); 128 | 129 | executionResult.Outcome.Should().Be(CommandOutcome.Success); 130 | executionResult.Result.Should().Be(expectedBech32Key); 131 | executionResult.Result.Should().Be(englishSpecificCommandResult.Result); 132 | } 133 | 134 | [Theory] 135 | [InlineData( 136 | "English", "rapid limit bicycle embrace speak column spoil casino become evolve unknown worry letter team laptop unknown false elbow bench analyst dilemma engage pulse plug", 137 | "root_xsk13qf2w4jsex0a27xjpwvv68jlk6vhlfql6la88wv495x9mfx5sa8h2xx5wxzx6ghgg504nqkaw55cev37xer2mpwcast76zk98zt7c35eagfuj4wnzv3pgmzxlfhucqg03s4c8ha6jg8j6y2h6ghdplpelqjtss3r")] 138 | [InlineData( 139 | "English","wagon extra crucial bomb lake thumb diamond damp carry window mammal name load barely mixed decorate boss cancel sadness anxiety swim friend bracket frame", 140 | "root_xsk1crr05lc9w35hdmz4qrgzv2895jvksqsk5lk58zt8l4kvntczrdr5we87q8mg0pfsefey2wsejpjp8hh94c8y3l976uha5qlmcsezpc7r975hd5vg30jfuu0g3qhux6ynjw7t5mamg57tkelpwukzcyrxty7s0qs7")] 141 | [InlineData( 142 | "English", "tobacco toe brand law piece awkward awkward angle hint hen flame morning drop oxygen mother mom click because bulk seminar strong above toilet bird", 143 | "root_xsk1rrqsavyh9ktz599kgd8jwmvmnhh2wavp6swqs7nh5vw6zktv0exg6h8quvuemwwcd3tr9pr3jmyh6ap0rqsn8dmafrl5u4p35vw50pe2r43t0yujkcarqygam5j0c3yjag0m0k2hxpuwd2eage9nhaduwct9dgnx")] 144 | [InlineData( 145 | "Spanish", "pensar leve rosca hueso ombligo cerrar guion molde bonito misa recaer amargo sodio noria tosco", 146 | "root_xsk17r385qlkz0g4fgn9fcyxw5cxtu9qju6wweravmgn7pd4z2ypr4wdh4erc8ww0n3d389hwrelggchvlu57ulxefjzepmdzx9jwx8z3lymeeemhjel5tdkqffhe75jwxrs3l4xv97lnqve7zn0svplp33aku4ywq68")] 147 | [InlineData( 148 | "Japanese", "たたかう しのぐ きひん てまえ むさぼる なれる しあさって りゆう ろめん げいのうじん したて たんか さんみ けんとう うけもつ", 149 | "root_xsk1yz4dsxpn79vdyxwe6pr7k3y5pzsljd22p8s2seushdcxdkj5gew0dvlyl83qe0cu85pkaplc5l3q4zm2p7tw59shdtw5rrhgd2utjgz3namtvt4n2gu2uexl9rnksqtqa2r76dxjngjxvj34ez53zy0zg5cr4qf6")] 150 | [InlineData( 151 | "Italian", "danzare diametro valanga piffero finire sbadiglio veterano fato frigo saraceno mirino fuggente sapere dondolo mitra", 152 | "root_xsk1ezkc853wqv3cynuqfpkp6hls45q85sueep5wmyhuuu4n7d0ksfzp4p8lkfz0zvvszt56hmynkvuphh822gsk08k4lx0anju88yxheuv9fduj2ffh0pmclxwwh6razk2cqn9cjqtk5w8r34fq09rf6tr3agqtvk4d")] 153 | [InlineData( 154 | "ChineseSimplified", "能 林 手 近 层 锭 先 伏 杯 彩 季 住 该 厉 亭", 155 | "root_xsk1vzx4pqxh4368mgwq289v569g6sflppxtcky00h4t3l7akr08we8lh50he0szdkz72ul8hew9cxy2peg4w5emmk5ux54lnjzjfrgnnsxczprrdlg53etdl7l3mextxqr3f90v5pka94m6y9ajy37crcy6859d79tp")] 156 | public async Task Derive_Correct_Bech32_Extended_Root_Signing_Key_Defaulting_To_Empty_Passphrase_When_Passphrase_Is_Not_Supplied_And_Mnemonic_Is_Valid_For_Language( 157 | string language, string mnemonic, string expectedBech32Key) 158 | { 159 | var command = new DeriveRootKeyCommand() 160 | { 161 | Mnemonic = mnemonic, 162 | Language = language, 163 | }; 164 | var emptyPassSpecificCommand = new DeriveRootKeyCommand() 165 | { 166 | Mnemonic = mnemonic, 167 | Language = language, 168 | Passphrase = "", 169 | }; 170 | 171 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 172 | var emptyPassCommandResult = await emptyPassSpecificCommand.ExecuteAsync(CancellationToken.None); 173 | 174 | executionResult.Outcome.Should().Be(CommandOutcome.Success); 175 | executionResult.Result.Should().Be(expectedBech32Key); 176 | executionResult.Result.Should().Be(emptyPassCommandResult.Result); 177 | } 178 | 179 | [Theory] 180 | [InlineData("pass", "English", "fitness juice ankle box prepare gallery purse narrow miracle next soccer category", 181 | "root_xsk1xzdq5chjgyzztg4926alf6fhe57aa48u5xkwt03qrcy7y7p2qazmsnmjyk0ejtzuy6feg4unz49r30e3ea7myz6ml6pz0uw55m7p6862wzcq3hz7cpxm5q4r5h7s9ct4wfeg3682fwz9p5cd6yu8v46l6q25dfu5")] 182 | [InlineData("Gxxk3A32Qch8ZcwtUib3g9gSs&#abSx01&Hfpf!VAcz72bz2G5", "English", "fitness juice ankle box prepare gallery purse narrow miracle next soccer category", 183 | "root_xsk1fqmvj05d5uw934zx8xqydvvdpyxgg67jnrecfhp9rqjrs3gl2pzn9akgzpwwq0472jwquwsq3gamnk27zsythggzsdzqaehqm38ragj0lsjcgw3ad98g5s9uwl0zvwdx8eqj8sj3qv4a564xgrhqzmmtyypkv5r7")] 184 | [InlineData("pass", "Spanish", "producto lluvia atún elefante bello lavar tatuaje chivo muñeca vaina cisne regir almeja llama muleta", 185 | "root_xsk1wrmyvj6sqfm0gpxntn3w3vfday55zu0szl88hjzl9rya9d0wyet6nfgnw80zcddll24ftef8mcdcg42kwyaacqnysfc2lflmffax8nhh8mfhgr88hv242k0rmxhvfscmw9aalw4pmmaa3grhlftt6ssd4yq05vsr")] 186 | [InlineData("#SCVh0%vyMWmBj!BR4EYIrUBB4UM%c5yvS8&S!m0W2PNFJX4di", "Spanish", "producto lluvia atún elefante bello lavar tatuaje chivo muñeca vaina cisne regir almeja llama muleta", 187 | "root_xsk1xpmalqmnpsux7hewqj9raz4xvavh9773pv9589ls58eujglhuag7hc0h6vwhyjzduh6vwrj687j2te4nsvt85jycvtgtz2l7luwvpx2x7e74tvjdt4866reqcv7h89stakzqa52xyxc696hvvl880ukj7c4jj9lz")] 188 | [InlineData("pass", "Japanese", "あまい るいさい はづき になう ことがら ふしぎ がっさん えんそく きうい みかん うんどう いだく せっけん にってい とおい", 189 | "root_xsk1nrxaqdjjz6vgm9c890w3u7u4udfeyhmf3a3879r46mnh3c0gn3vxd82r56q7myyvwh9m3h53st2wjxaqn6kvyneln5fwle82r0wlmecufzw0m3mdfn3uam5tpawtk0qrfs5tpxq2wpul264w5ay2zwsccuws6kc0")] 190 | [InlineData("AhkYZ!!*ng@x56#cN5wE83ugz9JD8Xju#fm3De9AWKYCyDSDZE", "Japanese", "あまい るいさい はづき になう ことがら ふしぎ がっさん えんそく きうい みかん うんどう いだく せっけん にってい とおい", 191 | "root_xsk1krrd6navw95dcwtlzhq0tmq9gd030kx4xunhj0zyawln7kpwvdvsqev5u9plyndq2dtkc5pj6e0w8g63t8y6fy32cfye7wpdyuja623mht5h5ryn8mt7r5h5clu4nsyaa8dfh674k0cuh468vk2dnjltegy3dcd3")] 192 | public async Task Derive_Correct_Bech32_Extended_Root_Signing_Key_When_Passphrase_And_Language_Are_Supplied_And_Mnemonic_Is_Valid_For_Language( 193 | string passPhrase, string language, string mnemonic, string expectedBech32Key) 194 | { 195 | var command = new DeriveRootKeyCommand() 196 | { 197 | Mnemonic = mnemonic, 198 | Language = language, 199 | Passphrase = passPhrase, 200 | }; 201 | 202 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 203 | 204 | executionResult.Outcome.Should().Be(CommandOutcome.Success); 205 | executionResult.Result.Should().Be(expectedBech32Key); 206 | } 207 | } -------------------------------------------------------------------------------- /Tests/ConsoleTool.UnitTests/EncodeBech32CommandShould.cs: -------------------------------------------------------------------------------- 1 | using Cscli.ConsoleTool.Crypto; 2 | using FluentAssertions; 3 | using Xunit; 4 | 5 | namespace Cscli.ConsoleTool.UnitTests; 6 | 7 | public class EncodeBech32CommandShould 8 | { 9 | [Theory] 10 | [InlineData( 11 | "019493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8e337b62cfff6403a06a3acbc34f8c46003c69fe79a3628cefa9c47251", 12 | "addr", 13 | "addr1qx2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer3n0d3vllmyqwsx5wktcd8cc3sq835lu7drv2xwl2wywfgse35a3x")] 14 | [InlineData( 15 | "11c37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f337b62cfff6403a06a3acbc34f8c46003c69fe79a3628cefa9c47251", 16 | "addr", 17 | "addr1z8phkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gten0d3vllmyqwsx5wktcd8cc3sq835lu7drv2xwl2wywfgs9yc0hh")] 18 | [InlineData( 19 | "219493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8ec37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f", 20 | "addr", 21 | "addr1yx2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzerkr0vd4msrxnuwnccdxlhdjar77j6lg0wypcc9uar5d2shs2z78ve")] 22 | [InlineData( 23 | "31c37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542fc37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f", 24 | "addr", 25 | "addr1x8phkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gt7r0vd4msrxnuwnccdxlhdjar77j6lg0wypcc9uar5d2shskhj42g")] 26 | [InlineData( 27 | "419493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8e8198bd431b03", 28 | "addr", 29 | "addr1gx2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer5pnz75xxcrzqf96k")] 30 | [InlineData( 31 | "51c37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f8198bd431b03", 32 | "addr", 33 | "addr128phkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtupnz75xxcrtw79hu")] 34 | [InlineData( 35 | "619493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8e", 36 | "addr", 37 | "addr1vx2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzers66hrl8")] 38 | [InlineData( 39 | "71c37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f", 40 | "addr", 41 | "addr1w8phkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtcyjy7wx")] 42 | [InlineData( 43 | "e1337b62cfff6403a06a3acbc34f8c46003c69fe79a3628cefa9c47251", 44 | "stake", 45 | "stake1uyehkck0lajq8gr28t9uxnuvgcqrc6070x3k9r8048z8y5gh6ffgw")] 46 | [InlineData( 47 | "f1c37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f", 48 | "stake", 49 | "stake178phkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtcccycj5")] 50 | [InlineData( 51 | "009493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8e337b62cfff6403a06a3acbc34f8c46003c69fe79a3628cefa9c47251", 52 | "addr_test", 53 | "addr_test1qz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer3n0d3vllmyqwsx5wktcd8cc3sq835lu7drv2xwl2wywfgs68faae")] 54 | [InlineData( 55 | "10c37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f337b62cfff6403a06a3acbc34f8c46003c69fe79a3628cefa9c47251", 56 | "addr_test", 57 | "addr_test1zrphkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gten0d3vllmyqwsx5wktcd8cc3sq835lu7drv2xwl2wywfgsxj90mg")] 58 | [InlineData( 59 | "209493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8ec37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f", 60 | "addr_test", 61 | "addr_test1yz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzerkr0vd4msrxnuwnccdxlhdjar77j6lg0wypcc9uar5d2shsf5r8qx")] 62 | [InlineData( 63 | "30c37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542fc37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f", 64 | "addr_test", 65 | "addr_test1xrphkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gt7r0vd4msrxnuwnccdxlhdjar77j6lg0wypcc9uar5d2shs4p04xh")] 66 | [InlineData( 67 | "409493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8e8198bd431b03", 68 | "addr_test", 69 | "addr_test1gz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer5pnz75xxcrdw5vky")] 70 | [InlineData( 71 | "50c37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f8198bd431b03", 72 | "addr_test", 73 | "addr_test12rphkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtupnz75xxcryqrvmw")] 74 | [InlineData( 75 | "609493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8e", 76 | "addr_test", 77 | "addr_test1vz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzerspjrlsz")] 78 | [InlineData( 79 | "70c37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f", 80 | "addr_test", 81 | "addr_test1wrphkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtcl6szpr")] 82 | [InlineData( 83 | "e0337b62cfff6403a06a3acbc34f8c46003c69fe79a3628cefa9c47251", 84 | "stake_test", 85 | "stake_test1uqehkck0lajq8gr28t9uxnuvgcqrc6070x3k9r8048z8y5gssrtvn")] 86 | [InlineData( 87 | "f0c37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f", 88 | "stake_test", 89 | "stake_test17rphkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtcljw6kf")] 90 | public async Task Execute_Successfully_With_Bech_Decoding_When_Properties_Are_Valid(string value, string prefix, string expectedBech32) 91 | { 92 | var command = new EncodeBech32Command() 93 | { 94 | Value = value, 95 | Prefix = prefix, 96 | }; 97 | 98 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 99 | 100 | executionResult.Outcome.Should().Be(CommandOutcome.Success); 101 | executionResult.Result.Should().Be(expectedBech32); 102 | } 103 | 104 | [Theory] 105 | [InlineData(null)] 106 | [InlineData("")] 107 | [InlineData(" ")] 108 | [InlineData("this is not a valid hex value")] 109 | [InlineData(" another invalid value")] 110 | public async Task Fail_With_Bech_Encoding_When_Properities_Are_Invalid(string invalidValue) 111 | { 112 | var command = new EncodeBech32Command() 113 | { 114 | Value = invalidValue 115 | }; 116 | 117 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 118 | 119 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 120 | } 121 | } -------------------------------------------------------------------------------- /Tests/ConsoleTool.UnitTests/GenerateMnemonicCommandShould.cs: -------------------------------------------------------------------------------- 1 | using Cscli.ConsoleTool.Wallet; 2 | using FluentAssertions; 3 | using Xunit; 4 | 5 | namespace Cscli.ConsoleTool.UnitTests; 6 | 7 | public class GenerateMnemonicCommandShould 8 | { 9 | [Fact] 10 | public async Task Execute_Successfully_With_Default_Options_When_No_Properties_Are_Initialised() 11 | { 12 | var command = new GenerateMnemonicCommand(); 13 | 14 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 15 | 16 | command.Size.Should().Be(Constants.DefaultMnemonicCount); 17 | command.Language.Should().Be(Constants.DefaultMnemonicLanguage); 18 | executionResult.Outcome.Should().Be(CommandOutcome.Success); 19 | executionResult.Result.Split(' ').Length.Should().Be(Constants.DefaultMnemonicCount); 20 | } 21 | 22 | [Theory] 23 | [InlineData(9, "English")] 24 | [InlineData(12, "English")] 25 | [InlineData(15, "English")] 26 | [InlineData(18, "English")] 27 | [InlineData(21, "English")] 28 | [InlineData(24, "English")] 29 | #region Non-English 30 | //[InlineData(9, "Spanish")] 31 | [InlineData(12, "Spanish")] 32 | [InlineData(15, "Spanish")] 33 | [InlineData(18, "Spanish")] 34 | [InlineData(21, "Spanish")] 35 | [InlineData(24, "Spanish")] 36 | //[InlineData(9, "Portuguese")] 37 | [InlineData(12, "Portuguese")] 38 | [InlineData(15, "Portuguese")] 39 | [InlineData(18, "Portuguese")] 40 | [InlineData(21, "Portuguese")] 41 | [InlineData(24, "Portuguese")] 42 | //[InlineData(9, "Japanese")] 43 | [InlineData(12, "Japanese")] 44 | [InlineData(15, "Japanese")] 45 | [InlineData(18, "Japanese")] 46 | [InlineData(21, "Japanese")] 47 | [InlineData(24, "Japanese")] 48 | //[InlineData(9, "ChineseTraditional")] 49 | [InlineData(12, "ChineseTraditional")] 50 | [InlineData(15, "ChineseTraditional")] 51 | [InlineData(18, "ChineseTraditional")] 52 | [InlineData(21, "ChineseTraditional")] 53 | [InlineData(24, "ChineseTraditional")] 54 | #endregion 55 | public async Task Execute_Successfully_With_Mnemonics_When_Properties_Are_Valid(int size, string language) 56 | { 57 | var command = new GenerateMnemonicCommand() 58 | { 59 | Size = size, 60 | Language = language 61 | }; 62 | 63 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 64 | 65 | executionResult.Outcome.Should().Be(CommandOutcome.Success); 66 | executionResult.Result.Split(' ').Length.Should().Be(size); 67 | } 68 | 69 | [Theory] 70 | [InlineData(-1, "")] 71 | [InlineData(0, null)] 72 | [InlineData(0, "English")] 73 | [InlineData(1, "English")] 74 | [InlineData(8, "English")] 75 | [InlineData(14, "English")] 76 | [InlineData(27, "English")] 77 | [InlineData(9, "x")] 78 | [InlineData(12, "en-US")] 79 | [InlineData(15, "Australian")] 80 | [InlineData(18, "British")] 81 | [InlineData(21, "!")] 82 | [InlineData(24, "uwotm8")] 83 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Properties_Are_Invalid(int size, string language) 84 | { 85 | var command = new GenerateMnemonicCommand() 86 | { 87 | Size = size, 88 | Language = language 89 | }; 90 | 91 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 92 | 93 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 94 | executionResult.Result.Should().StartWith("Invalid option"); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /Tests/ConsoleTool.UnitTests/HashBlake2bCommandShould.cs: -------------------------------------------------------------------------------- 1 | using Cscli.ConsoleTool.Crypto; 2 | using FluentAssertions; 3 | using Xunit; 4 | 5 | namespace Cscli.ConsoleTool.UnitTests 6 | { 7 | public class HashBlake2bCommandShould 8 | { 9 | [Theory] 10 | [InlineData(160, "20", "8307bbdd3537e6ed512e031521b5d857491594ed")] 11 | [InlineData(160, "d92b380b5413b76202056eea98b6bf579d52a54a44688c1f7f97b8237469636B65745F6D61647269645F3033", "14b10f77f116636f00a23fdbacf8a1d93bf52fe3")] 12 | [InlineData(160, "68656c6c6f", "b5531c7037f06c9f2947132a6a77202c308e8939")] 13 | [InlineData(224, "20", "3542acb3a64d80c29302260d62c3b87a742ad14abf855ebc6733081e")] 14 | [InlineData(224, "68656c6c6f", "a4963e4ea2aa9b4120672abfc4c4299ba365368fa5a3910d5c559fc5")] 15 | [InlineData(224, "8512f8eb5d0a26038f703d58e2b45123b6e441e2208cb37fc22605f0d215a26a", "e3f81c986990cfd80283944858ae50c2d82f6a79d330ce7014e0b7fd")] 16 | [InlineData(224, "1872bc5ecc95b419de3f72544a6656ceb9a813755544618bb6b4dcc230ed9721", "9df9179beb0ce89f84025e02ae11c18b3003e7690149caa662fafd01")] 17 | [InlineData(256, "20", "ae85d245a3d00bfde01f59f3c4fe0b4bfae1cb37e9cf91929eadcea4985711de")] 18 | [InlineData(256, "68656c6c6f", "324dcf027dd4a30a932c441f365a25e86b173defa4b8e58948253471b81b72cf")] 19 | [InlineData(256, "4D79206E616D65206973204F7A796D616E646961732C206B696E67206F66206B696E67733B204C6F6F6B206F6E206D7920776F726B732C207965204D69676874792C20616E642064657370616972212220546865206C6F6E6520616E64206C6576656C2073616E647320737472657463682066617220617761792E", "4fdc7eaf2f91482e42fb1213f19a38ab420bed1b88eb6025e9a9fc05204d649c")] 20 | [InlineData(512, "68656c6c6f", "e4cfa39a3d37be31c59609e807970799caa68a19bfaa15135f165085e01d41a65ba1e1b146aeb6bd0092b49eac214c103ccfa3a365954bbbe52f74a2b3620c94")] 21 | [InlineData(512, "4d79206e616d65206973204f7a796d616e646961732c206b696e67206f66206b696e67733b204c6f6f6b206f6e206d7920776f726b732c207965204d69676874792c20616e642064657370616972212220546865206c6f6e6520616e64206c6576656c2073616e647320737472657463682066617220617761792e", "9847f440d8d1ca88c781a7f672b940c8855ca582cf4dd1e7c11c460a08994fb349f7551262614875f1e241104d50af167c0dfa208a11ce6aad14ce624e7bd4a7")] 22 | public async Task Successfully_Hash_Values_When_Properities_Are_Invalid( 23 | int length, string value, string expectedDigestHex) 24 | { 25 | var command = new HashBlake2bCommand() 26 | { 27 | Length = length, 28 | Value = value 29 | }; 30 | 31 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 32 | 33 | executionResult.Result.Should().Be(expectedDigestHex); 34 | } 35 | 36 | [Theory] 37 | [InlineData(160, null)] 38 | [InlineData(160, "")] 39 | [InlineData(160, "feature damp short detail access install rookie spell parrot")] 40 | [InlineData(224, null)] 41 | [InlineData(224, "")] 42 | [InlineData(224, "addr_test1vr3ls8ycdxgvlkqzsw2ysk9w2rpdstm208fnpnnsznst0lgg4vjxk")] 43 | [InlineData(256, null)] 44 | [InlineData(256, "")] 45 | [InlineData(256, "0xAAA")] 46 | [InlineData(512, null)] 47 | [InlineData(512, "")] 48 | [InlineData(512, "policy_sk1czq9363h74e8asz4x8t0ptthgyty7rc2czgynkctv7lgfsrht4vadwd499q4n4w6cg8fnkexj9n4ukrnnle7k4zw4wuftmsgelns2acqctqrf")] 49 | public async Task Fail_Blake2b_Hashing_When_Value_Is_Invalid( 50 | int length, string value) 51 | { 52 | var command = new HashBlake2bCommand() 53 | { 54 | Length = length, 55 | Value = value 56 | }; 57 | 58 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 59 | 60 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 61 | } 62 | 63 | [Theory] 64 | [InlineData(-224)] 65 | [InlineData(-160)] 66 | [InlineData(-100)] 67 | [InlineData(0)] 68 | [InlineData(1)] 69 | [InlineData(32)] 70 | [InlineData(64)] 71 | [InlineData(128)] 72 | [InlineData(255)] 73 | [InlineData(500)] 74 | [InlineData(1024)] 75 | [InlineData(4096)] 76 | public async Task Fail_Blake2b_Hashing_When_Length_Is_Invalid(int length) 77 | { 78 | var command = new HashBlake2bCommand 79 | { 80 | Length = length, 81 | Value = "68656C6C6F" 82 | }; 83 | 84 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 85 | 86 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /Tests/ConsoleTool.UnitTests/QueryAccountAssetCommandShould.cs: -------------------------------------------------------------------------------- 1 | using Cscli.ConsoleTool.Query; 2 | using FluentAssertions; 3 | using Xunit; 4 | 5 | namespace Cscli.ConsoleTool.UnitTests; 6 | 7 | public class QueryAccountAssetCommandShould 8 | { 9 | [Theory] 10 | [InlineData("")] 11 | [InlineData("a")] 12 | [InlineData("test")] 13 | [InlineData("tastnet")] 14 | [InlineData("Mainet")] 15 | [InlineData("mainet")] 16 | [InlineData("mainnetwork")] 17 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Network_Is_Not_Valid( 18 | string network) 19 | { 20 | var command = new QueryAccountAssetCommand() 21 | { 22 | Network = network, 23 | StakeAddress = "stake1uxwlj9umavxw38uyqf0q9ts3cx9nqql8dyq5nj4xvta06qg8t55dn", 24 | }; 25 | 26 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 27 | 28 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 29 | executionResult.Result.Should().StartWith("Invalid option --network must be either testnet or mainnet"); 30 | } 31 | 32 | [Theory] 33 | [InlineData("testnet")] 34 | [InlineData("mainnet")] 35 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Stake_Address_And_Payment_Address_Are_Both_Not_Supplied( 36 | string network) 37 | { 38 | var command = new QueryAccountAssetCommand() 39 | { 40 | Network = network 41 | }; 42 | 43 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 44 | 45 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 46 | executionResult.Result.Should().Be("Invalid option, one of either --stake-address or --address is required"); 47 | } 48 | 49 | [Theory] 50 | [InlineData("testnet")] 51 | [InlineData("mainnet")] 52 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Valid_Stake_Address_And_Payment_Address_Are_Both_Supplied( 53 | string network) 54 | { 55 | var command = new QueryAccountAssetCommand() 56 | { 57 | Network = network, 58 | StakeAddress = "stake1u9wqktpz964g6jaemt5wr5tspy9cqxpdkw98d022d85kxxc2n2yxj", 59 | Address = "addr1qy5zuhh9685fup86syuzmu3e6eengzv8t46mfqxg086cvqzupvkzyt42349mnkhgu8ghqzgtsqvzmvu2w675560fvvdspma4ht" 60 | }; 61 | 62 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 63 | 64 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 65 | executionResult.Result.Should().Be("Invalid option, one of either --stake-address or --address is required"); 66 | } 67 | 68 | [Theory] 69 | [InlineData("a", "testnet")] 70 | [InlineData("a", "mainnet")] 71 | [InlineData("test", "testnet")] 72 | [InlineData("test", "mainnet")] 73 | [InlineData("stake1abc1234", "testnet")] 74 | [InlineData("stake1abc1234", "mainnet")] 75 | [InlineData("stake_test1abc1234", "testnet")] 76 | [InlineData("stake_test1abc1234", "mainnet")] 77 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Stake_Address_Is_Not_Valid_Bech32( 78 | string invalidStakeAddress, string network) 79 | { 80 | var command = new QueryAccountAssetCommand() 81 | { 82 | Network = network, 83 | StakeAddress = invalidStakeAddress, 84 | }; 85 | 86 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 87 | 88 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 89 | executionResult.Result.Should().Be($"Invalid option --stake-address {invalidStakeAddress} is invalid"); 90 | } 91 | 92 | [Theory] 93 | [InlineData("stake1uyneva7s00qnhmwnl9a6kzvahcqf7v3sa4h9wh970dxl6egwp9mlw", "testnet")] 94 | [InlineData("stake_test1uqneva7s00qnhmwnl9a6kzvahcqf7v3sa4h9wh970dxl6egft0emn", "mainnet")] 95 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Stake_Address_Is_Valid_But_For_Different_Network( 96 | string stakeAddress, string network) 97 | { 98 | var command = new QueryAccountAssetCommand() 99 | { 100 | Network = network, 101 | StakeAddress = stakeAddress, 102 | }; 103 | 104 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 105 | 106 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 107 | executionResult.Result.Should().Be($"Invalid option --stake-address {stakeAddress} is invalid for {network}"); 108 | } 109 | 110 | [Theory] 111 | [InlineData("a", "testnet")] 112 | [InlineData("a", "mainnet")] 113 | [InlineData("test", "testnet")] 114 | [InlineData("test", "mainnet")] 115 | [InlineData("addr1abc1234", "testnet")] 116 | [InlineData("addr1abc1234", "mainnet")] 117 | [InlineData("addr_test1abc1234", "testnet")] 118 | [InlineData("addr_test1abc1234", "mainnet")] 119 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Address_Is_Not_Valid_Bech32( 120 | string invalidAddress, string network) 121 | { 122 | var command = new QueryAccountAssetCommand() 123 | { 124 | Network = network, 125 | Address = invalidAddress, 126 | }; 127 | 128 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 129 | 130 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 131 | executionResult.Result.Should().Be($"Invalid option --address {invalidAddress} is not a base address with attached staking credentials"); 132 | } 133 | 134 | [Theory] 135 | [InlineData("addr1qyg4gu4vfd3775glq8rjm85x2crmysc920hf5qjj8m7rxef8jemaq77p80ka87tm4vyem0sqnuerpmtw2awtu76dl4jssqfzz4", "testnet")] 136 | [InlineData("addr_test1qqg4gu4vfd3775glq8rjm85x2crmysc920hf5qjj8m7rxef8jemaq77p80ka87tm4vyem0sqnuerpmtw2awtu76dl4jsnk5zw2", "mainnet")] 137 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Address_Is_Valid_But_For_Different_Network( 138 | string address, string network) 139 | { 140 | var command = new QueryAccountAssetCommand() 141 | { 142 | Network = network, 143 | Address = address, 144 | }; 145 | 146 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 147 | 148 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 149 | executionResult.Result.Should().Be($"Invalid option --address {address} is not a base address with attached staking credentials for {network}"); 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /Tests/ConsoleTool.UnitTests/QueryAccountInfoCommandShould.cs: -------------------------------------------------------------------------------- 1 | using Cscli.ConsoleTool.Query; 2 | using FluentAssertions; 3 | using Xunit; 4 | 5 | namespace Cscli.ConsoleTool.UnitTests; 6 | 7 | public class QueryAccountInfoCommandShould 8 | { 9 | [Theory] 10 | [InlineData("")] 11 | [InlineData("a")] 12 | [InlineData("test")] 13 | [InlineData("tastnet")] 14 | [InlineData("Mainet")] 15 | [InlineData("mainet")] 16 | [InlineData("mainnetwork")] 17 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Network_Is_Not_Valid( 18 | string network) 19 | { 20 | var command = new QueryAccountInfoCommand() 21 | { 22 | Network = network, 23 | StakeAddress = "stake1uxwlj9umavxw38uyqf0q9ts3cx9nqql8dyq5nj4xvta06qg8t55dn", 24 | }; 25 | 26 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 27 | 28 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 29 | executionResult.Result.Should().StartWith("Invalid option --network must be either testnet or mainnet"); 30 | } 31 | 32 | [Theory] 33 | [InlineData("testnet")] 34 | [InlineData("mainnet")] 35 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Stake_Address_And_Payment_Address_Are_Both_Not_Supplied( 36 | string network) 37 | { 38 | var command = new QueryAccountInfoCommand() 39 | { 40 | Network = network 41 | }; 42 | 43 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 44 | 45 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 46 | executionResult.Result.Should().Be("Invalid option, one of either --stake-address or --address is required"); 47 | } 48 | 49 | [Theory] 50 | [InlineData("testnet")] 51 | [InlineData("mainnet")] 52 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Valid_Stake_Address_And_Payment_Address_Are_Both_Supplied( 53 | string network) 54 | { 55 | var command = new QueryAccountInfoCommand() 56 | { 57 | Network = network, 58 | StakeAddress = "stake1u9wqktpz964g6jaemt5wr5tspy9cqxpdkw98d022d85kxxc2n2yxj", 59 | Address = "addr1qy5zuhh9685fup86syuzmu3e6eengzv8t46mfqxg086cvqzupvkzyt42349mnkhgu8ghqzgtsqvzmvu2w675560fvvdspma4ht" 60 | }; 61 | 62 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 63 | 64 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 65 | executionResult.Result.Should().Be("Invalid option, one of either --stake-address or --address is required"); 66 | } 67 | 68 | [Theory] 69 | [InlineData("a", "testnet")] 70 | [InlineData("a", "mainnet")] 71 | [InlineData("test", "testnet")] 72 | [InlineData("test", "mainnet")] 73 | [InlineData("stake1abc1234", "testnet")] 74 | [InlineData("stake1abc1234", "mainnet")] 75 | [InlineData("stake_test1abc1234", "testnet")] 76 | [InlineData("stake_test1abc1234", "mainnet")] 77 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Stake_Address_Is_Not_Valid_Bech32( 78 | string invalidStakeAddress, string network) 79 | { 80 | var command = new QueryAccountInfoCommand() 81 | { 82 | Network = network, 83 | StakeAddress = invalidStakeAddress, 84 | }; 85 | 86 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 87 | 88 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 89 | executionResult.Result.Should().Be($"Invalid option --stake-address {invalidStakeAddress} is invalid"); 90 | } 91 | 92 | [Theory] 93 | [InlineData("stake1uyneva7s00qnhmwnl9a6kzvahcqf7v3sa4h9wh970dxl6egwp9mlw", "testnet")] 94 | [InlineData("stake_test1uqneva7s00qnhmwnl9a6kzvahcqf7v3sa4h9wh970dxl6egft0emn", "mainnet")] 95 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Stake_Address_Is_Valid_But_For_Different_Network( 96 | string stakeAddress, string network) 97 | { 98 | var command = new QueryAccountInfoCommand() 99 | { 100 | Network = network, 101 | StakeAddress = stakeAddress, 102 | }; 103 | 104 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 105 | 106 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 107 | executionResult.Result.Should().Be($"Invalid option --stake-address {stakeAddress} is invalid for {network}"); 108 | } 109 | 110 | [Theory] 111 | [InlineData("a", "testnet")] 112 | [InlineData("a", "mainnet")] 113 | [InlineData("test", "testnet")] 114 | [InlineData("test", "mainnet")] 115 | [InlineData("addr1abc1234", "testnet")] 116 | [InlineData("addr1abc1234", "mainnet")] 117 | [InlineData("addr_test1abc1234", "testnet")] 118 | [InlineData("addr_test1abc1234", "mainnet")] 119 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Address_Is_Not_Valid_Bech32( 120 | string invalidAddress, string network) 121 | { 122 | var command = new QueryAccountInfoCommand() 123 | { 124 | Network = network, 125 | Address = invalidAddress, 126 | }; 127 | 128 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 129 | 130 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 131 | executionResult.Result.Should().Be($"Invalid option --address {invalidAddress} is not a base address with attached staking credentials"); 132 | } 133 | 134 | [Theory] 135 | [InlineData("addr1qyg4gu4vfd3775glq8rjm85x2crmysc920hf5qjj8m7rxef8jemaq77p80ka87tm4vyem0sqnuerpmtw2awtu76dl4jssqfzz4", "testnet")] 136 | [InlineData("addr_test1qqg4gu4vfd3775glq8rjm85x2crmysc920hf5qjj8m7rxef8jemaq77p80ka87tm4vyem0sqnuerpmtw2awtu76dl4jsnk5zw2", "mainnet")] 137 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Address_Is_Valid_But_For_Different_Network( 138 | string address, string network) 139 | { 140 | var command = new QueryAccountInfoCommand() 141 | { 142 | Network = network, 143 | Address = address, 144 | }; 145 | 146 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 147 | 148 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 149 | executionResult.Result.Should().Be($"Invalid option --address {address} is not a base address with attached staking credentials for {network}"); 150 | } 151 | } 152 | 153 | -------------------------------------------------------------------------------- /Tests/ConsoleTool.UnitTests/QueryAddressInfoCommandShould.cs: -------------------------------------------------------------------------------- 1 | using Cscli.ConsoleTool.Query; 2 | using FluentAssertions; 3 | using Xunit; 4 | 5 | namespace Cscli.ConsoleTool.UnitTests; 6 | 7 | public class QueryAddressInfoCommandShould 8 | { 9 | [Theory] 10 | [InlineData("")] 11 | [InlineData("a")] 12 | [InlineData("test")] 13 | [InlineData("tastnet")] 14 | [InlineData("Mainet")] 15 | [InlineData("mainet")] 16 | [InlineData("mainnetwork")] 17 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Network_Is_Not_Valid( 18 | string network) 19 | { 20 | var command = new QueryAddressInfoCommand() 21 | { 22 | Network = network, 23 | Address = "stake1uxwlj9umavxw38uyqf0q9ts3cx9nqql8dyq5nj4xvta06qg8t55dn", 24 | }; 25 | 26 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 27 | 28 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 29 | executionResult.Result.Should().StartWith("Invalid option --network must be either testnet or mainnet"); 30 | } 31 | 32 | [Theory] 33 | [InlineData("a", "testnet")] 34 | [InlineData("a", "mainnet")] 35 | [InlineData("test", "testnet")] 36 | [InlineData("test", "mainnet")] 37 | [InlineData("addr1abc1234", "testnet")] 38 | [InlineData("addr1abc1234", "mainnet")] 39 | [InlineData("addr_test1abc1234", "testnet")] 40 | [InlineData("addr_test1abc1234", "mainnet")] 41 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Address_Is_Not_Valid_Bech32( 42 | string invalidAddress, string network) 43 | { 44 | var command = new QueryAddressInfoCommand() 45 | { 46 | Network = network, 47 | Address = invalidAddress, 48 | }; 49 | 50 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 51 | 52 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 53 | executionResult.Result.Should().Be($"Invalid option --address {invalidAddress} is invalid for {network}"); 54 | } 55 | 56 | [Theory] 57 | [InlineData("addr1qyg4gu4vfd3775glq8rjm85x2crmysc920hf5qjj8m7rxef8jemaq77p80ka87tm4vyem0sqnuerpmtw2awtu76dl4jssqfzz4", "testnet")] 58 | [InlineData("addr_test1qqg4gu4vfd3775glq8rjm85x2crmysc920hf5qjj8m7rxef8jemaq77p80ka87tm4vyem0sqnuerpmtw2awtu76dl4jsnk5zw2", "mainnet")] 59 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Address_Is_Valid_But_For_Different_Network( 60 | string address, string network) 61 | { 62 | var command = new QueryAddressInfoCommand() 63 | { 64 | Network = network, 65 | Address = address, 66 | }; 67 | 68 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 69 | 70 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 71 | executionResult.Result.Should().Be($"Invalid option --address {address} is invalid for {network}"); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /Tests/ConsoleTool.UnitTests/QueryProtocolParametersCommandShould.cs: -------------------------------------------------------------------------------- 1 | using Cscli.ConsoleTool.Query; 2 | using FluentAssertions; 3 | using Xunit; 4 | 5 | namespace Cscli.ConsoleTool.UnitTests; 6 | 7 | public class QueryProtocolParametersCommandShould 8 | { 9 | [Theory] 10 | [InlineData("")] 11 | [InlineData("a")] 12 | [InlineData("test")] 13 | [InlineData("tastnet")] 14 | [InlineData("Mainet")] 15 | [InlineData("mainet")] 16 | [InlineData("mainnetwork")] 17 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Network_Is_Not_Valid( 18 | string network) 19 | { 20 | var command = new QueryProtocolParametersCommand() 21 | { 22 | Network = network, 23 | }; 24 | 25 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 26 | 27 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 28 | executionResult.Result.Should().StartWith("Invalid option --network must be either testnet or mainnet"); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Tests/ConsoleTool.UnitTests/QueryTipCommandShould.cs: -------------------------------------------------------------------------------- 1 | using Cscli.ConsoleTool.Query; 2 | using FluentAssertions; 3 | using Xunit; 4 | 5 | namespace Cscli.ConsoleTool.UnitTests; 6 | 7 | public class QueryTipCommandShould 8 | { 9 | [Theory] 10 | [InlineData("")] 11 | [InlineData("a")] 12 | [InlineData("test")] 13 | [InlineData("tastnet")] 14 | [InlineData("Mainet")] 15 | [InlineData("mainet")] 16 | [InlineData("mainnetwork")] 17 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Network_Is_Not_Valid( 18 | string network) 19 | { 20 | var command = new QueryTipCommand() 21 | { 22 | Network = network, 23 | }; 24 | 25 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 26 | 27 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 28 | executionResult.Result.Should().StartWith("Invalid option --network must be either testnet or mainnet"); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Tests/ConsoleTool.UnitTests/QueryTransactionInfoCommandShould.cs: -------------------------------------------------------------------------------- 1 | using Cscli.ConsoleTool.Query; 2 | using FluentAssertions; 3 | using Xunit; 4 | 5 | namespace Cscli.ConsoleTool.UnitTests; 6 | 7 | public class QueryTransactionInfoCommandShould 8 | { 9 | [Theory] 10 | [InlineData("")] 11 | [InlineData("a")] 12 | [InlineData("test")] 13 | [InlineData("tastnet")] 14 | [InlineData("Mainet")] 15 | [InlineData("mainet")] 16 | [InlineData("mainnetwork")] 17 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Network_Is_Not_Valid( 18 | string network) 19 | { 20 | var command = new QueryTransactionInfoCommand() 21 | { 22 | Network = network, 23 | TxId = "421734e5c8e5be24d788da2defeb9005516c20eb7d3ddef2140e836d20282a2a", 24 | }; 25 | 26 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 27 | 28 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 29 | executionResult.Result.Should().StartWith("Invalid option --network must be either testnet or mainnet"); 30 | } 31 | 32 | [Theory] 33 | [InlineData(null, "testnet")] 34 | [InlineData(null, "mainnet")] 35 | [InlineData("", "testnet")] 36 | [InlineData("", "mainnet")] 37 | [InlineData(" ", "testnet")] 38 | [InlineData(" ", "mainnet")] 39 | [InlineData(" ", "testnet")] 40 | [InlineData(" ", "mainnet")] 41 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_TxId_Is_Null_Or_Whitespace( 42 | string nullOrWhitespaceTxId, string network) 43 | { 44 | var command = new QueryTransactionInfoCommand() 45 | { 46 | Network = network, 47 | TxId = nullOrWhitespaceTxId, 48 | }; 49 | 50 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 51 | 52 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 53 | executionResult.Result.Should().Be("Invalid option --tx-id is required"); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Tests/ConsoleTool.UnitTests/SignTransactionCommandShould.cs: -------------------------------------------------------------------------------- 1 | using Cscli.ConsoleTool.Transaction; 2 | using FluentAssertions; 3 | using Xunit; 4 | 5 | namespace Cscli.ConsoleTool.UnitTests; 6 | 7 | public class SignTransactionCommandShould 8 | { 9 | [Theory] 10 | [InlineData(null)] 11 | [InlineData("")] 12 | [InlineData(" ")] 13 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Signing_Keys_Is_Not_Supplied( 14 | string invalidSigningKeys) 15 | { 16 | var command = new SignTransactionCommand() 17 | { 18 | SigningKeys = invalidSigningKeys, 19 | CborHex = "84a400818258205853cc86af075cc547a5a20658af54841f37a5832532a704c583ed4f010184a501018282581d6079c37fabad08662e16ad4950edd63d2a2ab0b63f8a44e4a504511ef51a1908b10082581d60282e5ee5d1e89e04fa81382df239d6733409875d75b480c879f586001a43e83ed4021a00028a9d031a03b00ee0a0f5f6", 20 | }; 21 | 22 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 23 | 24 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 25 | executionResult.Result.Should().StartWith("Invalid option --signing-keys is required"); 26 | } 27 | 28 | [Theory] 29 | [InlineData("", "addr_xsk1fzw9r482t0ekua7rcqewg3k8ju5d9run4juuehm2p24jtuzz4dg4wpeulnqhualvtx9lyy7u0h9pdjvmyhxdhzsyy49szs6y8c9zwfp0eqyrqyl290e6dr0q3fvngmsjn4aask9jjr6q34juh25hczw3euust0dw")] 30 | [InlineData(null, "addr_xsk1fzw9r482t0ekua7rcqewg3k8ju5d9run4juuehm2p24jtuzz4dg4wpeulnqhualvtx9lyy7u0h9pdjvmyhxdhzsyy49szs6y8c9zwfp0eqyrqyl290e6dr0q3fvngmsjn4aask9jjr6q34juh25hczw3euust0dw")] 31 | [InlineData("", "addr_xsk15pt6dccwyy2jjgmv9gxszjyzc6kchhas2dr9q6ky0xpwz4679e2t5qu0yehpmg7xr3sc3wkcyagujlk2euwl0007w68wcfdm7ajl2tzkqve7vmqds5sf38syns3u2wey05yeh70p9m5n05kftku30uqjlqy0gjh2,addr_xsk1fzw9r482t0ekua7rcqewg3k8ju5d9run4juuehm2p24jtuzz4dg4wpeulnqhualvtx9lyy7u0h9pdjvmyhxdhzsyy49szs6y8c9zwfp0eqyrqyl290e6dr0q3fvngmsjn4aask9jjr6q34juh25hczw3euust0dw")] 32 | [InlineData(" ", "addr_xsk1fzw9r482t0ekua7rcqewg3k8ju5d9run4juuehm2p24jtuzz4dg4wpeulnqhualvtx9lyy7u0h9pdjvmyhxdhzsyy49szs6y8c9zwfp0eqyrqyl290e6dr0q3fvngmsjn4aask9jjr6q34juh25hczw3euust0dw")] 33 | [InlineData(" ", "addr_xsk15pt6dccwyy2jjgmv9gxszjyzc6kchhas2dr9q6ky0xpwz4679e2t5qu0yehpmg7xr3sc3wkcyagujlk2euwl0007w68wcfdm7ajl2tzkqve7vmqds5sf38syns3u2wey05yeh70p9m5n05kftku30uqjlqy0gjh2")] 34 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_CborHex_Is_Null_Or_Whitespace( 35 | string invalidCborHex, string signingKeys) 36 | { 37 | var command = new SignTransactionCommand() 38 | { 39 | SigningKeys = signingKeys, 40 | CborHex = invalidCborHex, 41 | }; 42 | 43 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 44 | 45 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 46 | executionResult.Result.Should().Be($"Invalid option --cbor-hex is required"); 47 | } 48 | 49 | [Theory] 50 | [InlineData("0", "addr_xsk1fzw9r482t0ekua7rcqewg3k8ju5d9run4juuehm2p24jtuzz4dg4wpeulnqhualvtx9lyy7u0h9pdjvmyhxdhzsyy49szs6y8c9zwfp0eqyrqyl290e6dr0q3fvngmsjn4aask9jjr6q34juh25hczw3euust0dw")] 51 | [InlineData("0", "addr_xsk15pt6dccwyy2jjgmv9gxszjyzc6kchhas2dr9q6ky0xpwz4679e2t5qu0yehpmg7xr3sc3wkcyagujlk2euwl0007w68wcfdm7ajl2tzkqve7vmqds5sf38syns3u2wey05yeh70p9m5n05kftku30uqjlqy0gjh2,addr_xsk1fzw9r482t0ekua7rcqewg3k8ju5d9run4juuehm2p24jtuzz4dg4wpeulnqhualvtx9lyy7u0h9pdjvmyhxdhzsyy49szs6y8c9zwfp0eqyrqyl290e6dr0q3fvngmsjn4aask9jjr6q34juh25hczw3euust0dw")] 52 | [InlineData("fff", "addr_xsk1fzw9r482t0ekua7rcqewg3k8ju5d9run4juuehm2p24jtuzz4dg4wpeulnqhualvtx9lyy7u0h9pdjvmyhxdhzsyy49szs6y8c9zwfp0eqyrqyl290e6dr0q3fvngmsjn4aask9jjr6q34juh25hczw3euust0dw")] 53 | [InlineData("fff", "addr_xsk15pt6dccwyy2jjgmv9gxszjyzc6kchhas2dr9q6ky0xpwz4679e2t5qu0yehpmg7xr3sc3wkcyagujlk2euwl0007w68wcfdm7ajl2tzkqve7vmqds5sf38syns3u2wey05yeh70p9m5n05kftku30uqjlqy0gjh2,addr_xsk1fzw9r482t0ekua7rcqewg3k8ju5d9run4juuehm2p24jtuzz4dg4wpeulnqhualvtx9lyy7u0h9pdjvmyhxdhzsyy49szs6y8c9zwfp0eqyrqyl290e6dr0q3fvngmsjn4aask9jjr6q34juh25hczw3euust0dw")] 54 | [InlineData("addr1qyg4gu4vfd3775glq8rjm85x2crmysc920hf5qjj8m7rxef8jemaq77p80ka87tm4vyem0sqnuerpmtw2awtu76dl4jssqfzz4", "addr_xsk1fzw9r482t0ekua7rcqewg3k8ju5d9run4juuehm2p24jtuzz4dg4wpeulnqhualvtx9lyy7u0h9pdjvmyhxdhzsyy49szs6y8c9zwfp0eqyrqyl290e6dr0q3fvngmsjn4aask9jjr6q34juh25hczw3euust0dw")] 55 | [InlineData("addr1qyg4gu4vfd3775glq8rjm85x2crmysc920hf5qjj8m7rxef8jemaq77p80ka87tm4vyem0sqnuerpmtw2awtu76dl4jssqfzz4", "addr_xsk15pt6dccwyy2jjgmv9gxszjyzc6kchhas2dr9q6ky0xpwz4679e2t5qu0yehpmg7xr3sc3wkcyagujlk2euwl0007w68wcfdm7ajl2tzkqve7vmqds5sf38syns3u2wey05yeh70p9m5n05kftku30uqjlqy0gjh2,addr_xsk1fzw9r482t0ekua7rcqewg3k8ju5d9run4juuehm2p24jtuzz4dg4wpeulnqhualvtx9lyy7u0h9pdjvmyhxdhzsyy49szs6y8c9zwfp0eqyrqyl290e6dr0q3fvngmsjn4aask9jjr6q34juh25hczw3euust0dw")] 56 | [InlineData("stake1uyneva7s00qnhmwnl9a6kzvahcqf7v3sa4h9wh970dxl6egwp9mlw", "addr_xsk1fzw9r482t0ekua7rcqewg3k8ju5d9run4juuehm2p24jtuzz4dg4wpeulnqhualvtx9lyy7u0h9pdjvmyhxdhzsyy49szs6y8c9zwfp0eqyrqyl290e6dr0q3fvngmsjn4aask9jjr6q34juh25hczw3euust0dw")] 57 | [InlineData("stake1uyneva7s00qnhmwnl9a6kzvahcqf7v3sa4h9wh970dxl6egwp9mlw", "addr_xsk15pt6dccwyy2jjgmv9gxszjyzc6kchhas2dr9q6ky0xpwz4679e2t5qu0yehpmg7xr3sc3wkcyagujlk2euwl0007w68wcfdm7ajl2tzkqve7vmqds5sf38syns3u2wey05yeh70p9m5n05kftku30uqjlqy0gjh2,addr_xsk1fzw9r482t0ekua7rcqewg3k8ju5d9run4juuehm2p24jtuzz4dg4wpeulnqhualvtx9lyy7u0h9pdjvmyhxdhzsyy49szs6y8c9zwfp0eqyrqyl290e6dr0q3fvngmsjn4aask9jjr6q34juh25hczw3euust0dw")] 58 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_CborHex_Is_Not_Valid_Hexadecimal( 59 | string invalidCborHex, string signingKeys) 60 | { 61 | var command = new SignTransactionCommand() 62 | { 63 | SigningKeys = signingKeys, 64 | CborHex = invalidCborHex, 65 | }; 66 | 67 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 68 | 69 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 70 | executionResult.Result.Should().Be($"Invalid option --cbor-hex {invalidCborHex} is not in hexadecimal format"); 71 | } 72 | 73 | [Theory] 74 | [InlineData("84a50081825820dcfe996519321071430c812525393f431d75208428852491e9c0c6788dad5f9201018282581d6079c37fabad08662e16ad4950edd63d2a2ab0b63f8a44e4a504511ef51a1908b10082581d60282e5ee5d1e89e04fa81382df239d6733409875d75b480c879f586001a5cf39dd9021a00029ee5031a03afdc580758200088270ea98923127ef4c2e05b665b81b5a6c9fca1582eed1171ba17648f7b3da0f582a11902a2a1636d73676d74687820666f72206c756e636880", 75 | "addr_xsk1fzw9r482t0ekua7rcqewg3k8ju5d9run4juuehm2p24jtuzz4dg4wpeulnqhualvtx9lyy7u0h9pdjvmyhxdhzsyy49szs6y8c9zwfp0eqyrqyl290e6dr0q3fvngmsjn4aask9jjr6q34juh25hczw3euust0dw", 76 | "84a50081825820dcfe996519321071430c812525393f431d75208428852491e9c0c6788dad5f9201018282581d6079c37fabad08662e16ad4950edd63d2a2ab0b63f8a44e4a504511ef51a1908b10082581d60282e5ee5d1e89e04fa81382df239d6733409875d75b480c879f586001a5cf39dd9021a00029ee5031a03afdc580758200088270ea98923127ef4c2e05b665b81b5a6c9fca1582eed1171ba17648f7b3da10081825820de9503426759fa18624657f5bcc932f38220ec9eceb262907caf2d198b6e0faa5840d856197bc4f4cb62439ea9c2781e9764855685c3809364ef759b1926047d7bb326fecf2ee1144c5d49cf2f53feb432fa1af30e00d8d69c4145e6494fd1979a0cf582a11902a2a1636d73676d74687820666f72206c756e636880")] 77 | public async Task Execute_Successfully_With_Correct_Signed_Cbor_When_Options_Are_Valid(string cborHex, string signingKeys, string expectedCborHex) 78 | { 79 | var command = new SignTransactionCommand() 80 | { 81 | SigningKeys = signingKeys, 82 | CborHex = cborHex, 83 | }; 84 | 85 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 86 | 87 | executionResult.Outcome.Should().Be(CommandOutcome.Success); 88 | executionResult.Result.Should().Be(expectedCborHex); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /Tests/ConsoleTool.UnitTests/SubmitTransactionCommandShould.cs: -------------------------------------------------------------------------------- 1 | using Cscli.ConsoleTool.Transaction; 2 | using FluentAssertions; 3 | using Xunit; 4 | 5 | namespace Cscli.ConsoleTool.UnitTests; 6 | 7 | public class SubmitTransactionCommandShould 8 | { 9 | [Theory] 10 | [InlineData("")] 11 | [InlineData("a")] 12 | [InlineData("test")] 13 | [InlineData("tastnet")] 14 | [InlineData("Mainet")] 15 | [InlineData("mainet")] 16 | [InlineData("mainnetwork")] 17 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Network_Is_Not_Valid( 18 | string network) 19 | { 20 | var command = new SubmitTransactionCommand() 21 | { 22 | Network = network, 23 | CborHex = "83a500818258205f61dde2c9c05c104f81194f2cfc738b4463f098e46fa1ca62aedb1345561624000182825839005a99cb175eb944462d6bfd29d06e0a69defc091d8e5ecab740afac6f1922fcdeeb6df8592d78b20c6e22fdb73fa9446aad05626d78000b7f181982583900ae34b08e5a409e1e66683d0b04ff33bb7c5c1455046ad66ebe2b66d157664134527cd7cb875caa34251f7e063b337cd705649637c35df6c71bfffffffffffd1e5e021a0002e1ed031a037c8bb70758205fbac14ec74ffff7a1aa1b1acbf4bfed1ce774bf21a620092f647a04553b65d5a1008182582008c77407d35dab5e3f53ef4ad5066284ca269c8107e88de04fcdfb875de9a7055840d7250f2b39c8d3014aaa8fe6ba60f0b52a27240a6b8ae7f72d64079a4852acb4ecffb3559a5fb829d9868f0cd9806e567bc710f73513ba6eb9a699f71bb1800182a1183da1646e616d65783754657374202d204669786564206e6577206172726179207673206e6577206d617020666f7220656d707479207769746e6573732073657480", 24 | }; 25 | 26 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 27 | 28 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 29 | executionResult.Result.Should().StartWith("Invalid option --network must be either testnet or mainnet"); 30 | } 31 | 32 | [Theory] 33 | [InlineData(null, "testnet")] 34 | [InlineData(null, "mainnet")] 35 | [InlineData("", "testnet")] 36 | [InlineData("", "mainnet")] 37 | [InlineData(" ", "testnet")] 38 | [InlineData(" ", "mainnet")] 39 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_CborHex_Is_Null_Or_Whitespace( 40 | string invalidCborHex, string network) 41 | { 42 | var command = new SubmitTransactionCommand() 43 | { 44 | Network = network, 45 | CborHex = invalidCborHex, 46 | }; 47 | 48 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 49 | 50 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 51 | executionResult.Result.Should().Be($"Invalid option --cbor-hex is required"); 52 | } 53 | 54 | [Theory] 55 | [InlineData("fff", "testnet")] 56 | [InlineData("fff", "mainnet")] 57 | [InlineData("addr1qyg4gu4vfd3775glq8rjm85x2crmysc920hf5qjj8m7rxef8jemaq77p80ka87tm4vyem0sqnuerpmtw2awtu76dl4jssqfzz4", "testnet")] 58 | [InlineData("addr1qyg4gu4vfd3775glq8rjm85x2crmysc920hf5qjj8m7rxef8jemaq77p80ka87tm4vyem0sqnuerpmtw2awtu76dl4jssqfzz4", "mainnet")] 59 | [InlineData("stake1uyneva7s00qnhmwnl9a6kzvahcqf7v3sa4h9wh970dxl6egwp9mlw", "testnet")] 60 | [InlineData("stake1uyneva7s00qnhmwnl9a6kzvahcqf7v3sa4h9wh970dxl6egwp9mlw", "mainnet")] 61 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_CborHex_Is_Not_Valid_Hexadecimal( 62 | string invalidCborHex, string network) 63 | { 64 | var command = new SubmitTransactionCommand() 65 | { 66 | Network = network, 67 | CborHex = invalidCborHex, 68 | }; 69 | 70 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 71 | 72 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 73 | executionResult.Result.Should().Be($"Invalid option --cbor-hex {invalidCborHex} is not in hexadecimal format"); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /Tests/ConsoleTool.UnitTests/ViewTransactionCommandShould.cs: -------------------------------------------------------------------------------- 1 | using Cscli.ConsoleTool.Transaction; 2 | using FluentAssertions; 3 | using Xunit; 4 | 5 | namespace Cscli.ConsoleTool.UnitTests; 6 | 7 | public class ViewTransactionCommandShould 8 | { 9 | [Theory] 10 | [InlineData("")] 11 | [InlineData("a")] 12 | [InlineData("test")] 13 | [InlineData("tastnet")] 14 | [InlineData("Mainet")] 15 | [InlineData("mainet")] 16 | [InlineData("mainnetwork")] 17 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_Network_Is_Not_Valid( 18 | string network) 19 | { 20 | var command = new ViewTransactionCommand() 21 | { 22 | Network = network, 23 | CborHex = "83a500818258205f61dde2c9c05c104f81194f2cfc738b4463f098e46fa1ca62aedb1345561624000182825839005a99cb175eb944462d6bfd29d06e0a69defc091d8e5ecab740afac6f1922fcdeeb6df8592d78b20c6e22fdb73fa9446aad05626d78000b7f181982583900ae34b08e5a409e1e66683d0b04ff33bb7c5c1455046ad66ebe2b66d157664134527cd7cb875caa34251f7e063b337cd705649637c35df6c71bfffffffffffd1e5e021a0002e1ed031a037c8bb70758205fbac14ec74ffff7a1aa1b1acbf4bfed1ce774bf21a620092f647a04553b65d5a1008182582008c77407d35dab5e3f53ef4ad5066284ca269c8107e88de04fcdfb875de9a7055840d7250f2b39c8d3014aaa8fe6ba60f0b52a27240a6b8ae7f72d64079a4852acb4ecffb3559a5fb829d9868f0cd9806e567bc710f73513ba6eb9a699f71bb1800182a1183da1646e616d65783754657374202d204669786564206e6577206172726179207673206e6577206d617020666f7220656d707479207769746e6573732073657480", 24 | }; 25 | 26 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 27 | 28 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 29 | executionResult.Result.Should().StartWith("Invalid option --network must be either testnet or mainnet"); 30 | } 31 | 32 | [Theory] 33 | [InlineData(null, "testnet")] 34 | [InlineData(null, "mainnet")] 35 | [InlineData("", "testnet")] 36 | [InlineData("", "mainnet")] 37 | [InlineData(" ", "testnet")] 38 | [InlineData(" ", "mainnet")] 39 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_CborHex_Is_Null_Or_Whitespace( 40 | string invalidCborHex, string network) 41 | { 42 | var command = new ViewTransactionCommand() 43 | { 44 | Network = network, 45 | CborHex = invalidCborHex, 46 | }; 47 | 48 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 49 | 50 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 51 | executionResult.Result.Should().Be($"Invalid option --cbor-hex is required"); 52 | } 53 | 54 | [Theory] 55 | [InlineData("0", "testnet")] 56 | [InlineData("0", "mainnet")] 57 | [InlineData("fff", "testnet")] 58 | [InlineData("fff", "mainnet")] 59 | [InlineData("addr1qyg4gu4vfd3775glq8rjm85x2crmysc920hf5qjj8m7rxef8jemaq77p80ka87tm4vyem0sqnuerpmtw2awtu76dl4jssqfzz4", "testnet")] 60 | [InlineData("addr1qyg4gu4vfd3775glq8rjm85x2crmysc920hf5qjj8m7rxef8jemaq77p80ka87tm4vyem0sqnuerpmtw2awtu76dl4jssqfzz4", "mainnet")] 61 | [InlineData("stake1uyneva7s00qnhmwnl9a6kzvahcqf7v3sa4h9wh970dxl6egwp9mlw", "testnet")] 62 | [InlineData("stake1uyneva7s00qnhmwnl9a6kzvahcqf7v3sa4h9wh970dxl6egwp9mlw", "mainnet")] 63 | public async Task Execute_Unsuccessfully_With_FailureInvalidOptions_When_CborHex_Is_Not_Valid_Hexadecimal( 64 | string invalidCborHex, string network) 65 | { 66 | var command = new ViewTransactionCommand() 67 | { 68 | Network = network, 69 | CborHex = invalidCborHex, 70 | }; 71 | 72 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 73 | 74 | executionResult.Outcome.Should().Be(CommandOutcome.FailureInvalidOptions); 75 | executionResult.Result.Should().Be($"Invalid option --cbor-hex {invalidCborHex} is not in hexadecimal format"); 76 | } 77 | 78 | [Theory] 79 | [InlineData("84a50081825820dcfe996519321071430c812525393f431d75208428852491e9c0c6788dad5f9201018282581d6079c37fabad08662e16ad4950edd63d2a2ab0b63f8a44e4a504511ef51a1908b10082581d60282e5ee5d1e89e04fa81382df239d6733409875d75b480c879f586001a5cf39dd9021a00029ee5031a03afdc580758200088270ea98923127ef4c2e05b665b81b5a6c9fca1582eed1171ba17648f7b3da0f582a11902a2a1636d73676d74687820666f72206c756e636880", "testnet", 80 | @"{ 81 | ""id"": ""n/a"", 82 | ""isValid"": true, 83 | ""transactionBody"": { 84 | ""inputs"": [ 85 | { 86 | ""transactionId"": ""dcfe996519321071430c812525393f431d75208428852491e9c0c6788dad5f92"", 87 | ""transactionIndex"": 1 88 | } 89 | ], 90 | ""outputs"": [ 91 | { 92 | ""address"": ""addr_test1vpuuxlat45yxvtsk44y4pmwk854z4v9k879yfe99q3g3aagqqzar3"", 93 | ""value"": { 94 | ""lovelaces"": 420000000, 95 | ""nativeAssets"": [] 96 | } 97 | }, 98 | { 99 | ""address"": ""addr_test1vq5zuhh9685fup86syuzmu3e6eengzv8t46mfqxg086cvqqc5zr4t"", 100 | ""value"": { 101 | ""lovelaces"": 1559469529, 102 | ""nativeAssets"": [] 103 | } 104 | } 105 | ], 106 | ""mint"": [], 107 | ""fee"": 171749, 108 | ""ttl"": 61856856, 109 | ""auxiliaryDataHash"": ""0088270ea98923127ef4c2e05b665b81b5a6c9fca1582eed1171ba17648f7b3d"", 110 | ""transactionStartInterval"": null 111 | }, 112 | ""transactionWitnessSet"": null, 113 | ""auxiliaryData"": { 114 | ""metadata"": { 115 | ""674"": { 116 | ""msg"": ""thx for lunch"" 117 | } 118 | } 119 | } 120 | }")] 121 | [InlineData("84a500818258205853cc86af075cc547a5a20658af54841f37a5832532a704c583ed4f010184a501018282581d6079c37fabad08662e16ad4950edd63d2a2ab0b63f8a44e4a504511ef51a1908b10082581d60282e5ee5d1e89e04fa81382df239d6733409875d75b480c879f586001a43e80724021a0002c24d031a03afe00c0758200088270ea98923127ef4c2e05b665b81b5a6c9fca1582eed1171ba17648f7b3da10081825820de9503426759fa18624657f5bcc932f38220ec9eceb262907caf2d198b6e0faa584025f49ad0cb27c0a297ebd2237134be2803b19d11c6e52416d3d7beba130bbc2bd95eb9b7e9e7410d7efcd5c2abd338dd62100d86b26308636335b533873bb508f582a11902a2a1636d73676d74687820666f72206c756e636880", "testnet", 122 | @"{ 123 | ""id"": ""03818a7d5875bf67523dea56a37e5654e549f095b55888dc53bbe9ef42824125"", 124 | ""isValid"": true, 125 | ""transactionBody"": { 126 | ""inputs"": [ 127 | { 128 | ""transactionId"": ""5853cc86af075cc547a5a20658af54841f37a5832532a704c583ed4f010184a5"", 129 | ""transactionIndex"": 1 130 | } 131 | ], 132 | ""outputs"": [ 133 | { 134 | ""address"": ""addr_test1vpuuxlat45yxvtsk44y4pmwk854z4v9k879yfe99q3g3aagqqzar3"", 135 | ""value"": { 136 | ""lovelaces"": 420000000, 137 | ""nativeAssets"": [] 138 | } 139 | }, 140 | { 141 | ""address"": ""addr_test1vq5zuhh9685fup86syuzmu3e6eengzv8t46mfqxg086cvqqc5zr4t"", 142 | ""value"": { 143 | ""lovelaces"": 1139279652, 144 | ""nativeAssets"": [] 145 | } 146 | } 147 | ], 148 | ""mint"": [], 149 | ""fee"": 180813, 150 | ""ttl"": 61857804, 151 | ""auxiliaryDataHash"": ""0088270ea98923127ef4c2e05b665b81b5a6c9fca1582eed1171ba17648f7b3d"", 152 | ""transactionStartInterval"": null 153 | }, 154 | ""transactionWitnessSet"": { 155 | ""vKeyWitnesses"": [ 156 | { 157 | ""verificationkey"": ""de9503426759fa18624657f5bcc932f38220ec9eceb262907caf2d198b6e0faa"", 158 | ""signature"": ""25f49ad0cb27c0a297ebd2237134be2803b19d11c6e52416d3d7beba130bbc2bd95eb9b7e9e7410d7efcd5c2abd338dd62100d86b26308636335b533873bb508"" 159 | } 160 | ], 161 | ""nativeScripts"": [] 162 | }, 163 | ""auxiliaryData"": { 164 | ""metadata"": { 165 | ""674"": { 166 | ""msg"": ""thx for lunch"" 167 | } 168 | } 169 | } 170 | }")] 171 | public async Task Execute_Successfully_With_Correct_Json_When_Options_Are_Valid(string cborHex, string network, string expectedJson) 172 | { 173 | var command = new ViewTransactionCommand() 174 | { 175 | Network = network, 176 | CborHex = cborHex, 177 | }; 178 | 179 | var executionResult = await command.ExecuteAsync(CancellationToken.None); 180 | 181 | executionResult.Outcome.Should().Be(CommandOutcome.Success); 182 | executionResult.Result.Should().Be(expectedJson); 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /build.ps1: -------------------------------------------------------------------------------- 1 | dotnet clean 2 | dotnet restore 3 | dotnet build --no-restore -c Release 4 | dotnet test --no-build -c Release 5 | dotnet pack --no-build Src/ConsoleTool/CsCli.ConsoleTool.csproj -o nupkg -c Release 6 | 7 | # Generate cross-platform executables 8 | #dotnet publish --no-build Src/ConsoleTool/CsCli.ConsoleTool.csproj -c Release -o release --nologo 9 | #dotnet publish -r win-x64 Src/ConsoleTool/CsCli.ConsoleTool.csproj -c Release -o release -p:PublishSingleFile=true -p:PublishTrimmed=true -p:AssemblyName=cscli --self-contained true 10 | #dotnet publish -r linux-x64 Src/ConsoleTool/CsCli.ConsoleTool.csproj -c Release -o release -p:PublishSingleFile=true -p:PublishTrimmed=true -p:AssemblyName=cscli --self-contained true 11 | #dotnet publish -r osx-x64 Src/ConsoleTool/CsCli.ConsoleTool.csproj -c Release -o release -p:PublishSingleFile=true --self-contained true 12 | #dotnet publish -r osx.12-arm64 Src/ConsoleTool/CsCli.ConsoleTool.csproj -c Release -o release -p:PublishSingleFile=true --self-contained true 13 | 14 | # Another way (per target) 15 | #$targets = @("win-x64", "linux-x64", "osx-x64") 16 | #foreach ($target in $targets) { 17 | # $tag=$(git describe --tags --abbrev=0) 18 | # $release_name="cscli-$tag-$target" 19 | # dotnet publish Src/ConsoleTool/CsCli.ConsoleTool.csproj -r $target -c Release -o $release_name "-p:PublishSingleFile=true" "-p:AssemblyName=cscli.$target" --self-contained true 20 | #} --------------------------------------------------------------------------------