cryptean / bitcoinlib Goto Github PK
View Code? Open in Web Editor NEWBitcoin Core RPC compatible, battle-tested .NET library and RPC wrapper for Bitcoin and Altcoins
License: MIT License
Bitcoin Core RPC compatible, battle-tested .NET library and RPC wrapper for Bitcoin and Altcoins
License: MIT License
Cf. bitcoin-dot-org/Bitcoin.org#1287, the account system has been deprecated and will be removed in Bitcoin Core 0.18. But I cannot see that this repo uses the new label system. The deprecated and new methods are listed here:
https://bitcoincore.org/en/releases/0.17.0/#label-and-account-apis-for-wallet
i try to use bitcoinLib with rpc.blockchain.info , it's always return 0 as balance
Hello,
i´ve got this exception, when i try to call BitcoinService.GetNewAddress():
"[RpcException: The RPC request was either not understood by the Bitcoin server or there was a problem executing the request]
BitcoinLib.RPC.RpcConnector.MakeRpcRequest(JsonRpcRequest jsonRpcRequest, Int16 timedOutRequests) in c:\Users\VM\Downloads\BitcoinLib-master\BitcoinLib-master\BitcoinWrapper\RPC\RpcConnector.cs:76
BitcoinLib.RPC.RpcConnector.MakeRequest(RpcMethods rpcMethod, Object[] parameters) in c:\Users\VM\Downloads\BitcoinLib-master\BitcoinLib-master\BitcoinWrapper\RPC\RpcConnector.cs:33
BitcoinLib.Services.BitcoinService.GetNewAddress(String account) in c:\Users\VM\Downloads\BitcoinLib-master\BitcoinLib-master\BitcoinWrapper\Services\RpcService.cs:169
_Default.Page_Load(Object sender, EventArgs e) +359
System.Web.UI.Control.LoadRecursive() +71
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3178"
So i hope i understand it correctly, and the method should create a new Bitcoin address :d
Thanks for all your help and work, i´ve made a little payment API with help of yours, when we get that fixed, it should work. You can get it for free, when you help me, of course. When you need, i can also offer you a virtual server in netherlands 1 year for free.
Regards from Germany,
Dieter Kuhn
This is related to #15.
For example, BitcoinService has differetn constructors in release and debug, Looks like debug is newer than release and NuGet package. Is it safe to use current debug build in production?
i'm using BitcoinLib. when i run my code this error occurs "There was a problem sending the request to the wallet"
My webconfig code is
<add key="Bitcoin_DaemonUrl" value="http://localhost:8332" />
<add key="Bitcoin_DaemonUrl_Testnet" value="http://localhost:18332" />
<add key="Bitcoin_WalletPassword" value="MyWalletPassword" />
<add key="Bitcoin_RpcUsername" value="MyRpcUsername" />
<add key="Bitcoin_RpcPassword" value="MyRpcPassword" />
I see it in RpcMethods enum but there is no method in RpcService. Why? In my case I need it to get exact fee to determine if a user has enough funds to make a transfer (desired amount to sent + fee).
getWalletInfoResponse is missing keyPoolSize atribute.
from
https://bitcoin.org/en/developer-reference#getwalletinfo
BitcoinLib should also target .NET Standard, similar to what's discussed in
Is it OK to calculate merkle root with hash? What about witness transactions?
ListTransactions
should return the label field. I'm not in a position to make a pull request right now so here's the new source code:
public class ListTransactionsResponse
{
public string Account { get; set; }
public string Address { get; set; }
public string Category { get; set; }
public decimal Amount { get; set; }
public string Label { get; set; }
public int Vout { get; set; }
public decimal Fee { get; set; }
public int Confirmations { get; set; }
public string BlockHash { get; set; }
public int BlockIndex { get; set; }
public int BlockTime { get; set; }
public string TxId { get; set; }
public List<string> WalletConflicts { get; set; }
public int Time { get; set; }
public int TimeReceived { get; set; }
public string Comment { get; set; }
public string OtherAccount { get; set; }
public bool InvolvesWatchonly { get; set; }
public bool Abandoned { get; set; }
}
I also fixed double
to int
and added a new field bool Abandoned
which I found returned in the current version of Bitcoin Core.
Can this library be use to handle more than 1 wallet, bitcoin-cli.exe have the createwallet
command with a unique id and the connection can have the --rpcwallet
with the same id.
What are the alternative if I need to handle more than 1 wallet. Thanks
Hi,
Is there any reason the web response is not wrapped in a using block?
Cheers,
Chaz
public ListSinceBlockResponse ListSinceBlock(string blockHash, int targetConfirmations, bool? includeWatchonly) { return includeWatchonly == null ? _rpcConnector.MakeRequest<ListSinceBlockResponse>(RpcMethods.listsinceblock, (string.IsNullOrWhiteSpace(blockHash) ? "*" : blockHash), targetConfirmations) : _rpcConnector.MakeRequest<ListSinceBlockResponse>(RpcMethods.listsinceblock, (string.IsNullOrWhiteSpace(blockHash) ? "*" : blockHash), targetConfirmations, includeWatchonly); }
When blockHash parameter is omitted - function should not fail, but instead should return all transactions. Right now it passes "*" when nothing specified, which is wrong. The fix is to supply empty string in that case.
Results:
Before fix - Invoking method with blockHash as empty string results in exception from bitcoin rpc service.
After fix - Returns all transactions since genesis block.
It seems to force me to use the xml settings specifically, even when I pass in the settings in the constructor:
new BitcoinService(appSettings.Bitcoin.ServerUrl, appSettings.Bitcoin.Username, appSettings.Bitcoin.Password, appSettings.Bitcoin.WalletPassword);
It still tries to read from the settings file, throwing the error:
One or more required parameters, as defined in CoinParameters, were not found in the configuration file!
There's an IgnoreConfigFiles
but there's no way for me to interact with it...
Trying to call " CoinService.ListTransactions("*", 100, 0)" results in an exception:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[BitcoinLib.Responses.ListTransactionsResponse]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'result.lastblock', line 1, position 23.
Obviously - the response is not compatible with being deserialized into ListTransactionsResponse
Hi,
Where is the following bitcoin.conf file stored on a mac, I notice on the front page it gives the info of where i should find it on Windows but i currently use a mac.
thanks
Hi,
can I use with your project bip39 and Mnemonic wallets?
Is it possible to add the estimatesmartfee
RPC call please?
Although the Json request is done and retreived, GetBlockTemplate crash when the lib is trying to deserialize...
Thanks
BitcoinLib.ExceptionHandling.Rpc.RpcResponseDeserializationException was unhandled
HResult=-2146233088
Message=There was a problem deserializing the response from the wallet
Source=BitcoinLib
StackTrace:
at BitcoinLib.RPC.Connector.RpcConnector.MakeRequest[T](RpcMethods rpcMethod, Int16 timedOutRequestsCount, Object[] parameters) in g:\Downloads\BitcoinLib-master\BitcoinLib-master\CoinWrapper\RPC\RequestResponse\RpcConnector.cs:line 166
at BitcoinLib.RPC.Connector.RpcConnector.MakeRequest[T](RpcMethods rpcMethod, Object[] parameters) in g:\Downloads\BitcoinLib-master\BitcoinLib-master\CoinWrapper\RPC\RequestResponse\RpcConnector.cs:line 31
at BitcoinLib.Services.CoinService.GetBlockTemplate(Object[] parameters) in g:\Downloads\BitcoinLib-master\BitcoinLib-master\CoinWrapper\Services\RpcServices\RpcService\RpcService.cs:line 165
at ConsoleClient.Program.Main() in g:\Downloads\BitcoinLib-master\BitcoinLib-master\ConsoleClient\Program.cs:line 38
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: Newtonsoft.Json.JsonReaderException
HResult=-2146233088
Message=Error reading string. Unexpected token: StartObject. Path 'result', line 1, position 11.
Source=Newtonsoft.Json
LineNumber=1
LinePosition=11
Path=result
StackTrace:
at Newtonsoft.Json.JsonReader.ReadAsStringInternal()
at Newtonsoft.Json.JsonTextReader.ReadAsString()
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value)
at BitcoinLib.RPC.Connector.RpcConnector.MakeRequest[T](RpcMethods rpcMethod, Int16 timedOutRequestsCount, Object[] parameters) in g:\Downloads\BitcoinLib-master\BitcoinLib-master\CoinWrapper\RPC\RequestResponse\RpcConnector.cs:line 80
InnerException:
Weight was introduced as part of the segwit softfork as a new way of enforcing the max block size. It would be nice to have for the block explorer, I am currently working on.
When using the latest bitcoin core 0.17.1, it produces 500 server error, and bitcoin core version 0.16.3 works without any issue.
(note: not really a bug just a little confused)
So I'm connecting to Dogecoin at runtime and I cant really use a file like app.config which I see is what is used in the console example. What I have at the moment is this:
ICryptocoinService cryptocoinService;
try {
cryptocoinService = new CryptocoinService("myhost", "myuser", "mypass");
cryptocoinService.Parameters.RpcRequestTimeoutInSeconds = 10;
cryptocoinService.Parameters.RpcResendTimedOutRequests = true;
cryptocoinService.Parameters.RpcTimedOutRequestsResendAttempts = 5;
cryptocoinService.Parameters.RpcDelayResendingTimedOutRequests = true; cryptocoinService.Parameters.RpcUseBase2ExponentialDelaysWhenResendingTimedOutRequests = true;
cryptocoinService.Parameters.RpcUnlockWalletImplicitlyWhenRequired = true;
cryptocoinService.Parameters.CoinLongName = "Dogecoin";
cryptocoinService.Parameters.CoinShortName = "Doge";
cryptocoinService.Parameters.IsoCurrencyCode = "XDG";
cryptocoinService.Parameters.UseTestnet = false;
} catch(Exception e1) {
Log.Error (e1.Message); // Custom class I have you'll ned to use Console.log here
}
and I seem to be getting this:
[01-09-2014 20:55:32] ERROR: One or more required parameters, as defined in CoinParameters, were not found in the configuration file!
So just what are the required parameters? And how would one obtain them?
I have looked in the "CoinParameters" class and there are a lot of parameters do I need all of them?
When using for example the method ICoinService.GetBalance()
, it would be nice to be able to read from the function description (formally: "documentation comments") which units a function returns. Is it satoshi or bitcoins? I believe it is bitcoins, like the RPC, but that ought to be appear from the documentation, in my opinion.
Feel free to assign this issue to me if you think it is a good idea.
public T MakeRequest(RpcMethods rpcMethod, params object[] parameters) sometimes throws a null reference exception when trying to return rpcResponse.Result; (it's the .Error that contains info in these cases).
In my personal version, I implemented a workaround, if (rpcResponse == null) return default(T);
1: I wish to avoid a "personal version", but 2: not sure my workaround is a correct approach.
Please let me know if "return default(T);" is a correct approach in this null result, or should I catch the exception at my application level (which for me would translate to multiple locations). I'm suspecting I'm using a wrong approach.
When I think of it, the best for me is that in case there's a null reference exception, the application would somehow have access to the full Json response (instead of just the exception or just a default(T) that I'm returning. The reason is that we need to let the application "see" the error property that's in the Json.
below is my current workaround code. Waiting to read your thoughts.
public T MakeRequest(RpcMethods rpcMethod, params object[] parameters)
{
JsonRpcResponse rpcResponse = MakeRpcRequest(new JsonRpcRequest(1, rpcMethod.ToString(), parameters), 0);
if (rpcResponse == null)
return default(T);
else
return rpcResponse.Result;
My intuition tells me that when this variable is set to true BitcoinLib should automatically call WalletPassphrase() when I use methods like SendToAddress(), right?
I don't see it working.
And when I search code for this variable I don't see it used anywhere.
https://github.com/GeorgeKimionis/BitcoinLib/search?utf8=%E2%9C%93&q=RpcUnlockWalletImplicitlyWhenRequired
So I guess it should be removed or implemented :)
When ListAccounts() called it throws jsonException {"Error reading string. Unexpected token: StartObject. Path 'result', line 1, position 11."} Newtonsoft.Json.JsonException {Newtonsoft.Json.JsonReaderException}
Hi,
I'm developing my application that should be able to work with Bitcoin Core via RPC.
Many thanks for your library at first!
I guess I found a bug:
When I call DumpWallet method, exception occured related to newtonsoft json library. In the same time wallet backup file with private keys was succesfully created!
I guess that when you send dumpwallet command, if the operation was successfull, RPC return null and newtonsoft json library didn't recognize it like JSON.
I guess before to call JsonConvert.DeserializeObject method you should to check if it's valid json string, not empty or null.
Could you check this issue please.
Thanks in advance.
Hi so everytime when i run the sendtoaddress in C#, and enabledsubtractfeefromamount, it keeps subtracting the fees from the balance instead of the amount of coin they sent, can this be fixed?
Quick update for BCH support?
Seems like your library is not friendly to predefined objects..
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'System.Configuration.ConfigurationManager, Version=0.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The system cannot find the file specified.
at BitcoinLib.Services.CoinService.CoinParameters..ctor(ICoinService coinService, String daemonUrl, String rpcUsername, String rpcPassword, String walletPassword, Int16 rpcRequestTimeoutInSeconds)
at BitcoinLib.Services.CoinService..ctor(String daemonUrl, String rpcUsername, String rpcPassword, String walletPassword, Int16 rpcRequestTimeoutInSeconds)
at WalletServer.Program.Main(String[] args) in
And in case you assume ApplicationSettings could be invalid:
// Bitcoind
_BitcoinService = new BitcoinService(ApplicationSettings.GetEncryptedString("BTCNodeDaemonURL"),
ApplicationSettings.GetEncryptedString("BTCNodeJsonRPCUser"),
ApplicationSettings.GetEncryptedString("BTCNodeJsonRPCPass"),
"", 10);
This method returns 500 Internal Server Error.
It'd be nice with a build script (build.cmd
, build.sh
, or similar) that builds the project(s) from the command-line and (optionally) creates NuGet Packages (see also #30).
I'm trying to connect to a blockchain.info wallet which has a Bitcoind compatible RPC API as described here:
https://blockchain.info/fr/api/json_rpc_api
the GetBalance() method works, but I can't make SendToAddress() work, here is the error I get:(which btw throws a RpcResponseDeserializationException when the lib try to parse it)
"{"error":{"message":null,"code":-32603},"jsonrpc":"2.0"}"
anyone tested this lib with blockchain.info?
Basically I compiled an entire .NET Core Console App and ran it with BitcoinLib that's added as a package. It can't seem to run because of it.
2018-02-05T17:02:58 PID[4556] Information D:\local\Temp\jobs\continuous\walletservice\jx1rtgpb.j3j>dotnet WalletServer.dll
2018-02-05T17:02:58 PID[4556] Error Error:
2018-02-05T17:02:58 PID[4556] Error An assembly specified in the application dependencies manifest (WalletServer.deps.json) was not found:
2018-02-05T17:02:58 PID[4556] Error package: 'BitcoinLib', version: '1.6.0'
2018-02-05T17:02:58 PID[4556] Error path: 'lib/netstandard2.0/BitcoinLib.dll'
2018-02-05T17:02:58 PID[4556] Error
Proposal :
Class ListTransactionsResponse should use
int Confirmations instead of UInt32 Confirmations.
Reason :
when you execute the method on a wallet that has transactions, but is using an empty data (downloading the blockchain from scratch).
the returned JSON will contain -1 for Confirmations in this case.
Solution:
public int Confirmations { get; set; } //changed from UInt32
As the title says, when I call get block with verbose it does not return the full details of the transactions.
for example:
neither
var balance = BitcoinService.GetBalance(address, 1, true);
nor
var balance = BitcoinService.GetBalance(address);
does not return correct balance - but only 0.000000000
Is there a way to work the client without revealing the passphrase in the config file ?
I would recommend making the keys : Bitcoin_WalletPassword , Bitcoin_RpcUsername , Bitcoin_RpcPassword optional and let the user call WalletPassphrase instead
It'd be easier to troubleshoot issues if a NuGet Package is pushed on the NuGet Gallery every time a pull request gets merged into the master
branch.
Is the current license updated as intended?
It reads like a closed source license and not like a open-source license. I don't think I can even make a fork of this in GitHub.
On the Preamble:
without the rights to create derivative works
On the Permitted Use and Restrictions:
shall not distribute, sell or transfer the Software or Improvements to any person or third parties without prior written permission from the Licensor.
On the Ownership and Assignment of Copyright:
The Licensee agrees to use its reasonable best efforts to protect the contents of the Software and to prevent unauthorized disclosure by its agents, officers, employees, and consultants
On the Copies:
The Licensee may make a reasonable number of copies of the Software for the purposes of backup and maintenance of the Software
There is no support for sendtoaddress
to add param subtractfeefromamount
bool
sorry, forgive my request
We need to verify that a Bitcoin address is valid.
We are currently not using BitcoinLib.
Do you happen to have code that verifies this, and if so can you point us in its general direction?
Install-Package : Unable to resolve dependencies. 'Newtonsoft.Json 10.0.3' is not compatible with 'BitcoinLib 1.4.1 constraint: Newtonsoft.Json (= 6.0.3)'.
At line:1 char:1
gettransaction
returns a label for each details items. Quoting the Bitcoin Core source code:
"gettransaction \"txid\" ( include_watchonly )\n"
...
" \"details\" : [\n"
" {\n"
" \"account\" : \"accountname\", (string) DEPRECATED. The account name involved in the transaction, can be \"\" for the default account.\n"
" \"address\" : \"address\", (string) The bitcoin address involved in the transaction\n"
...
" \"label\" : \"label\", (string) A comment for the address/transaction, if any\n"
...
It would be nice to have access to that label via BitcoinService.GetTransaction()
.
Very useful function
Hi and thanks for a neat library.
I'm getting an RpcException (Additional information: The RPC request was either not understood by the Bitcoin server or there was a problem executing the request) when trying to get the following transaction:
GetTransactionResponse txResp = BitcoinService.GetTransaction("9157e69f449b5c8d443b134a8af75197c5f1baa8cf293db79928b9454e4626e5");
Any ideas on what's causing this?
Is there a way to handle SendToAddress errors like fee too low?
All I get is RpcException:
BitcoinLib.ExceptionHandling.Rpc.RpcException: The RPC request was either not understood by the server or there was a problem executing the request ---> System.Net.WebException: The remote server returned an error: (500) Internal Server Error.
at System.Net.HttpWebRequest.GetResponse()
at System.Net.HttpWebRequest.GetResponse()
at BitcoinLib.RPC.Connector.RpcConnector.GetJsonResponse(HttpWebRequest httpWebRequest)
--- End of inner exception stack trace ---
at BitcoinLib.RPC.Connector.RpcConnector.MakeRpcRequest[T](JsonRpcRequest jsonRpcRequest, Int16 timedOutRequests)
at BitcoinLib.RPC.Connector.RpcConnector.MakeRequest[T](RpcMethods rpcMethod, Object[] parameters)
....
Is there a way to access json response ?
When I call the GetAccount
method with a valid Bitcoin address on the testnet the method returns an empty string. This happens for every address I pass to the method. I need the account to send bitcoins via the SendFrom
method which first parameter is FromAccount
public string SendFrom(
string fromAccount, string toBitcoinAddress, decimal amount, int minConf, string comment, string commentTo)
I know the address is valid because I have transfered bitcoins to it.
If this is not the way to send bitcoins from one address to another could you please tell me which is the correct way to send coins from one address to another. Because I need to send coins from multiple addresses.
How to create transactions that carry messages in OP_RETURN
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.