Commit c6f578c0 authored by Pavel Pavlov's avatar Pavel Pavlov

Adding block to chain

- bug fix
parent 64caca76
using System;
using NBitcoin.JsonConverters;
using NBitcoin.OpenAsset;
using Xunit;
namespace NBitcoin.Tests
{
public class JsonConverterTests
{
[Fact]
[Trait("UnitTest", "UnitTest")]
public void CanSerializeInJson()
{
Key k = new Key();
CanSerializeInJsonCore(DateTimeOffset.UtcNow);
CanSerializeInJsonCore(new byte[] { 1, 2, 3 });
CanSerializeInJsonCore(k);
CanSerializeInJsonCore(Money.Coins(5.0m));
CanSerializeInJsonCore(k.PubKey.GetAddress(Network.Main));
CanSerializeInJsonCore(new KeyPath("1/2"));
CanSerializeInJsonCore(Network.Main);
CanSerializeInJsonCore(new uint256(RandomUtils.GetBytes(32)));
CanSerializeInJsonCore(new uint160(RandomUtils.GetBytes(20)));
CanSerializeInJsonCore(new AssetId(k.PubKey));
CanSerializeInJsonCore(k.PubKey.ScriptPubKey);
CanSerializeInJsonCore(new Key().PubKey.WitHash.GetAddress(Network.Main));
CanSerializeInJsonCore(new Key().PubKey.WitHash.ScriptPubKey.GetWitScriptAddress(Network.Main));
var sig = k.Sign(new uint256(RandomUtils.GetBytes(32)));
CanSerializeInJsonCore(sig);
CanSerializeInJsonCore(new TransactionSignature(sig, SigHash.All));
CanSerializeInJsonCore(k.PubKey.Hash);
CanSerializeInJsonCore(k.PubKey.ScriptPubKey.Hash);
CanSerializeInJsonCore(k.PubKey.WitHash);
CanSerializeInJsonCore(k);
CanSerializeInJsonCore(k.PubKey);
CanSerializeInJsonCore(new WitScript(new Script(Op.GetPushOp(sig.ToDER()), Op.GetPushOp(sig.ToDER()))));
CanSerializeInJsonCore(new LockTime(1));
CanSerializeInJsonCore(new LockTime(DateTime.UtcNow));
}
private T CanSerializeInJsonCore<T>(T value)
{
var str = Serializer.ToString(value);
var obj2 = Serializer.ToObject<T>(str);
Assert.Equal(str, Serializer.ToString(obj2));
return obj2;
}
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
#if NOWEBCLIENT
using System;
using System.IO;
using System.Net.Http;
namespace NBitcoin.Tests
{
public class WebClient
{
public void DownloadFile(string url, string file)
{
HttpClient client = new HttpClient();
// The default value is 100,000 milliseconds (100 seconds) and
// that's not long enough to download Bitcoin on slower connections.
client.Timeout = TimeSpan.FromMinutes(5);
var bytes = client.GetByteArrayAsync(url).GetAwaiter().GetResult();
File.WriteAllBytes(file, bytes);
}
}
}
#endif
\ No newline at end of file
namespace NBitcoin.Tests
{
public class alert_tests
{
/*
* TODO: Consider importing to FN.
[Fact]
[Trait("UnitTest", "UnitTest")]
public void CanParseAlertAndChangeUpdatePayloadAndSignature()
{
var alertStr = "73010000003766404f00000000b305434f00000000f2030000f1030000001027000048ee00000064000000004653656520626974636f696e2e6f72672f666562323020696620796f7520686176652074726f75626c6520636f6e6e656374696e67206166746572203230204665627275617279004730450221008389df45f0703f39ec8c1cc42c13810ffcae14995bb648340219e353b63b53eb022009ec65e1c1aaeec1fd334c6b684bde2b3f573060d5b70c3a46723326e4e8a4f1";
AlertPayload alert = new AlertPayload();
alert.FromBytes(TestUtils.ParseHex(alertStr));
Assert.True(alert.CheckSignature(Network.Main));
Assert.Equal("See bitcoin.org/feb20 if you have trouble connecting after 20 February", alert.StatusBar);
alert.StatusBar = "Changing...";
Assert.True(alert.CheckSignature(Network.Main));
alert.UpdatePayload();
Assert.False(alert.CheckSignature(Network.Main));
Key key = new Key();
alert.UpdateSignature(key);
Assert.True(alert.CheckSignature(key.PubKey));
}
[Fact]
[Trait("Core", "Core")]
public void AlertApplies()
{
var alerts = ReadAlerts();
foreach(var alert in alerts)
{
Assert.True(alert.CheckSignature(Network.Main));
Assert.True(!alert.CheckSignature(Network.TestNet));
alert.Now = Utils.UnixTimeToDateTime(11);
}
Assert.True(alerts.Length >= 3);
// Matches:
Assert.True(alerts[0].AppliesTo(1, ""));
Assert.True(alerts[0].AppliesTo(999001, ""));
Assert.True(alerts[0].AppliesTo(1, "/Satoshi:11.11.11/"));
Assert.True(alerts[1].AppliesTo(1, "/Satoshi:0.1.0/"));
Assert.True(alerts[1].AppliesTo(999001, "/Satoshi:0.1.0/"));
Assert.True(alerts[2].AppliesTo(1, "/Satoshi:0.1.0/"));
Assert.True(alerts[2].AppliesTo(1, "/Satoshi:0.2.0/"));
// Don't match:
Assert.True(!alerts[0].AppliesTo(-1, ""));
Assert.True(!alerts[0].AppliesTo(999002, ""));
Assert.True(!alerts[1].AppliesTo(1, ""));
Assert.True(!alerts[1].AppliesTo(1, "Satoshi:0.1.0"));
Assert.True(!alerts[1].AppliesTo(1, "/Satoshi:0.1.0"));
Assert.True(!alerts[1].AppliesTo(1, "Satoshi:0.1.0/"));
Assert.True(!alerts[1].AppliesTo(-1, "/Satoshi:0.1.0/"));
Assert.True(!alerts[1].AppliesTo(999002, "/Satoshi:0.1.0/"));
Assert.True(!alerts[1].AppliesTo(1, "/Satoshi:0.2.0/"));
Assert.True(!alerts[2].AppliesTo(1, "/Satoshi:0.3.0/"));
}
private AlertPayload[] ReadAlerts()
{
List<AlertPayload> alerts = new List<AlertPayload>();
using(var fs = File.OpenRead("data/alertTests.raw"))
{
BitcoinStream stream = new BitcoinStream(fs, false);
while(stream.Inner.Position != stream.Inner.Length)
{
AlertPayload payload = null;
stream.ReadWrite(ref payload);
alerts.Add(payload);
}
}
return alerts.ToArray();
}
*/
}
}
This diff is collapsed.
#if !NOJSONNET
using System;
using System.Reflection;
using NBitcoin.OpenAsset;
using Newtonsoft.Json;
namespace NBitcoin.JsonConverters
{
#if !NOJSONNET
public
#else
internal
#endif
class AssetIdJsonConverter : JsonConverter
{
public AssetIdJsonConverter(Network network)
{
if(network == null)
throw new ArgumentNullException("network");
Network = network;
}
public override bool CanConvert(Type objectType)
{
return typeof(AssetId).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if(reader.TokenType == JsonToken.Null)
return null;
try
{
var value = reader.Value.ToString();
return new BitcoinAssetId(value, Network).AssetId;
}
catch(FormatException)
{
throw new JsonObjectException("Invalid BitcoinAssetId ", reader);
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var assetId = value as AssetId;
if(assetId != null)
{
writer.WriteValue(assetId.ToString(Network));
}
}
public Network Network
{
get;
set;
}
}
}
#endif
\ No newline at end of file
#if !NOJSONNET
using System;
using System.IO;
using System.Reflection;
using NBitcoin.DataEncoders;
using Newtonsoft.Json;
namespace NBitcoin.JsonConverters
{
#if !NOJSONNET
public
#else
internal
#endif
class BitcoinSerializableJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(IBitcoinSerializable).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
try
{
var obj = (IBitcoinSerializable)Activator.CreateInstance(objectType);
var bytes = Encoders.Hex.DecodeData((string)reader.Value);
obj.ReadWrite(bytes);
return obj;
}
catch (EndOfStreamException)
{
}
catch (FormatException)
{
}
throw new JsonObjectException("Invalid bitcoin object of type " + objectType.Name, reader);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var bytes = ((IBitcoinSerializable)value).ToBytes();
writer.WriteValue(Encoders.Hex.EncodeData(bytes));
}
}
}
#endif
\ No newline at end of file
#if !NOJSONNET
using System;
using System.Reflection;
using Newtonsoft.Json;
namespace NBitcoin.JsonConverters
{
#if !NOJSONNET
public
#else
internal
#endif
class BitcoinStringJsonConverter : JsonConverter
{
public BitcoinStringJsonConverter()
{
}
public BitcoinStringJsonConverter(Network network)
{
Network = network;
}
public override bool CanConvert(Type objectType)
{
return
typeof(IBitcoinString).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo()) ||
(typeof(IDestination).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo()) && objectType.GetTypeInfo().AssemblyQualifiedName.Contains("NBitcoin"));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if(reader.TokenType == JsonToken.Null)
return null;
try
{
var result = Network.Parse(reader.Value.ToString(), null);
if(result == null)
{
throw new JsonObjectException("Invalid BitcoinString data", reader);
}
if(Network != null)
{
if(result.Network != Network)
{
result = Network.Parse(reader.Value.ToString());
if(result.Network != Network)
{
throw new JsonObjectException("Invalid BitcoinString network", reader);
}
}
}
if(!objectType.GetTypeInfo().IsAssignableFrom(result.GetType().GetTypeInfo()))
{
throw new JsonObjectException("Invalid BitcoinString type expected " + objectType.Name + ", actual " + result.GetType().Name, reader);
}
return result;
}
catch(FormatException)
{
throw new JsonObjectException("Invalid Base58Check data", reader);
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var base58 = value as IBitcoinString;
if(base58 != null)
{
writer.WriteValue(value.ToString());
}
}
public Network Network
{
get;
set;
}
}
}
#endif
\ No newline at end of file
#if !NOJSONNET
using System;
using System.Reflection;
using NBitcoin.OpenAsset;
using Newtonsoft.Json;
namespace NBitcoin.JsonConverters
{
#if !NOJSONNET
public
#else
internal
#endif
class CoinJsonConverter : JsonConverter
{
public class CoinJson
{
public CoinJson()
{
}
public CoinJson(ICoin coin, Network network)
{
if (network == null)
network = Network.Main;
TransactionId = coin.Outpoint.Hash;
Index = coin.Outpoint.N;
ScriptPubKey = coin.TxOut.ScriptPubKey;
if (coin is ScriptCoin)
{
RedeemScript = ((ScriptCoin)coin).Redeem;
}
if(coin is Coin)
{
Value = ((Coin)coin).Amount;
}
if (coin is ColoredCoin)
{
var cc = (ColoredCoin)coin;
AssetId = cc.AssetId.GetWif(network);
Quantity = cc.Amount.Quantity;
Value = cc.Bearer.Amount;
var scc = cc.Bearer as ScriptCoin;
if (scc != null)
{
RedeemScript = scc.Redeem;
}
}
}
public ICoin ToCoin()
{
var coin = RedeemScript == null ? new Coin(new OutPoint(TransactionId, Index), new TxOut(Value, ScriptPubKey)) : new ScriptCoin(new OutPoint(TransactionId, Index), new TxOut(Value, ScriptPubKey), RedeemScript);
if (AssetId != null)
return coin.ToColoredCoin(new AssetMoney(AssetId, Quantity));
return coin;
}
public uint256 TransactionId
{
get;
set;
}
public uint Index
{
get;
set;
}
public Money Value
{
get;
set;
}
public Script ScriptPubKey
{
get;
set;
}
public Script RedeemScript
{
get;
set;
}
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public BitcoinAssetId AssetId
{
get;
set;
}
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public long Quantity
{
get;
set;
}
}
public CoinJsonConverter(Network network)
{
Network = network;
}
public Network Network
{
get;
set;
}
public override bool CanConvert(Type objectType)
{
return typeof(ICoin).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return reader.TokenType == JsonToken.Null ? null : serializer.Deserialize<CoinJson>(reader).ToCoin();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, new CoinJson((ICoin)value, Network));
}
}
}
#endif
\ No newline at end of file
#if !NOJSONNET
using System;
using System.Reflection;
using Newtonsoft.Json;
namespace NBitcoin.JsonConverters
{
#if !NOJSONNET
public
#else
internal
#endif
class DateTimeToUnixTimeConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(DateTime).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo()) ||
typeof(DateTimeOffset).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo()) ||
typeof(DateTimeOffset?).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.Value == null)
return null;
var result = Utils.UnixTimeToDateTime((ulong)(long)reader.Value);
if (objectType == typeof(DateTime))
return result.UtcDateTime;
return result;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
DateTime time;
if (value is DateTime)
time = (DateTime)value;
else
time = ((DateTimeOffset)value).UtcDateTime;
if (time < Utils.UnixTimeToDateTime(0))
time = Utils.UnixTimeToDateTime(0).UtcDateTime;
writer.WriteValue(Utils.DateTimeToUnixTime(time));
}
}
}
#endif
\ No newline at end of file
#if !NOJSONNET
using System;
using NBitcoin.DataEncoders;
using Newtonsoft.Json;
namespace NBitcoin.JsonConverters
{
#if !NOJSONNET
public
#else
internal
#endif
class HexJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(byte[]);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
try
{
return reader.TokenType == JsonToken.Null ? null : Encoders.Hex.DecodeData((string)reader.Value);
}
catch
{
throw new JsonObjectException("Invalid hex", reader);
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if(value != null)
{
writer.WriteValue(Encoders.Hex.EncodeData((byte[])value));
}
}
}
}
#endif
\ No newline at end of file
#if !NOJSONNET
using System;
using Newtonsoft.Json;
namespace NBitcoin.JsonConverters
{
#if !NOJSONNET
public
#else
internal
#endif
class JsonObjectException : Exception
{
public JsonObjectException(Exception inner, JsonReader reader)
: base(inner.Message, inner)
{
Path = reader.Path;
}
public JsonObjectException(string message, JsonReader reader)
: base(message)
{
Path = reader.Path;
}
public string Path
{
get;
private set;
}
}
}
#endif
\ No newline at end of file
#if !NOJSONNET
using System;
using System.IO;
using NBitcoin.DataEncoders;
using Newtonsoft.Json;
namespace NBitcoin.JsonConverters
{
#if !NOJSONNET
public
#else
internal
#endif
class KeyJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(Key) == objectType || typeof(PubKey) == objectType;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if(reader.TokenType == JsonToken.Null)
return null;
try
{
var bytes = Encoders.Hex.DecodeData((string)reader.Value);
if(objectType == typeof(Key))
return new Key(bytes);
else
return new PubKey(bytes);
}
catch(EndOfStreamException)
{
}
catch(FormatException)
{
}
throw new JsonObjectException("Invalid bitcoin object of type " + objectType.Name, reader);
}
private static void InverseIfNeeded(Type type, byte[] bytes)
{
var inverse = type == typeof(uint256) || type == typeof(uint160);
if(inverse)
Array.Reverse(bytes);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if(value != null)
{
var bytes = ((IBitcoinSerializable)value).ToBytes();
writer.WriteValue(Encoders.Hex.EncodeData(bytes));
}
}
}
}
#endif
\ No newline at end of file
#if !NOJSONNET
using System;
using System.Reflection;
using Newtonsoft.Json;
namespace NBitcoin.JsonConverters
{
#if !NOJSONNET
public
#else
internal
#endif
class KeyPathJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(KeyPath).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
try
{
return reader.TokenType == JsonToken.Null ? null : KeyPath.Parse(reader.Value.ToString());
}
catch (FormatException)
{
throw new JsonObjectException("Invalid key path", reader);
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var keyPath = value as KeyPath;
if (keyPath != null)
writer.WriteValue(keyPath.ToString());
}
}
}
#endif
\ No newline at end of file
#if !NOJSONNET
using System;
using Newtonsoft.Json;
namespace NBitcoin.JsonConverters
{
public class LockTimeJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(LockTime);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
try
{
return reader.TokenType == JsonToken.Null ? LockTime.Zero : new LockTime((uint)reader.Value);
}
catch
{
throw new JsonObjectException("Invalid locktime", reader);
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if(value != null)
{
writer.WriteValue(((LockTime)value).Value);
}
}
}
}
#endif
\ No newline at end of file
#if !NOJSONNET
using System;
using System.Reflection;
using Newtonsoft.Json;
namespace NBitcoin.JsonConverters
{
#if !NOJSONNET
public
#else
internal
#endif
class MoneyJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(Money).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
try
{
return reader.TokenType == JsonToken.Null ? null : new Money((long)reader.Value);
}
catch (InvalidCastException)
{
throw new JsonObjectException("Money amount should be in satoshi", reader);
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((Money)value).Satoshi);
}
}
}
#endif
\ No newline at end of file
#if !NOJSONNET
using System;
using System.Reflection;
using Newtonsoft.Json;
namespace NBitcoin.JsonConverters
{
#if !NOJSONNET
public
#else
internal
#endif
class NetworkJsonConverter : JsonConverter
{
/// <inheritdoc />
public override bool CanConvert(Type objectType)
{
return typeof(Network).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
}
/// <inheritdoc />
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
string network = (string)reader.Value;
if (network == null)
return null;
if (network.Equals("MainNet", StringComparison.OrdinalIgnoreCase) || network.Equals("main", StringComparison.OrdinalIgnoreCase))
return Network.Main;
if (network.Equals("TestNet", StringComparison.OrdinalIgnoreCase) || network.Equals("test", StringComparison.OrdinalIgnoreCase))
return Network.TestNet;
if (network.Equals("RegTest", StringComparison.OrdinalIgnoreCase) || network.Equals("reg", StringComparison.OrdinalIgnoreCase))
return Network.RegTest;
Network net = NetworksContainer.GetNetwork(network);
if (net != null)
return net;
throw new JsonObjectException("Unknown network (valid values : main, test, reg)", reader);
}
/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var network = (Network)value;
string str = null;
if (network == Network.Main)
str = "MainNet";
else if (network == Network.TestNet)
str = "TestNet";
else if (network == Network.RegTest)
str = "RegTest";
else if (network != null)
str = network.ToString();
if (str != null)
writer.WriteValue(str);
}
}
}
#endif
\ No newline at end of file
#if !NOJSONNET
using System;
using System.Reflection;
using NBitcoin.DataEncoders;
using Newtonsoft.Json;
namespace NBitcoin.JsonConverters
{
#if !NOJSONNET
public
#else
internal
#endif
class ScriptJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(Script).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo()) || typeof(WitScript).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if(reader.TokenType == JsonToken.Null)
return null;
try
{
if(objectType == typeof(Script))
return Script.FromBytesUnsafe(Encoders.Hex.DecodeData((string)reader.Value));
if(objectType == typeof(WitScript))
return new WitScript((string)reader.Value);
}
catch(FormatException)
{
}
throw new JsonObjectException("A script should be a byte string", reader);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if(value != null)
{
if(value is Script)
writer.WriteValue(Encoders.Hex.EncodeData(((Script)value).ToBytes(false)));
if(value is WitScript)
writer.WriteValue(((WitScript)value).ToString());
}
}
}
}
#endif
\ No newline at end of file
#if !NOJSONNET
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace NBitcoin.JsonConverters
{
public class Serializer
{
#if !NOJSONNET
public
#else
internal
#endif
static void RegisterFrontConverters(JsonSerializerSettings settings, Network network = null)
{
settings.Converters.Add(new MoneyJsonConverter());
settings.Converters.Add(new KeyJsonConverter());
settings.Converters.Add(new CoinJsonConverter(network));
settings.Converters.Add(new ScriptJsonConverter());
settings.Converters.Add(new UInt160JsonConverter());
settings.Converters.Add(new UInt256JsonConverter());
settings.Converters.Add(new BitcoinSerializableJsonConverter());
settings.Converters.Add(new NetworkJsonConverter());
settings.Converters.Add(new KeyPathJsonConverter());
settings.Converters.Add(new SignatureJsonConverter());
settings.Converters.Add(new HexJsonConverter());
settings.Converters.Add(new DateTimeToUnixTimeConverter());
settings.Converters.Add(new TxDestinationJsonConverter());
settings.Converters.Add(new LockTimeJsonConverter());
settings.Converters.Add(new BitcoinStringJsonConverter()
{
Network = network
});
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
public static T ToObject<T>(string data)
{
return ToObject<T>(data, null);
}
public static T ToObject<T>(string data, Network network)
{
JsonSerializerSettings settings = new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
RegisterFrontConverters(settings, network);
return JsonConvert.DeserializeObject<T>(data, settings);
}
public static string ToString<T>(T response, Network network)
{
JsonSerializerSettings settings = new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
RegisterFrontConverters(settings, network);
return JsonConvert.SerializeObject(response, settings);
}
public static string ToString<T>(T response)
{
return ToString<T>(response, null);
}
}
}
#endif
\ No newline at end of file
#if !NOJSONNET
using System;
using NBitcoin.Crypto;
using NBitcoin.DataEncoders;
using Newtonsoft.Json;
namespace NBitcoin.JsonConverters
{
#if !NOJSONNET
public
#else
internal
#endif
class SignatureJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(ECDSASignature) || objectType == typeof(TransactionSignature);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if(reader.TokenType == JsonToken.Null)
return null;
try
{
if(objectType == typeof(ECDSASignature))
return new ECDSASignature(Encoders.Hex.DecodeData((string)reader.Value));
if(objectType == typeof(TransactionSignature))
return new TransactionSignature(Encoders.Hex.DecodeData((string)reader.Value));
}
catch
{
}
throw new JsonObjectException("Invalid signature", reader);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if(value != null)
{
if(value is ECDSASignature)
writer.WriteValue(Encoders.Hex.EncodeData(((ECDSASignature)value).ToDER()));
if(value is TransactionSignature)
writer.WriteValue(Encoders.Hex.EncodeData(((TransactionSignature)value).ToBytes()));
}
}
}
}
#endif
\ No newline at end of file
#if !NOJSONNET
using System;
using NBitcoin.DataEncoders;
using Newtonsoft.Json;
namespace NBitcoin.JsonConverters
{
#if !NOJSONNET
public
#else
internal
#endif
class TxDestinationJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(KeyId) ||
objectType == typeof(ScriptId) ||
objectType == typeof(WitKeyId) ||
objectType == typeof(WitScriptId);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if(reader.TokenType == JsonToken.Null)
return null;
try
{
if(objectType == typeof(KeyId))
return new KeyId(Encoders.Hex.DecodeData((string)reader.Value));
if(objectType == typeof(ScriptId))
return new ScriptId(Encoders.Hex.DecodeData((string)reader.Value));
if(objectType == typeof(WitKeyId))
return new WitKeyId(Encoders.Hex.DecodeData((string)reader.Value));
if(objectType == typeof(WitScriptId))
return new WitScriptId(Encoders.Hex.DecodeData((string)reader.Value));
}
catch
{
}
throw new JsonObjectException("Invalid signature", reader);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if(value != null)
{
if(value is KeyId)
writer.WriteValue(Encoders.Hex.EncodeData(((KeyId)value).ToBytes()));
if(value is ScriptId)
writer.WriteValue(Encoders.Hex.EncodeData(((ScriptId)value).ToBytes()));
if(value is WitKeyId)
writer.WriteValue(Encoders.Hex.EncodeData(((WitKeyId)value).ToBytes()));
if(value is WitScriptId)
writer.WriteValue(Encoders.Hex.EncodeData(((WitScriptId)value).ToBytes()));
}
}
}
}
#endif
\ No newline at end of file
#if !NOJSONNET
using System;
using System.IO;
using Newtonsoft.Json;
namespace NBitcoin.JsonConverters
{
#if !NOJSONNET
public
#else
internal
#endif
class UInt160JsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(uint160) == objectType;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if(reader.TokenType == JsonToken.Null)
return null;
try
{
return uint160.Parse((string)reader.Value);
}
catch(EndOfStreamException)
{
}
catch(FormatException)
{
}
throw new JsonObjectException("Invalid bitcoin object of type " + objectType.Name, reader);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString());
}
}
#if !NOJSONNET
public
#else
internal
#endif
class UInt256JsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(uint256) == objectType;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if(reader.TokenType == JsonToken.Null)
return null;
try
{
return uint256.Parse((string)reader.Value);
}
catch(EndOfStreamException)
{
}
catch(FormatException)
{
}
throw new JsonObjectException("Invalid bitcoin object of type " + objectType.Name, reader);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString());
}
}
}
#endif
\ No newline at end of file
using System;
using System.IO;
using System.Text;
namespace NBitcoin.Protobuf
{
internal class ProtobufReaderWriter
{
internal const int PROTOBUF_VARINT = 0; // int32, int64, uint32, uint64, sint32, sint64, bool, enum
internal const int PROTOBUF_64BIT = 1; // fixed64, sfixed64, double
internal const int PROTOBUF_LENDELIM = 2; // string, bytes, embedded messages, packed repeated fields
internal const int PROTOBUF_32BIT = 5; // fixed32, sfixed32, float
Stream _Inner;
public Stream Inner
{
get
{
return _Inner;
}
}
public ProtobufReaderWriter(Stream stream)
{
_Inner = stream;
}
public ulong ReadULong()
{
ulong v = 0;
TryReadULong(out v);
return v;
}
public bool TryReadULong(out ulong value)
{
value = 0;
ulong varInt = 0;
byte b = 0x80;
int i = 0;
while((b & 0x80) != 0)
{
var v = _Inner.ReadByte();
if(v < 0)
return false;
b = (byte)v;
Position++;
varInt += (ulong)(b & 0x7f) << 7 * i++;
}
value = ((b & 0x80) != 0) ? 0 : varInt;
return true;
}
public void WriteULong(ulong value)
{
byte[] ioBuffer = new byte[10];
int ioIndex = 0;
int count = 0;
do
{
ioBuffer[ioIndex++] = (byte)((value & 0x7F) | 0x80);
count++;
} while((value >>= 7) != 0);
ioBuffer[ioIndex - 1] &= 0x7F;
_Inner.Write(ioBuffer, 0, ioIndex);
Position += ioIndex;
}
Encoding Encoding = Encoding.UTF8;
public void WriteKey(int key, int type)
{
ulong v = (ulong)((key << 3) | type);
WriteULong(v);
}
public bool TryReadKey(out int key)
{
key = 0;
ulong lkey;
if(!TryReadULong(out lkey))
return false;
key = (int)lkey;
int dataType = (int)(key & 0x07);
key = (int)(key >> 3);
return true;
}
public string ReadString()
{
var len = ReadULong();
AssertBounds(len);
byte[] ioBuffer = new byte[(int)len];
_Inner.Read(ioBuffer, 0, ioBuffer.Length);
Position += ioBuffer.Length;
return Encoding.GetString(ioBuffer, 0, ioBuffer.Length);
}
public void WriteString(string value)
{
var predicted = Encoding.GetByteCount(value);
WriteULong((ulong)predicted);
AssertBounds((ulong)predicted);
byte[] ioBuffer = new byte[predicted];
Encoding.GetBytes(value, 0, predicted, ioBuffer, 0);
_Inner.Write(ioBuffer, 0, predicted);
Position += predicted;
}
public byte[] ReadBytes()
{
var len = ReadULong();
AssertBounds(len);
byte[] ioBuffer = new byte[(int)len];
_Inner.Read(ioBuffer, 0, ioBuffer.Length);
Position += ioBuffer.Length;
return ioBuffer;
}
private void AssertBounds(ulong len)
{
if((int)len > MaxLength)
throw new ArgumentOutOfRangeException("The deserialized message is too big");
}
public void WriteBytes(byte[] value)
{
WriteULong((ulong)value.Length);
_Inner.Write(value, 0, value.Length);
Position += value.Length;
}
int _Position;
public int Position
{
get
{
return _Position;
}
private set
{
_Position = value;
if(Position > MaxLength)
throw new ArgumentOutOfRangeException("The deserialized message is too big");
}
}
const int MaxLength = 60000;
}
}
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
namespace NBitcoin.RPC
{
public class AddedNodeInfo
{
public EndPoint AddedNode { get; internal set; }
public bool Connected { get; internal set; }
public IEnumerable<NodeAddressInfo> Addresses { get; internal set; }
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace NBitcoin.RPC
{
public class AddressGrouping
{
public AddressGrouping()
{
this.ChangeAddresses = new List<ChangeAddress>();
}
public BitcoinAddress PublicAddress { get; set; }
public Money Amount { get; set; }
public string Account { get; set; }
public List<ChangeAddress> ChangeAddresses { get; set; }
}
}
#if !NOJSONNET
using NBitcoin.DataEncoders;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace NBitcoin.RPC
{
internal class BlockExplorerFormatter : RawFormatter
{
internal BlockExplorerFormatter(Network network) : base(network)
{
}
protected override void BuildTransaction(JObject json, Transaction tx)
{
tx.Version = (uint)json.GetValue("ver");
tx.LockTime = (uint)json.GetValue("lock_time");
var vin = (JArray)json.GetValue("in");
int vinCount = (int)json.GetValue("vin_sz");
for (int i = 0; i < vinCount; i++)
{
var jsonIn = (JObject)vin[i];
var txin = new TxIn();
tx.Inputs.Add(txin);
var prevout = (JObject)jsonIn.GetValue("prev_out");
txin.PrevOut.Hash = uint256.Parse((string)prevout.GetValue("hash"));
txin.PrevOut.N = (uint)prevout.GetValue("n");
string script = (string)jsonIn.GetValue("scriptSig");
if (script != null)
{
txin.ScriptSig = new Script(script);
}
else
{
string coinbase = (string)jsonIn.GetValue("coinbase");
txin.ScriptSig = new Script(Encoders.Hex.DecodeData(coinbase));
}
JToken seq = jsonIn.GetValue("sequence");
if (seq != null)
{
txin.Sequence = (uint)seq;
}
}
var vout = (JArray)json.GetValue("out");
int voutCount = (int)json.GetValue("vout_sz");
for (int i = 0; i < voutCount; i++)
{
var jsonOut = (JObject)vout[i];
var txout = new TxOut();
tx.Outputs.Add(txout);
txout.Value = Money.Parse((string)jsonOut.GetValue("value"));
txout.ScriptPubKey = new Script((string)jsonOut.GetValue("scriptPubKey"));
}
}
protected override void WriteTransaction(JsonTextWriter writer, Transaction tx)
{
WritePropertyValue(writer, "hash", tx.GetHash().ToString());
WritePropertyValue(writer, "ver", tx.Version);
WritePropertyValue(writer, "vin_sz", tx.Inputs.Count);
WritePropertyValue(writer, "vout_sz", tx.Outputs.Count);
WritePropertyValue(writer, "lock_time", tx.LockTime.Value);
WritePropertyValue(writer, "size", tx.GetSerializedSize());
writer.WritePropertyName("in");
writer.WriteStartArray();
foreach (IndexedTxIn input in tx.Inputs.AsIndexedInputs())
{
TxIn txin = input.TxIn;
writer.WriteStartObject();
writer.WritePropertyName("prev_out");
writer.WriteStartObject();
WritePropertyValue(writer, "hash", txin.PrevOut.Hash.ToString());
WritePropertyValue(writer, "n", txin.PrevOut.N);
writer.WriteEndObject();
if (txin.PrevOut.Hash == uint256.Zero)
{
WritePropertyValue(writer, "coinbase", Encoders.Hex.EncodeData(txin.ScriptSig.ToBytes()));
}
else
{
WritePropertyValue(writer, "scriptSig", txin.ScriptSig.ToString());
}
if (input.WitScript != WitScript.Empty)
{
WritePropertyValue(writer, "witness", input.WitScript.ToString());
}
if (txin.Sequence != uint.MaxValue)
{
WritePropertyValue(writer, "sequence", (uint)txin.Sequence);
}
writer.WriteEndObject();
}
writer.WriteEndArray();
writer.WritePropertyName("out");
writer.WriteStartArray();
foreach (TxOut txout in tx.Outputs)
{
writer.WriteStartObject();
WritePropertyValue(writer, "value", txout.Value.ToString(false, false));
WritePropertyValue(writer, "scriptPubKey", txout.ScriptPubKey.ToString());
writer.WriteEndObject();
}
writer.WriteEndArray();
}
}
}
#endif
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Text;
namespace NBitcoin.RPC
{
public class ChangeAddress
{
public Money Amount { get; set; }
public BitcoinAddress Address { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace NBitcoin.RPC.Exceptions
{
public class NoEstimationException : Exception
{
public NoEstimationException(int nblock)
: base("The FeeRate couldn't be estimated because of insufficient data from Bitcoin Core. Try to use smaller nBlock, or wait Bitcoin Core to gather more data.")
{
}
}
}
namespace NBitcoin.RPC
{
public class FundRawTransactionOptions
{
public BitcoinAddress ChangeAddress
{
get; set;
}
public int? ChangePosition
{
get; set;
}
public bool IncludeWatching
{
get; set;
}
public bool LockUnspents
{
get; set;
}
public bool? ReserveChangeKey
{
get; set;
}
public FeeRate FeeRate
{
get; set;
}
public int[] SubtractFeeFromOutputs
{
get; set;
}
}
}
namespace NBitcoin.RPC
{
public class FundRawTransactionResponse
{
public Transaction Transaction
{
get; set;
}
public Money Fee
{
get; set;
}
public int ChangePos
{
get; set;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace NBitcoin.RPC
{
/// <summary>
/// Interface for an RPC client.
/// </summary>
/// <remarks>Extend where necessary.</remarks>
/// <see cref="https://en.bitcoin.it/wiki/Original_Bitcoin_client/API_calls_list"/>
public interface IRPCClient
{
/// <summary>Send a command over RPC.</summary>
/// <param name="commandName">The command to execute.</param>
/// <param name="parameters">An array of command parameters.</param>
/// <returns>The RPC response.</returns>
RPCResponse SendCommand(RPCOperations commandName, params object[] parameters);
/// <summary>Send a command over RPC.</summary>
/// <param name="request">The rpc request to execute.</param>
/// <param name="throwIfRPCError">A value indicating whether an exception should be thrown when there is an RPC error.</param>
/// <returns>The RPC response.</returns>
RPCResponse SendCommand(RPCRequest request, bool throwIfRPCError = true);
/// <summary>Send a command over RPC.</summary>
/// <param name="commandName">The command to execute.</param>
/// <param name="parameters">An array of command parameters.</param>
/// <returns>The RPC response.</returns>
RPCResponse SendCommand(string commandName, params object[] parameters);
/// <summary>Send a command over RPC.</summary>
/// <param name="commandName">The command to execute.</param>
/// <param name="parameters">An array of command parameters.</param>
/// <returns>The RPC response.</returns>
Task<RPCResponse> SendCommandAsync(RPCOperations commandName, params object[] parameters);
/// <summary>Send a command over RPC.</summary>
/// <param name="request">The rpc request to execute.</param>
/// <param name="throwIfRPCError">A value indicating whether an exception should be thrown when there is an RPC error.</param>
/// <returns>The RPC response.</returns>
Task<RPCResponse> SendCommandAsync(RPCRequest request, bool throwIfRPCError = true);
/// <summary>Send a command over RPC.</summary>
/// <param name="commandName">The command to execute.</param>
/// <param name="parameters">An array of command parameters.</param>
/// <returns>The RPC response.</returns>
Task<RPCResponse> SendCommandAsync(string commandName, params object[] parameters);
}
}
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
namespace NBitcoin.RPC
{
public class NodeAddressInfo
{
public IPEndPoint Address { get; internal set; }
public bool Connected { get; internal set; }
}
}
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
namespace NBitcoin.RPC
{
public class PeerInfo
{
public int Id { get; internal set; }
public IPEndPoint Address { get; internal set; }
public IPEndPoint LocalAddress { get; internal set; }
public ulong Services { get; internal set; }
public DateTimeOffset LastSend { get; internal set; }
public DateTimeOffset LastReceive { get; internal set; }
public long BytesSent { get; internal set; }
public long BytesReceived { get; internal set; }
public DateTimeOffset ConnectionTime { get; internal set; }
public TimeSpan? PingTime { get; internal set; }
public int Version { get; internal set; }
public string SubVersion { get; internal set; }
public bool Inbound { get; internal set; }
public int StartingHeight { get; internal set; }
public int BanScore { get; internal set; }
public int SynchronizedHeaders { get; internal set; }
public int SynchronizedBlocks { get; internal set; }
public uint[] Inflight { get; internal set; }
public bool IsWhiteListed { get; internal set; }
public TimeSpan PingWait { get; internal set; }
public int Blocks { get; internal set; }
public TimeSpan TimeOffset { get; internal set; }
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace NBitcoin.RPC
{
public class RPCAccount
{
public Money Amount { get; set; }
public string AccountName { get; set; }
}
}
This diff is collapsed.
This diff is collapsed.
using System;
using System.Linq;
using System.Net;
namespace NBitcoin.RPC
{
public class RPCCredentialString
{
public static RPCCredentialString Parse(string str)
{
RPCCredentialString r;
if(!TryParse(str, out r))
throw new FormatException("Invalid RPC Credential string");
return r;
}
public static bool TryParse(string str, out RPCCredentialString connectionString)
{
if(str == null)
throw new ArgumentNullException(nameof(str));
str = str.Trim();
if(str.Equals("default", StringComparison.OrdinalIgnoreCase) || string.IsNullOrEmpty(str))
{
connectionString = new RPCCredentialString();
return true;
}
if(str.StartsWith("cookiefile=", StringComparison.OrdinalIgnoreCase))
{
var path = str.Substring("cookiefile=".Length);
connectionString = new RPCCredentialString();
connectionString.CookieFile = path;
return true;
}
if(str.IndexOf(':') != -1)
{
var parts = str.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
if(parts.Length >= 2)
{
parts[1] = string.Join(":", parts.Skip(1).ToArray());
connectionString = new RPCCredentialString();
connectionString.UserPassword = new NetworkCredential(parts[0], parts[1]);
return true;
}
}
connectionString = null;
return false;
}
/// <summary>
/// Use default connection settings of the chain
/// </summary>
public bool UseDefault
{
get
{
return CookieFile == null && UserPassword == null;
}
}
/// <summary>
/// Path to cookie file
/// </summary>
public string CookieFile
{
get
{
return _CookieFile;
}
set
{
if(value != null)
Reset();
_CookieFile = value;
}
}
private void Reset()
{
_CookieFile = null;
_UsernamePassword = null;
}
string _CookieFile;
/// <summary>
/// Username and password
/// </summary>
public NetworkCredential UserPassword
{
get
{
return _UsernamePassword;
}
set
{
if(value != null)
Reset();
_UsernamePassword = value;
}
}
NetworkCredential _UsernamePassword;
public override string ToString()
{
return UseDefault ? "default" :
CookieFile != null ? ("cookiefile=" + CookieFile) :
UserPassword != null ? $"{UserPassword.UserName}:{UserPassword.Password}" :
"default";
}
}
}
#if !NOJSONNET
using System;
namespace NBitcoin.RPC
{
public enum RPCErrorCode
{
// Standard JSON-RPC 2.0 errors
RPC_INVALID_REQUEST = -32600,
RPC_METHOD_NOT_FOUND = -32601,
RPC_INVALID_PARAMS = -32602,
RPC_INTERNAL_ERROR = -32603,
RPC_PARSE_ERROR = -32700,
// General application defined errors
RPC_MISC_ERROR = -1, // std::exception thrown in command handling
RPC_FORBIDDEN_BY_SAFE_MODE = -2, // Server is in safe mode, and command is not allowed in safe mode
RPC_TYPE_ERROR = -3, // Unexpected type was passed as parameter
RPC_INVALID_ADDRESS_OR_KEY = -5, // Invalid address or key
RPC_OUT_OF_MEMORY = -7, // Ran out of memory during operation
RPC_INVALID_PARAMETER = -8, // Invalid, missing or duplicate parameter
RPC_DATABASE_ERROR = -20, // Database error
RPC_DESERIALIZATION_ERROR = -22, // Error parsing or validating structure in raw format
RPC_TRANSACTION_ERROR = -25, // General error during transaction submission
RPC_TRANSACTION_REJECTED = -26, // Transaction was rejected by network rules
RPC_TRANSACTION_ALREADY_IN_CHAIN = -27, // Transaction already in chain
// P2P client errors
RPC_CLIENT_NOT_CONNECTED = -9, // Bitcoin is not connected
RPC_CLIENT_IN_INITIAL_DOWNLOAD = -10, // Still downloading initial blocks
RPC_CLIENT_NODE_ALREADY_ADDED = -23, // Node is already added
RPC_CLIENT_NODE_NOT_ADDED = -24, // Node has not been added before
// Wallet errors
RPC_WALLET_ERROR = -4, // Unspecified problem with wallet (key not found etc.)
RPC_WALLET_INSUFFICIENT_FUNDS = -6, // Not enough funds in wallet or account
RPC_WALLET_INVALID_ACCOUNT_NAME = -11, // Invalid account name
RPC_WALLET_KEYPOOL_RAN_OUT = -12, // Keypool ran out, call keypoolrefill first
RPC_WALLET_UNLOCK_NEEDED = -13, // Enter the wallet passphrase with walletpassphrase first
RPC_WALLET_PASSPHRASE_INCORRECT = -14, // The wallet passphrase entered was incorrect
RPC_WALLET_WRONG_ENC_STATE = -15, // Command given in wrong wallet encryption state (encrypting an encrypted wallet etc.)
RPC_WALLET_ENCRYPTION_FAILED = -16, // Failed to encrypt the wallet
RPC_WALLET_ALREADY_UNLOCKED = -17, // Wallet is already unlocked
}
public class RPCException : Exception
{
public RPCException(RPCErrorCode code, string message, RPCResponse result)
: base(String.IsNullOrEmpty(message) ? FindMessage(code) : message)
{
_RPCCode = code;
_RPCCodeMessage = FindMessage(code);
_RPCResult = result;
}
private readonly RPCResponse _RPCResult;
public RPCResponse RPCResult
{
get
{
return _RPCResult;
}
}
private static string FindMessage(RPCErrorCode code)
{
switch(code)
{
case RPCErrorCode.RPC_MISC_ERROR:
return "std::exception thrown in command handling";
case RPCErrorCode.RPC_FORBIDDEN_BY_SAFE_MODE:
return "Server is in safe mode, and command is not allowed in safe mode";
case RPCErrorCode.RPC_TYPE_ERROR:
return "Unexpected type was passed as parameter";
case RPCErrorCode.RPC_INVALID_ADDRESS_OR_KEY:
return "Invalid address or key";
case RPCErrorCode.RPC_OUT_OF_MEMORY:
return "Ran out of memory during operation";
case RPCErrorCode.RPC_INVALID_PARAMETER:
return "Invalid, missing or duplicate parameter";
case RPCErrorCode.RPC_DATABASE_ERROR:
return "Database error";
case RPCErrorCode.RPC_DESERIALIZATION_ERROR:
return "Error parsing or validating structure in raw format";
case RPCErrorCode.RPC_TRANSACTION_ERROR:
return "General error during transaction submission";
case RPCErrorCode.RPC_TRANSACTION_REJECTED:
return "Transaction was rejected by network rules";
case RPCErrorCode.RPC_TRANSACTION_ALREADY_IN_CHAIN:
return "Transaction already in chain";
default:
return code.ToString();
}
}
private readonly RPCErrorCode _RPCCode;
public RPCErrorCode RPCCode
{
get
{
return _RPCCode;
}
}
private readonly string _RPCCodeMessage;
public string RPCCodeMessage
{
get
{
return _RPCCodeMessage;
}
}
}
}
#endif
\ No newline at end of file
namespace NBitcoin.RPC
{
//from rpcserver.h
public enum RPCOperations
{
getconnectioncount,
getpeerinfo,
ping,
addnode,
getaddednodeinfo,
getnettotals,
dumpprivkey,
importprivkey,
importaddress,
dumpwallet,
importwallet,
getgenerate,
setgenerate,
generate,
getnetworkhashps,
gethashespersec,
getmininginfo,
prioritisetransaction,
getwork,
getblocktemplate,
submitblock,
estimatefee,
getnewaddress,
getaccountaddress,
getrawchangeaddress,
setaccount,
getaccount,
getaddressesbyaccount,
sendtoaddress,
signmessage,
verifymessage,
getreceivedbyaddress,
getreceivedbyaccount,
getbalance,
getunconfirmedbalance,
movecmd,
sendfrom,
sendmany,
addmultisigaddress,
createmultisig,
listreceivedbyaddress,
listreceivedbyaccount,
listtransactions,
listaddressgroupings,
listaccounts,
listsinceblock,
gettransaction,
backupwallet,
keypoolrefill,
walletpassphrase,
walletpassphrasechange,
walletlock,
encryptwallet,
validateaddress,
getinfo,
getwalletinfo,
getblockchaininfo,
getnetworkinfo,
getrawtransaction,
listunspent,
lockunspent,
listlockunspent,
createrawtransaction,
decoderawtransaction,
decodescript,
signrawtransaction,
sendrawtransaction,
gettxoutproof,
verifytxoutproof,
getblockcount,
getbestblockhash,
getdifficulty,
settxfee,
getmempoolinfo,
getrawmempool,
getblockhash,
getblock,
gettxoutsetinfo,
gettxout,
verifychain,
getchaintips
}
}
#if !NOJSONNET
using System;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace NBitcoin.RPC
{
public class RPCRequest
{
public RPCRequest(RPCOperations method, object[] parameters)
: this(method.ToString(), parameters)
{
}
public RPCRequest(string method, object[] parameters)
: this()
{
Method = method;
Params = parameters;
}
public RPCRequest()
{
JsonRpc = "1.0";
Id = 1;
}
public string JsonRpc
{
get;
set;
}
public int Id
{
get;
set;
}
public string Method
{
get;
set;
}
public object[] Params
{
get;
set;
}
public void WriteJSON(TextWriter writer)
{
var jsonWriter = new JsonTextWriter(writer);
WriteJSON(jsonWriter);
jsonWriter.Flush();
}
internal void WriteJSON(JsonTextWriter writer)
{
writer.WriteStartObject();
WriteProperty(writer, "jsonrpc", JsonRpc);
WriteProperty(writer, "id", Id);
WriteProperty(writer, "method", Method);
writer.WritePropertyName("params");
writer.WriteStartArray();
if(Params != null)
{
for(int i = 0; i < Params.Length; i++)
{
if(Params[i] is JToken)
{
((JToken)Params[i]).WriteTo(writer);
}
else if(Params[i] is Array)
{
writer.WriteStartArray();
foreach(var x in (Array)Params[i])
{
writer.WriteValue(x);
}
writer.WriteEndArray();
}
else
{
writer.WriteValue(Params[i]);
}
}
}
writer.WriteEndArray();
writer.WriteEndObject();
}
private void WriteProperty<TValue>(JsonTextWriter writer, string property, TValue value)
{
writer.WritePropertyName(property);
writer.WriteValue(value);
}
}
}
#endif
\ No newline at end of file
#if !NOJSONNET
using System.IO;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace NBitcoin.RPC
{
//{"code":-32601,"message":"Method not found"}
public class RPCError
{
internal RPCError(JObject error)
{
Code = (RPCErrorCode)((int)error.GetValue("code"));
Message = (string)error.GetValue("message");
}
public RPCErrorCode Code
{
get;
set;
}
public string Message
{
get;
set;
}
}
//{"result":null,"error":{"code":-32601,"message":"Method not found"},"id":1}
public class RPCResponse
{
internal RPCResponse(JObject json)
{
var error = json.GetValue("error") as JObject;
if(error != null)
{
Error = new RPCError(error);
}
Result = json.GetValue("result") as JToken;
}
public RPCError Error
{
get;
set;
}
#if !NOJSONNET
public
#else
internal
#endif
JToken Result
{
get;
set;
}
public string ResultString
{
get
{
if(Result == null)
return null;
return Result.ToString();
}
}
public static RPCResponse Load(Stream stream)
{
JsonTextReader reader = new JsonTextReader(new StreamReader(stream, Encoding.UTF8));
return new RPCResponse(JObject.Load(reader));
}
public void ThrowIfError()
{
if(Error != null)
{
throw new RPCException(Error.Code, Error.Message, this);
}
}
}
}
#endif
\ No newline at end of file
#if !NOJSONNET
using System;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace NBitcoin.RPC
{
internal abstract class RawFormatter
{
public Network Network { get; set; }
protected RawFormatter(Network network)
{
this.Network = network;
}
protected abstract void BuildTransaction(JObject json, Transaction tx);
protected abstract void WriteTransaction(JsonTextWriter writer, Transaction tx);
public Transaction ParseJson(string str)
{
JObject obj = JObject.Parse(str);
return Parse(obj);
}
[Obsolete("Use RawFormatter.ParseJson method instead")]
public Transaction Parse(string str)
{
JObject obj = JObject.Parse(str);
return Parse(obj);
}
public Transaction Parse(JObject obj)
{
var tx = new Transaction();
BuildTransaction(obj, tx);
return tx;
}
protected void WritePropertyValue<TValue>(JsonWriter writer, string name, TValue value)
{
writer.WritePropertyName(name);
writer.WriteValue(value);
}
public string ToString(Transaction transaction)
{
var strWriter = new StringWriter();
var jsonWriter = new JsonTextWriter(strWriter);
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.WriteStartObject();
WriteTransaction(jsonWriter, transaction);
jsonWriter.WriteEndObject();
jsonWriter.Flush();
return strWriter.ToString();
}
}
}
#endif
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment