Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add rpc methods #377

Merged
merged 7 commits into from
Mar 20, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions NBitcoin.Tests/RPCClientTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,49 @@ public void CanSignRawTransaction()
}
}

[Fact]
public void CanRBFTransaction()
{
using(var builder = NodeBuilder.Create())
{
var node = builder.CreateNode();
var rpc = node.CreateRPCClient();
builder.StartAll();
node.CreateRPCClient().Generate(101);

var key = new Key();
var address = key.PubKey.GetAddress(rpc.Network);

var txid = rpc.SendToAddress(address, Money.Coins(2), null, null, false, true);
var txbumpid = rpc.BumpFee(txid);
var blocks = rpc.Generate(1);

var block = rpc.GetBlock(blocks.First());
Assert.False( block.Transactions.Any(x=>x.GetHash() == txid) );
Assert.True( block.Transactions.Any(x=>x.GetHash() == txbumpid.TransactionId) );
}
}


[Fact]
public async Task CanGetBlockchainInfo()
{
using(var builder = NodeBuilder.Create())
{
var rpc = builder.CreateNode().CreateRPCClient();
builder.StartAll();
var response = await rpc.GetBlockchainInfoAsync();

Assert.Equal(Network.RegTest, response.Chain);
Assert.Equal(Network.RegTest.GetGenesis().GetHash(), response.BestBlockHash);
Assert.True(response.Bip9SoftForks.Any(x=>x.Name == "segwit"));
Assert.True(response.Bip9SoftForks.Any(x=>x.Name == "csv"));
Assert.True(response.SoftForks.Any(x=>x.Bip == "bip34"));
Assert.True(response.SoftForks.Any(x=>x.Bip == "bip65"));
Assert.True(response.SoftForks.Any(x=>x.Bip == "bip66"));
}
}

[Fact]
public void CanGetBlockFromRPC()
{
Expand Down Expand Up @@ -215,6 +258,7 @@ public async Task CanGetTxOutFromRPCAsync()
}
}


