PSGridCoin.psm1

function Get-grcBanned {
    $RequestParameters = @{
        method = "listbanned"
    }

    $results = (Invoke-grcRPCRequest -RequestParameters $RequestParameters -OutVariable result).results
    if ($results -ne $Null){
        $results
    }
    else{
        Write-Warning "No banned ips or subnets found"
    }
    
}
function Get-grcBestBlockHash{
    $RequestParameters = @{
        method = "getbestblockhash"
    }
    (Invoke-grcRPCRequest -RequestParameters $RequestParameters).result
}
function Get-grcBlockByNumber {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory,ValueFromPipelineByPropertyName,ValueFromPipeline)]
        [int]$Number,
        [switch]$IncludeTxInfo
    )
    
    $RequestParameters = @{
        method = "getblockbynumber"
        params = [array]@($Number, $IncludeTxInfo.IsPresent)
    }
    (Invoke-grcRPCRequest -RequestParameters $RequestParameters).result
}
function Get-grcBlockChainInfo {
    $RequestParameters = @{
        method = "getblockchaininfo"
    }
    (Invoke-grcRPCRequest -RequestParameters $RequestParameters).result
}
function Get-grcBlockCount {

    $RequestParameters = @{
        method = "getblockcount"
    }

    if ((Invoke-grcRPCRequest -RequestParameters $RequestParameters -OutVariable results).result -ne $Null){
        [PSCustomObject]@{
            BlockCount = $results.result
            RequestId = $results.id
        }
    }
}
function Get-grcCheckPoint {
    $RequestParameters = @{
        method = "getcheckpoint"
    }

    (Invoke-grcRPCRequest -RequestParameters $RequestParameters).result
}
function Get-grcConnectionCount {
    $RequestParameters = @{
        method = "getconnectioncount"
    }

    $results = Invoke-grcRPCRequest -RequestParameters $RequestParameters
    if ($results.result -ne $null){
        [PSCustomObject]@{
            ConnectionCount = $results.result
            RequestId = $results.id
        }
    }
}
function Get-grcDifficulty {
    $RequestParameters = @{
        method = "getdifficulty"
    }

    $results = (Invoke-grcRPCRequest -RequestParameters $RequestParameters -OutVariable ID).result
    $results | Add-Member -MemberType NoteProperty -Name RequestId -Value $ID.Id
    $results
}
function Get-grcInfo {

    $RequestParameters = @{
        method = "getinfo"
    }

    (Invoke-grcRPCRequest -RequestParameters $RequestParameters).result
}
function Get-grcNetTotals {
    $RequestParameters = @{
        method = "getnettotals"
    }

    $results = (Invoke-grcRPCRequest -RequestParameters $RequestParameters -OutVariable ID).result
    $results | Add-Member -MemberType NoteProperty -Name RequestId -Value $ID.Id
    $results
}
function Get-grcNetworkInfo {
    $RequestParameters = @{
        method = "getnetworkinfo"
    }

    $results = (Invoke-grcRPCRequest -RequestParameters $RequestParameters -OutVariable ID).result
    $results | Add-Member -MemberType NoteProperty -Name RequestId -Value $ID.Id
    $results
}
function Get-grcPeerInfo {
    $RequestParameters = @{
        method = "getpeerinfo"
    }

    $results = (Invoke-grcRPCRequest -RequestParameters $RequestParameters -OutVariable ID).result
    $results | Add-Member -MemberType NoteProperty -Name RequestId -Value $ID.Id
    $results
}
function Get-grcPollResults {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
        [string]$PollName,
        [bool]$ShowExpired
    )

    $RequestParameters = @{
        method = "getpollresults"
        params = [array]@($PollName)
    }

    Write-Warning "This will take a few moments and your GUI wallet will become unresponsive if open"
    (Invoke-grcRPCRequest -RequestParameters $RequestParameters).result
    #Write-Warning "Function not implemented"
}
function Get-grcPolls{
    param(
        [switch]$IncludeFinishedPolls
    )
    $RequestParameters = @{
        method = "listpolls"
        params = [array]@($IncludeFinishedPolls.IsPresent)
    }

    (Invoke-grcRPCRequest -RequestParameters $RequestParameters).result
}
function Get-grcRawMemPool {
    $RequestParameters = @{
        method = "getrawmempool"
    }

    $results = Invoke-grcRPCRequest -RequestParameters $RequestParameters
    [PSCustomObject]@{
        RawMemPool = $results.result
        RequestId = $results.id
    }
}
function Set-grcCredential {
    [CmdletBinding(DefaultParameterSetName="Credentials")]
    param(
        [Parameter(ParameterSetName = "Credentials")]
        [pscredential]$Credential,

        [Parameter(ParameterSetName="Auto")]
        [switch]$AutoGenerate
    )

    if (-not$AutoGenerate.IsPresent){
        $Credential = Get-Credential -Message "Enter in a long rpc password - You will not need to remember this!" -UserName "gridcoinrpc"
    }

    $Config = Get-grcConfig
    $UserName = $Config | Select-String -SimpleMatch "rpcuser" | foreach {$_.line.split('=')[1]}
    $Password = $Config | Select-String -SimpleMatch "rpcpassword" | foreach {$_.line.split('=')[1]} | ConvertTo-SecureString -AsPlainText -Force
    if ([string]::IsNullOrEmpty($UserName) -and [string]::IsNullOrEmpty($Password) -or $true){
        if ($PSCmdlet.ParameterSetName -eq "Credentials"){
            if ($Credential.Password.Length -gt 0){
                $Config += "rpcuser=$($Credential.UserName)"
                $Config += "rpcpassword=$($Credential.GetNetworkCredential().Password)"
            }
            else{
                Write-Error -Message "Password not given" -ErrorAction Stop
            }
            
        }
        elseif ($AutoGenerate){
            $Config += "rpcuser=gridcoinrpc"
            $Config += "rpcpassword=$(New-grcPassword)"
        }

        Set-Content -Path "$ENV:APPDATA\GridcoinResearch\gridcoinresearch.conf" -Value $Config -Force -PassThru
        Write-Warning "You will need to restart the GridCoin Wallet in order for the changes to take effect!"
    }
    else{
        Write-Error -Message "Username or password already set in config file!"
    }  
}
function Get-grcConfig {
    try{
        $GridCoinConfigPath = "$ENV:APPDATA\GridcoinResearch\gridcoinresearch.conf"
        if (Test-Path -Path $GridCoinConfigPath){
            Get-Content $GridCoinConfigPath
        }
        else{
            Write-Error -Exception [System.IO.FileNotFoundException] -Message "Config file was not found in default location of $GridCoinConfigPath!"
        }
    }
    catch{
        $PSCmdlet.WriteError($_)
    } 
}
function Get-grcCredential {
    [CmdletBinding()]
    param()
    try{
        $Config = Get-grcConfig
        $UserName = $Config | Select-String -SimpleMatch "rpcuser" | foreach {$_.line.split('=')[1]}
        $Password = $Config | Select-String -SimpleMatch "rpcpassword" | foreach {$_.line.split('=')[1]} | ConvertTo-SecureString -AsPlainText -Force
        if ([string]::IsNullOrEmpty($UserName) -or [string]::IsNullOrEmpty($Password)){
            Write-Error -Message "Username or password not set in config file! Please add these to your config file to communicate with the RPC using Set-grcCredential"
        }
        else{
            [pscredential]::new($UserName,$Password)
        }
    }
    catch{
        $PSCmdlet.WriteError($_)
    }  
}
function Invoke-grcRPCRequest{
    [cmdletbinding()]
    param(
        $RequestParameters
    )
    try{
        $Global:RequestId++
        $RequestParameters["id"] = $Global:RequestId
        $Json = $RequestParameters | ConvertTo-Json
        $grcCredential = Get-grcCredential -ErrorAction Stop
        
        $RequestParameters = @{
            URI = "http://127.0.0.1:15715/"
            Method = "Post"
            ContentType = "application/json"
            Credential = $grcCredential
            Body = $Json
        }

        Invoke-RestMethod @RequestParameters
    }
    catch{
        if ($_.Exception.Message -like "*Unable to connect to the remote server*"){
            Write-Warning "Make sure to add server=1 and rpcallowip=127.0.0.1 to config file"
        }
        $PSCmdlet.WriteError($_)
    }
}
function New-grcPassword {
    $Length = 0..20
    [System.Collections.ArrayList]$ASCII = @(48..57)
    65..90 | foreach {$ASCII.Add($_)} | Out-Null
    97..122 | foreach {$ASCII.Add($_)} | Out-Null
    ($Length | foreach {[char](Get-Random -InputObject $ASCII)}) -join ""
}
Export-ModuleMember -function Get-grcBanned, Get-grcBestBlockHash, Get-grcBlockByNumber, Get-grcBlockChainInfo, Get-grcBlockCount, Get-grcCheckPoint, Get-grcConnectionCount, Get-grcDifficulty, Get-grcInfo, Get-grcNetTotals, Get-grcNetworkInfo, Get-grcPeerInfo, Get-grcPollResults, Get-grcPolls, Get-grcRawMemPool, Set-grcCredential