├── LICENSE
├── README.md
├── demo
├── App.config
├── DemoClient.csproj
├── Program.cs
├── Properties
│ └── AssemblyInfo.cs
└── paket.references
├── paket.dependencies
├── paket.lock
└── src
├── BitcoinLib.sln
└── BitcoinLib
├── Auxiliary
├── Encoders
│ ├── ASCIIEncoder.cs
│ ├── DataEncoder.cs
│ └── HexEncoder.cs
├── GlobalConstants.cs
├── Hashing.cs
└── UnixTime.cs
├── BitcoinLib.csproj
├── CoinParameters
├── Base
│ ├── CoinConstants.cs
│ ├── CoinParameters.cs
│ └── ICoinParameters.cs
├── Bitcoin
│ ├── BitcoinConstants.cs
│ └── IBitcoinConstants.cs
├── Dallar
│ ├── DallarConstants.cs
│ └── IDallarConstants.cs
├── Dash
│ ├── DashConstants.cs
│ └── IDashConstants.cs
├── Dogecoin
│ ├── DogecoinConstants.cs
│ └── IDogecoinConstants.cs
├── Litecoin
│ ├── ILitecoinConstants.cs
│ └── LitecoinConstants.cs
├── Mogwaicoin
│ ├── IMogwaicoinConstants.cs
│ └── MogwaicoinConstants.cs
└── Smartcash
│ ├── ISmartcashConstants.cs
│ └── SmartcashConstants.cs
├── ExceptionHandling
├── RawTransactions
│ ├── RawTransactionExcessiveFeeException.cs
│ └── RawTransactionInvalidAmountException.cs
├── Rpc
│ ├── RpcException.cs
│ ├── RpcInternalServerErrorException.cs
│ ├── RpcRequestTimeoutException.cs
│ └── RpcResponseDeserializationException.cs
└── RpcExtenderService
│ └── GetAddressBalanceException.cs
├── ExtensionMethods
├── CoinServiceExtensionMethods.cs
└── DecimalExtensionMethods.cs
├── RPC
├── Connector
│ ├── IRpcConnector.cs
│ ├── RawRpcConnector.cs
│ └── RpcConnector.cs
├── RequestResponse
│ ├── JsonRpcError.cs
│ ├── JsonRpcRequest.cs
│ └── JsonRpcResponse.cs
└── Specifications
│ ├── RpcErrorCode.cs
│ └── RpcMethods.cs
├── Requests
├── AddNode
│ └── NodeAction.cs
├── CreateRawTransaction
│ ├── CreateRawTransactionInput.cs
│ ├── CreateRawTransactionOutput.cs
│ └── CreateRawTransactionRequest.cs
└── SignRawTransaction
│ ├── SigHashType.cs
│ ├── SignRawTransactionInput.cs
│ └── SignRawTransactionRequest.cs
├── Responses
├── Bridges
│ └── ITransactionResponse.cs
├── CreateMultiSigResponse.cs
├── DecodeRawTransactionResponse.cs
├── DecodeScriptResponse.cs
├── EstimateSmartFeeResponse.cs
├── GetAddedNodeInfoResponse.cs
├── GetBlockResponse.cs
├── GetBlockTemplateResponse.cs
├── GetBlockchainInfoResponse.cs
├── GetChainTipsResponse.cs
├── GetFundRawTransactionResponse.cs
├── GetInfoResponse.cs
├── GetMemPoolInfoResponse.cs
├── GetMiningInfoResponse.cs
├── GetNetTotalsResponse.cs
├── GetNetworkInfoResponse.cs
├── GetPeerInfoResponse.cs
├── GetRawMemPoolResponse.cs
├── GetRawTransactionResponse.cs
├── GetTransactionResponse.cs
├── GetTxOutSetInfoResponse.cs
├── GetWalletInfoResponse.cs
├── ListAddressGroupingsResponse.cs
├── ListReceivedByAccountResponse.cs
├── ListReceivedByAddressResponse.cs
├── ListSinceBlockResponse.cs
├── ListTransactionsResponse.cs
├── ListUnspentResponse.cs
├── SharedComponents
│ ├── Vin.cs
│ └── Vout.cs
├── SignRawTransactionResponse.cs
└── ValidateAddressResponse.cs
├── Services
├── Coins
│ ├── Base
│ │ └── ICoinService.cs
│ ├── Bitcoin
│ │ ├── BitcoinService.cs
│ │ └── IBitcoinService.cs
│ ├── Cryptocoin
│ │ ├── CryptocoinService.cs
│ │ └── ICryptocoinService.cs
│ ├── Dallar
│ │ ├── DallarService.cs
│ │ └── IDallarService.cs
│ ├── Dash
│ │ ├── DashService.cs
│ │ └── IDashService.cs
│ ├── Dogecoin
│ │ ├── DogecoinService.cs
│ │ └── IDogecoinService.cs
│ ├── Litecoin
│ │ ├── ILitecoinService.cs
│ │ └── LitecoinService.cs
│ ├── Mogwaicoin
│ │ ├── IMogwaicoinService.cs
│ │ └── MogwaicoinService.cs
│ ├── Sarcoin
│ │ ├── ISarcoinService.cs
│ │ └── SarcoinService.cs
│ └── Smartcash
│ │ ├── ISmartcashService.cs
│ │ └── SmartcashService.cs
└── RpcServices
│ ├── RpcExtenderService
│ ├── IRpcExtenderService.cs
│ └── RpcExtenderService.cs
│ └── RpcService
│ ├── IRpcService.cs
│ └── RpcService.cs
└── paket.references
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 PowerMobile Team
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # BitcoinLib
2 |
3 | **.NET Bitcoin & Altcoins library**
4 |
5 | ## Features
6 |
7 | - Compatible with [Bitcoin Core](https://bitcoin.org/en/download) RPC API.
8 | - Strongly-typed structures for complex RPC requests and responses.
9 | - Implicit JSON casting for all RPC messages.
10 | - Extended methods for every-day scenarios where the built-in methods fall short.
11 | - Exposure of all [RPC API's functionality](https://en.bitcoin.it/wiki/Original_Bitcoin_client/API_calls_list) as well as the extended methods through a single interface.
12 | - Custom RPC exceptions.
13 | - Supports all Bitcoin clones.
14 | - Can operate on unlimited daemons with a single library reference.
15 | - [Bitcoin](http://en.wikipedia.org/wiki/Bitcoin), [Litecoin](http://en.wikipedia.org/wiki/Litecoin), [Dogecoin](http://en.wikipedia.org/wiki/Dogecoin), SmartCash, Dash and other Altcoins included.
16 | - Each coin instance can be fully parametrized at run-time and implement its own constants.
17 | - Demo client included.
18 | - Disconnected raw RPC connector included for quick'n'dirty debugging.
19 | - Handles and relays RPC internal server errors along with their error code.
20 | - Can work without a `.config` file.
21 | - Fully compatible with [Mono](http://www.mono-project.com/).
22 | - [Test Network (testnet)](https://bitcoin.org/en/developer-examples#testnet) and [Regression Test Mode (regtest)](https://bitcoin.org/en/developer-examples#regtest-mode) ready.
23 | - Fully configurable.
24 |
25 | ## Donations
26 |
27 | This library took a significant amount of time and effort to build and requires continuous maintenance in order to keep up with changes introduced with every new Bitcoin-Core release. Keep it up by donating at: [15Nb3RhMd13zp5Pc7yngUon83nFtEZUyBA](bitcoin:15Nb3RhMd13zp5Pc7yngUon83nFtEZUyBA?label=BitcoinLib)
28 |
29 | ## Support
30 |
31 | Premium Support is available by our team of experts at: [info@powermobile.org](mailto:info@powermobile.org).
32 |
33 | ## License
34 |
35 | See [LICENSE](LICENSE).
36 |
37 | ## NuGet packages
38 |
39 | BitcoinLib is available on NuGet:
40 |
41 | * [BitcoinLib](https://www.nuget.org/packages/BitcoinLib/)
42 |
43 | ## Versioning
44 |
45 | From version 1.4.0, BitcoinLib follows [Semantic Versioning 2.0.0](http://semver.org/spec/v2.0.0.html).
46 |
47 | ## Building from source
48 |
49 | To build BitcoinLib from source, you will need either the
50 | [.NET Core SDK or Visual Studio](https://www.microsoft.com/net/download/).
51 |
52 | ### Linux-specific
53 |
54 | If you are using Linux you will also need Mono installed
55 | (in order to run Paket). The full install sequence (for Ubuntu)
56 | will be something like [this](https://github.com/powermobileteam/fsharp-hedgehog/pull/153#issuecomment-364325504).
57 |
58 | ### Building & running tests
59 |
60 | With Visual Studio you can build BitcoinLib and run the tests
61 | from inside the IDE, otherwise with the `dotnet` command-line
62 | tool you can execute:
63 |
64 | ```sh
65 | dotnet build src/BitcoinLib.sln
66 | ```
67 |
68 | The first time you run it, this will use Paket to restore all
69 | the packages, and then build the code.
70 |
71 | ## Instructions for Bitcoin
72 |
73 | - Locate your `bitcoin.conf` file (in Windows it's under: `%AppData%\Roaming\Bitcoin`, if it's not there just go ahead and create it) and add these lines:
74 | ```
75 | rpcuser = MyRpcUsername
76 | rpcpassword = MyRpcPassword
77 | server=1
78 | txindex=1
79 | ```
80 | - Edit the `app.config` file in the Console test client to best fit your needs. Make sure you also update the `bitcoin.conf` file when you alter the `Bitcoin_RpcUsername` and `Bitcoin_RpcPassword` parameters.
81 |
82 | ## Instructions for Litecoin and other Bitcoin clones
83 |
84 | - Perform the same steps as those mentioned above for Bitcoin.
85 | - Litecoin configuration file is: `litecoin.conf` under: `%AppData%\Roaming\Litecoin` and its daemon is: `litecoind`.
86 | - Each coin can be initialized by its own interface specification:
87 | - `IBitcoinService BitcoinService = new BitcoinService();`
88 | - `ILitecoinService LitecoinService = new LitecoinService();`
89 | - Any bitcoin clone can be adopted without any further installation steps with the use of the generic `ICryptocoinService`:
90 | - `ICryptocoinService cryptocoinService = new CryptocoinService("daemonUrl", "rpcUsername", "rpcPassword", "walletPassword");`
91 | - Use `(ICryptocoinService).Parameters` to fully configure each coin pointer at run-time.
92 |
93 | ## Configuration
94 |
95 | Sample configuration:
96 |
97 | ```xml
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 | ```
119 |
--------------------------------------------------------------------------------
/demo/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
--------------------------------------------------------------------------------
/demo/Program.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Configuration;
7 | using System.Globalization;
8 | using System.Linq;
9 | using System.Reflection;
10 | using BitcoinLib.Auxiliary;
11 | using BitcoinLib.ExceptionHandling.Rpc;
12 | using BitcoinLib.Responses;
13 | using BitcoinLib.Services.Coins.Base;
14 | using BitcoinLib.Services.Coins.Bitcoin;
15 |
16 | namespace ConsoleClient
17 | {
18 | internal sealed class Program
19 | {
20 | private static readonly ICoinService CoinService = new BitcoinService(useTestnet: true);
21 |
22 | private static void Main()
23 | {
24 | try
25 | {
26 | Console.Write("\n\nConnecting to {0} {1}Net via RPC at {2}...", CoinService.Parameters.CoinLongName, (CoinService.Parameters.UseTestnet ? "Test" : "Main"), CoinService.Parameters.SelectedDaemonUrl);
27 |
28 | // Network difficulty
29 | var networkDifficulty = CoinService.GetDifficulty();
30 | Console.WriteLine("[OK]\n\n{0} Network Difficulty: {1}", CoinService.Parameters.CoinLongName, networkDifficulty.ToString("#,###", CultureInfo.InvariantCulture));
31 |
32 | // My balance
33 | var myBalance = CoinService.GetBalance();
34 | Console.WriteLine("\nMy balance: {0} {1}", myBalance, CoinService.Parameters.CoinShortName);
35 |
36 | // Current block
37 | Console.WriteLine("Current block: {0}",
38 | CoinService.GetBlockCount().ToString("#,#", CultureInfo.InvariantCulture));
39 |
40 | // Wallet state
41 | Console.WriteLine("Wallet state: {0}", CoinService.IsWalletEncrypted() ? "Encrypted" : "Unencrypted");
42 |
43 | // Keys and addresses
44 | if (myBalance > 0)
45 | {
46 | // My non-empty addresses
47 | Console.WriteLine("\n\nMy non-empty addresses:");
48 |
49 | var myNonEmptyAddresses = CoinService.ListReceivedByAddress();
50 |
51 | foreach (var address in myNonEmptyAddresses)
52 | {
53 | Console.WriteLine("\n--------------------------------------------------");
54 | Console.WriteLine("Account: " + (string.IsNullOrWhiteSpace(address.Account) ? "(no label)" : address.Account));
55 | Console.WriteLine("Address: " + address.Address);
56 | Console.WriteLine("Amount: " + address.Amount);
57 | Console.WriteLine("Confirmations: " + address.Confirmations);
58 | Console.WriteLine("--------------------------------------------------");
59 | }
60 |
61 | // My private keys
62 | if (bool.Parse(ConfigurationManager.AppSettings["ExtractMyPrivateKeys"]) && myNonEmptyAddresses.Count > 0 && CoinService.IsWalletEncrypted())
63 | {
64 | const short secondsToUnlockTheWallet = 30;
65 |
66 | Console.Write("\nWill now unlock the wallet for " + secondsToUnlockTheWallet + ((secondsToUnlockTheWallet > 1) ? " seconds" : " second") + "...");
67 | CoinService.WalletPassphrase(CoinService.Parameters.WalletPassword, secondsToUnlockTheWallet);
68 | Console.WriteLine("[OK]\n\nMy private keys for non-empty addresses:\n");
69 |
70 | foreach (var address in myNonEmptyAddresses)
71 | {
72 | Console.WriteLine("Private Key for address " + address.Address + ": " + CoinService.DumpPrivKey(address.Address));
73 | }
74 |
75 | Console.Write("\nLocking wallet...");
76 | CoinService.WalletLock();
77 | Console.WriteLine("[OK]");
78 | }
79 |
80 | // My transactions
81 | Console.WriteLine("\n\nMy transactions: ");
82 | var myTransactions = CoinService.ListTransactions(null, int.MaxValue, 0);
83 |
84 | foreach (var transaction in myTransactions)
85 | {
86 | Console.WriteLine("\n---------------------------------------------------------------------------");
87 | Console.WriteLine("Account: " + (string.IsNullOrWhiteSpace(transaction.Account) ? "(no label)" : transaction.Account));
88 | Console.WriteLine("Address: " + transaction.Address);
89 | Console.WriteLine("Category: " + transaction.Category);
90 | Console.WriteLine("Amount: " + transaction.Amount);
91 | Console.WriteLine("Fee: " + transaction.Fee);
92 | Console.WriteLine("Confirmations: " + transaction.Confirmations);
93 | Console.WriteLine("BlockHash: " + transaction.BlockHash);
94 | Console.WriteLine("BlockIndex: " + transaction.BlockIndex);
95 | Console.WriteLine("BlockTime: " + transaction.BlockTime + " - " + UnixTime.UnixTimeToDateTime(transaction.BlockTime));
96 | Console.WriteLine("TxId: " + transaction.TxId);
97 | Console.WriteLine("Time: " + transaction.Time + " - " + UnixTime.UnixTimeToDateTime(transaction.Time));
98 | Console.WriteLine("TimeReceived: " + transaction.TimeReceived + " - " + UnixTime.UnixTimeToDateTime(transaction.TimeReceived));
99 |
100 | if (!string.IsNullOrWhiteSpace(transaction.Comment))
101 | {
102 | Console.WriteLine("Comment: " + transaction.Comment);
103 | }
104 |
105 | if (!string.IsNullOrWhiteSpace(transaction.OtherAccount))
106 | {
107 | Console.WriteLine("Other Account: " + transaction.OtherAccount);
108 | }
109 |
110 | if (transaction.WalletConflicts != null && transaction.WalletConflicts.Any())
111 | {
112 | Console.Write("Conflicted Transactions: ");
113 |
114 | foreach (var conflictedTxId in transaction.WalletConflicts)
115 | {
116 | Console.Write(conflictedTxId + " ");
117 | }
118 |
119 | Console.WriteLine();
120 | }
121 |
122 | Console.WriteLine("---------------------------------------------------------------------------");
123 | }
124 |
125 | // Transaction Details
126 | Console.WriteLine("\n\nMy transactions' details:");
127 | foreach (var transaction in myTransactions)
128 | {
129 | // Move transactions don't have a txId, which this logic fails for
130 | if (transaction.Category == "move")
131 | {
132 | continue;
133 | }
134 |
135 | var localWalletTransaction = CoinService.GetTransaction(transaction.TxId);
136 | IEnumerable localWalletTrasactionProperties = localWalletTransaction.GetType().GetProperties();
137 | IList localWalletTransactionDetailsList = localWalletTransaction.Details.ToList();
138 |
139 | Console.WriteLine("\nTransaction\n-----------");
140 |
141 | foreach (var propertyInfo in localWalletTrasactionProperties)
142 | {
143 | var propertyInfoName = propertyInfo.Name;
144 |
145 | if (propertyInfoName != "Details" && propertyInfoName != "WalletConflicts")
146 | {
147 | Console.WriteLine(propertyInfoName + ": " + propertyInfo.GetValue(localWalletTransaction, null));
148 | }
149 | }
150 |
151 | foreach (var details in localWalletTransactionDetailsList)
152 | {
153 | IEnumerable detailsProperties = details.GetType().GetProperties();
154 | Console.WriteLine("\nTransaction details " + (localWalletTransactionDetailsList.IndexOf(details) + 1) + " of total " + localWalletTransactionDetailsList.Count + "\n--------------------------------");
155 |
156 | foreach (var propertyInfo in detailsProperties)
157 | {
158 | Console.WriteLine(propertyInfo.Name + ": " + propertyInfo.GetValue(details, null));
159 | }
160 | }
161 | }
162 |
163 | // Unspent transactions
164 | Console.WriteLine("\nMy unspent transactions:");
165 | var unspentList = CoinService.ListUnspent();
166 |
167 | foreach (var unspentResponse in unspentList)
168 | {
169 | IEnumerable detailsProperties = unspentResponse.GetType().GetProperties();
170 |
171 | Console.WriteLine("\nUnspent transaction " + (unspentList.IndexOf(unspentResponse) + 1) + " of " + unspentList.Count + "\n--------------------------------");
172 |
173 | foreach (var propertyInfo in detailsProperties)
174 | {
175 | Console.WriteLine(propertyInfo.Name + " : " + propertyInfo.GetValue(unspentResponse, null));
176 | }
177 | }
178 | }
179 |
180 | Console.ReadLine();
181 | }
182 | catch (RpcInternalServerErrorException exception)
183 | {
184 | var errorCode = 0;
185 | var errorMessage = string.Empty;
186 |
187 | if (exception.RpcErrorCode.GetHashCode() != 0)
188 | {
189 | errorCode = exception.RpcErrorCode.GetHashCode();
190 | errorMessage = exception.RpcErrorCode.ToString();
191 | }
192 |
193 | Console.WriteLine("[Failed] {0} {1} {2}", exception.Message, errorCode != 0 ? "Error code: " + errorCode : string.Empty, !string.IsNullOrWhiteSpace(errorMessage) ? errorMessage : string.Empty);
194 | }
195 | catch (Exception exception)
196 | {
197 | Console.WriteLine("[Failed]\n\nPlease check your configuration and make sure that the daemon is up and running and that it is synchronized. \n\nException: " + exception);
198 | }
199 | }
200 | }
201 | }
--------------------------------------------------------------------------------
/demo/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using System.Reflection;
5 | using System.Runtime.InteropServices;
6 |
7 | // General Information about an assembly is controlled through the following
8 | // set of attributes. Change these attribute values to modify the information
9 | // associated with an assembly.
10 |
11 | [assembly: AssemblyTitle("ConsoleClient")]
12 | [assembly: AssemblyDescription("Demo Console Client for BitcoinLib")]
13 | [assembly: AssemblyConfiguration("")]
14 | [assembly: AssemblyCompany("George Kimionis")]
15 | [assembly: AssemblyProduct("ConsoleClient")]
16 | [assembly: AssemblyCopyright("Copyright © 2014")]
17 | [assembly: AssemblyTrademark("")]
18 | [assembly: AssemblyCulture("")]
19 |
20 | // Setting ComVisible to false makes the types in this assembly not visible
21 | // to COM components. If you need to access a type in this assembly from
22 | // COM, set the ComVisible attribute to true on that type.
23 |
24 | [assembly: ComVisible(false)]
25 |
26 | // The following GUID is for the ID of the typelib if this project is exposed to COM
27 |
28 | [assembly: Guid("567159bb-15c6-461a-a22c-18eecd3ba894")]
29 |
30 | // Version information for an assembly consists of the following four values:
31 | //
32 | // Major Version
33 | // Minor Version
34 | // Build Number
35 | // Revision
36 | //
37 | // You can specify all the values or you can default the Build and Revision Numbers
38 | // by using the '*' as shown below:
39 | // [assembly: AssemblyVersion("1.0.*")]
40 |
41 | [assembly: AssemblyVersion("1.6.0.0")]
42 | [assembly: AssemblyFileVersion("1.6.0.0")]
--------------------------------------------------------------------------------
/demo/paket.references:
--------------------------------------------------------------------------------
1 | Newtonsoft.Json
--------------------------------------------------------------------------------
/paket.dependencies:
--------------------------------------------------------------------------------
1 | source https://api.nuget.org/v3/index.json
2 | nuget FAKE
3 | nuget NuGet.CommandLine
4 | nuget System.Configuration.ConfigurationManager
5 | nuget Newtonsoft.Json
6 |
--------------------------------------------------------------------------------
/src/BitcoinLib.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.27130.2003
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".paket", ".paket", "{8C09BFEC-8BFA-42B3-88B2-47F5010CA418}"
7 | ProjectSection(SolutionItems) = preProject
8 | ..\paket.dependencies = ..\paket.dependencies
9 | EndProjectSection
10 | EndProject
11 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BitcoinLib", "BitcoinLib\BitcoinLib.csproj", "{B853E315-7103-4CBA-8873-D5202019F267}"
12 | EndProject
13 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DemoClient", "..\demo\DemoClient.csproj", "{56F54485-7B42-4E41-95D3-1998EA614695}"
14 | EndProject
15 | Global
16 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
17 | Debug|Any CPU = Debug|Any CPU
18 | Release|Any CPU = Release|Any CPU
19 | EndGlobalSection
20 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
21 | {B853E315-7103-4CBA-8873-D5202019F267}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
22 | {B853E315-7103-4CBA-8873-D5202019F267}.Debug|Any CPU.Build.0 = Debug|Any CPU
23 | {B853E315-7103-4CBA-8873-D5202019F267}.Release|Any CPU.ActiveCfg = Release|Any CPU
24 | {B853E315-7103-4CBA-8873-D5202019F267}.Release|Any CPU.Build.0 = Release|Any CPU
25 | {56F54485-7B42-4E41-95D3-1998EA614695}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
26 | {56F54485-7B42-4E41-95D3-1998EA614695}.Debug|Any CPU.Build.0 = Debug|Any CPU
27 | {56F54485-7B42-4E41-95D3-1998EA614695}.Release|Any CPU.ActiveCfg = Release|Any CPU
28 | {56F54485-7B42-4E41-95D3-1998EA614695}.Release|Any CPU.Build.0 = Release|Any CPU
29 | EndGlobalSection
30 | GlobalSection(SolutionProperties) = preSolution
31 | HideSolutionNode = FALSE
32 | EndGlobalSection
33 | EndGlobal
34 |
--------------------------------------------------------------------------------
/src/BitcoinLib/Auxiliary/Encoders/ASCIIEncoder.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using System.Linq;
5 |
6 | namespace BitcoinLib.Auxiliary.Encoders
7 | {
8 | public class ASCIIEncoder : DataEncoder
9 | {
10 | public override byte[] DecodeData(string encoded)
11 | {
12 | return string.IsNullOrEmpty(encoded) ? new byte[0] : encoded.ToCharArray().Select(o => (byte) o).ToArray();
13 | }
14 |
15 | public override string EncodeData(byte[] data, int offset, int count)
16 | {
17 | return new string(data.Skip(offset).Take(count).Select(o => (char) o).ToArray()).Replace("\0", "");
18 | }
19 | }
20 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/Auxiliary/Encoders/DataEncoder.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | namespace BitcoinLib.Auxiliary.Encoders
5 | {
6 | public abstract class DataEncoder
7 | {
8 | internal DataEncoder()
9 | {
10 | }
11 |
12 | // char.IsWhiteSpace fits well but it match other whitespaces
13 | // characters too and also works for unicode characters.
14 | public static bool IsSpace(char c)
15 | {
16 | return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r';
17 | }
18 |
19 | public string EncodeData(byte[] data)
20 | {
21 | return EncodeData(data, 0, data.Length);
22 | }
23 |
24 | public abstract string EncodeData(byte[] data, int offset, int count);
25 |
26 | public abstract byte[] DecodeData(string encoded);
27 | }
28 |
29 | public static class Encoders
30 | {
31 | private static readonly ASCIIEncoder _ASCII = new ASCIIEncoder();
32 |
33 | private static readonly HexEncoder _Hex = new HexEncoder();
34 |
35 | public static DataEncoder ASCII => _ASCII;
36 |
37 | public static DataEncoder Hex => _Hex;
38 | }
39 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/Auxiliary/Encoders/HexEncoder.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using System;
5 | using System.Linq;
6 |
7 | namespace BitcoinLib.Auxiliary.Encoders
8 | {
9 | public class HexEncoder : DataEncoder
10 | {
11 | private static readonly string[] HexTbl = Enumerable.Range(0, 256).Select(v => v.ToString("x2")).ToArray();
12 |
13 | private static readonly int[] HexValueArray;
14 |
15 | static HexEncoder()
16 | {
17 | var hexDigits = new[]
18 | {
19 | '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
20 | 'A', 'B', 'C', 'D', 'E', 'F'
21 | };
22 | var hexValues = new byte[]
23 | {
24 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
25 | 10, 11, 12, 13, 14, 15
26 | };
27 |
28 | var max = hexDigits.Max();
29 | HexValueArray = new int[max + 1];
30 | for (var i = 0; i < HexValueArray.Length; i++)
31 | {
32 | var idx = Array.IndexOf(hexDigits, (char) i);
33 | var value = -1;
34 | if (idx != -1)
35 | value = hexValues[idx];
36 | HexValueArray[i] = value;
37 | }
38 | }
39 |
40 | public bool Space { get; set; }
41 |
42 | public override string EncodeData(byte[] data, int offset, int count)
43 | {
44 | if (data == null)
45 | throw new ArgumentNullException(nameof(data));
46 |
47 | var pos = 0;
48 | var spaces = (Space ? Math.Max((count - 1), 0) : 0);
49 | var s = new char[2 * count + spaces];
50 | for (var i = offset; i < offset + count; i++)
51 | {
52 | if (Space && i != 0)
53 | s[pos++] = ' ';
54 | var c = HexTbl[data[i]];
55 | s[pos++] = c[0];
56 | s[pos++] = c[1];
57 | }
58 | return new string(s);
59 | }
60 |
61 | public override byte[] DecodeData(string encoded)
62 | {
63 | if (encoded == null)
64 | throw new ArgumentNullException(nameof(encoded));
65 | if (encoded.Length % 2 == 1)
66 | throw new FormatException("Invalid Hex String");
67 |
68 | var result = new byte[encoded.Length / 2];
69 | for (int i = 0, j = 0; i < encoded.Length; i += 2, j++)
70 | {
71 | var a = IsDigit(encoded[i]);
72 | var b = IsDigit(encoded[i + 1]);
73 | if (a == -1 || b == -1)
74 | throw new FormatException("Invalid Hex String");
75 | result[j] = (byte) (((uint) a << 4) | (uint) b);
76 | }
77 | return result;
78 | }
79 |
80 | public bool IsValid(string str)
81 | {
82 | return str.ToCharArray().All(c => IsDigit(c) != -1) && str.Length % 2 == 0;
83 | }
84 |
85 | public static int IsDigit(char c)
86 | {
87 | return c + 1 <= HexValueArray.Length
88 | ? HexValueArray[c]
89 | : -1;
90 | }
91 |
92 | public static bool IsWellFormed(string str)
93 | {
94 | try
95 | {
96 | Encoders.Hex.DecodeData(str);
97 | return true;
98 | }
99 | catch (FormatException)
100 | {
101 | return false;
102 | }
103 | }
104 | }
105 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/Auxiliary/GlobalConstants.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | namespace BitcoinLib.Auxiliary
5 | {
6 | public static class GlobalConstants
7 | {
8 | public const ushort MillisecondsInASecond = 1000;
9 | public const ushort MinutesInADay = 1440;
10 | }
11 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/Auxiliary/Hashing.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using System.Linq;
5 | using System.Security.Cryptography;
6 | using System.Text;
7 |
8 | namespace BitcoinLib.Auxiliary
9 | {
10 | public class Hashing
11 | {
12 | public static string GetSha256(string text)
13 | {
14 | return new SHA256Managed().ComputeHash(Encoding.UTF8.GetBytes(text)).Aggregate(string.Empty, (current, x) => current + $"{x:x2}");
15 | }
16 | }
17 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/Auxiliary/UnixTime.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using System;
5 |
6 | namespace BitcoinLib.Auxiliary
7 | {
8 | public static class UnixTime
9 | {
10 | private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);
11 |
12 | public static DateTime UnixTimeToDateTime(double unixTimeStamp)
13 | {
14 | return Epoch.AddSeconds(unixTimeStamp).ToUniversalTime();
15 | }
16 | }
17 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/BitcoinLib.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard20;net461
5 | BitcoinLib
6 | The most complete, up-to-date, battle-tested library and RPC wrapper for Bitcoin, Litecoin, Dogecoin and other Bitcoin clones in .NET.
7 | © George Kimionis 2018
8 | 1.9.0.0
9 | 1.9.0.0
10 | George Kimionis
11 | https://github.com/GeorgeKimionis/BitcoinLib/blob/master/LICENSE
12 | https://github.com/GeorgeKimionis/BitcoinLib
13 | c#;dotnet;bitcoin
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/src/BitcoinLib/CoinParameters/Base/CoinConstants.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using System;
5 |
6 | namespace BitcoinLib.CoinParameters.Base
7 | {
8 | public abstract class CoinConstants where T : CoinConstants, new()
9 | {
10 | private static readonly Lazy Lazy = new Lazy(() => new T());
11 | public static T Instance => Lazy.Value;
12 | }
13 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/CoinParameters/Base/CoinParameters.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using System;
5 | using System.Configuration;
6 | using System.Diagnostics;
7 | using BitcoinLib.Auxiliary;
8 | using BitcoinLib.Services.Coins.Base;
9 | using BitcoinLib.Services.Coins.Bitcoin;
10 | using BitcoinLib.Services.Coins.Cryptocoin;
11 | using BitcoinLib.Services.Coins.Dallar;
12 | using BitcoinLib.Services.Coins.Dash;
13 | using BitcoinLib.Services.Coins.Dogecoin;
14 | using BitcoinLib.Services.Coins.Litecoin;
15 | using BitcoinLib.Services.Coins.Mogwaicoin;
16 | using BitcoinLib.Services.Coins.Sarcoin;
17 | using BitcoinLib.Services.Coins.Smartcash;
18 |
19 | namespace BitcoinLib.Services
20 | {
21 | public partial class CoinService
22 | {
23 | public CoinParameters Parameters { get; }
24 |
25 | public class CoinParameters
26 | {
27 | #region Constructor
28 |
29 | public CoinParameters(ICoinService coinService,
30 | string daemonUrl,
31 | string rpcUsername,
32 | string rpcPassword,
33 | string walletPassword,
34 | short rpcRequestTimeoutInSeconds)
35 | {
36 | if (!string.IsNullOrWhiteSpace(daemonUrl))
37 | {
38 | DaemonUrl = daemonUrl;
39 | UseTestnet = false; // this will force the CoinParameters.SelectedDaemonUrl dynamic property to automatically pick the daemonUrl defined above
40 | IgnoreConfigFiles = true;
41 | RpcUsername = rpcUsername;
42 | RpcPassword = rpcPassword;
43 | WalletPassword = walletPassword;
44 | }
45 |
46 | if (rpcRequestTimeoutInSeconds > 0)
47 | {
48 | RpcRequestTimeoutInSeconds = rpcRequestTimeoutInSeconds;
49 | }
50 | else
51 | {
52 | short rpcRequestTimeoutTryParse = 0;
53 |
54 | if (short.TryParse(ConfigurationManager.AppSettings.Get("RpcRequestTimeoutInSeconds"), out rpcRequestTimeoutTryParse))
55 | {
56 | RpcRequestTimeoutInSeconds = rpcRequestTimeoutTryParse;
57 | }
58 | }
59 |
60 | if (IgnoreConfigFiles && (string.IsNullOrWhiteSpace(DaemonUrl) || string.IsNullOrWhiteSpace(RpcUsername) || string.IsNullOrWhiteSpace(RpcPassword)))
61 | {
62 | throw new Exception($"One or more required parameters, as defined in {GetType().Name}, were not found in the configuration file!");
63 | }
64 |
65 | if (IgnoreConfigFiles && Debugger.IsAttached && string.IsNullOrWhiteSpace(WalletPassword))
66 | {
67 | Console.ForegroundColor = ConsoleColor.Yellow;
68 | Console.WriteLine("[WARNING] The wallet password is either null or empty");
69 | Console.ResetColor();
70 | }
71 |
72 | #region Bitcoin
73 |
74 | if (coinService is BitcoinService)
75 | {
76 | if (!IgnoreConfigFiles)
77 | {
78 | DaemonUrl = ConfigurationManager.AppSettings.Get("Bitcoin_DaemonUrl");
79 | DaemonUrlTestnet = ConfigurationManager.AppSettings.Get("Bitcoin_DaemonUrl_Testnet");
80 | RpcUsername = ConfigurationManager.AppSettings.Get("Bitcoin_RpcUsername");
81 | RpcPassword = ConfigurationManager.AppSettings.Get("Bitcoin_RpcPassword");
82 | WalletPassword = ConfigurationManager.AppSettings.Get("Bitcoin_WalletPassword");
83 | }
84 |
85 | CoinShortName = "BTC";
86 | CoinLongName = "Bitcoin";
87 | IsoCurrencyCode = "XBT";
88 |
89 | TransactionSizeBytesContributedByEachInput = 148;
90 | TransactionSizeBytesContributedByEachOutput = 34;
91 | TransactionSizeFixedExtraSizeInBytes = 10;
92 |
93 | FreeTransactionMaximumSizeInBytes = 1000;
94 | FreeTransactionMinimumOutputAmountInCoins = 0.01M;
95 | FreeTransactionMinimumPriority = 57600000;
96 | FeePerThousandBytesInCoins = 0.0001M;
97 | MinimumTransactionFeeInCoins = 0.0001M;
98 | MinimumNonDustTransactionAmountInCoins = 0.0000543M;
99 |
100 | TotalCoinSupplyInCoins = 21000000;
101 | EstimatedBlockGenerationTimeInMinutes = 10;
102 | BlocksHighestPriorityTransactionsReservedSizeInBytes = 50000;
103 |
104 | BaseUnitName = "Satoshi";
105 | BaseUnitsPerCoin = 100000000;
106 | CoinsPerBaseUnit = 0.00000001M;
107 | }
108 |
109 | #endregion
110 |
111 | #region Litecoin
112 |
113 | else if (coinService is LitecoinService)
114 | {
115 | if (!IgnoreConfigFiles)
116 | {
117 | DaemonUrl = ConfigurationManager.AppSettings.Get("Litecoin_DaemonUrl");
118 | DaemonUrlTestnet = ConfigurationManager.AppSettings.Get("Litecoin_DaemonUrl_Testnet");
119 | RpcUsername = ConfigurationManager.AppSettings.Get("Litecoin_RpcUsername");
120 | RpcPassword = ConfigurationManager.AppSettings.Get("Litecoin_RpcPassword");
121 | WalletPassword = ConfigurationManager.AppSettings.Get("Litecoin_WalletPassword");
122 | }
123 |
124 | CoinShortName = "LTC";
125 | CoinLongName = "Litecoin";
126 | IsoCurrencyCode = "XLT";
127 |
128 | TransactionSizeBytesContributedByEachInput = 148;
129 | TransactionSizeBytesContributedByEachOutput = 34;
130 | TransactionSizeFixedExtraSizeInBytes = 10;
131 |
132 | FreeTransactionMaximumSizeInBytes = 5000;
133 | FreeTransactionMinimumOutputAmountInCoins = 0.001M;
134 | FreeTransactionMinimumPriority = 230400000;
135 | FeePerThousandBytesInCoins = 0.001M;
136 | MinimumTransactionFeeInCoins = 0.001M;
137 | MinimumNonDustTransactionAmountInCoins = 0.001M;
138 |
139 | TotalCoinSupplyInCoins = 84000000;
140 | EstimatedBlockGenerationTimeInMinutes = 2.5;
141 | BlocksHighestPriorityTransactionsReservedSizeInBytes = 16000;
142 | BlockMaximumSizeInBytes = 250000;
143 |
144 | BaseUnitName = "Litetoshi";
145 | BaseUnitsPerCoin = 100000000;
146 | CoinsPerBaseUnit = 0.00000001M;
147 | }
148 |
149 | #endregion
150 |
151 | #region Dogecoin
152 |
153 | else if (coinService is DogecoinService)
154 | {
155 | if (!IgnoreConfigFiles)
156 | {
157 | DaemonUrl = ConfigurationManager.AppSettings.Get("Dogecoin_DaemonUrl");
158 | DaemonUrlTestnet = ConfigurationManager.AppSettings.Get("Dogecoin_DaemonUrl_Testnet");
159 | RpcUsername = ConfigurationManager.AppSettings.Get("Dogecoin_RpcUsername");
160 | RpcPassword = ConfigurationManager.AppSettings.Get("Dogecoin_RpcPassword");
161 | WalletPassword = ConfigurationManager.AppSettings.Get("Dogecoin_WalletPassword");
162 | }
163 |
164 | CoinShortName = "Doge";
165 | CoinLongName = "Dogecoin";
166 | IsoCurrencyCode = "XDG";
167 | TransactionSizeBytesContributedByEachInput = 148;
168 | TransactionSizeBytesContributedByEachOutput = 34;
169 | TransactionSizeFixedExtraSizeInBytes = 10;
170 | FreeTransactionMaximumSizeInBytes = 1; // free txs are not supported from v.1.8+
171 | FreeTransactionMinimumOutputAmountInCoins = 1;
172 | FreeTransactionMinimumPriority = 230400000;
173 | FeePerThousandBytesInCoins = 1;
174 | MinimumTransactionFeeInCoins = 1;
175 | MinimumNonDustTransactionAmountInCoins = 0.1M;
176 | TotalCoinSupplyInCoins = 100000000000;
177 | EstimatedBlockGenerationTimeInMinutes = 1;
178 | BlocksHighestPriorityTransactionsReservedSizeInBytes = 16000;
179 | BlockMaximumSizeInBytes = 500000;
180 | BaseUnitName = "Koinu";
181 | BaseUnitsPerCoin = 100000000;
182 | CoinsPerBaseUnit = 0.00000001M;
183 | }
184 |
185 | #endregion
186 |
187 | #region Sarcoin
188 |
189 | else if (coinService is SarcoinService)
190 | {
191 | if (!IgnoreConfigFiles)
192 | {
193 | DaemonUrl = ConfigurationManager.AppSettings.Get("Sarcoin_DaemonUrl");
194 | DaemonUrlTestnet = ConfigurationManager.AppSettings.Get("Sarcoin_DaemonUrl_Testnet");
195 | RpcUsername = ConfigurationManager.AppSettings.Get("Sarcoin_RpcUsername");
196 | RpcPassword = ConfigurationManager.AppSettings.Get("Sarcoin_RpcPassword");
197 | WalletPassword = ConfigurationManager.AppSettings.Get("Sarcoin_WalletPassword");
198 | }
199 |
200 | CoinShortName = "SAR";
201 | CoinLongName = "Sarcoin";
202 | IsoCurrencyCode = "SAR";
203 |
204 | TransactionSizeBytesContributedByEachInput = 148;
205 | TransactionSizeBytesContributedByEachOutput = 34;
206 | TransactionSizeFixedExtraSizeInBytes = 10;
207 |
208 | FreeTransactionMaximumSizeInBytes = 0;
209 | FreeTransactionMinimumOutputAmountInCoins = 0;
210 | FreeTransactionMinimumPriority = 0;
211 | FeePerThousandBytesInCoins = 0.00001M;
212 | MinimumTransactionFeeInCoins = 0.00001M;
213 | MinimumNonDustTransactionAmountInCoins = 0.00001M;
214 |
215 | TotalCoinSupplyInCoins = 2000000000;
216 | EstimatedBlockGenerationTimeInMinutes = 1.5;
217 | BlocksHighestPriorityTransactionsReservedSizeInBytes = 50000;
218 |
219 | BaseUnitName = "Satoshi";
220 | BaseUnitsPerCoin = 100000000;
221 | CoinsPerBaseUnit = 0.00000001M;
222 | }
223 |
224 | #endregion
225 |
226 | #region Dash
227 |
228 | else if (coinService is DashService)
229 | {
230 | if (!IgnoreConfigFiles)
231 | {
232 | DaemonUrl = ConfigurationManager.AppSettings.Get("Dash_DaemonUrl");
233 | DaemonUrlTestnet = ConfigurationManager.AppSettings.Get("Dash_DaemonUrl_Testnet");
234 | RpcUsername = ConfigurationManager.AppSettings.Get("Dash_RpcUsername");
235 | RpcPassword = ConfigurationManager.AppSettings.Get("Dash_RpcPassword");
236 | WalletPassword = ConfigurationManager.AppSettings.Get("Dash_WalletPassword");
237 | }
238 |
239 | CoinShortName = "DASH";
240 | CoinLongName = "Dash";
241 | IsoCurrencyCode = "DASH";
242 |
243 | TransactionSizeBytesContributedByEachInput = 148;
244 | TransactionSizeBytesContributedByEachOutput = 34;
245 | TransactionSizeFixedExtraSizeInBytes = 10;
246 |
247 | FreeTransactionMaximumSizeInBytes = 1000;
248 | FreeTransactionMinimumOutputAmountInCoins = 0.0001M;
249 | FreeTransactionMinimumPriority = 57600000;
250 | FeePerThousandBytesInCoins = 0.0001M;
251 | MinimumTransactionFeeInCoins = 0.001M;
252 | MinimumNonDustTransactionAmountInCoins = 0.0000543M;
253 |
254 | TotalCoinSupplyInCoins = 18900000;
255 | EstimatedBlockGenerationTimeInMinutes = 2.7;
256 | BlocksHighestPriorityTransactionsReservedSizeInBytes = 50000;
257 |
258 | BaseUnitName = "Duff";
259 | BaseUnitsPerCoin = 100000000;
260 | CoinsPerBaseUnit = 0.00000001M;
261 | }
262 |
263 | #endregion
264 |
265 | #region Mogwai
266 | else if (coinService is MogwaicoinService)
267 | {
268 | if (!IgnoreConfigFiles)
269 | {
270 | DaemonUrl = ConfigurationManager.AppSettings.Get("Mogwaicoin_DaemonUrl");
271 | DaemonUrlTestnet = ConfigurationManager.AppSettings.Get("Mogwaicoin_DaemonUrl_Testnet");
272 | RpcUsername = ConfigurationManager.AppSettings.Get("Mogwaicoin_RpcUsername");
273 | RpcPassword = ConfigurationManager.AppSettings.Get("Mogwaicoin_RpcPassword");
274 | WalletPassword = ConfigurationManager.AppSettings.Get("Mogwaicoin_WalletPassword");
275 | }
276 | CoinShortName = "Mogwaicoin";
277 | CoinLongName = "Mogwaicoin";
278 | IsoCurrencyCode = "MOG";
279 | TransactionSizeBytesContributedByEachInput = 148;
280 | TransactionSizeBytesContributedByEachOutput = 34;
281 | TransactionSizeFixedExtraSizeInBytes = 10;
282 | FreeTransactionMaximumSizeInBytes = 1000;
283 | FreeTransactionMinimumOutputAmountInCoins = 0.0001M;
284 | FreeTransactionMinimumPriority = 57600000;
285 | FeePerThousandBytesInCoins = 0.0001M;
286 | MinimumTransactionFeeInCoins = 0.001M;
287 | MinimumNonDustTransactionAmountInCoins = 0.0000543M;
288 | TotalCoinSupplyInCoins = 50000000;
289 | EstimatedBlockGenerationTimeInMinutes = 2.0;
290 | BlocksHighestPriorityTransactionsReservedSizeInBytes = 50000;
291 | BaseUnitName = "Puff";
292 | BaseUnitsPerCoin = 100000000;
293 | CoinsPerBaseUnit = 0.00000001M;
294 | }
295 | #endregion
296 |
297 | #region Smartcash
298 |
299 | else if (coinService is SmartcashService)
300 | {
301 | if (!IgnoreConfigFiles)
302 | {
303 | DaemonUrl = ConfigurationManager.AppSettings.Get("Smartcash_DaemonUrl");
304 | DaemonUrlTestnet = ConfigurationManager.AppSettings.Get("Smartcash_DaemonUrl_Testnet");
305 | RpcUsername = ConfigurationManager.AppSettings.Get("Smartcash_RpcUsername");
306 | RpcPassword = ConfigurationManager.AppSettings.Get("Smartcash_RpcPassword");
307 | WalletPassword = ConfigurationManager.AppSettings.Get("Smartcash_WalletPassword");
308 | }
309 |
310 | CoinShortName = "SMART";
311 | CoinLongName = "Smartcash";
312 | IsoCurrencyCode = "SMART";
313 |
314 | TransactionSizeBytesContributedByEachInput = 148;
315 | TransactionSizeBytesContributedByEachOutput = 34;
316 | TransactionSizeFixedExtraSizeInBytes = 10;
317 |
318 | FreeTransactionMaximumSizeInBytes = 0; // free txs are not supported
319 | FreeTransactionMinimumOutputAmountInCoins = 0;
320 | FreeTransactionMinimumPriority = 0;
321 | FeePerThousandBytesInCoins = 0.0001M;
322 | MinimumTransactionFeeInCoins = 0.001M;
323 | MinimumNonDustTransactionAmountInCoins = 0.00001M;
324 |
325 | TotalCoinSupplyInCoins = 5000000000;
326 | EstimatedBlockGenerationTimeInMinutes = 0.916667;
327 | BlocksHighestPriorityTransactionsReservedSizeInBytes = 50000;
328 |
329 | BaseUnitName = "Smartoshi";
330 | BaseUnitsPerCoin = 100000000;
331 | CoinsPerBaseUnit = 0.00000001M;
332 | }
333 |
334 | #endregion
335 |
336 | #region Dallar
337 |
338 | else if (coinService is DallarService)
339 | {
340 | if (!IgnoreConfigFiles)
341 | {
342 | DaemonUrl = ConfigurationManager.AppSettings.Get("Dallar_DaemonUrl");
343 | DaemonUrlTestnet = ConfigurationManager.AppSettings.Get("Dallar_DaemonUrl_Testnet");
344 | RpcUsername = ConfigurationManager.AppSettings.Get("Dallar_RpcUsername");
345 | RpcPassword = ConfigurationManager.AppSettings.Get("Dallar_RpcPassword");
346 | WalletPassword = ConfigurationManager.AppSettings.Get("Dallar_WalletPassword");
347 | }
348 |
349 | CoinShortName = "DAL";
350 | CoinLongName = "Dallar";
351 | IsoCurrencyCode = "DAL";
352 |
353 | TransactionSizeBytesContributedByEachInput = 148;
354 | TransactionSizeBytesContributedByEachOutput = 34;
355 | TransactionSizeFixedExtraSizeInBytes = 10;
356 |
357 | FreeTransactionMaximumSizeInBytes = 1000;
358 | FreeTransactionMinimumOutputAmountInCoins = 0.001M;
359 | FreeTransactionMinimumPriority = 230400000;
360 | FeePerThousandBytesInCoins = 0.001M;
361 | MinimumTransactionFeeInCoins = 0.0001M;
362 | MinimumNonDustTransactionAmountInCoins = 0.001M;
363 |
364 | TotalCoinSupplyInCoins = 80000000;
365 | EstimatedBlockGenerationTimeInMinutes = 1.0;
366 | BlocksHighestPriorityTransactionsReservedSizeInBytes = 16000;
367 | BlockMaximumSizeInBytes = 750000;
368 |
369 | BaseUnitName = "Allar";
370 | BaseUnitsPerCoin = 100000000;
371 | CoinsPerBaseUnit = 0.00000001M;
372 | }
373 |
374 | #endregion
375 |
376 | #region Agnostic coin (cryptocoin)
377 |
378 | else if (coinService is CryptocoinService)
379 | {
380 | CoinShortName = "XXX";
381 | CoinLongName = "Generic Cryptocoin Template";
382 | IsoCurrencyCode = "XXX";
383 |
384 | // Note: The rest of the parameters will have to be defined at run-time
385 | }
386 |
387 | #endregion
388 |
389 | #region Uknown coin exception
390 |
391 | else
392 | {
393 | throw new Exception("Unknown coin!");
394 | }
395 |
396 | #endregion
397 |
398 | #region Invalid configuration / Missing parameters
399 |
400 | if (RpcRequestTimeoutInSeconds <= 0)
401 | {
402 | throw new Exception("RpcRequestTimeoutInSeconds must be greater than zero");
403 | }
404 |
405 | if (string.IsNullOrWhiteSpace(DaemonUrl)
406 | || string.IsNullOrWhiteSpace(RpcUsername)
407 | || string.IsNullOrWhiteSpace(RpcPassword))
408 | {
409 | throw new Exception($"One or more required parameters, as defined in {GetType().Name}, were not found in the configuration file!");
410 | }
411 |
412 | #endregion
413 | }
414 |
415 | #endregion
416 |
417 | public string BaseUnitName { get; set; }
418 | public uint BaseUnitsPerCoin { get; set; }
419 | public int BlocksHighestPriorityTransactionsReservedSizeInBytes { get; set; }
420 | public int BlockMaximumSizeInBytes { get; set; }
421 | public string CoinShortName { get; set; }
422 | public string CoinLongName { get; set; }
423 | public decimal CoinsPerBaseUnit { get; set; }
424 | public string DaemonUrl { private get; set; }
425 | public string DaemonUrlTestnet { private get; set; }
426 | public double EstimatedBlockGenerationTimeInMinutes { get; set; }
427 | public int ExpectedNumberOfBlocksGeneratedPerDay => (int) EstimatedBlockGenerationTimeInMinutes * GlobalConstants.MinutesInADay;
428 | public decimal FeePerThousandBytesInCoins { get; set; }
429 | public short FreeTransactionMaximumSizeInBytes { get; set; }
430 | public decimal FreeTransactionMinimumOutputAmountInCoins { get; set; }
431 | public int FreeTransactionMinimumPriority { get; set; }
432 | public bool IgnoreConfigFiles { get; }
433 | public string IsoCurrencyCode { get; set; }
434 | public decimal MinimumNonDustTransactionAmountInCoins { get; set; }
435 | public decimal MinimumTransactionFeeInCoins { get; set; }
436 | public decimal OneBaseUnitInCoins => CoinsPerBaseUnit;
437 | public uint OneCoinInBaseUnits => BaseUnitsPerCoin;
438 | public string RpcPassword { get; set; }
439 | public short RpcRequestTimeoutInSeconds { get; set; }
440 | public string RpcUsername { get; set; }
441 | public string SelectedDaemonUrl => !UseTestnet ? DaemonUrl : DaemonUrlTestnet;
442 | public ulong TotalCoinSupplyInCoins { get; set; }
443 | public int TransactionSizeBytesContributedByEachInput { get; set; }
444 | public int TransactionSizeBytesContributedByEachOutput { get; set; }
445 | public int TransactionSizeFixedExtraSizeInBytes { get; set; }
446 | public bool UseTestnet { get; set; }
447 | public string WalletPassword { get; set; }
448 | }
449 | }
450 | }
451 |
--------------------------------------------------------------------------------
/src/BitcoinLib/CoinParameters/Base/ICoinParameters.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using BitcoinLib.Services;
5 |
6 | namespace BitcoinLib.CoinParameters.Base
7 | {
8 | public interface ICoinParameters
9 | {
10 | CoinService.CoinParameters Parameters { get; }
11 | }
12 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/CoinParameters/Bitcoin/BitcoinConstants.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using BitcoinLib.CoinParameters.Base;
5 |
6 | namespace BitcoinLib.CoinParameters.Bitcoin
7 | {
8 | public static class BitcoinConstants
9 | {
10 | public sealed class Constants : CoinConstants
11 | {
12 | public readonly int OneBitcoinInSatoshis = 100000000;
13 | public readonly decimal OneSatoshiInBTC = 0.00000001M;
14 | public readonly int SatoshisPerBitcoin = 100000000;
15 | public readonly string Symbol = "฿";
16 |
17 | #region Custom constructor example - commented out on purpose
18 |
19 | //private static readonly Lazy Lazy = new Lazy(() => new Constants());
20 |
21 | //public static Constants Instance
22 | //{
23 | // get
24 | // {
25 | // return Lazy.Value;
26 | // }
27 | //}
28 |
29 | //private Constants()
30 | //{
31 | // // custom logic here
32 | //}
33 |
34 | #endregion
35 | }
36 | }
37 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/CoinParameters/Bitcoin/IBitcoinConstants.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | namespace BitcoinLib.CoinParameters.Bitcoin
5 | {
6 | public interface IBitcoinConstants
7 | {
8 | BitcoinConstants.Constants Constants { get; }
9 | }
10 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/CoinParameters/Dallar/DallarConstants.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using BitcoinLib.CoinParameters.Base;
5 |
6 | namespace BitcoinLib.CoinParameters.Dallar
7 | {
8 | public static class DallarConstants
9 | {
10 | public sealed class Constants : CoinConstants
11 | {
12 | public readonly ushort CoinReleaseReduceEveryXInBlocks = 10080;
13 | public readonly ushort DifficultyIncreasesEveryXInBlocks = 6;
14 | public readonly uint OneDallarInAllars = 100000000;
15 | public readonly decimal OneAllarInDAL = 0.00000001M;
16 | public readonly decimal OneMicroDallarInDAL = 0.000001M;
17 | public readonly decimal OneMilliDallarInDAL = 0.001M;
18 | public readonly string Symbol = "D";
19 | }
20 | }
21 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/CoinParameters/Dallar/IDallarConstants.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | namespace BitcoinLib.CoinParameters.Dallar
5 | {
6 | public interface IDallarConstants
7 | {
8 | DallarConstants.Constants Constants { get; }
9 | }
10 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/CoinParameters/Dash/DashConstants.cs:
--------------------------------------------------------------------------------
1 | using BitcoinLib.CoinParameters.Base;
2 |
3 | namespace BitcoinLib.CoinParameters.Dash
4 | {
5 | public static class DashConstants
6 | {
7 | public sealed class Constants : CoinConstants
8 | {
9 | public readonly ushort CoinReleaseHalfsEveryXInYears = 7;
10 | public readonly ushort DifficultyIncreasesEveryXInBlocks = 34560;
11 | public readonly uint OneDashInDuffs = 100000000;
12 | public readonly decimal OneDuffInDash = 0.00000001M;
13 | public readonly decimal OneMicrodashInDash = 0.000001M;
14 | public readonly decimal OneMillidashInDash = 0.001M;
15 | public readonly string Symbol = "DASH";
16 | }
17 | }
18 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/CoinParameters/Dash/IDashConstants.cs:
--------------------------------------------------------------------------------
1 | namespace BitcoinLib.CoinParameters.Dash
2 | {
3 | public interface IDashConstants
4 | {
5 | DashConstants.Constants Constants { get; }
6 | }
7 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/CoinParameters/Dogecoin/DogecoinConstants.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using BitcoinLib.CoinParameters.Base;
5 |
6 | namespace BitcoinLib.CoinParameters.Dogecoin
7 | {
8 | public static class DogecoinConstants
9 | {
10 | public sealed class Constants : CoinConstants
11 | {
12 | public readonly ushort CoinReleaseHalfsEveryXInYears = 4;
13 | public readonly ushort DifficultyIncreasesEveryXInBlocks = 2016;
14 | public readonly uint OneDogecoinInKoinus = 100000000;
15 | public readonly decimal OneKoinuInXDG = 0.00000001M;
16 | public readonly decimal OneMicrocoinInXDG = 0.000001M;
17 | public readonly decimal OneMillicoinInXDG = 0.001M;
18 | public readonly string Symbol = "Ð";
19 | }
20 | }
21 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/CoinParameters/Dogecoin/IDogecoinConstants.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | namespace BitcoinLib.CoinParameters.Dogecoin
5 | {
6 | public interface IDogecoinConstants
7 | {
8 | DogecoinConstants.Constants Constants { get; }
9 | }
10 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/CoinParameters/Litecoin/ILitecoinConstants.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | namespace BitcoinLib.CoinParameters.Litecoin
5 | {
6 | public interface ILitecoinConstants
7 | {
8 | LitecoinConstants.Constants Constants { get; }
9 | }
10 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/CoinParameters/Litecoin/LitecoinConstants.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using BitcoinLib.CoinParameters.Base;
5 |
6 | namespace BitcoinLib.CoinParameters.Litecoin
7 | {
8 | public static class LitecoinConstants
9 | {
10 | public sealed class Constants : CoinConstants
11 | {
12 | public readonly ushort CoinReleaseHalfsEveryXInYears = 4;
13 | public readonly ushort DifficultyIncreasesEveryXInBlocks = 2016;
14 | public readonly uint OneLitecoinInLitetoshis = 100000000;
15 | public readonly decimal OneLitetoshiInLTC = 0.00000001M;
16 | public readonly decimal OneMicrocoinInLTC = 0.000001M;
17 | public readonly decimal OneMillicoinInLTC = 0.001M;
18 | public readonly string Symbol = "Ł";
19 | }
20 | }
21 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/CoinParameters/Mogwaicoin/IMogwaicoinConstants.cs:
--------------------------------------------------------------------------------
1 | namespace BitcoinLib.CoinParameters.Mogwaicoin
2 | {
3 | public interface IMogwaicoinConstants
4 | {
5 | MogwaicoinConstants.Constants Constants { get; }
6 | }
7 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/CoinParameters/Mogwaicoin/MogwaicoinConstants.cs:
--------------------------------------------------------------------------------
1 | using BitcoinLib.CoinParameters.Base;
2 |
3 | namespace BitcoinLib.CoinParameters.Mogwaicoin
4 | {
5 | public static class MogwaicoinConstants
6 | {
7 | public sealed class Constants : CoinConstants
8 | {
9 | public readonly ushort CoinReleaseHalfsEveryXInYears = 7;
10 | public readonly ushort DifficultyIncreasesEveryXInBlocks = 34560;
11 | public readonly uint OneDashInDuffs = 100000000;
12 | public readonly decimal OneDuffInDash = 0.00000001M;
13 | public readonly decimal OneMicrodashInDash = 0.000001M;
14 | public readonly decimal OneMillidashInDash = 0.001M;
15 | public readonly string Symbol = "MOG";
16 | }
17 | }
18 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/CoinParameters/Smartcash/ISmartcashConstants.cs:
--------------------------------------------------------------------------------
1 | namespace BitcoinLib.CoinParameters.Smartcash
2 | {
3 | public interface ISmartcashConstants
4 | {
5 | SmartcashConstants.Constants Constants { get; }
6 | }
7 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/CoinParameters/Smartcash/SmartcashConstants.cs:
--------------------------------------------------------------------------------
1 | using BitcoinLib.CoinParameters.Base;
2 |
3 | namespace BitcoinLib.CoinParameters.Smartcash
4 | {
5 | public static class SmartcashConstants
6 | {
7 | public sealed class Constants : CoinConstants
8 | {
9 | public readonly ushort CoinReleaseHalfsEveryXInYears = 4;
10 | public readonly ushort DifficultyIncreasesEveryXInBlocks = 2016;
11 | public readonly uint OneSmartInSmartoshis = 100000000;
12 | public readonly decimal OneSmartoshisInSmart = 0.00000001M;
13 | public readonly decimal OneMicrosmartInSmart = 0.000001M;
14 | public readonly decimal OneMillismartInSmart = 0.001M;
15 | public readonly string Symbol = "SMART";
16 | }
17 | }
18 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/ExceptionHandling/RawTransactions/RawTransactionExcessiveFeeException.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using System;
5 |
6 | namespace BitcoinLib.ExceptionHandling.RawTransactions
7 | {
8 | [Serializable]
9 | public class RawTransactionExcessiveFeeException : Exception
10 | {
11 | public RawTransactionExcessiveFeeException() : base("Fee in raw transaction is greater than specified amount.")
12 | {
13 | }
14 |
15 | public RawTransactionExcessiveFeeException(decimal maxSpecifiedFee) : base($"Fee in raw transaction is greater than specified amount of {maxSpecifiedFee}.")
16 | {
17 | }
18 |
19 | public RawTransactionExcessiveFeeException(decimal actualFee, decimal maxSpecifiedFee) : base($"Fee of {actualFee} in raw transaction is greater than specified amount of {maxSpecifiedFee}.")
20 | {
21 | }
22 |
23 | public RawTransactionExcessiveFeeException(string message) : base(message)
24 | {
25 | }
26 |
27 | public RawTransactionExcessiveFeeException(string message, Exception innerException) : base(message, innerException)
28 | {
29 | }
30 | }
31 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/ExceptionHandling/RawTransactions/RawTransactionInvalidAmountException.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using System;
5 |
6 | namespace BitcoinLib.ExceptionHandling.RawTransactions
7 | {
8 | [Serializable]
9 | public class RawTransactionInvalidAmountException : Exception
10 | {
11 | public RawTransactionInvalidAmountException() : base("Raw Transaction amount is invalid.")
12 | {
13 | }
14 |
15 | public RawTransactionInvalidAmountException(string message) : base(message)
16 | {
17 | }
18 |
19 | public RawTransactionInvalidAmountException(string message, Exception innerException) : base(message, innerException)
20 | {
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/ExceptionHandling/Rpc/RpcException.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using System;
5 |
6 | namespace BitcoinLib.ExceptionHandling.Rpc
7 | {
8 | [Serializable]
9 | public class RpcException : Exception
10 | {
11 | public RpcException()
12 | {
13 | }
14 |
15 | public RpcException(string customMessage) : base(customMessage)
16 | {
17 | }
18 |
19 | public RpcException(string customMessage, Exception exception) : base(customMessage, exception)
20 | {
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/ExceptionHandling/Rpc/RpcInternalServerErrorException.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using System;
5 | using System.Runtime.Serialization;
6 | using BitcoinLib.RPC.Specifications;
7 |
8 | namespace BitcoinLib.ExceptionHandling.Rpc
9 | {
10 | [Serializable]
11 | public class RpcInternalServerErrorException : Exception
12 | {
13 | public RpcInternalServerErrorException()
14 | {
15 | }
16 |
17 | public RpcInternalServerErrorException(string customMessage) : base(customMessage)
18 | {
19 | }
20 |
21 | public RpcInternalServerErrorException(string customMessage, Exception exception) : base(customMessage, exception)
22 | {
23 | }
24 |
25 | public RpcErrorCode? RpcErrorCode { get; set; }
26 |
27 | public override void GetObjectData(SerializationInfo info, StreamingContext context)
28 | {
29 | if (info == null)
30 | {
31 | throw new ArgumentNullException("info");
32 | }
33 |
34 | info.AddValue("RpcErrorCode", RpcErrorCode, typeof(RpcErrorCode));
35 | base.GetObjectData(info, context);
36 | }
37 | }
38 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/ExceptionHandling/Rpc/RpcRequestTimeoutException.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using System;
5 |
6 | namespace BitcoinLib.ExceptionHandling.Rpc
7 | {
8 | [Serializable]
9 | public class RpcRequestTimeoutException : Exception
10 | {
11 | public RpcRequestTimeoutException()
12 | {
13 | }
14 |
15 | public RpcRequestTimeoutException(string customMessage) : base(customMessage)
16 | {
17 | }
18 |
19 | public RpcRequestTimeoutException(string customMessage, Exception exception) : base(customMessage, exception)
20 | {
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/ExceptionHandling/Rpc/RpcResponseDeserializationException.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using System;
5 |
6 | namespace BitcoinLib.ExceptionHandling.Rpc
7 | {
8 | [Serializable]
9 | public class RpcResponseDeserializationException : Exception
10 | {
11 | public RpcResponseDeserializationException()
12 | {
13 | }
14 |
15 | public RpcResponseDeserializationException(string customMessage) : base(customMessage)
16 | {
17 | }
18 |
19 | public RpcResponseDeserializationException(string customMessage, Exception exception) : base(customMessage, exception)
20 | {
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/ExceptionHandling/RpcExtenderService/GetAddressBalanceException.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using System;
5 |
6 | namespace BitcoinLib.ExceptionHandling.RpcExtenderService
7 | {
8 | [Serializable]
9 | public class GetAddressBalanceException : Exception
10 | {
11 | public GetAddressBalanceException()
12 | {
13 | }
14 |
15 | public GetAddressBalanceException(string customMessage) : base(customMessage)
16 | {
17 | }
18 |
19 | public GetAddressBalanceException(string customMessage, Exception exception) : base(customMessage, exception)
20 | {
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/ExtensionMethods/CoinServiceExtensionMethods.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using BitcoinLib.Services.Coins.Base;
5 |
6 | namespace BitcoinLib.ExtensionMethods
7 | {
8 | public static class CoinServiceExtensionMethods
9 | {
10 | public static void SwitchNetworks(this ICoinService coinService)
11 | {
12 | coinService.Parameters.UseTestnet = !coinService.Parameters.UseTestnet;
13 | }
14 | }
15 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/ExtensionMethods/DecimalExtensionMethods.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using System;
5 |
6 | namespace BitcoinLib.ExtensionMethods
7 | {
8 | public static class DecimalExtensionMethods
9 | {
10 | public static ushort GetNumberOfDecimalPlaces(this decimal number)
11 | {
12 | return BitConverter.GetBytes(decimal.GetBits(number)[3])[2];
13 | }
14 | }
15 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/RPC/Connector/IRpcConnector.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using BitcoinLib.RPC.Specifications;
5 |
6 | namespace BitcoinLib.RPC.Connector
7 | {
8 | public interface IRpcConnector
9 | {
10 | T MakeRequest(RpcMethods method, params object[] parameters);
11 | }
12 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/RPC/Connector/RawRpcConnector.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using System;
5 | using System.IO;
6 | using System.Net;
7 | using System.Text;
8 | using BitcoinLib.Services.Coins.Base;
9 |
10 | namespace BitcoinLib.RPC.Connector
11 | {
12 | // This class is disconnected from the core logic and its sole purpose is to serve as a quick and dirty means of debugging
13 | public static class RawRpcConnector
14 | {
15 | // Usage example: String networkDifficultyJsonResult = RawRpcConnector.MakeRequest("{\"method\":\"getdifficulty\",\"params\":[],\"id\":1}", "http://127.0.0.1:8332/", "MyRpcUsername", "MyRpcPassword");
16 | public static string MakeRequest(string jsonRequest, string daemonUrl, string rpcUsername, string rpcPassword)
17 | {
18 | try
19 | {
20 | var tempCookies = new CookieContainer();
21 | var encoding = new ASCIIEncoding();
22 | var byteData = encoding.GetBytes(jsonRequest);
23 | var postReq = (HttpWebRequest) WebRequest.Create(daemonUrl);
24 | postReq.Credentials = new NetworkCredential(rpcUsername, rpcPassword);
25 | postReq.Method = "POST";
26 | postReq.KeepAlive = true;
27 | postReq.CookieContainer = tempCookies;
28 | postReq.ContentType = "application/json";
29 | postReq.ContentLength = byteData.Length;
30 | var postreqstream = postReq.GetRequestStream();
31 | postreqstream.Write(byteData, 0, byteData.Length);
32 | postreqstream.Close();
33 | var postresponse = (HttpWebResponse) postReq.GetResponse();
34 | var postreqreader = new StreamReader(postresponse.GetResponseStream());
35 | return postreqreader.ReadToEnd();
36 | }
37 | catch (Exception exception)
38 | {
39 | return exception.ToString();
40 | }
41 | }
42 |
43 | // Usage example: String networkDifficultyJsonResult = RawRpcConnector.MakeRequest("{\"method\":\"getdifficulty\",\"params\":[],\"id\":1}", new BitcoinService());
44 | public static string MakeRequest(string jsonRequest, ICoinService coinService)
45 | {
46 | return MakeRequest(jsonRequest, coinService.Parameters.SelectedDaemonUrl, coinService.Parameters.RpcUsername, coinService.Parameters.RpcPassword);
47 | }
48 | }
49 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/RPC/Connector/RpcConnector.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using System;
5 | using System.IO;
6 | using System.Linq;
7 | using System.Net;
8 | using System.Text;
9 | using BitcoinLib.Auxiliary;
10 | using BitcoinLib.ExceptionHandling.Rpc;
11 | using BitcoinLib.RPC.RequestResponse;
12 | using BitcoinLib.RPC.Specifications;
13 | using BitcoinLib.Services.Coins.Base;
14 | using Newtonsoft.Json;
15 |
16 | namespace BitcoinLib.RPC.Connector
17 | {
18 | public sealed class RpcConnector : IRpcConnector
19 | {
20 | private readonly ICoinService _coinService;
21 |
22 | public RpcConnector(ICoinService coinService)
23 | {
24 | _coinService = coinService;
25 | }
26 |
27 | public T MakeRequest(RpcMethods rpcMethod, params object[] parameters)
28 | {
29 | var jsonRpcRequest = new JsonRpcRequest(1, rpcMethod.ToString(), parameters);
30 | var webRequest = (HttpWebRequest) WebRequest.Create(_coinService.Parameters.SelectedDaemonUrl);
31 | SetBasicAuthHeader(webRequest, _coinService.Parameters.RpcUsername, _coinService.Parameters.RpcPassword);
32 | webRequest.Credentials = new NetworkCredential(_coinService.Parameters.RpcUsername, _coinService.Parameters.RpcPassword);
33 | webRequest.ContentType = "application/json-rpc";
34 | webRequest.Method = "POST";
35 | webRequest.Proxy = null;
36 | webRequest.Timeout = _coinService.Parameters.RpcRequestTimeoutInSeconds * GlobalConstants.MillisecondsInASecond;
37 | var byteArray = jsonRpcRequest.GetBytes();
38 | webRequest.ContentLength = jsonRpcRequest.GetBytes().Length;
39 |
40 | try
41 | {
42 | using (var dataStream = webRequest.GetRequestStream())
43 | {
44 | dataStream.Write(byteArray, 0, byteArray.Length);
45 | dataStream.Dispose();
46 | }
47 | }
48 | catch (Exception exception)
49 | {
50 | throw new RpcException("There was a problem sending the request to the wallet", exception);
51 | }
52 |
53 | try
54 | {
55 | string json;
56 |
57 | using (var webResponse = webRequest.GetResponse())
58 | {
59 | using (var stream = webResponse.GetResponseStream())
60 | {
61 | using (var reader = new StreamReader(stream))
62 | {
63 | var result = reader.ReadToEnd();
64 | reader.Dispose();
65 | json = result;
66 | }
67 | }
68 | }
69 |
70 | var rpcResponse = JsonConvert.DeserializeObject>(json);
71 | return rpcResponse.Result;
72 | }
73 | catch (WebException webException)
74 | {
75 | #region RPC Internal Server Error (with an Error Code)
76 |
77 | var webResponse = webException.Response as HttpWebResponse;
78 |
79 | if (webResponse != null)
80 | {
81 | switch (webResponse.StatusCode)
82 | {
83 | case HttpStatusCode.InternalServerError:
84 | {
85 | using (var stream = webResponse.GetResponseStream())
86 | {
87 | if (stream == null)
88 | {
89 | throw new RpcException("The RPC request was either not understood by the server or there was a problem executing the request", webException);
90 | }
91 |
92 | using (var reader = new StreamReader(stream))
93 | {
94 | var result = reader.ReadToEnd();
95 | reader.Dispose();
96 |
97 | try
98 | {
99 | var jsonRpcResponseObject = JsonConvert.DeserializeObject>(result);
100 |
101 | var internalServerErrorException = new RpcInternalServerErrorException(jsonRpcResponseObject.Error.Message, webException)
102 | {
103 | RpcErrorCode = jsonRpcResponseObject.Error.Code
104 | };
105 |
106 | throw internalServerErrorException;
107 | }
108 | catch (JsonException)
109 | {
110 | throw new RpcException(result, webException);
111 | }
112 | }
113 | }
114 | }
115 |
116 | default:
117 | throw new RpcException("The RPC request was either not understood by the server or there was a problem executing the request", webException);
118 | }
119 | }
120 |
121 | #endregion
122 |
123 | #region RPC Time-Out
124 |
125 | if (webException.Message == "The operation has timed out")
126 | {
127 | throw new RpcRequestTimeoutException(webException.Message);
128 | }
129 |
130 | #endregion
131 |
132 | throw new RpcException("An unknown web exception occured while trying to read the JSON response", webException);
133 | }
134 | catch (JsonException jsonException)
135 | {
136 | throw new RpcResponseDeserializationException("There was a problem deserializing the response from the wallet", jsonException);
137 | }
138 | catch (ProtocolViolationException protocolViolationException)
139 | {
140 | throw new RpcException("Unable to connect to the server", protocolViolationException);
141 | }
142 | catch (Exception exception)
143 | {
144 | var queryParameters = jsonRpcRequest.Parameters.Cast().Aggregate(string.Empty, (current, parameter) => current + (parameter + " "));
145 | throw new Exception($"A problem was encountered while calling MakeRpcRequest() for: {jsonRpcRequest.Method} with parameters: {queryParameters}. \nException: {exception.Message}");
146 | }
147 | }
148 |
149 | private static void SetBasicAuthHeader(WebRequest webRequest, string username, string password)
150 | {
151 | var authInfo = username + ":" + password;
152 | authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
153 | webRequest.Headers["Authorization"] = "Basic " + authInfo;
154 | }
155 | }
156 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/RPC/RequestResponse/JsonRpcError.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using BitcoinLib.RPC.Specifications;
5 | using Newtonsoft.Json;
6 |
7 | namespace BitcoinLib.RPC.RequestResponse
8 | {
9 | public class JsonRpcError
10 | {
11 | [JsonProperty(PropertyName = "code")]
12 | public RpcErrorCode Code { get; set; }
13 |
14 | [JsonProperty(PropertyName = "message")]
15 | public string Message { get; set; }
16 | }
17 | }
--------------------------------------------------------------------------------
/src/BitcoinLib/RPC/RequestResponse/JsonRpcRequest.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2014 - 2016 George Kimionis
2 | // See the accompanying file LICENSE for the Software License Aggrement
3 |
4 | using System.Collections.Generic;
5 | using System.Linq;
6 | using System.Text;
7 | using Newtonsoft.Json;
8 |
9 | namespace BitcoinLib.RPC.RequestResponse
10 | {
11 | public class JsonRpcRequest
12 | {
13 | public JsonRpcRequest(int id, string method, params object[] parameters)
14 | {
15 | Id = id;
16 | Method = method;
17 | Parameters = parameters?.ToList() ?? new List