[Fact]
public void EstimateSmartFee()
{
Expand Down
143 changes: 135 additions & 8 deletions NBitcoin/RPC/RPCClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ network listbanned
network clearbanned

------------------ Block chain and UTXO
blockchain getblockchaininfo
blockchain getblockchaininfo Yes
blockchain getbestblockhash Yes
blockchain getblockcount Yes
blockchain getblock Yes
Expand Down Expand Up @@ -883,6 +883,53 @@ public async Task<AddedNodeInfo> GetAddedNodeInfoAync(bool detailed, EndPoint no

#region Block chain and UTXO

public async Task<BlockchainInfo> GetBlockchainInfoAsync()
{
var response = await SendCommandAsync(RPCOperations.getblockchaininfo).ConfigureAwait(false);
var result = response.Result;

var epochToDtateTimeOffset = new Func<ulong, DateTimeOffset>(epoch=>{
try{
return Utils.UnixTimeToDateTime(epoch);
}catch(OverflowException){
return DateTimeOffset.MaxValue;
}
});

var blockchainInfo = new BlockchainInfo
{
Chain = Network.GetNetwork(result.Value<string>("chain")),
Blocks = result.Value<ulong>("blocks"),
Headers = result.Value<ulong>("headers"),
BestBlockHash = new uint256(result.Value<string>("bestblockhash")), // the block hash
Difficulty = result.Value<ulong>("difficulty"),
MedianTime = result.Value<ulong>("mediantime"),
VerificationProgress = result.Value<float>("verificationprogress"),
InitialBlockDownload = result.Value<bool>("initialblockdownload"),
ChainWork = new uint256(result.Value<string>("chainwork")),
SizeOnDisk = result.Value<ulong>("size_on_disk"),
Pruned = result.Value<bool>("pruned"),
SoftForks = result["softforks"].Select(x=>
new BlockchainInfo.SoftFork {
Bip = (string)(x["id"]),
Version = (int)(x["version"]),
RejectStatus = bool.Parse((string)(x["reject"]["status"]))
}).ToList(),
Bip9SoftForks = result["bip9_softforks"].Select(x=> {
var o = x.First();
return new BlockchainInfo.Bip9SoftFork {
Name = ((JProperty)x).Name,
Status = (string)o["status"],
StartTime = epochToDtateTimeOffset((ulong)o["startTime"]),
Timeout = epochToDtateTimeOffset((ulong)o["timeout"]),
SinceHeight = (ulong)o["since"],
};
}).ToList()
};

return blockchainInfo;
}

public uint256 GetBestBlockHash()
{
return uint256.Parse((string)SendCommand(RPCOperations.getbestblockhash).Result);
Expand Down Expand Up @@ -1150,6 +1197,23 @@ public Task SendRawTransactionAsync(byte[] bytes)
return SendCommandAsync(RPCOperations.sendrawtransaction, Encoders.Hex.EncodeData(bytes));
}

public BumpResponse BumpFee(uint256 txid)
{
return BumpFeeAsync(txid).GetAwaiter().GetResult();
}

public async Task<BumpResponse> BumpFeeAsync(uint256 txid)
{
var response = await SendCommandAsync(RPCOperations.bumpfee, txid.ToString());
var o = response.Result;
return new BumpResponse{
TransactionId = uint256.Parse((string)o["txid"]),
OriginalFee = (ulong)o["origfee"],
Fee = (ulong)o["fee"],
Errors = o["errors"].Select(x=>(string)x).ToList()
};
}

#endregion

#region Utility functions
Expand Down Expand Up @@ -1358,12 +1422,21 @@ public async Task<decimal> EstimatePriorityAsync(int nblock)
/// <param name="amount">The amount to spend</param>
/// <param name="commentTx">A locally-stored (not broadcast) comment assigned to this transaction. Default is no comment</param>
/// <param name="commentDest">A locally-stored (not broadcast) comment assigned to this transaction. Meant to be used for describing who the payment was sent to. Default is no comment</param>
/// <param name="subtractFeeFromAmount">The fee will be deducted from the amount being sent. The recipient will receive less bitcoins than you enter in the amount field. </param>
/// <param name="replaceable">Allow this transaction to be replaced by a transaction with higher fees. </param>
/// <returns>The TXID of the sent transaction</returns>
public uint256 SendToAddress(BitcoinAddress address, Money amount, string commentTx = null, string commentDest = null)
public uint256 SendToAddress(
BitcoinAddress address,
Money amount,
string commentTx = null,
string commentDest = null,
bool subtractFeeFromAmount = false,
bool replaceable = false
)
{
uint256 txid = null;

txid = SendToAddressAsync(address, amount, commentTx, commentDest).GetAwaiter().GetResult();
txid = SendToAddressAsync(address, amount, commentTx, commentDest, subtractFeeFromAmount, replaceable).GetAwaiter().GetResult();
return txid;
}

Expand All @@ -1374,16 +1447,25 @@ public uint256 SendToAddress(BitcoinAddress address, Money amount, string commen
/// <param name="amount">The amount to spend</param>
/// <param name="commentTx">A locally-stored (not broadcast) comment assigned to this transaction. Default is no comment</param>
/// <param name="commentDest">A locally-stored (not broadcast) comment assigned to this transaction. Meant to be used for describing who the payment was sent to. Default is no comment</param>
/// <param name="subtractFeeFromAmount">The fee will be deducted from the amount being sent. The recipient will receive less bitcoins than you enter in the amount field. </param>
/// <param name="replaceable">Allow this transaction to be replaced by a transaction with higher fees. </param>
/// <returns>The TXID of the sent transaction</returns>
public async Task<uint256> SendToAddressAsync(BitcoinAddress address, Money amount, string commentTx = null, string commentDest = null)
public async Task<uint256> SendToAddressAsync(
BitcoinAddress address,
Money amount,
string commentTx = null,
string commentDest = null,
bool subtractFeeFromAmount = false,
bool replaceable = false
)
{
List<object> parameters = new List<object>();
parameters.Add(address.ToString());
parameters.Add(amount.ToString());
if(commentTx != null)
parameters.Add(commentTx);
if(commentDest != null)
parameters.Add(commentDest);
parameters.Add($"{commentTx}");
parameters.Add($"{commentDest}");
parameters.Add(subtractFeeFromAmount);
parameters.Add(replaceable);
var resp = await SendCommandAsync(RPCOperations.sendtoaddress, parameters.ToArray()).ConfigureAwait(false);
return uint256.Parse(resp.Result.ToString());
}
Expand Down Expand Up @@ -1551,8 +1633,53 @@ public bool Connected
get; internal set;
}
}

#endif

public class BlockchainInfo
{
public class SoftFork
{
public string Bip { get; set; }
public int Version { get; set; }
public bool RejectStatus { get; set; }
}

public class Bip9SoftFork
{
public string Name { get; set; }
public string Status { get; set; }
public DateTimeOffset StartTime { get; set; }
public DateTimeOffset Timeout { get; set; }
public ulong SinceHeight { get; set; }

}

public Network Chain { get; set; }
public ulong Blocks { get; set; }
public ulong Headers { get; set; }
public uint256 BestBlockHash { get; set; }
public ulong Difficulty { get; set; }
public ulong MedianTime { get; set; }

public float VerificationProgress { get; set; }
public bool InitialBlockDownload { get; set; }
public uint256 ChainWork { get; set; }
public ulong SizeOnDisk { get; set; }
public bool Pruned { get; set; }

public List<SoftFork> SoftForks { get; set; }
public List<Bip9SoftFork> Bip9SoftForks { get; set; }
}

public class BumpResponse
{
public uint256 TransactionId { get; set; }
public ulong OriginalFee { get; set; }
public ulong Fee { get; set; }
public List<string> Errors { get; set; }
}

public class NoEstimationException : Exception
{
public NoEstimationException(int nblock)
Expand Down
3 changes: 2 additions & 1 deletion NBitcoin/RPC/RPCOperations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ public enum RPCOperations
gettxout,
verifychain,
getchaintips,
invalidateblock
invalidateblock,
bumpfee
}
}