Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions BitcoinRpcSharp/BitcoinRpcException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,26 @@ protected BitcoinRpcException(System.Runtime.Serialization.SerializationInfo inf
{
}
}


[Serializable]
public class BitcoinRpcServerErrorException : BitcoinRpcException
{
public BitcoinRpcServerErrorException() { }
public BitcoinRpcServerErrorException(string message) : base(message) { }
public BitcoinRpcServerErrorException(string message, Exception inner) : base(message, inner) { }
protected BitcoinRpcServerErrorException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
public JsonRpcResponse<object> JsonObject { get; set; }

public RPCErrorCode RpcErrorCode
{
get
{
return JsonObject.Error.Code;
}
}
}
}
14 changes: 12 additions & 2 deletions BitcoinRpcSharp/BitcoinRpcSharp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
<AssemblyName>BitcoinRpcSharp</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\..\src\</SolutionDir>
<RestorePackages>true</RestorePackages>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
Expand All @@ -35,8 +37,9 @@
<StartupObject />
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json">
<HintPath>..\packages\Newtonsoft.Json.5.0.6\lib\net45\Newtonsoft.Json.dll</HintPath>
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\src\packages\Newtonsoft.Json.6.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
Expand Down Expand Up @@ -84,6 +87,13 @@
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
Expand Down
20 changes: 20 additions & 0 deletions BitcoinRpcSharp/BitcoinWallet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,26 @@ public List<ListTransaction> ListTransactions(string account = "", int count = 1
return MakeRequest<List<ListTransaction>>("listtransactions", account, count, from);
}

public List<ListTransaction> BlockChainListTransactions(string account = "", int count = 10, int from = 0)
{
var list= MakeRequest<TransactionsSinceBlock>("listtransactions", account, count, from);
return list.transactions.Select(p => new ListTransaction()
{
Account = p.Account,
Address = p.Address,
Amount = p.Amount,
BlockHash = p.BlockHash,
BlockIndex = p.BlockIndex,
BlockTime = p.BlockTime,
Category = p.Category,
Confirmations = p.Confirmations,
Generated = p.Generated,
Time = p.Time,
TimeReceived = p.TimeReceived,
TxId = p.TxId
}).ToList();
}

/// <summary>
/// Version 0.7: Returns array of unspent transaction inputs in the wallet.
/// </summary>
Expand Down
42 changes: 38 additions & 4 deletions BitcoinRpcSharp/BitcoinWalletBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System;
using System.IO;
using System.Net;
using System.Text;

namespace BitcoinRpcSharp
{
Expand Down Expand Up @@ -63,6 +64,12 @@ private JsonRpcResponse<T> MakeRpcRequest<T>(JsonRpcRequest jsonRpcRequest)
return GetRpcResponse<T>(httpWebRequest);
}

static void SetBasicAuthHeader(WebRequest request, String userName, String userPassword)
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
}
/// <summary>
/// Make the actual HTTP request to the Bitcoin RPC interface.
/// </summary>
Expand All @@ -71,12 +78,12 @@ private JsonRpcResponse<T> MakeRpcRequest<T>(JsonRpcRequest jsonRpcRequest)
private HttpWebRequest MakeHttpRequest(JsonRpcRequest jsonRpcRequest)
{
var webRequest = (HttpWebRequest)WebRequest.Create(RpcUrl);
webRequest.Credentials = new NetworkCredential(RpcUser, RpcPassword);

//webRequest.Credentials = new NetworkCredential(RpcUser, RpcPassword);
SetBasicAuthHeader(webRequest, RpcUser, RpcPassword);
// Important, otherwise the service can't deserialse your request properly
webRequest.ContentType = "application/json-rpc";
webRequest.Method = "POST";
webRequest.Timeout = 2000; // 2 seconds
webRequest.Timeout = 100 * 1000; // 2 seconds

byte[] byteArray = jsonRpcRequest.GetBytes();
webRequest.ContentLength = byteArray.Length;
Expand Down Expand Up @@ -107,9 +114,12 @@ private JsonRpcResponse<T> GetRpcResponse<T>(HttpWebRequest httpWebRequest)
{
string json = GetJsonResponse(httpWebRequest);

var jsonSerializerSettings = new JsonSerializerSettings();
jsonSerializerSettings.MissingMemberHandling = MissingMemberHandling.Ignore;

try
{
return JsonConvert.DeserializeObject<JsonRpcResponse<T>>(json);
return JsonConvert.DeserializeObject<JsonRpcResponse<T>>(json, jsonSerializerSettings);
}
catch (JsonException jsonEx)
{
Expand Down Expand Up @@ -154,7 +164,31 @@ private string GetJsonResponse(HttpWebRequest httpWebRequest)
{
switch (webResponse.StatusCode)
{

case HttpStatusCode.InternalServerError:
{
using (var stream = webResponse.GetResponseStream())
using (var reader = new StreamReader(stream))
{
string result = reader.ReadToEnd();
reader.Close();

if (LogJsonResultToConsole)
{
Console.WriteLine(JsonFormatter.PrettyPrint(result));
}
try
{
var obj = JsonConvert.DeserializeObject<JsonRpcResponse<object>>(result);
throw new BitcoinRpcServerErrorException(result, webEx) { JsonObject = obj };
}
catch (JsonException)
{
throw new BitcoinRpcException(result, webEx);
}
//throw new BitcoinRpcException(result,webEx);
}
}
throw new BitcoinRpcException("The RPC request was either not understood by the Bitcoin server or there was a problem executing the request.", webEx);
}
}
Expand Down
4 changes: 4 additions & 0 deletions BitcoinRpcSharp/JsonRpcRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ public class JsonRpcRequest
[JsonProperty(PropertyName = "method", Order = 0)]
public string Method { get; set; }

[JsonProperty(PropertyName = "jsonrpc", Order = 3)]
public string JsonRpc { get; set; }

/// <summary>
/// A list of parameters to pass to the method.
/// </summary>
Expand All @@ -39,6 +42,7 @@ public JsonRpcRequest(int id, string method, params object[] parameters)
Id = id;
Method = method;

JsonRpc = "2.0";
if (parameters != null)
{
Parameters = parameters.ToList<object>();
Expand Down
61 changes: 54 additions & 7 deletions BitcoinRpcSharp/JsonRpcResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,66 @@ public class JsonRpcResponse<T>
/// The error returned by the wallet, if any.
/// </summary>
[JsonProperty(PropertyName = "error", Order = 2)]
public string Error { get; set; }
public RpcError Error { get; set; }

[JsonProperty(PropertyName = "jsonrpc", Order = 2)]
public string JsonRpc { get; set; }
/// <summary>
/// Create a new JSON RPC response with the given id, error and result object.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="error">The error.</param>
/// <param name="result">The result object.</param>
public JsonRpcResponse(int id, string error, T result)
{
Id = id;
Error = error;
Result = result;
}
//public JsonRpcResponse(int id, string error, T result)
//{
// Id = id;
// Error = error;
// Result = result;
//}
}

public class RpcError
{
[JsonProperty(PropertyName = "code")]
public RPCErrorCode Code { get; set; }
[JsonProperty(PropertyName = "message")]
public string Message { get; set; }
}

public enum RPCErrorCode
{
// Standard JSON-RPC 2.0 errors
RPC_INVALID_REQUEST = -32600,
RPC_METHOD_NOT_FOUND = -32601,
RPC_INVALID_PARAMS = -32602,
RPC_INTERNAL_ERROR = -32603,
RPC_PARSE_ERROR = -32700,

// General application defined errors
RPC_MISC_ERROR = -1, // std::exception thrown in command handling
RPC_FORBIDDEN_BY_SAFE_MODE = -2, // Server is in safe mode, and command is not allowed in safe mode
RPC_TYPE_ERROR = -3, // Unexpected type was passed as parameter
RPC_INVALID_ADDRESS_OR_KEY = -5, // Invalid address or key
RPC_OUT_OF_MEMORY = -7, // Ran out of memory during operation
RPC_INVALID_PARAMETER = -8, // Invalid, missing or duplicate parameter
RPC_DATABASE_ERROR = -20, // Database error
RPC_DESERIALIZATION_ERROR = -22, // Error parsing or validating structure in raw format

// P2P client errors
RPC_CLIENT_NOT_CONNECTED = -9, // Bitcoin is not connected
RPC_CLIENT_IN_INITIAL_DOWNLOAD = -10, // Still downloading initial blocks
RPC_CLIENT_NODE_ALREADY_ADDED = -23, // Node is already added
RPC_CLIENT_NODE_NOT_ADDED = -24, // Node has not been added before

// Wallet errors
RPC_WALLET_ERROR = -4, // Unspecified problem with wallet (key not found etc.)
RPC_WALLET_INSUFFICIENT_FUNDS = -6, // Not enough funds in wallet or account
RPC_WALLET_INVALID_ACCOUNT_NAME = -11, // Invalid account name
RPC_WALLET_KEYPOOL_RAN_OUT = -12, // Keypool ran out, call keypoolrefill first
RPC_WALLET_UNLOCK_NEEDED = -13, // Enter the wallet passphrase with walletpassphrase first
RPC_WALLET_PASSPHRASE_INCORRECT = -14, // The wallet passphrase entered was incorrect
RPC_WALLET_WRONG_ENC_STATE = -15, // Command given in wrong wallet encryption state (encrypting an encrypted wallet etc.)
RPC_WALLET_ENCRYPTION_FAILED = -16, // Failed to encrypt the wallet
RPC_WALLET_ALREADY_UNLOCKED = -17, // Wallet is already unlocked
};
}
2 changes: 1 addition & 1 deletion BitcoinRpcSharp/Responses/Block.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public class Block
public string MerkleRoot { get; set; }
public List<string> Tx { get; set; }
public int Time { get; set; }
public int Nonce { get; set; }
public uint Nonce { get; set; }
public string Bits { get; set; }
public double Difficulty { get; set; }
public string NextBlockHash { get; set; }
Expand Down
2 changes: 2 additions & 0 deletions BitcoinRpcSharp/Responses/Transaction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,7 @@ public class Transaction
public string Comment { get; set; }
public string To { get; set; }
public List<TransactionDetail> Details { get; set; }
public string BlockHash { get; set; }
public int BlockIndex { get; set; }
}
}
5 changes: 5 additions & 0 deletions BitcoinRpcSharp/Responses/TransactionSinceBlock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,10 @@ public class TransactionSinceBlock
public string TxId { get; set; }
public int Time { get; set; }
public int TimeReceived { get; set; }
public string BlockHash { get; set; }
public int BlockIndex { get; set; }
public int BlockTime { get; set; }

public bool Generated { get; set; }
}
}
2 changes: 1 addition & 1 deletion BitcoinRpcSharp/packages.config
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="5.0.6" targetFramework="net45" />
<package id="Newtonsoft.Json" version="6.0.3" targetFramework="net45" />
</packages>