Commit c0331514 authored by Pavel Pavlov's avatar Pavel Pavlov

Bug fix after merge.

parent 0191a5d6
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
"profiles": { "profiles": {
"Stratis.StratisD": { "Stratis.StratisD": {
"commandName": "Project", "commandName": "Project",
"commandLineArgs": "-testnet -debug -loglevel=trace" "commandLineArgs": "-testnet -debug -loglevel=trace -addnode=192.168.31.142:56849"
}, },
"Stratis.StratisD Test": { "Stratis.StratisD Test": {
"commandName": "Project", "commandName": "Project",
......
...@@ -16,9 +16,9 @@ namespace NBitcoin ...@@ -16,9 +16,9 @@ namespace NBitcoin
public BIP9DeploymentsParameters(int bit, DateTimeOffset startTime, DateTimeOffset timeout) public BIP9DeploymentsParameters(int bit, DateTimeOffset startTime, DateTimeOffset timeout)
{ {
Bit = bit; this.Bit = bit;
StartTime = startTime; this.StartTime = startTime;
Timeout = timeout; this.Timeout = timeout;
} }
public BIP9DeploymentsParameters(int bit, long startTime, long timeout) public BIP9DeploymentsParameters(int bit, long startTime, long timeout)
......
...@@ -5,14 +5,14 @@ using System.Text; ...@@ -5,14 +5,14 @@ using System.Text;
namespace NBitcoin namespace NBitcoin
{ {
class BitReader internal class BitReader
{ {
BitArray array; private BitArray array;
public BitReader(byte[] data, int bitCount) public BitReader(byte[] data, int bitCount)
{ {
BitWriter writer = new BitWriter(); var writer = new BitWriter();
writer.Write(data, bitCount); writer.Write(data, bitCount);
array = writer.ToBitArray(); this.array = writer.ToBitArray();
} }
public BitReader(BitArray array) public BitReader(BitArray array)
...@@ -24,8 +24,8 @@ namespace NBitcoin ...@@ -24,8 +24,8 @@ namespace NBitcoin
public bool Read() public bool Read()
{ {
var v = array.Get(Position); bool v = this.array.Get(this.Position);
Position++; this.Position++;
return v; return v;
} }
...@@ -40,7 +40,7 @@ namespace NBitcoin ...@@ -40,7 +40,7 @@ namespace NBitcoin
uint value = 0; uint value = 0;
for(int i = 0; i < bitCount; i++) for(int i = 0; i < bitCount; i++)
{ {
var v = Read() ? 1U : 0U; uint v = Read() ? 1U : 0U;
value += (v << i); value += (v << i);
} }
return value; return value;
...@@ -50,36 +50,36 @@ namespace NBitcoin ...@@ -50,36 +50,36 @@ namespace NBitcoin
{ {
get get
{ {
return array.Length; return this.array.Length;
} }
} }
public BitArray ToBitArray() public BitArray ToBitArray()
{ {
BitArray result = new BitArray(array.Length); var result = new BitArray(this.array.Length);
for(int i = 0; i < array.Length; i++) for(int i = 0; i < this.array.Length; i++)
result.Set(i, array.Get(i)); result.Set(i, this.array.Get(i));
return result; return result;
} }
public BitWriter ToWriter() public BitWriter ToWriter()
{ {
var writer = new BitWriter(); var writer = new BitWriter();
writer.Write(array); writer.Write(this.array);
return writer; return writer;
} }
public void Consume(int count) public void Consume(int count)
{ {
Position += count; this.Position += count;
} }
public bool Same(BitReader b) public bool Same(BitReader b)
{ {
while(Position != Count && b.Position != b.Count) while(this.Position != this.Count && b.Position != b.Count)
{ {
var valuea = Read(); bool valuea = Read();
var valueb = b.Read(); bool valueb = b.Read();
if(valuea != valueb) if(valuea != valueb)
return false; return false;
} }
...@@ -88,30 +88,31 @@ namespace NBitcoin ...@@ -88,30 +88,31 @@ namespace NBitcoin
public override string ToString() public override string ToString()
{ {
StringBuilder builder = new StringBuilder(array.Length); var builder = new StringBuilder(this.array.Length);
for(int i = 0; i < Count; i++) for(int i = 0; i < this.Count; i++)
{ {
if(i != 0 && i % 8 == 0) if(i != 0 && i % 8 == 0)
builder.Append(' '); builder.Append(' ');
builder.Append(array.Get(i) ? "1" : "0"); builder.Append(this.array.Get(i) ? "1" : "0");
} }
return builder.ToString(); return builder.ToString();
} }
} }
class BitWriter
internal class BitWriter
{ {
List<bool> values = new List<bool>(); private List<bool> values = new List<bool>();
public int Count public int Count
{ {
get get
{ {
return values.Count; return this.values.Count;
} }
} }
public void Write(bool value) public void Write(bool value)
{ {
values.Insert(Position, value); this.values.Insert(this.Position, value);
_Position++; this._Position++;
} }
internal void Write(byte[] bytes) internal void Write(byte[] bytes)
...@@ -122,26 +123,26 @@ namespace NBitcoin ...@@ -122,26 +123,26 @@ namespace NBitcoin
public void Write(byte[] bytes, int bitCount) public void Write(byte[] bytes, int bitCount)
{ {
bytes = SwapEndianBytes(bytes); bytes = SwapEndianBytes(bytes);
BitArray array = new BitArray(bytes); var array = new BitArray(bytes);
values.InsertRange(Position, array.OfType<bool>().Take(bitCount)); this.values.InsertRange(this.Position, array.OfType<bool>().Take(bitCount));
_Position += bitCount; this._Position += bitCount;
} }
public byte[] ToBytes() public byte[] ToBytes()
{ {
var array = ToBitArray(); BitArray array = ToBitArray();
var bytes = ToByteArray(array); byte[] bytes = ToByteArray(array);
bytes = SwapEndianBytes(bytes); bytes = SwapEndianBytes(bytes);
return bytes; return bytes;
} }
//BitArray.CopyTo do not exist in portable lib //BitArray.CopyTo do not exist in portable lib
static byte[] ToByteArray(BitArray bits) private static byte[] ToByteArray(BitArray bits)
{ {
int arrayLength = bits.Length / 8; int arrayLength = bits.Length / 8;
if(bits.Length % 8 != 0) if(bits.Length % 8 != 0)
arrayLength++; arrayLength++;
byte[] array = new byte[arrayLength]; var array = new byte[arrayLength];
for(int i = 0; i < bits.Length; i++) for(int i = 0; i < bits.Length; i++)
{ {
...@@ -155,19 +156,19 @@ namespace NBitcoin ...@@ -155,19 +156,19 @@ namespace NBitcoin
public BitArray ToBitArray() public BitArray ToBitArray()
{ {
return new BitArray(values.ToArray()); return new BitArray(this.values.ToArray());
} }
public int[] ToIntegers() public int[] ToIntegers()
{ {
var array = new BitArray(values.ToArray()); var array = new BitArray(this.values.ToArray());
return Wordlist.ToIntegers(array); return Wordlist.ToIntegers(array);
} }
static byte[] SwapEndianBytes(byte[] bytes) private static byte[] SwapEndianBytes(byte[] bytes)
{ {
byte[] output = new byte[bytes.Length]; var output = new byte[bytes.Length];
for(int i = 0; i < output.Length; i++) for(int i = 0; i < output.Length; i++)
{ {
byte newByte = 0; byte newByte = 0;
...@@ -191,16 +192,16 @@ namespace NBitcoin ...@@ -191,16 +192,16 @@ namespace NBitcoin
} }
} }
int _Position; private int _Position;
public int Position public int Position
{ {
get get
{ {
return _Position; return this._Position;
} }
set set
{ {
_Position = value; this._Position = value;
} }
} }
...@@ -236,12 +237,12 @@ namespace NBitcoin ...@@ -236,12 +237,12 @@ namespace NBitcoin
public override string ToString() public override string ToString()
{ {
StringBuilder builder = new StringBuilder(values.Count); var builder = new StringBuilder(this.values.Count);
for(int i = 0; i < Count; i++) for(int i = 0; i < this.Count; i++)
{ {
if(i != 0 && i % 8 == 0) if(i != 0 && i % 8 == 0)
builder.Append(' '); builder.Append(' ');
builder.Append(values[i] ? "1" : "0"); builder.Append(this.values[i] ? "1" : "0");
} }
return builder.ToString(); return builder.ToString();
} }
......
...@@ -12,8 +12,8 @@ namespace NBitcoin ...@@ -12,8 +12,8 @@ namespace NBitcoin
public BitcoinScriptAddress(string base58, Network expectedNetwork) public BitcoinScriptAddress(string base58, Network expectedNetwork)
: base(Validate(base58, ref expectedNetwork), expectedNetwork) : base(Validate(base58, ref expectedNetwork), expectedNetwork)
{ {
var decoded = Encoders.Base58Check.DecodeData(base58); byte[] decoded = Encoders.Base58Check.DecodeData(base58);
_Hash = new ScriptId(new uint160(decoded.Skip(expectedNetwork.GetVersionBytes(Base58Type.SCRIPT_ADDRESS, true).Length).ToArray())); this._Hash = new ScriptId(new uint160(decoded.Skip(expectedNetwork.GetVersionBytes(Base58Type.SCRIPT_ADDRESS, true).Length).ToArray()));
} }
private static string Validate(string base58, ref Network expectedNetwork) private static string Validate(string base58, ref Network expectedNetwork)
...@@ -27,8 +27,8 @@ namespace NBitcoin ...@@ -27,8 +27,8 @@ namespace NBitcoin
{ {
if (base58 == null) if (base58 == null)
throw new ArgumentNullException("base58"); throw new ArgumentNullException("base58");
var data = Encoders.Base58Check.DecodeData(base58); byte[] data = Encoders.Base58Check.DecodeData(base58);
var versionBytes = expectedNetwork.GetVersionBytes(Base58Type.SCRIPT_ADDRESS, false); byte[] versionBytes = expectedNetwork.GetVersionBytes(Base58Type.SCRIPT_ADDRESS, false);
if (versionBytes != null && data.StartWith(versionBytes)) if (versionBytes != null && data.StartWith(versionBytes))
{ {
if (data.Length == versionBytes.Length + 20) if (data.Length == versionBytes.Length + 20)
...@@ -42,7 +42,7 @@ namespace NBitcoin ...@@ -42,7 +42,7 @@ namespace NBitcoin
public BitcoinScriptAddress(ScriptId scriptId, Network network) public BitcoinScriptAddress(ScriptId scriptId, Network network)
: base(NotNull(scriptId) ?? Network.CreateBase58(Base58Type.SCRIPT_ADDRESS, scriptId.ToBytes(), network), network) : base(NotNull(scriptId) ?? Network.CreateBase58(Base58Type.SCRIPT_ADDRESS, scriptId.ToBytes(), network), network)
{ {
_Hash = scriptId; this._Hash = scriptId;
} }
private static string NotNull(ScriptId scriptId) private static string NotNull(ScriptId scriptId)
...@@ -52,12 +52,12 @@ namespace NBitcoin ...@@ -52,12 +52,12 @@ namespace NBitcoin
return null; return null;
} }
ScriptId _Hash; private ScriptId _Hash;
public ScriptId Hash public ScriptId Hash
{ {
get get
{ {
return _Hash; return this._Hash;
} }
} }
...@@ -71,7 +71,7 @@ namespace NBitcoin ...@@ -71,7 +71,7 @@ namespace NBitcoin
protected override Script GeneratePaymentScript() protected override Script GeneratePaymentScript()
{ {
return PayToScriptHashTemplate.Instance.GenerateScriptPubKey((ScriptId)Hash); return PayToScriptHashTemplate.Instance.GenerateScriptPubKey((ScriptId) this.Hash);
} }
} }
...@@ -100,22 +100,22 @@ namespace NBitcoin ...@@ -100,22 +100,22 @@ namespace NBitcoin
throw new ArgumentNullException("network"); throw new ArgumentNullException("network");
if(str == null) if(str == null)
throw new ArgumentNullException("str"); throw new ArgumentNullException("str");
_Str = str; this._Str = str;
_Network = network; this._Network = network;
} }
string _Str; private string _Str;
Script _ScriptPubKey; private Script _ScriptPubKey;
public Script ScriptPubKey public Script ScriptPubKey
{ {
get get
{ {
if(_ScriptPubKey == null) if(this._ScriptPubKey == null)
{ {
_ScriptPubKey = GeneratePaymentScript(); this._ScriptPubKey = GeneratePaymentScript();
} }
return _ScriptPubKey; return this._ScriptPubKey;
} }
} }
...@@ -127,7 +127,7 @@ namespace NBitcoin ...@@ -127,7 +127,7 @@ namespace NBitcoin
if(bitcoinScriptAddress != null) if(bitcoinScriptAddress != null)
return bitcoinScriptAddress; return bitcoinScriptAddress;
return new BitcoinScriptAddress(this.ScriptPubKey.Hash, Network); return new BitcoinScriptAddress(this.ScriptPubKey.Hash, this.Network);
} }
public BitcoinColoredAddress ToColoredAddress() public BitcoinColoredAddress ToColoredAddress()
...@@ -141,26 +141,26 @@ namespace NBitcoin ...@@ -141,26 +141,26 @@ namespace NBitcoin
{ {
get get
{ {
return _Network; return this._Network;
} }
} }
public override string ToString() public override string ToString()
{ {
return _Str; return this._Str;
} }
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
BitcoinAddress item = obj as BitcoinAddress; var item = obj as BitcoinAddress;
if(item == null) if(item == null)
return false; return false;
return _Str.Equals(item._Str); return this._Str.Equals(item._Str);
} }
public static bool operator ==(BitcoinAddress a, BitcoinAddress b) public static bool operator ==(BitcoinAddress a, BitcoinAddress b)
{ {
if(System.Object.ReferenceEquals(a, b)) if(ReferenceEquals(a, b))
return true; return true;
if(((object)a == null) || ((object)b == null)) if(((object)a == null) || ((object)b == null))
return false; return false;
...@@ -174,7 +174,7 @@ namespace NBitcoin ...@@ -174,7 +174,7 @@ namespace NBitcoin
public override int GetHashCode() public override int GetHashCode()
{ {
return _Str.GetHashCode(); return this._Str.GetHashCode();
} }
} }
} }
...@@ -12,8 +12,8 @@ namespace NBitcoin ...@@ -12,8 +12,8 @@ namespace NBitcoin
public BitcoinPubKeyAddress(string base58, Network expectedNetwork) public BitcoinPubKeyAddress(string base58, Network expectedNetwork)
: base(Validate(base58, ref expectedNetwork), expectedNetwork) : base(Validate(base58, ref expectedNetwork), expectedNetwork)
{ {
var decoded = Encoders.Base58Check.DecodeData(base58); byte[] decoded = Encoders.Base58Check.DecodeData(base58);
_KeyId = new KeyId(new uint160(decoded.Skip(expectedNetwork.GetVersionBytes(Base58Type.PUBKEY_ADDRESS, true).Length).ToArray())); this._KeyId = new KeyId(new uint160(decoded.Skip(expectedNetwork.GetVersionBytes(Base58Type.PUBKEY_ADDRESS, true).Length).ToArray()));
} }
private static string Validate(string base58, ref Network expectedNetwork) private static string Validate(string base58, ref Network expectedNetwork)
...@@ -27,8 +27,8 @@ namespace NBitcoin ...@@ -27,8 +27,8 @@ namespace NBitcoin
{ {
if (base58 == null) if (base58 == null)
throw new ArgumentNullException("base58"); throw new ArgumentNullException("base58");
var data = Encoders.Base58Check.DecodeData(base58); byte[] data = Encoders.Base58Check.DecodeData(base58);
var versionBytes = expectedNetwork.GetVersionBytes(Base58Type.PUBKEY_ADDRESS, false); byte[] versionBytes = expectedNetwork.GetVersionBytes(Base58Type.PUBKEY_ADDRESS, false);
if (versionBytes != null && data.StartWith(versionBytes)) if (versionBytes != null && data.StartWith(versionBytes))
{ {
if (data.Length == versionBytes.Length + 20) if (data.Length == versionBytes.Length + 20)
...@@ -42,7 +42,7 @@ namespace NBitcoin ...@@ -42,7 +42,7 @@ namespace NBitcoin
public BitcoinPubKeyAddress(KeyId keyId, Network network) : public BitcoinPubKeyAddress(KeyId keyId, Network network) :
base(NotNull(keyId) ?? Network.CreateBase58(Base58Type.PUBKEY_ADDRESS, keyId.ToBytes(), network), network) base(NotNull(keyId) ?? Network.CreateBase58(Base58Type.PUBKEY_ADDRESS, keyId.ToBytes(), network), network)
{ {
_KeyId = keyId; this._KeyId = keyId;
} }
private static string NotNull(KeyId keyId) private static string NotNull(KeyId keyId)
...@@ -54,16 +54,16 @@ namespace NBitcoin ...@@ -54,16 +54,16 @@ namespace NBitcoin
public bool VerifyMessage(string message, string signature) public bool VerifyMessage(string message, string signature)
{ {
var key = PubKey.RecoverFromMessage(message, signature); PubKey key = PubKey.RecoverFromMessage(message, signature);
return key.Hash == Hash; return key.Hash == this.Hash;
} }
KeyId _KeyId; private KeyId _KeyId;
public KeyId Hash public KeyId Hash
{ {
get get
{ {
return _KeyId; return this._KeyId;
} }
} }
......
using System.Linq; using System.Collections.Generic;
using System.Linq;
using NBitcoin.DataEncoders; using NBitcoin.DataEncoders;
namespace NBitcoin namespace NBitcoin
...@@ -12,7 +13,7 @@ namespace NBitcoin ...@@ -12,7 +13,7 @@ namespace NBitcoin
private static byte[] ToBytes(Key key) private static byte[] ToBytes(Key key)
{ {
var keyBytes = key.ToBytes(); byte[] keyBytes = key.ToBytes();
if(!key.IsCompressed) if(!key.IsCompressed)
return keyBytes; return keyBytes;
else else
...@@ -27,14 +28,14 @@ namespace NBitcoin ...@@ -27,14 +28,14 @@ namespace NBitcoin
public BitcoinPubKeyAddress GetAddress() public BitcoinPubKeyAddress GetAddress()
{ {
return _address ?? (_address = PrivateKey.PubKey.GetAddress(Network)); return this._address ?? (this._address = this.PrivateKey.PubKey.GetAddress(this.Network));
} }
public virtual KeyId PubKeyHash public virtual KeyId PubKeyHash
{ {
get get
{ {
return PrivateKey.PubKey.Hash; return this.PrivateKey.PubKey.Hash;
} }
} }
...@@ -42,17 +43,18 @@ namespace NBitcoin ...@@ -42,17 +43,18 @@ namespace NBitcoin
{ {
get get
{ {
return PrivateKey.PubKey; return this.PrivateKey.PubKey;
} }
} }
#region ISecret Members #region ISecret Members
Key _Key;
private Key _Key;
public Key PrivateKey public Key PrivateKey
{ {
get get
{ {
return _Key ?? (_Key = new Key(vchData, 32, IsCompressed)); return this._Key ?? (this._Key = new Key(this.vchData, 32, this.IsCompressed));
} }
} }
#endregion #endregion
...@@ -61,12 +63,12 @@ namespace NBitcoin ...@@ -61,12 +63,12 @@ namespace NBitcoin
{ {
get get
{ {
if(vchData.Length != 33 && vchData.Length != 32) if(this.vchData.Length != 33 && this.vchData.Length != 32)
return false; return false;
if(vchData.Length == 33 && IsCompressed) if(this.vchData.Length == 33 && this.IsCompressed)
return true; return true;
if(vchData.Length == 32 && !IsCompressed) if(this.vchData.Length == 32 && !this.IsCompressed)
return true; return true;
return false; return false;
} }
...@@ -74,23 +76,23 @@ namespace NBitcoin ...@@ -74,23 +76,23 @@ namespace NBitcoin
public BitcoinEncryptedSecret Encrypt(string password) public BitcoinEncryptedSecret Encrypt(string password)
{ {
return PrivateKey.GetEncryptedBitcoinSecret(password, Network); return this.PrivateKey.GetEncryptedBitcoinSecret(password, this.Network);
} }
public BitcoinSecret Copy(bool? compressed) public BitcoinSecret Copy(bool? compressed)
{ {
if(compressed == null) if(compressed == null)
compressed = IsCompressed; compressed = this.IsCompressed;
if(compressed.Value && IsCompressed) if(compressed.Value && this.IsCompressed)
{ {
return new BitcoinSecret(wifData, Network); return new BitcoinSecret(this.wifData, this.Network);
} }
else else
{ {
byte[] result = Encoders.Base58Check.DecodeData(wifData); byte[] result = Encoders.Base58Check.DecodeData(this.wifData);
var resultList = result.ToList(); List<byte> resultList = result.ToList();
if(compressed.Value) if(compressed.Value)
{ {
...@@ -100,7 +102,7 @@ namespace NBitcoin ...@@ -100,7 +102,7 @@ namespace NBitcoin
{ {
resultList.RemoveAt(resultList.Count - 1); resultList.RemoveAt(resultList.Count - 1);
} }
return new BitcoinSecret(Encoders.Base58Check.EncodeData(resultList.ToArray()), Network); return new BitcoinSecret(Encoders.Base58Check.EncodeData(resultList.ToArray()), this.Network);
} }
} }
...@@ -108,7 +110,7 @@ namespace NBitcoin ...@@ -108,7 +110,7 @@ namespace NBitcoin
{ {
get get
{ {
return vchData.Length > 32 && vchData[32] == 1; return this.vchData.Length > 32 && this.vchData[32] == 1;
} }
} }
......
...@@ -8,10 +8,10 @@ namespace NBitcoin ...@@ -8,10 +8,10 @@ namespace NBitcoin
public BitcoinWitPubKeyAddress(string bech32, Network expectedNetwork) public BitcoinWitPubKeyAddress(string bech32, Network expectedNetwork)
: base(Validate(bech32, ref expectedNetwork), expectedNetwork) : base(Validate(bech32, ref expectedNetwork), expectedNetwork)
{ {
var encoder = expectedNetwork.GetBech32Encoder(Bech32Type.WITNESS_PUBKEY_ADDRESS, true); Bech32Encoder encoder = expectedNetwork.GetBech32Encoder(Bech32Type.WITNESS_PUBKEY_ADDRESS, true);
byte witVersion; byte witVersion;
var decoded = encoder.Decode(bech32, out witVersion); byte[] decoded = encoder.Decode(bech32, out witVersion);
_Hash = new WitKeyId(decoded); this._Hash = new WitKeyId(decoded);
} }
private static string Validate(string bech32, ref Network expectedNetwork) private static string Validate(string bech32, ref Network expectedNetwork)
...@@ -37,14 +37,14 @@ namespace NBitcoin ...@@ -37,14 +37,14 @@ namespace NBitcoin
return false; return false;
} }
var encoder = expectedNetwork.GetBech32Encoder(Bech32Type.WITNESS_PUBKEY_ADDRESS, false); Bech32Encoder encoder = expectedNetwork.GetBech32Encoder(Bech32Type.WITNESS_PUBKEY_ADDRESS, false);
if (encoder == null) if (encoder == null)
return false; return false;
try try
{ {
byte witVersion; byte witVersion;
var data = encoder.Decode(bech32, out witVersion); byte[] data = encoder.Decode(bech32, out witVersion);
if (data.Length == 20 && witVersion == 0) if (data.Length == 20 && witVersion == 0)
{ {
return true; return true;
...@@ -68,7 +68,7 @@ namespace NBitcoin ...@@ -68,7 +68,7 @@ namespace NBitcoin
public BitcoinWitPubKeyAddress(WitKeyId segwitKeyId, Network network) : public BitcoinWitPubKeyAddress(WitKeyId segwitKeyId, Network network) :
base(NotNull(segwitKeyId) ?? Network.CreateBech32(Bech32Type.WITNESS_PUBKEY_ADDRESS, segwitKeyId.ToBytes(), 0, network), network) base(NotNull(segwitKeyId) ?? Network.CreateBech32(Bech32Type.WITNESS_PUBKEY_ADDRESS, segwitKeyId.ToBytes(), 0, network), network)
{ {
_Hash = segwitKeyId; this._Hash = segwitKeyId;
} }
private static string NotNull(WitKeyId segwitKeyId) private static string NotNull(WitKeyId segwitKeyId)
...@@ -80,23 +80,23 @@ namespace NBitcoin ...@@ -80,23 +80,23 @@ namespace NBitcoin
public bool VerifyMessage(string message, string signature) public bool VerifyMessage(string message, string signature)
{ {
var key = PubKey.RecoverFromMessage(message, signature); PubKey key = PubKey.RecoverFromMessage(message, signature);
return key.WitHash == this.Hash; return key.WitHash == this.Hash;
} }
WitKeyId _Hash; private WitKeyId _Hash;
public WitKeyId Hash public WitKeyId Hash
{ {
get get
{ {
return _Hash; return this._Hash;
} }
} }
protected override Script GeneratePaymentScript() protected override Script GeneratePaymentScript()
{ {
return PayToWitTemplate.Instance.GenerateScriptPubKey(OpcodeType.OP_0, Hash._DestBytes); return PayToWitTemplate.Instance.GenerateScriptPubKey(OpcodeType.OP_0, this.Hash._DestBytes);
} }
public Bech32Type Type public Bech32Type Type
...@@ -113,10 +113,10 @@ namespace NBitcoin ...@@ -113,10 +113,10 @@ namespace NBitcoin
public BitcoinWitScriptAddress(string bech32, Network expectedNetwork = null) public BitcoinWitScriptAddress(string bech32, Network expectedNetwork = null)
: base(Validate(bech32, ref expectedNetwork), expectedNetwork) : base(Validate(bech32, ref expectedNetwork), expectedNetwork)
{ {
var encoder = expectedNetwork.GetBech32Encoder(Bech32Type.WITNESS_SCRIPT_ADDRESS, true); Bech32Encoder encoder = expectedNetwork.GetBech32Encoder(Bech32Type.WITNESS_SCRIPT_ADDRESS, true);
byte witVersion; byte witVersion;
var decoded = encoder.Decode(bech32, out witVersion); byte[] decoded = encoder.Decode(bech32, out witVersion);
_Hash = new WitScriptId(decoded); this._Hash = new WitScriptId(decoded);
} }
private static string Validate(string bech32, ref Network expectedNetwork) private static string Validate(string bech32, ref Network expectedNetwork)
...@@ -142,13 +142,13 @@ namespace NBitcoin ...@@ -142,13 +142,13 @@ namespace NBitcoin
return false; return false;
} }
var encoder = expectedNetwork.GetBech32Encoder(Bech32Type.WITNESS_SCRIPT_ADDRESS, false); Bech32Encoder encoder = expectedNetwork.GetBech32Encoder(Bech32Type.WITNESS_SCRIPT_ADDRESS, false);
if (encoder == null) if (encoder == null)
return false; return false;
try try
{ {
byte witVersion; byte witVersion;
var data = encoder.Decode(bech32, out witVersion); byte[] data = encoder.Decode(bech32, out witVersion);
if (data.Length == 32 && witVersion == 0) if (data.Length == 32 && witVersion == 0)
{ {
return true; return true;
...@@ -172,7 +172,7 @@ namespace NBitcoin ...@@ -172,7 +172,7 @@ namespace NBitcoin
public BitcoinWitScriptAddress(WitScriptId segwitScriptId, Network network) public BitcoinWitScriptAddress(WitScriptId segwitScriptId, Network network)
: base(NotNull(segwitScriptId) ?? Network.CreateBech32(Bech32Type.WITNESS_SCRIPT_ADDRESS, segwitScriptId.ToBytes(), 0, network), network) : base(NotNull(segwitScriptId) ?? Network.CreateBech32(Bech32Type.WITNESS_SCRIPT_ADDRESS, segwitScriptId.ToBytes(), 0, network), network)
{ {
_Hash = segwitScriptId; this._Hash = segwitScriptId;
} }
...@@ -183,18 +183,18 @@ namespace NBitcoin ...@@ -183,18 +183,18 @@ namespace NBitcoin
return null; return null;
} }
WitScriptId _Hash; private WitScriptId _Hash;
public WitScriptId Hash public WitScriptId Hash
{ {
get get
{ {
return _Hash; return this._Hash;
} }
} }
protected override Script GeneratePaymentScript() protected override Script GeneratePaymentScript()
{ {
return PayToWitTemplate.Instance.GenerateScriptPubKey(OpcodeType.OP_0, Hash._DestBytes); return PayToWitTemplate.Instance.GenerateScriptPubKey(OpcodeType.OP_0, this.Hash._DestBytes);
} }
public Bech32Type Type public Bech32Type Type
......
This diff is collapsed.
...@@ -10,20 +10,20 @@ namespace NBitcoin ...@@ -10,20 +10,20 @@ namespace NBitcoin
{ {
protected bool Equals(BlockSignature other) protected bool Equals(BlockSignature other)
{ {
return Equals(signature, other.signature); return Equals(this.signature, other.signature);
} }
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true; if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false; if (obj.GetType() != GetType()) return false;
return Equals((BlockSignature) obj); return Equals((BlockSignature) obj);
} }
public override int GetHashCode() public override int GetHashCode()
{ {
return (signature?.GetHashCode() ?? 0); return (this.signature?.GetHashCode() ?? 0);
} }
public BlockSignature() public BlockSignature()
...@@ -37,17 +37,17 @@ namespace NBitcoin ...@@ -37,17 +37,17 @@ namespace NBitcoin
{ {
get get
{ {
return signature; return this.signature;
} }
set set
{ {
signature = value; this.signature = value;
} }
} }
internal void SetNull() internal void SetNull()
{ {
signature = new byte[0]; this.signature = new byte[0];
} }
public bool IsEmpty() public bool IsEmpty()
...@@ -57,7 +57,7 @@ namespace NBitcoin ...@@ -57,7 +57,7 @@ namespace NBitcoin
public static bool operator ==(BlockSignature a, BlockSignature b) public static bool operator ==(BlockSignature a, BlockSignature b)
{ {
if (System.Object.ReferenceEquals(a, b)) if (ReferenceEquals(a, b))
return true; return true;
if (((object)a == null) || ((object)b == null)) if (((object)a == null) || ((object)b == null))
...@@ -75,7 +75,7 @@ namespace NBitcoin ...@@ -75,7 +75,7 @@ namespace NBitcoin
public void ReadWrite(BitcoinStream stream) public void ReadWrite(BitcoinStream stream)
{ {
stream.ReadWriteAsVarString(ref signature); stream.ReadWriteAsVarString(ref this.signature);
} }
#endregion #endregion
......
...@@ -6,18 +6,18 @@ namespace NBitcoin ...@@ -6,18 +6,18 @@ namespace NBitcoin
{ {
public class CachedTransactionRepository : ITransactionRepository public class CachedTransactionRepository : ITransactionRepository
{ {
ITransactionRepository _Inner; private ITransactionRepository _Inner;
Dictionary<uint256, Transaction> _Transactions = new Dictionary<uint256, Transaction>(); private Dictionary<uint256, Transaction> _Transactions = new Dictionary<uint256, Transaction>();
Queue<uint256> _EvictionQueue = new Queue<uint256>(); private Queue<uint256> _EvictionQueue = new Queue<uint256>();
ReaderWriterLock @lock = new ReaderWriterLock(); private ReaderWriterLock @lock = new ReaderWriterLock();
public CachedTransactionRepository(ITransactionRepository inner) public CachedTransactionRepository(ITransactionRepository inner)
{ {
if(inner == null) if(inner == null)
throw new ArgumentNullException("inner"); throw new ArgumentNullException("inner");
ReadThrough = true; this.ReadThrough = true;
WriteThrough = true; this.WriteThrough = true;
_Inner = inner; this._Inner = inner;
MaxCachedTransactions = 100; this.MaxCachedTransactions = 100;
} }
public int MaxCachedTransactions public int MaxCachedTransactions
...@@ -28,9 +28,9 @@ namespace NBitcoin ...@@ -28,9 +28,9 @@ namespace NBitcoin
public Transaction GetFromCache(uint256 txId) public Transaction GetFromCache(uint256 txId)
{ {
using(@lock.LockRead()) using(this.@lock.LockRead())
{ {
return _Transactions.TryGet(txId); return this._Transactions.TryGet(txId);
} }
} }
...@@ -40,19 +40,18 @@ namespace NBitcoin ...@@ -40,19 +40,18 @@ namespace NBitcoin
{ {
bool found = false; bool found = false;
Transaction result = null; Transaction result = null;
using(@lock.LockRead()) using(this.@lock.LockRead())
{ {
found = _Transactions.TryGetValue(txId, out result); found = this._Transactions.TryGetValue(txId, out result);
} }
if(!found) if(!found)
{ {
result = await _Inner.GetAsync(txId).ConfigureAwait(false); result = await this._Inner.GetAsync(txId).ConfigureAwait(false);
if(ReadThrough) if(this.ReadThrough)
{ {
using(@lock.LockWrite()) using(this.@lock.LockWrite())
{ {
this._Transactions.AddOrReplace(txId, result);
_Transactions.AddOrReplace(txId, result);
EvictIfNecessary(txId); EvictIfNecessary(txId);
} }
} }
...@@ -63,29 +62,27 @@ namespace NBitcoin ...@@ -63,29 +62,27 @@ namespace NBitcoin
private void EvictIfNecessary(uint256 txId) private void EvictIfNecessary(uint256 txId)
{ {
_EvictionQueue.Enqueue(txId); this._EvictionQueue.Enqueue(txId);
while(_Transactions.Count > MaxCachedTransactions && _EvictionQueue.Count > 0) while(this._Transactions.Count > this.MaxCachedTransactions && this._EvictionQueue.Count > 0) this._Transactions.Remove(this._EvictionQueue.Dequeue());
_Transactions.Remove(_EvictionQueue.Dequeue());
} }
public Task PutAsync(uint256 txId, Transaction tx) public Task PutAsync(uint256 txId, Transaction tx)
{ {
if(WriteThrough) if(this.WriteThrough)
{ {
using(@lock.LockWrite()) using(this.@lock.LockWrite())
{ {
if(!_Transactions.ContainsKey(txId)) if(!this._Transactions.ContainsKey(txId))
{ {
this._Transactions.AddOrReplace(txId, tx);
_Transactions.AddOrReplace(txId, tx);
EvictIfNecessary(txId); EvictIfNecessary(txId);
} }
else else
_Transactions[txId] = tx; this._Transactions[txId] = tx;
} }
} }
return _Inner.PutAsync(txId, tx); return this._Inner.PutAsync(txId, tx);
} }
#endregion #endregion
......
...@@ -43,7 +43,7 @@ namespace NBitcoin ...@@ -43,7 +43,7 @@ namespace NBitcoin
public abstract ChainedHeader SetTip(ChainedHeader chainedHeader); public abstract ChainedHeader SetTip(ChainedHeader chainedHeader);
/// <summary>Gets the genesis block for the chain.</summary> /// <summary>Gets the genesis block for the chain.</summary>
public virtual ChainedHeader Genesis { get { return this.GetBlock(0); } } public virtual ChainedHeader Genesis { get { return GetBlock(0); } }
/// <summary> /// <summary>
/// Gets an enumerable iterator for the chain. /// Gets an enumerable iterator for the chain.
...@@ -59,7 +59,7 @@ namespace NBitcoin ...@@ -59,7 +59,7 @@ namespace NBitcoin
} }
else else
{ {
foreach (ChainedHeader block in this.EnumerateFromStart()) foreach (ChainedHeader block in EnumerateFromStart())
yield return block; yield return block;
} }
} }
...@@ -74,7 +74,7 @@ namespace NBitcoin ...@@ -74,7 +74,7 @@ namespace NBitcoin
if (otherChain == null) if (otherChain == null)
throw new ArgumentNullException("otherChain"); throw new ArgumentNullException("otherChain");
return this.SetTip(otherChain.Tip); return SetTip(otherChain.Tip);
} }
/// <summary> /// <summary>
...@@ -85,7 +85,7 @@ namespace NBitcoin ...@@ -85,7 +85,7 @@ namespace NBitcoin
public bool SetTip(BlockHeader header) public bool SetTip(BlockHeader header)
{ {
ChainedHeader chainedHeader; ChainedHeader chainedHeader;
return this.TrySetTip(header, out chainedHeader); return TrySetTip(header, out chainedHeader);
} }
/// <summary> /// <summary>
...@@ -102,12 +102,12 @@ namespace NBitcoin ...@@ -102,12 +102,12 @@ namespace NBitcoin
throw new ArgumentNullException("header"); throw new ArgumentNullException("header");
chainedHeader = null; chainedHeader = null;
ChainedHeader prev = this.GetBlock(header.HashPrevBlock); ChainedHeader prev = GetBlock(header.HashPrevBlock);
if (prev == null) if (prev == null)
return false; return false;
chainedHeader = new ChainedHeader(header, header.GetHash(), this.GetBlock(header.HashPrevBlock)); chainedHeader = new ChainedHeader(header, header.GetHash(), GetBlock(header.HashPrevBlock));
this.SetTip(chainedHeader); SetTip(chainedHeader);
return true; return true;
} }
...@@ -118,7 +118,7 @@ namespace NBitcoin ...@@ -118,7 +118,7 @@ namespace NBitcoin
/// <returns>Whether the chain contains the chained block header.</returns> /// <returns>Whether the chain contains the chained block header.</returns>
public bool Contains(uint256 hash) public bool Contains(uint256 hash)
{ {
ChainedHeader block = this.GetBlock(hash); ChainedHeader block = GetBlock(hash);
return block != null; return block != null;
} }
...@@ -143,7 +143,7 @@ namespace NBitcoin ...@@ -143,7 +143,7 @@ namespace NBitcoin
/// <returns>The required work.</returns> /// <returns>The required work.</returns>
public Target GetWorkRequired(Network network, int height) public Target GetWorkRequired(Network network, int height)
{ {
return this.GetBlock(height).GetWorkRequired(network); return GetBlock(height).GetWorkRequired(network);
} }
/// <summary> /// <summary>
...@@ -159,7 +159,7 @@ namespace NBitcoin ...@@ -159,7 +159,7 @@ namespace NBitcoin
// Find the first block the caller has in the main chain. // Find the first block the caller has in the main chain.
foreach (uint256 hash in hashes) foreach (uint256 hash in hashes)
{ {
ChainedHeader mi = this.GetBlock(hash); ChainedHeader mi = GetBlock(hash);
if (mi != null) if (mi != null)
return mi; return mi;
} }
...@@ -177,7 +177,7 @@ namespace NBitcoin ...@@ -177,7 +177,7 @@ namespace NBitcoin
if (locator == null) if (locator == null)
throw new ArgumentNullException("locator"); throw new ArgumentNullException("locator");
return this.FindFork(locator.Blocks); return FindFork(locator.Blocks);
} }
/// <summary> /// <summary>
...@@ -187,12 +187,12 @@ namespace NBitcoin ...@@ -187,12 +187,12 @@ namespace NBitcoin
/// <returns>Enumeration of chained block headers after given block hash.</returns> /// <returns>Enumeration of chained block headers after given block hash.</returns>
public IEnumerable<ChainedHeader> EnumerateAfter(uint256 blockHash) public IEnumerable<ChainedHeader> EnumerateAfter(uint256 blockHash)
{ {
ChainedHeader block = this.GetBlock(blockHash); ChainedHeader block = GetBlock(blockHash);
if (block == null) if (block == null)
return new ChainedHeader[0]; return new ChainedHeader[0];
return this.EnumerateAfter(block); return EnumerateAfter(block);
} }
/// <summary> /// <summary>
...@@ -205,7 +205,7 @@ namespace NBitcoin ...@@ -205,7 +205,7 @@ namespace NBitcoin
if (block == null) if (block == null)
throw new ArgumentNullException("block"); throw new ArgumentNullException("block");
return this.EnumerateToTip(block.HashBlock); return EnumerateToTip(block.HashBlock);
} }
/// <summary> /// <summary>
...@@ -215,13 +215,13 @@ namespace NBitcoin ...@@ -215,13 +215,13 @@ namespace NBitcoin
/// <returns>Enumeration of chained block headers from the given block hash to tip.</returns> /// <returns>Enumeration of chained block headers from the given block hash to tip.</returns>
public IEnumerable<ChainedHeader> EnumerateToTip(uint256 blockHash) public IEnumerable<ChainedHeader> EnumerateToTip(uint256 blockHash)
{ {
ChainedHeader block = this.GetBlock(blockHash); ChainedHeader block = GetBlock(blockHash);
if (block == null) if (block == null)
yield break; yield break;
yield return block; yield return block;
foreach (ChainedHeader chainedBlock in this.EnumerateAfter(blockHash)) foreach (ChainedHeader chainedBlock in EnumerateAfter(blockHash))
yield return chainedBlock; yield return chainedBlock;
} }
...@@ -237,7 +237,7 @@ namespace NBitcoin ...@@ -237,7 +237,7 @@ namespace NBitcoin
while (true) while (true)
{ {
ChainedHeader b = this.GetBlock(i); ChainedHeader b = GetBlock(i);
if ((b == null) || (b.Previous != prev)) if ((b == null) || (b.Previous != prev))
yield break; yield break;
......
...@@ -28,7 +28,7 @@ namespace NBitcoin ...@@ -28,7 +28,7 @@ namespace NBitcoin
public ConcurrentChain(BlockHeader genesisHeader, Network network = null) // TODO: Remove the null default public ConcurrentChain(BlockHeader genesisHeader, Network network = null) // TODO: Remove the null default
{ {
this.network = network ?? Network.Main; this.network = network ?? Network.Main;
this.SetTip(new ChainedHeader(genesisHeader, genesisHeader.GetHash(), 0)); SetTip(new ChainedHeader(genesisHeader, genesisHeader.GetHash(), 0));
} }
public ConcurrentChain(Network network) public ConcurrentChain(Network network)
...@@ -39,17 +39,17 @@ namespace NBitcoin ...@@ -39,17 +39,17 @@ namespace NBitcoin
public ConcurrentChain(byte[] bytes, Network network = null) // TODO: Remove the null default public ConcurrentChain(byte[] bytes, Network network = null) // TODO: Remove the null default
: this(network ?? Network.Main) : this(network ?? Network.Main)
{ {
this.Load(bytes); Load(bytes);
} }
public void Load(byte[] chain) public void Load(byte[] chain)
{ {
this.Load(new MemoryStream(chain)); Load(new MemoryStream(chain));
} }
public void Load(Stream stream) public void Load(Stream stream)
{ {
this.Load(new BitcoinStream(stream, false)); Load(new BitcoinStream(stream, false));
} }
public void Load(BitcoinStream stream) public void Load(BitcoinStream stream)
...@@ -72,10 +72,10 @@ namespace NBitcoin ...@@ -72,10 +72,10 @@ namespace NBitcoin
this.blocksByHeight.Clear(); this.blocksByHeight.Clear();
this.blocksById.Clear(); this.blocksById.Clear();
this.tip = null; this.tip = null;
this.SetTipLocked(new ChainedHeader(header, header.GetHash(), 0)); SetTipLocked(new ChainedHeader(header, header.GetHash(), 0));
} }
else if (this.tip.HashBlock == header.HashPrevBlock && !(header.IsNull && header.Nonce == 0)) else if (this.tip.HashBlock == header.HashPrevBlock && !(header.IsNull && header.Nonce == 0))
this.SetTipLocked(new ChainedHeader(header, id.Value, this.Tip)); SetTipLocked(new ChainedHeader(header, id.Value, this.Tip));
else else
break; break;
...@@ -90,14 +90,14 @@ namespace NBitcoin ...@@ -90,14 +90,14 @@ namespace NBitcoin
public byte[] ToBytes() public byte[] ToBytes()
{ {
MemoryStream ms = new MemoryStream(); var ms = new MemoryStream();
this.WriteTo(ms); WriteTo(ms);
return ms.ToArray(); return ms.ToArray();
} }
public void WriteTo(Stream stream) public void WriteTo(Stream stream)
{ {
this.WriteTo(new BitcoinStream(stream, true)); WriteTo(new BitcoinStream(stream, true));
} }
public void WriteTo(BitcoinStream stream) public void WriteTo(BitcoinStream stream)
...@@ -117,7 +117,7 @@ namespace NBitcoin ...@@ -117,7 +117,7 @@ namespace NBitcoin
public ConcurrentChain Clone() public ConcurrentChain Clone()
{ {
ConcurrentChain chain = new ConcurrentChain(); var chain = new ConcurrentChain();
chain.network = this.network; chain.network = this.network;
chain.tip = this.tip; chain.tip = this.tip;
using (this.lockObject.LockRead()) using (this.lockObject.LockRead())
...@@ -140,7 +140,7 @@ namespace NBitcoin ...@@ -140,7 +140,7 @@ namespace NBitcoin
{ {
using (this.lockObject.LockWrite()) using (this.lockObject.LockWrite())
{ {
return this.SetTipLocked(block); return SetTipLocked(block);
} }
} }
...@@ -155,7 +155,7 @@ namespace NBitcoin ...@@ -155,7 +155,7 @@ namespace NBitcoin
{ {
if ((this.tip == null) || (block.ChainWork > this.tip.ChainWork)) if ((this.tip == null) || (block.ChainWork > this.tip.ChainWork))
{ {
this.SetTipLocked(block); SetTipLocked(block);
return true; return true;
} }
} }
...@@ -166,14 +166,14 @@ namespace NBitcoin ...@@ -166,14 +166,14 @@ namespace NBitcoin
private ChainedHeader SetTipLocked(ChainedHeader block) private ChainedHeader SetTipLocked(ChainedHeader block)
{ {
int height = this.Tip == null ? -1 : this.Tip.Height; int height = this.Tip == null ? -1 : this.Tip.Height;
foreach (ChainedHeader orphaned in this.EnumerateThisToFork(block)) foreach (ChainedHeader orphaned in EnumerateThisToFork(block))
{ {
this.blocksById.Remove(orphaned.HashBlock); this.blocksById.Remove(orphaned.HashBlock);
this.blocksByHeight.Remove(orphaned.Height); this.blocksByHeight.Remove(orphaned.Height);
height--; height--;
} }
ChainedHeader fork = this.GetBlockLocked(height); ChainedHeader fork = GetBlockLocked(height);
foreach (ChainedHeader newBlock in block.EnumerateToGenesis().TakeWhile(c => c != fork)) foreach (ChainedHeader newBlock in block.EnumerateToGenesis().TakeWhile(c => c != fork))
{ {
this.blocksById.AddOrReplace(newBlock.HashBlock, newBlock); this.blocksById.AddOrReplace(newBlock.HashBlock, newBlock);
...@@ -192,7 +192,7 @@ namespace NBitcoin ...@@ -192,7 +192,7 @@ namespace NBitcoin
ChainedHeader tip = this.tip; ChainedHeader tip = this.tip;
while (true) while (true)
{ {
if (object.ReferenceEquals(null, block) || object.ReferenceEquals(null, tip)) if (ReferenceEquals(null, block) || ReferenceEquals(null, tip))
throw new InvalidOperationException("No fork found between the two chains"); throw new InvalidOperationException("No fork found between the two chains");
if (tip.Height > block.Height) if (tip.Height > block.Height)
...@@ -240,7 +240,7 @@ namespace NBitcoin ...@@ -240,7 +240,7 @@ namespace NBitcoin
{ {
using (this.lockObject.LockRead()) using (this.lockObject.LockRead())
{ {
return this.GetBlockLocked(height); return GetBlockLocked(height);
} }
} }
...@@ -254,7 +254,7 @@ namespace NBitcoin ...@@ -254,7 +254,7 @@ namespace NBitcoin
{ {
using (this.lockObject.LockRead()) using (this.lockObject.LockRead())
{ {
block = this.GetBlockLocked(i); block = GetBlockLocked(i);
if (block == null) if (block == null)
yield break; yield break;
} }
......
...@@ -12,11 +12,11 @@ namespace NBitcoin ...@@ -12,11 +12,11 @@ namespace NBitcoin
{ {
get get
{ {
return _FeePerK; return this._FeePerK;
} }
} }
readonly static FeeRate _Zero = new FeeRate(Money.Zero); private readonly static FeeRate _Zero = new FeeRate(Money.Zero);
public static FeeRate Zero public static FeeRate Zero
{ {
get get
...@@ -31,7 +31,7 @@ namespace NBitcoin ...@@ -31,7 +31,7 @@ namespace NBitcoin
throw new ArgumentNullException("feePerK"); throw new ArgumentNullException("feePerK");
if(feePerK.Satoshi < 0) if(feePerK.Satoshi < 0)
throw new ArgumentOutOfRangeException("feePerK"); throw new ArgumentOutOfRangeException("feePerK");
_FeePerK = feePerK; this._FeePerK = feePerK;
} }
public FeeRate(Money feePaid, int size) public FeeRate(Money feePaid, int size)
...@@ -41,9 +41,9 @@ namespace NBitcoin ...@@ -41,9 +41,9 @@ namespace NBitcoin
if(feePaid.Satoshi < 0) if(feePaid.Satoshi < 0)
throw new ArgumentOutOfRangeException("feePaid"); throw new ArgumentOutOfRangeException("feePaid");
if(size > 0) if(size > 0)
_FeePerK = feePaid * 1000 / size; this._FeePerK = feePaid * 1000 / size;
else else
_FeePerK = 0; this._FeePerK = 0;
} }
/// <summary> /// <summary>
...@@ -53,9 +53,9 @@ namespace NBitcoin ...@@ -53,9 +53,9 @@ namespace NBitcoin
/// <returns></returns> /// <returns></returns>
public Money GetFee(int virtualSize) public Money GetFee(int virtualSize)
{ {
Money nFee = _FeePerK.Satoshi * virtualSize / 1000; Money nFee = this._FeePerK.Satoshi * virtualSize / 1000;
if(nFee == 0 && _FeePerK.Satoshi > 0) if(nFee == 0 && this._FeePerK.Satoshi > 0)
nFee = _FeePerK.Satoshi; nFee = this._FeePerK.Satoshi;
return nFee; return nFee;
} }
public Money GetFee(Transaction tx) public Money GetFee(Transaction tx)
...@@ -65,11 +65,11 @@ namespace NBitcoin ...@@ -65,11 +65,11 @@ namespace NBitcoin
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
if(Object.ReferenceEquals(this, obj)) if(ReferenceEquals(this, obj))
return true; return true;
if(((object)this == null) || (obj == null)) if(((object)this == null) || (obj == null))
return false; return false;
var left = this; FeeRate left = this;
var right = obj as FeeRate; var right = obj as FeeRate;
if(right == null) if(right == null)
return false; return false;
...@@ -78,21 +78,21 @@ namespace NBitcoin ...@@ -78,21 +78,21 @@ namespace NBitcoin
public override string ToString() public override string ToString()
{ {
return String.Format("{0} BTC/kB", _FeePerK.ToString()); return String.Format("{0} BTC/kB", this._FeePerK.ToString());
} }
#region IEquatable<FeeRate> Members #region IEquatable<FeeRate> Members
public bool Equals(FeeRate other) public bool Equals(FeeRate other)
{ {
return other != null && _FeePerK.Equals(other._FeePerK); return other != null && this._FeePerK.Equals(other._FeePerK);
} }
public int CompareTo(FeeRate other) public int CompareTo(FeeRate other)
{ {
return other == null return other == null
? 1 ? 1
: _FeePerK.CompareTo(other._FeePerK); : this._FeePerK.CompareTo(other._FeePerK);
} }
#endregion #endregion
...@@ -105,11 +105,11 @@ namespace NBitcoin ...@@ -105,11 +105,11 @@ namespace NBitcoin
return 1; return 1;
var m = obj as FeeRate; var m = obj as FeeRate;
if (m != null) if (m != null)
return _FeePerK.CompareTo(m._FeePerK); return this._FeePerK.CompareTo(m._FeePerK);
#if !(PORTABLE || NETCORE) #if !NETCORE
return _FeePerK.CompareTo(obj); return _FeePerK.CompareTo(obj);
#else #else
return _FeePerK.CompareTo((long)obj); return this._FeePerK.CompareTo((long)obj);
#endif #endif
} }
...@@ -150,7 +150,7 @@ namespace NBitcoin ...@@ -150,7 +150,7 @@ namespace NBitcoin
public static bool operator ==(FeeRate left, FeeRate right) public static bool operator ==(FeeRate left, FeeRate right)
{ {
if (Object.ReferenceEquals(left, right)) if (ReferenceEquals(left, right))
return true; return true;
if (((object)left == null) || ((object)right == null)) if (((object)left == null) || ((object)right == null))
return false; return false;
...@@ -164,7 +164,7 @@ namespace NBitcoin ...@@ -164,7 +164,7 @@ namespace NBitcoin
public override int GetHashCode() public override int GetHashCode()
{ {
return _FeePerK.GetHashCode(); return this._FeePerK.GetHashCode();
} }
public static FeeRate Min(FeeRate left, FeeRate right) public static FeeRate Min(FeeRate left, FeeRate right)
......
#if !NOFILEIO using System;
using System;
using System.IO; using System.IO;
using System.Threading; using System.Threading;
...@@ -12,12 +11,13 @@ namespace NBitcoin ...@@ -12,12 +11,13 @@ namespace NBitcoin
} }
public class FileLock : IDisposable public class FileLock : IDisposable
{ {
FileStream _Fs = null; private FileStream _Fs = null;
public FileLock(string filePath, FileLockType lockType) public FileLock(string filePath, FileLockType lockType)
{ {
if(filePath == null) if(filePath == null)
throw new ArgumentNullException("filePath"); throw new ArgumentNullException("filePath");
if(!File.Exists(filePath)) if(!File.Exists(filePath))
{
try try
{ {
File.Create(filePath).Dispose(); File.Create(filePath).Dispose();
...@@ -25,16 +25,16 @@ namespace NBitcoin ...@@ -25,16 +25,16 @@ namespace NBitcoin
catch catch
{ {
} }
CancellationTokenSource source = new CancellationTokenSource(); }
var source = new CancellationTokenSource();
source.CancelAfter(20000); source.CancelAfter(20000);
while(true) while(true)
{ {
try try
{ {
if(lockType == FileLockType.Read) if(lockType == FileLockType.Read) this._Fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
_Fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); if(lockType == FileLockType.ReadWrite) this._Fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
if(lockType == FileLockType.ReadWrite)
_Fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
break; break;
} }
catch(IOException) catch(IOException)
...@@ -48,7 +48,7 @@ namespace NBitcoin ...@@ -48,7 +48,7 @@ namespace NBitcoin
public void Dispose() public void Dispose()
{ {
_Fs.Dispose(); this._Fs.Dispose();
} }
...@@ -68,4 +68,3 @@ namespace NBitcoin ...@@ -68,4 +68,3 @@ namespace NBitcoin
//} //}
} }
} }
#endif
\ No newline at end of file
...@@ -6,16 +6,16 @@ namespace NBitcoin ...@@ -6,16 +6,16 @@ namespace NBitcoin
{ {
public class InMemoryNoSqlRepository : NoSqlRepository public class InMemoryNoSqlRepository : NoSqlRepository
{ {
Dictionary<string, byte[]> table = new Dictionary<string, byte[]>(); private readonly Dictionary<string, byte[]> table = new Dictionary<string, byte[]>();
public InMemoryNoSqlRepository(Network network = null) public InMemoryNoSqlRepository(Network network)
:base(network ?? Network.Main) :base(network)
{ {
} }
protected override Task PutBytesBatch(IEnumerable<Tuple<string, byte[]>> enumerable) protected override Task PutBytesBatch(IEnumerable<Tuple<string, byte[]>> enumerable)
{ {
foreach(var data in enumerable) foreach(Tuple<string, byte[]> data in enumerable)
{ {
if(data.Item2 == null) if(data.Item2 == null)
{ {
......
#if !NOSOCKET using System;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
...@@ -8,53 +7,10 @@ namespace NBitcoin ...@@ -8,53 +7,10 @@ namespace NBitcoin
{ {
public static class IpExtensions public static class IpExtensions
{ {
#if WIN
interface ICompatibility
{
IPAddress MapToIPv6(IPAddress address);
bool IsIPv4MappedToIPv6(IPAddress address);
}
class MonoCompatibility : ICompatibility
{
public bool IsIPv4MappedToIPv6(IPAddress address)
{
return Utils.IsIPv4MappedToIPv6(address);
}
public IPAddress MapToIPv6(IPAddress address)
{
return Utils.MapToIPv6(address);
}
}
class WinCompatibility : ICompatibility
{
public bool IsIPv4MappedToIPv6(IPAddress address)
{
return address.IsIPv4MappedToIPv6;
}
public IPAddress MapToIPv6(IPAddress address)
{
return address.MapToIPv6();
}
}
static ICompatibility _Compatibility;
static ICompatibility Compatibility
{
get
{
if(_Compatibility == null)
{
_Compatibility = IsRunningOnMono() ? (ICompatibility)new MonoCompatibility() : new WinCompatibility();
}
return _Compatibility;
}
}
#endif
public static bool IsRFC1918(this IPAddress address) public static bool IsRFC1918(this IPAddress address)
{ {
address = address.EnsureIPv6(); address = address.EnsureIPv6();
var bytes = address.GetAddressBytes(); byte[] bytes = address.GetAddressBytes();
return address.IsIPv4() && ( return address.IsIPv4() && (
bytes[15 - 3] == 10 || bytes[15 - 3] == 10 ||
(bytes[15 - 3] == 192 && bytes[15 - 2] == 168) || (bytes[15 - 3] == 192 && bytes[15 - 2] == 168) ||
...@@ -64,76 +20,76 @@ namespace NBitcoin ...@@ -64,76 +20,76 @@ namespace NBitcoin
public static bool IsIPv4(this IPAddress address) public static bool IsIPv4(this IPAddress address)
{ {
return address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork || address.IsIPv4MappedToIPv6Ex(); return address.AddressFamily == AddressFamily.InterNetwork || address.IsIPv4MappedToIPv6Ex();
} }
public static bool IsRFC3927(this IPAddress address) public static bool IsRFC3927(this IPAddress address)
{ {
address = address.EnsureIPv6(); address = address.EnsureIPv6();
var bytes = address.GetAddressBytes(); byte[] bytes = address.GetAddressBytes();
return address.IsIPv4() && (bytes[15 - 3] == 169 && bytes[15 - 2] == 254); return address.IsIPv4() && (bytes[15 - 3] == 169 && bytes[15 - 2] == 254);
} }
public static bool IsRFC3849(this IPAddress address) public static bool IsRFC3849(this IPAddress address)
{ {
var bytes = address.GetAddressBytes(); byte[] bytes = address.GetAddressBytes();
return bytes[15 - 15] == 0x20 && bytes[15 - 14] == 0x01 && bytes[15 - 13] == 0x0D && bytes[15 - 12] == 0xB8; return bytes[15 - 15] == 0x20 && bytes[15 - 14] == 0x01 && bytes[15 - 13] == 0x0D && bytes[15 - 12] == 0xB8;
} }
public static bool IsRFC3964(this IPAddress address) public static bool IsRFC3964(this IPAddress address)
{ {
var bytes = address.GetAddressBytes(); byte[] bytes = address.GetAddressBytes();
return (bytes[15 - 15] == 0x20 && bytes[15 - 14] == 0x02); return (bytes[15 - 15] == 0x20 && bytes[15 - 14] == 0x02);
} }
public static bool IsRFC6052(this IPAddress address) public static bool IsRFC6052(this IPAddress address)
{ {
var bytes = address.GetAddressBytes(); byte[] bytes = address.GetAddressBytes();
byte[] pchRFC6052 = new byte[] { 0, 0x64, 0xFF, 0x9B, 0, 0, 0, 0, 0, 0, 0, 0 }; var pchRFC6052 = new byte[] { 0, 0x64, 0xFF, 0x9B, 0, 0, 0, 0, 0, 0, 0, 0 };
return ((Utils.ArrayEqual(bytes, 0, pchRFC6052, 0, pchRFC6052.Length) ? 0 : 1) == 0); return ((Utils.ArrayEqual(bytes, 0, pchRFC6052, 0, pchRFC6052.Length) ? 0 : 1) == 0);
} }
public static bool IsRFC4380(this IPAddress address) public static bool IsRFC4380(this IPAddress address)
{ {
var bytes = address.GetAddressBytes(); byte[] bytes = address.GetAddressBytes();
return (bytes[15 - 15] == 0x20 && bytes[15 - 14] == 0x01 && bytes[15 - 13] == 0 && bytes[15 - 12] == 0); return (bytes[15 - 15] == 0x20 && bytes[15 - 14] == 0x01 && bytes[15 - 13] == 0 && bytes[15 - 12] == 0);
} }
public static bool IsRFC4862(this IPAddress address) public static bool IsRFC4862(this IPAddress address)
{ {
var bytes = address.GetAddressBytes(); byte[] bytes = address.GetAddressBytes();
byte[] pchRFC4862 = new byte[] { 0xFE, 0x80, 0, 0, 0, 0, 0, 0 }; var pchRFC4862 = new byte[] { 0xFE, 0x80, 0, 0, 0, 0, 0, 0 };
return ((Utils.ArrayEqual(bytes, 0, pchRFC4862, 0, pchRFC4862.Length) ? 0 : 1) == 0); return ((Utils.ArrayEqual(bytes, 0, pchRFC4862, 0, pchRFC4862.Length) ? 0 : 1) == 0);
} }
public static bool IsRFC4193(this IPAddress address) public static bool IsRFC4193(this IPAddress address)
{ {
var bytes = address.GetAddressBytes(); byte[] bytes = address.GetAddressBytes();
return ((bytes[15 - 15] & 0xFE) == 0xFC); return ((bytes[15 - 15] & 0xFE) == 0xFC);
} }
public static bool IsRFC6145(this IPAddress address) public static bool IsRFC6145(this IPAddress address)
{ {
var bytes = address.GetAddressBytes(); byte[] bytes = address.GetAddressBytes();
byte[] pchRFC6145 = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0, 0 }; var pchRFC6145 = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0, 0 };
return ((Utils.ArrayEqual(bytes, 0, pchRFC6145, 0, pchRFC6145.Length) ? 0 : 1) == 0); return ((Utils.ArrayEqual(bytes, 0, pchRFC6145, 0, pchRFC6145.Length) ? 0 : 1) == 0);
} }
public static bool IsRFC4843(this IPAddress address) public static bool IsRFC4843(this IPAddress address)
{ {
var bytes = address.GetAddressBytes(); byte[] bytes = address.GetAddressBytes();
return (bytes[15 - 15] == 0x20 && bytes[15 - 14] == 0x01 && bytes[15 - 13] == 0x00 && (bytes[15 - 12] & 0xF0) == 0x10); return (bytes[15 - 15] == 0x20 && bytes[15 - 14] == 0x01 && bytes[15 - 13] == 0x00 && (bytes[15 - 12] & 0xF0) == 0x10);
} }
public static byte[] GetGroup(this IPAddress address) public static byte[] GetGroup(this IPAddress address)
{ {
List<byte> vchRet = new List<byte>(); var vchRet = new List<byte>();
int nClass = 2; int nClass = 2;
int nStartByte = 0; int nStartByte = 0;
int nBits = 16; int nBits = 16;
address = address.EnsureIPv6(); address = address.EnsureIPv6();
var bytes = address.GetAddressBytes(); byte[] bytes = address.GetAddressBytes();
// all local addresses belong to the same group // all local addresses belong to the same group
if(address.IsLocal()) if(address.IsLocal())
...@@ -196,10 +152,10 @@ namespace NBitcoin ...@@ -196,10 +152,10 @@ namespace NBitcoin
return vchRet.ToArray(); return vchRet.ToArray();
} }
static byte[] pchOnionCat = new byte[] { 0xFD, 0x87, 0xD8, 0x7E, 0xEB, 0x43 }; private static byte[] pchOnionCat = new byte[] { 0xFD, 0x87, 0xD8, 0x7E, 0xEB, 0x43 };
public static bool IsTor(this IPAddress address) public static bool IsTor(this IPAddress address)
{ {
var bytes = address.GetAddressBytes(); byte[] bytes = address.GetAddressBytes();
return ((Utils.ArrayEqual(bytes, 0, pchOnionCat, 0, pchOnionCat.Length) ? 0 : 1) == 0); return ((Utils.ArrayEqual(bytes, 0, pchOnionCat, 0, pchOnionCat.Length) ? 0 : 1) == 0);
} }
public static IPAddress EnsureIPv6(this IPAddress address) public static IPAddress EnsureIPv6(this IPAddress address)
...@@ -209,7 +165,7 @@ namespace NBitcoin ...@@ -209,7 +165,7 @@ namespace NBitcoin
return address.MapToIPv6Ex(); return address.MapToIPv6Ex();
} }
static bool? _IsRunningOnMono; private static bool? _IsRunningOnMono;
public static bool IsRunningOnMono() public static bool IsRunningOnMono()
{ {
if(_IsRunningOnMono == null) if(_IsRunningOnMono == null)
...@@ -219,32 +175,24 @@ namespace NBitcoin ...@@ -219,32 +175,24 @@ namespace NBitcoin
public static IPAddress MapToIPv6Ex(this IPAddress address) public static IPAddress MapToIPv6Ex(this IPAddress address)
{ {
#if WIN
return Compatibility.MapToIPv6(address);
#else
return Utils.MapToIPv6(address); return Utils.MapToIPv6(address);
#endif
} }
public static bool IsIPv4MappedToIPv6Ex(this IPAddress address) public static bool IsIPv4MappedToIPv6Ex(this IPAddress address)
{ {
#if WIN
return Compatibility.IsIPv4MappedToIPv6(address);
#else
return Utils.IsIPv4MappedToIPv6(address); return Utils.IsIPv4MappedToIPv6(address);
#endif
} }
public static bool IsLocal(this IPAddress address) public static bool IsLocal(this IPAddress address)
{ {
address = address.EnsureIPv6(); address = address.EnsureIPv6();
var bytes = address.GetAddressBytes(); byte[] bytes = address.GetAddressBytes();
// IPv4 loopback // IPv4 loopback
if(address.IsIPv4() && (bytes[15 - 3] == 127 || bytes[15 - 3] == 0)) if(address.IsIPv4() && (bytes[15 - 3] == 127 || bytes[15 - 3] == 0))
return true; return true;
// IPv6 loopback (::1/128) // IPv6 loopback (::1/128)
byte[] pchLocal = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; var pchLocal = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
if((Utils.ArrayEqual(bytes, 0, pchLocal, 0, 16) ? 0 : 1) == 0) if((Utils.ArrayEqual(bytes, 0, pchLocal, 0, 16) ? 0 : 1) == 0)
return true; return true;
...@@ -254,7 +202,7 @@ namespace NBitcoin ...@@ -254,7 +202,7 @@ namespace NBitcoin
public static bool IsMulticast(this IPAddress address) public static bool IsMulticast(this IPAddress address)
{ {
address = address.EnsureIPv6(); address = address.EnsureIPv6();
var bytes = address.GetAddressBytes(); byte[] bytes = address.GetAddressBytes();
return (address.IsIPv4() && (bytes[15 - 3] & 0xF0) == 0xE0) return (address.IsIPv4() && (bytes[15 - 3] & 0xF0) == 0xE0)
|| (bytes[15 - 15] == 0xFF); || (bytes[15 - 15] == 0xFF);
} }
...@@ -277,9 +225,9 @@ namespace NBitcoin ...@@ -277,9 +225,9 @@ namespace NBitcoin
public static bool IsValid(this IPAddress address) public static bool IsValid(this IPAddress address)
{ {
address = address.EnsureIPv6(); address = address.EnsureIPv6();
var ip = address.GetAddressBytes(); byte[] ip = address.GetAddressBytes();
// unspecified IPv6 address (::/128) // unspecified IPv6 address (::/128)
byte[] ipNone = new byte[16]; var ipNone = new byte[16];
if((Utils.ArrayEqual(ip, 0, ipNone, 0, 16) ? 0 : 1) == 0) if((Utils.ArrayEqual(ip, 0, ipNone, 0, 16) ? 0 : 1) == 0)
return false; return false;
...@@ -302,4 +250,3 @@ namespace NBitcoin ...@@ -302,4 +250,3 @@ namespace NBitcoin
} }
} }
} }
#endif
\ No newline at end of file
using System; using System;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using NBitcoin.BouncyCastle.Asn1.X9;
using NBitcoin.BouncyCastle.Math; using NBitcoin.BouncyCastle.Math;
using NBitcoin.Crypto; using NBitcoin.Crypto;
...@@ -21,7 +22,7 @@ namespace NBitcoin ...@@ -21,7 +22,7 @@ namespace NBitcoin
return Network.Parse<BitcoinEncryptedSecret>(wif, network).GetKey(password); return Network.Parse<BitcoinEncryptedSecret>(wif, network).GetKey(password);
} }
byte[] vch = new byte[0]; private byte[] vch = new byte[0];
internal ECKey _ECKey; internal ECKey _ECKey;
public bool IsCompressed public bool IsCompressed
{ {
...@@ -63,9 +64,9 @@ namespace NBitcoin ...@@ -63,9 +64,9 @@ namespace NBitcoin
private void SetBytes(byte[] data, int count, bool fCompressedIn) private void SetBytes(byte[] data, int count, bool fCompressedIn)
{ {
vch = data.SafeSubarray(0, count); this.vch = data.SafeSubarray(0, count);
IsCompressed = fCompressedIn; this.IsCompressed = fCompressedIn;
_ECKey = new ECKey(vch, true); this._ECKey = new ECKey(this.vch, true);
} }
private static bool Check(byte[] vch) private static bool Check(byte[] vch)
...@@ -74,24 +75,24 @@ namespace NBitcoin ...@@ -74,24 +75,24 @@ namespace NBitcoin
return candidateKey > 0 && candidateKey < N; return candidateKey > 0 && candidateKey < N;
} }
PubKey _PubKey; private PubKey _PubKey;
public PubKey PubKey public PubKey PubKey
{ {
get get
{ {
if(_PubKey == null) if(this._PubKey == null)
{ {
ECKey key = new ECKey(vch, true); var key = new ECKey(this.vch, true);
_PubKey = key.GetPubKey(IsCompressed); this._PubKey = key.GetPubKey(this.IsCompressed);
} }
return _PubKey; return this._PubKey;
} }
} }
public ECDSASignature Sign(uint256 hash) public ECDSASignature Sign(uint256 hash)
{ {
return _ECKey.Sign(hash); return this._ECKey.Sign(hash);
} }
...@@ -102,20 +103,20 @@ namespace NBitcoin ...@@ -102,20 +103,20 @@ namespace NBitcoin
public string SignMessage(byte[] messageBytes) public string SignMessage(byte[] messageBytes)
{ {
byte[] data = Utils.FormatMessageForSigning(messageBytes); byte[] data = Utils.FormatMessageForSigning(messageBytes);
var hash = Hashes.Hash256(data); uint256 hash = Hashes.Hash256(data);
return Convert.ToBase64String(SignCompact(hash)); return Convert.ToBase64String(SignCompact(hash));
} }
public byte[] SignCompact(uint256 hash) public byte[] SignCompact(uint256 hash)
{ {
var sig = _ECKey.Sign(hash); ECDSASignature sig = this._ECKey.Sign(hash);
// Now we have to work backwards to figure out the recId needed to recover the signature. // Now we have to work backwards to figure out the recId needed to recover the signature.
int recId = -1; int recId = -1;
for(int i = 0; i < 4; i++) for(int i = 0; i < 4; i++)
{ {
ECKey k = ECKey.RecoverFromSignature(i, sig, hash, IsCompressed); ECKey k = ECKey.RecoverFromSignature(i, sig, hash, this.IsCompressed);
if(k != null && k.GetPubKey(IsCompressed).ToHex() == PubKey.ToHex()) if(k != null && k.GetPubKey(this.IsCompressed).ToHex() == this.PubKey.ToHex())
{ {
recId = i; recId = i;
break; break;
...@@ -125,9 +126,9 @@ namespace NBitcoin ...@@ -125,9 +126,9 @@ namespace NBitcoin
if(recId == -1) if(recId == -1)
throw new InvalidOperationException("Could not construct a recoverable key. This should never happen."); throw new InvalidOperationException("Could not construct a recoverable key. This should never happen.");
int headerByte = recId + 27 + (IsCompressed ? 4 : 0); int headerByte = recId + 27 + (this.IsCompressed ? 4 : 0);
byte[] sigData = new byte[65]; // 1 header + 32 bytes for R + 32 bytes for S var sigData = new byte[65]; // 1 header + 32 bytes for R + 32 bytes for S
sigData[0] = (byte)headerByte; sigData[0] = (byte)headerByte;
...@@ -140,10 +141,10 @@ namespace NBitcoin ...@@ -140,10 +141,10 @@ namespace NBitcoin
public void ReadWrite(BitcoinStream stream) public void ReadWrite(BitcoinStream stream)
{ {
stream.ReadWrite(ref vch); stream.ReadWrite(ref this.vch);
if(!stream.Serializing) if(!stream.Serializing)
{ {
_ECKey = new ECKey(vch, true); this._ECKey = new ECKey(this.vch, true);
} }
} }
...@@ -154,29 +155,29 @@ namespace NBitcoin ...@@ -154,29 +155,29 @@ namespace NBitcoin
byte[] l = null; byte[] l = null;
if((nChild >> 31) == 0) if((nChild >> 31) == 0)
{ {
var pubKey = PubKey.ToBytes(); byte[] pubKey = this.PubKey.ToBytes();
l = Hashes.BIP32Hash(cc, nChild, pubKey[0], pubKey.SafeSubarray(1)); l = Hashes.BIP32Hash(cc, nChild, pubKey[0], pubKey.SafeSubarray(1));
} }
else else
{ {
l = Hashes.BIP32Hash(cc, nChild, 0, this.ToBytes()); l = Hashes.BIP32Hash(cc, nChild, 0, this.ToBytes());
} }
var ll = l.SafeSubarray(0, 32); byte[] ll = l.SafeSubarray(0, 32);
var lr = l.SafeSubarray(32, 32); byte[] lr = l.SafeSubarray(32, 32);
ccChild = lr; ccChild = lr;
var parse256LL = new BigInteger(1, ll); var parse256LL = new BigInteger(1, ll);
var kPar = new BigInteger(1, vch); var kPar = new BigInteger(1, this.vch);
var N = ECKey.CURVE.N; BigInteger N = ECKey.CURVE.N;
if(parse256LL.CompareTo(N) >= 0) if(parse256LL.CompareTo(N) >= 0)
throw new InvalidOperationException("You won a prize ! this should happen very rarely. Take a screenshot, and roll the dice again."); throw new InvalidOperationException("You won a prize ! this should happen very rarely. Take a screenshot, and roll the dice again.");
var key = parse256LL.Add(kPar).Mod(N); BigInteger key = parse256LL.Add(kPar).Mod(N);
if(key == BigInteger.Zero) if(key == BigInteger.Zero)
throw new InvalidOperationException("You won the big prize ! this has probability lower than 1 in 2^127. Take a screenshot, and roll the dice again."); throw new InvalidOperationException("You won the big prize ! this has probability lower than 1 in 2^127. Take a screenshot, and roll the dice again.");
var keyBytes = key.ToByteArrayUnsigned(); byte[] keyBytes = key.ToByteArrayUnsigned();
if(keyBytes.Length < 32) if(keyBytes.Length < 32)
keyBytes = new byte[32 - keyBytes.Length].Concat(keyBytes).ToArray(); keyBytes = new byte[32 - keyBytes.Length].Concat(keyBytes).ToArray();
return new Key(keyBytes); return new Key(keyBytes);
...@@ -184,8 +185,8 @@ namespace NBitcoin ...@@ -184,8 +185,8 @@ namespace NBitcoin
public Key Uncover(Key scan, PubKey ephem) public Key Uncover(Key scan, PubKey ephem)
{ {
var curve = ECKey.Secp256k1; X9ECParameters curve = ECKey.Secp256k1;
var priv = new BigInteger(1, PubKey.GetStealthSharedSecret(scan, ephem)) byte[] priv = new BigInteger(1, PubKey.GetStealthSharedSecret(scan, ephem))
.Add(new BigInteger(1, this.ToBytes())) .Add(new BigInteger(1, this.ToBytes()))
.Mod(curve.N) .Mod(curve.N)
.ToByteArrayUnsigned(); .ToByteArrayUnsigned();
...@@ -228,7 +229,7 @@ namespace NBitcoin ...@@ -228,7 +229,7 @@ namespace NBitcoin
{ {
get get
{ {
return PubKey.Hash.ScriptPubKey; return this.PubKey.Hash.ScriptPubKey;
} }
} }
...@@ -242,14 +243,14 @@ namespace NBitcoin ...@@ -242,14 +243,14 @@ namespace NBitcoin
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
Key item = obj as Key; var item = obj as Key;
if(item == null) if(item == null)
return false; return false;
return PubKey.Equals(item.PubKey); return this.PubKey.Equals(item.PubKey);
} }
public static bool operator ==(Key a, Key b) public static bool operator ==(Key a, Key b)
{ {
if(System.Object.ReferenceEquals(a, b)) if(ReferenceEquals(a, b))
return true; return true;
if(((object)a == null) || ((object)b == null)) if(((object)a == null) || ((object)b == null))
return false; return false;
...@@ -263,7 +264,7 @@ namespace NBitcoin ...@@ -263,7 +264,7 @@ namespace NBitcoin
public override int GetHashCode() public override int GetHashCode()
{ {
return PubKey.GetHashCode(); return this.PubKey.GetHashCode();
} }
} }
} }
...@@ -10,20 +10,20 @@ namespace NBitcoin ...@@ -10,20 +10,20 @@ namespace NBitcoin
public TxDestination() public TxDestination()
{ {
_DestBytes = new byte[] { 0 }; this._DestBytes = new byte[] { 0 };
} }
public TxDestination(byte[] value) public TxDestination(byte[] value)
{ {
if(value == null) if(value == null)
throw new ArgumentNullException("value"); throw new ArgumentNullException("value");
_DestBytes = value; this._DestBytes = value;
} }
public TxDestination(string value) public TxDestination(string value)
{ {
_DestBytes = Encoders.Hex.DecodeData(value); this._DestBytes = Encoders.Hex.DecodeData(value);
_Str = value; this._Str = value;
} }
public abstract BitcoinAddress GetAddress(Network network); public abstract BitcoinAddress GetAddress(Network network);
...@@ -45,22 +45,22 @@ namespace NBitcoin ...@@ -45,22 +45,22 @@ namespace NBitcoin
public byte[] ToBytes(bool @unsafe) public byte[] ToBytes(bool @unsafe)
{ {
if(@unsafe) if(@unsafe)
return _DestBytes; return this._DestBytes;
var array = new byte[_DestBytes.Length]; var array = new byte[this._DestBytes.Length];
Array.Copy(_DestBytes, array, _DestBytes.Length); Array.Copy(this._DestBytes, array, this._DestBytes.Length);
return array; return array;
} }
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
TxDestination item = obj as TxDestination; var item = obj as TxDestination;
if(item == null) if(item == null)
return false; return false;
return Utils.ArrayEqual(_DestBytes, item._DestBytes) && item.GetType() == this.GetType(); return Utils.ArrayEqual(this._DestBytes, item._DestBytes) && item.GetType() == GetType();
} }
public static bool operator ==(TxDestination a, TxDestination b) public static bool operator ==(TxDestination a, TxDestination b)
{ {
if(System.Object.ReferenceEquals(a, b)) if(ReferenceEquals(a, b))
return true; return true;
if(((object)a == null) || ((object)b == null)) if(((object)a == null) || ((object)b == null))
return false; return false;
...@@ -74,15 +74,14 @@ namespace NBitcoin ...@@ -74,15 +74,14 @@ namespace NBitcoin
public override int GetHashCode() public override int GetHashCode()
{ {
return Utils.GetHashCode(_DestBytes); return Utils.GetHashCode(this._DestBytes);
} }
string _Str; private string _Str;
public override string ToString() public override string ToString()
{ {
if(_Str == null) if(this._Str == null) this._Str = Encoders.Hex.EncodeData(this._DestBytes);
_Str = Encoders.Hex.EncodeData(_DestBytes); return this._Str;
return _Str;
} }
} }
public class KeyId : TxDestination public class KeyId : TxDestination
...@@ -159,7 +158,7 @@ namespace NBitcoin ...@@ -159,7 +158,7 @@ namespace NBitcoin
{ {
get get
{ {
return PayToWitTemplate.Instance.GenerateScriptPubKey(OpcodeType.OP_0, _DestBytes); return PayToWitTemplate.Instance.GenerateScriptPubKey(OpcodeType.OP_0, this._DestBytes);
} }
} }
...@@ -168,7 +167,7 @@ namespace NBitcoin ...@@ -168,7 +167,7 @@ namespace NBitcoin
{ {
get get
{ {
return new KeyId(_DestBytes).ScriptPubKey; return new KeyId(this._DestBytes).ScriptPubKey;
} }
} }
...@@ -217,7 +216,7 @@ namespace NBitcoin ...@@ -217,7 +216,7 @@ namespace NBitcoin
{ {
get get
{ {
return PayToWitTemplate.Instance.GenerateScriptPubKey(OpcodeType.OP_0, _DestBytes); return PayToWitTemplate.Instance.GenerateScriptPubKey(OpcodeType.OP_0, this._DestBytes);
} }
} }
......
...@@ -5,7 +5,7 @@ namespace NBitcoin ...@@ -5,7 +5,7 @@ namespace NBitcoin
public struct LockTime : IBitcoinSerializable public struct LockTime : IBitcoinSerializable
{ {
internal const uint LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC internal const uint LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
uint _value; private uint _value;
public static LockTime Zero public static LockTime Zero
{ {
...@@ -16,17 +16,17 @@ namespace NBitcoin ...@@ -16,17 +16,17 @@ namespace NBitcoin
} }
public LockTime(DateTimeOffset dateTime) public LockTime(DateTimeOffset dateTime)
{ {
_value = Utils.DateTimeToUnixTime(dateTime); this._value = Utils.DateTimeToUnixTime(dateTime);
if(_value < LOCKTIME_THRESHOLD) if(this._value < LOCKTIME_THRESHOLD)
throw new ArgumentOutOfRangeException("dateTime", "The minimum possible date is be Tue Nov 5 00:53:20 1985 UTC"); throw new ArgumentOutOfRangeException("dateTime", "The minimum possible date is be Tue Nov 5 00:53:20 1985 UTC");
} }
public LockTime(int valueOrHeight) public LockTime(int valueOrHeight)
{ {
_value = (uint)valueOrHeight; this._value = (uint)valueOrHeight;
} }
public LockTime(uint valueOrHeight) public LockTime(uint valueOrHeight)
{ {
_value = valueOrHeight; this._value = valueOrHeight;
} }
...@@ -34,9 +34,9 @@ namespace NBitcoin ...@@ -34,9 +34,9 @@ namespace NBitcoin
{ {
get get
{ {
if(!IsTimeLock) if(!this.IsTimeLock)
throw new InvalidOperationException("This is not a time based lock"); throw new InvalidOperationException("This is not a time based lock");
return Utils.UnixTimeToDateTime(_value); return Utils.UnixTimeToDateTime(this._value);
} }
} }
...@@ -44,9 +44,9 @@ namespace NBitcoin ...@@ -44,9 +44,9 @@ namespace NBitcoin
{ {
get get
{ {
if(!IsHeightLock) if(!this.IsHeightLock)
throw new InvalidOperationException("This is not a height based lock"); throw new InvalidOperationException("This is not a height based lock");
return (int)_value; return (int) this._value;
} }
} }
...@@ -54,7 +54,7 @@ namespace NBitcoin ...@@ -54,7 +54,7 @@ namespace NBitcoin
{ {
get get
{ {
return _value; return this._value;
} }
} }
...@@ -63,7 +63,7 @@ namespace NBitcoin ...@@ -63,7 +63,7 @@ namespace NBitcoin
{ {
get get
{ {
return _value < LOCKTIME_THRESHOLD; // Tue Nov 5 00:53:20 1985 UTC return this._value < LOCKTIME_THRESHOLD; // Tue Nov 5 00:53:20 1985 UTC
} }
} }
...@@ -71,7 +71,7 @@ namespace NBitcoin ...@@ -71,7 +71,7 @@ namespace NBitcoin
{ {
get get
{ {
return !IsHeightLock; return !this.IsHeightLock;
} }
} }
...@@ -80,14 +80,14 @@ namespace NBitcoin ...@@ -80,14 +80,14 @@ namespace NBitcoin
public void ReadWrite(BitcoinStream stream) public void ReadWrite(BitcoinStream stream)
{ {
stream.ReadWrite(ref _value); stream.ReadWrite(ref this._value);
} }
#endregion #endregion
public override string ToString() public override string ToString()
{ {
return IsHeightLock ? "Height : " + Height : "Date : " + Date; return this.IsHeightLock ? "Height : " + this.Height : "Date : " + this.Date;
} }
public static implicit operator LockTime(int valueOrHeight) public static implicit operator LockTime(int valueOrHeight)
...@@ -129,7 +129,7 @@ namespace NBitcoin ...@@ -129,7 +129,7 @@ namespace NBitcoin
if(!(obj is LockTime)) if(!(obj is LockTime))
return false; return false;
var item = (LockTime)obj; var item = (LockTime)obj;
return _value.Equals(item._value); return this._value.Equals(item._value);
} }
public static bool operator ==(LockTime a, LockTime b) public static bool operator ==(LockTime a, LockTime b)
{ {
...@@ -143,7 +143,7 @@ namespace NBitcoin ...@@ -143,7 +143,7 @@ namespace NBitcoin
public override int GetHashCode() public override int GetHashCode()
{ {
return _value.GetHashCode(); return this._value.GetHashCode();
} }
} }
} }
...@@ -10,30 +10,31 @@ namespace NBitcoin ...@@ -10,30 +10,31 @@ namespace NBitcoin
} }
// Public only for unit testing // Public only for unit testing
BlockHeader header; private BlockHeader header;
public BlockHeader Header public BlockHeader Header
{ {
get get
{ {
return header; return this.header;
} }
set set
{ {
header = value; this.header = value;
} }
} }
PartialMerkleTree _PartialMerkleTree;
private PartialMerkleTree _PartialMerkleTree;
public PartialMerkleTree PartialMerkleTree public PartialMerkleTree PartialMerkleTree
{ {
get get
{ {
return _PartialMerkleTree; return this._PartialMerkleTree;
} }
set set
{ {
_PartialMerkleTree = value; this._PartialMerkleTree = value;
} }
} }
...@@ -42,10 +43,10 @@ namespace NBitcoin ...@@ -42,10 +43,10 @@ namespace NBitcoin
// thus the filter will likely be modified. // thus the filter will likely be modified.
public MerkleBlock(Block block, BloomFilter filter) public MerkleBlock(Block block, BloomFilter filter)
{ {
header = block.Header; this.header = block.Header;
List<bool> vMatch = new List<bool>(); var vMatch = new List<bool>();
List<uint256> vHashes = new List<uint256>(); var vHashes = new List<uint256>();
for(uint i = 0; i < block.Transactions.Count; i++) for(uint i = 0; i < block.Transactions.Count; i++)
...@@ -55,30 +56,31 @@ namespace NBitcoin ...@@ -55,30 +56,31 @@ namespace NBitcoin
vHashes.Add(hash); vHashes.Add(hash);
} }
_PartialMerkleTree = new PartialMerkleTree(vHashes.ToArray(), vMatch.ToArray()); this._PartialMerkleTree = new PartialMerkleTree(vHashes.ToArray(), vMatch.ToArray());
} }
public MerkleBlock(Block block, uint256[] txIds) public MerkleBlock(Block block, uint256[] txIds)
{ {
header = block.Header; this.header = block.Header;
List<bool> vMatch = new List<bool>(); var vMatch = new List<bool>();
List<uint256> vHashes = new List<uint256>(); var vHashes = new List<uint256>();
for(int i = 0; i < block.Transactions.Count; i++) for(int i = 0; i < block.Transactions.Count; i++)
{ {
var hash = block.Transactions[i].GetHash(); uint256 hash = block.Transactions[i].GetHash();
vHashes.Add(hash); vHashes.Add(hash);
vMatch.Add(txIds.Contains(hash)); vMatch.Add(txIds.Contains(hash));
} }
_PartialMerkleTree = new PartialMerkleTree(vHashes.ToArray(), vMatch.ToArray());
this._PartialMerkleTree = new PartialMerkleTree(vHashes.ToArray(), vMatch.ToArray());
} }
#region IBitcoinSerializable Members #region IBitcoinSerializable Members
public void ReadWrite(BitcoinStream stream) public void ReadWrite(BitcoinStream stream)
{ {
stream.ReadWrite(ref header); stream.ReadWrite(ref this.header);
stream.ReadWrite(ref _PartialMerkleTree); stream.ReadWrite(ref this._PartialMerkleTree);
} }
#endregion #endregion
......
...@@ -10,7 +10,7 @@ namespace NBitcoin ...@@ -10,7 +10,7 @@ namespace NBitcoin
{ {
public static MerkleNode GetRoot(IEnumerable<uint256> leafs) public static MerkleNode GetRoot(IEnumerable<uint256> leafs)
{ {
var row = leafs.Select(l => new MerkleNode(l)).ToList(); List<MerkleNode> row = leafs.Select(l => new MerkleNode(l)).ToList();
if(row.Count == 0) if(row.Count == 0)
return new MerkleNode(uint256.Zero); return new MerkleNode(uint256.Zero);
while(row.Count != 1) while(row.Count != 1)
...@@ -18,8 +18,8 @@ namespace NBitcoin ...@@ -18,8 +18,8 @@ namespace NBitcoin
var parentRow = new List<MerkleNode>(); var parentRow = new List<MerkleNode>();
for(int i = 0; i < row.Count; i += 2) for(int i = 0; i < row.Count; i += 2)
{ {
var left = row[i]; MerkleNode left = row[i];
var right = i + 1 < row.Count ? row[i + 1] : null; MerkleNode right = i + 1 < row.Count ? row[i + 1] : null;
var parent = new MerkleNode(left, right); var parent = new MerkleNode(left, right);
parentRow.Add(parent); parentRow.Add(parent);
} }
...@@ -37,14 +37,14 @@ namespace NBitcoin ...@@ -37,14 +37,14 @@ namespace NBitcoin
public MerkleNode(uint256 hash) public MerkleNode(uint256 hash)
{ {
_Hash = hash; this._Hash = hash;
IsLeaf = true; this.IsLeaf = true;
} }
public MerkleNode(MerkleNode left, MerkleNode right) public MerkleNode(MerkleNode left, MerkleNode right)
{ {
Left = left; this.Left = left;
Right = right; this.Right = right;
if(left != null) if(left != null)
left.Parent = this; left.Parent = this;
if(right != null) if(right != null)
...@@ -56,19 +56,18 @@ namespace NBitcoin ...@@ -56,19 +56,18 @@ namespace NBitcoin
{ {
get get
{ {
return _Hash; return this._Hash;
} }
set set
{ {
_Hash = value; this._Hash = value;
} }
} }
public void UpdateHash() public void UpdateHash()
{ {
var right = Right ?? Left; MerkleNode right = this.Right ?? this.Left;
if(Left != null && Left.Hash != null && right.Hash != null) if(this.Left != null && this.Left.Hash != null && right.Hash != null) this._Hash = Hashes.Hash256(this.Left.Hash.ToBytes().Concat(right.Hash.ToBytes()).ToArray());
_Hash = Hashes.Hash256(Left.Hash.ToBytes().Concat(right.Hash.ToBytes()).ToArray());
} }
public bool IsLeaf public bool IsLeaf
...@@ -76,7 +75,8 @@ namespace NBitcoin ...@@ -76,7 +75,8 @@ namespace NBitcoin
get; get;
private set; private set;
} }
uint256 _Hash;
private uint256 _Hash;
public MerkleNode Parent public MerkleNode Parent
{ {
get; get;
...@@ -96,10 +96,10 @@ namespace NBitcoin ...@@ -96,10 +96,10 @@ namespace NBitcoin
public IEnumerable<MerkleNode> EnumerateDescendants() public IEnumerable<MerkleNode> EnumerateDescendants()
{ {
IEnumerable<MerkleNode> result = new MerkleNode[] { this }; IEnumerable<MerkleNode> result = new MerkleNode[] { this };
if(Right != null) if(this.Right != null)
result = Right.EnumerateDescendants().Concat(result); result = this.Right.EnumerateDescendants().Concat(result);
if(Left != null) if(this.Left != null)
result = Left.EnumerateDescendants().Concat(result); result = this.Left.EnumerateDescendants().Concat(result);
return result; return result;
} }
...@@ -121,7 +121,7 @@ namespace NBitcoin ...@@ -121,7 +121,7 @@ namespace NBitcoin
public IEnumerable<MerkleNode> Ancestors() public IEnumerable<MerkleNode> Ancestors()
{ {
var n = Parent; MerkleNode n = this.Parent;
while(n != null) while(n != null)
{ {
yield return n; yield return n;
...@@ -131,27 +131,25 @@ namespace NBitcoin ...@@ -131,27 +131,25 @@ namespace NBitcoin
public override string ToString() public override string ToString()
{ {
return Hash == null ? "???" : Hash.ToString(); return this.Hash == null ? "???" : this.Hash.ToString();
} }
public string ToString(bool hierachy) public string ToString(bool hierachy)
{ {
if(!hierachy) if(!hierachy)
return ToString(); return ToString();
StringBuilder builder = new StringBuilder(); var builder = new StringBuilder();
ToString(builder, 0); ToString(builder, 0);
return builder.ToString(); return builder.ToString();
} }
private void ToString(StringBuilder builder, int indent) private void ToString(StringBuilder builder, int indent)
{ {
var tabs = new String(Enumerable.Range(0, indent).Select(_ => '\t').ToArray()); string tabs = new String(Enumerable.Range(0, indent).Select(_ => '\t').ToArray());
builder.Append(tabs); builder.Append(tabs);
builder.AppendLine(ToString()); builder.AppendLine(ToString());
if(Left != null) if(this.Left != null) this.Left.ToString(builder, indent + 1);
Left.ToString(builder, indent + 1); if(this.Right != null) this.Right.ToString(builder, indent + 1);
if(Right != null)
Right.ToString(builder, indent + 1);
} }
} }
} }
This diff is collapsed.
...@@ -5,31 +5,21 @@ namespace NBitcoin ...@@ -5,31 +5,21 @@ namespace NBitcoin
{ {
public class NoSqlTransactionRepository : ITransactionRepository public class NoSqlTransactionRepository : ITransactionRepository
{ {
private readonly NoSqlRepository repository; public NoSqlRepository Repository { get; }
public NoSqlRepository Repository
{
get
{
return this.repository;
}
}
public NoSqlTransactionRepository(Network network = null) public NoSqlTransactionRepository(Network network)
:this(new InMemoryNoSqlRepository(network)) :this(new InMemoryNoSqlRepository(network))
{ {
} }
public NoSqlTransactionRepository(NoSqlRepository repository) public NoSqlTransactionRepository(NoSqlRepository repository)
{ {
if(repository == null) this.Repository = repository ?? throw new ArgumentNullException("repository");
throw new ArgumentNullException("repository");
this.repository = repository;
} }
#region ITransactionRepository Members
public Task<Transaction> GetAsync(uint256 txId) public Task<Transaction> GetAsync(uint256 txId)
{ {
return this.repository.GetAsync<Transaction>(GetId(txId)); return this.Repository.GetAsync<Transaction>(GetId(txId));
} }
private string GetId(uint256 txId) private string GetId(uint256 txId)
...@@ -39,9 +29,7 @@ namespace NBitcoin ...@@ -39,9 +29,7 @@ namespace NBitcoin
public Task PutAsync(uint256 txId, Transaction tx) public Task PutAsync(uint256 txId, Transaction tx)
{ {
return this.repository.PutAsync(GetId(txId), tx); return this.Repository.PutAsync(GetId(txId), tx);
} }
#endregion
} }
} }
\ No newline at end of file
...@@ -11,38 +11,39 @@ namespace NBitcoin ...@@ -11,38 +11,39 @@ namespace NBitcoin
{ {
} }
uint _TransactionCount;
private uint _TransactionCount;
public uint TransactionCount public uint TransactionCount
{ {
get get
{ {
return _TransactionCount; return this._TransactionCount;
} }
set set
{ {
_TransactionCount = value; this._TransactionCount = value;
} }
} }
List<uint256> _Hashes = new List<uint256>(); private List<uint256> _Hashes = new List<uint256>();
public List<uint256> Hashes public List<uint256> Hashes
{ {
get get
{ {
return _Hashes; return this._Hashes;
} }
} }
BitArray _Flags = new BitArray(0); private BitArray _Flags = new BitArray(0);
public BitArray Flags public BitArray Flags
{ {
get get
{ {
return _Flags; return this._Flags;
} }
set set
{ {
_Flags = value; this._Flags = value;
} }
} }
...@@ -51,22 +52,22 @@ namespace NBitcoin ...@@ -51,22 +52,22 @@ namespace NBitcoin
public void ReadWrite(BitcoinStream stream) public void ReadWrite(BitcoinStream stream)
{ {
stream.ReadWrite(ref _TransactionCount); stream.ReadWrite(ref this._TransactionCount);
stream.ReadWrite(ref _Hashes); stream.ReadWrite(ref this._Hashes);
byte[] vBytes = null; byte[] vBytes = null;
if(!stream.Serializing) if(!stream.Serializing)
{ {
stream.ReadWriteAsVarString(ref vBytes); stream.ReadWriteAsVarString(ref vBytes);
BitWriter writer = new BitWriter(); var writer = new BitWriter();
for(int p = 0; p < vBytes.Length * 8; p++) for(int p = 0; p < vBytes.Length * 8; p++)
writer.Write((vBytes[p / 8] & (1 << (p % 8))) != 0); writer.Write((vBytes[p / 8] & (1 << (p % 8))) != 0);
_Flags = writer.ToBitArray(); this._Flags = writer.ToBitArray();
} }
else else
{ {
vBytes = new byte[(_Flags.Length + 7) / 8]; vBytes = new byte[(this._Flags.Length + 7) / 8];
for(int p = 0; p < _Flags.Length; p++) for(int p = 0; p < this._Flags.Length; p++)
vBytes[p / 8] |= (byte)(ToByte(_Flags.Get(p)) << (p % 8)); vBytes[p / 8] |= (byte)(ToByte(this._Flags.Get(p)) << (p % 8));
stream.ReadWriteAsVarString(ref vBytes); stream.ReadWriteAsVarString(ref vBytes);
} }
} }
...@@ -82,21 +83,21 @@ namespace NBitcoin ...@@ -82,21 +83,21 @@ namespace NBitcoin
{ {
if(vMatch.Length != vTxid.Length) if(vMatch.Length != vTxid.Length)
throw new ArgumentException("The size of the array of txid and matches is different"); throw new ArgumentException("The size of the array of txid and matches is different");
TransactionCount = (uint)vTxid.Length; this.TransactionCount = (uint)vTxid.Length;
MerkleNode root = MerkleNode.GetRoot(vTxid); MerkleNode root = MerkleNode.GetRoot(vTxid);
BitWriter flags = new BitWriter(); var flags = new BitWriter();
MarkNodes(root, vMatch); MarkNodes(root, vMatch);
BuildCore(root, flags); BuildCore(root, flags);
Flags = flags.ToBitArray(); this.Flags = flags.ToBitArray();
} }
private static void MarkNodes(MerkleNode root, bool[] vMatch) private static void MarkNodes(MerkleNode root, bool[] vMatch)
{ {
BitReader matches = new BitReader(new BitArray(vMatch)); var matches = new BitReader(new BitArray(vMatch));
foreach(var leaf in root.GetLeafs()) foreach(MerkleNode leaf in root.GetLeafs())
{ {
if(matches.Read()) if(matches.Read())
{ {
...@@ -108,7 +109,7 @@ namespace NBitcoin ...@@ -108,7 +109,7 @@ namespace NBitcoin
private static void MarkToTop(MerkleNode leaf, bool value) private static void MarkToTop(MerkleNode leaf, bool value)
{ {
leaf.IsMarked = value; leaf.IsMarked = value;
foreach(var ancestor in leaf.Ancestors()) foreach(MerkleNode ancestor in leaf.Ancestors())
{ {
ancestor.IsMarked = value; ancestor.IsMarked = value;
} }
...@@ -116,9 +117,9 @@ namespace NBitcoin ...@@ -116,9 +117,9 @@ namespace NBitcoin
public MerkleNode GetMerkleRoot() public MerkleNode GetMerkleRoot()
{ {
MerkleNode node = MerkleNode.GetRoot((int)TransactionCount); MerkleNode node = MerkleNode.GetRoot((int) this.TransactionCount);
BitReader flags = new BitReader(Flags); var flags = new BitReader(this.Flags);
var hashes = Hashes.GetEnumerator(); List<uint256>.Enumerator hashes = this.Hashes.GetEnumerator();
GetMatchedTransactionsCore(node, flags, hashes, true).AsEnumerable(); GetMatchedTransactionsCore(node, flags, hashes, true).AsEnumerable();
return node; return node;
} }
...@@ -126,7 +127,7 @@ namespace NBitcoin ...@@ -126,7 +127,7 @@ namespace NBitcoin
{ {
try try
{ {
var hash = GetMerkleRoot().Hash; uint256 hash = GetMerkleRoot().Hash;
return expectedMerkleRootHash == null || hash == expectedMerkleRootHash; return expectedMerkleRootHash == null || hash == expectedMerkleRootHash;
} }
catch(Exception) catch(Exception)
...@@ -142,8 +143,7 @@ namespace NBitcoin ...@@ -142,8 +143,7 @@ namespace NBitcoin
if(node == null) if(node == null)
return; return;
flags.Write(node.IsMarked); flags.Write(node.IsMarked);
if(node.IsLeaf || !node.IsMarked) if(node.IsLeaf || !node.IsMarked) this.Hashes.Add(node.Hash);
Hashes.Add(node.Hash);
if(node.IsMarked) if(node.IsMarked)
{ {
...@@ -154,9 +154,9 @@ namespace NBitcoin ...@@ -154,9 +154,9 @@ namespace NBitcoin
public IEnumerable<uint256> GetMatchedTransactions() public IEnumerable<uint256> GetMatchedTransactions()
{ {
BitReader flags = new BitReader(Flags); var flags = new BitReader(this.Flags);
MerkleNode root = MerkleNode.GetRoot((int)TransactionCount); MerkleNode root = MerkleNode.GetRoot((int) this.TransactionCount);
var hashes = Hashes.GetEnumerator(); List<uint256>.Enumerator hashes = this.Hashes.GetEnumerator();
return GetMatchedTransactionsCore(root, flags, hashes, false); return GetMatchedTransactionsCore(root, flags, hashes, false);
} }
...@@ -175,8 +175,8 @@ namespace NBitcoin ...@@ -175,8 +175,8 @@ namespace NBitcoin
return new uint256[0]; return new uint256[0];
if(node.IsLeaf) if(node.IsLeaf)
return new uint256[] { node.Hash }; return new uint256[] { node.Hash };
var left = GetMatchedTransactionsCore(node.Left, flags, hashes, calculateHash); IEnumerable<uint256> left = GetMatchedTransactionsCore(node.Left, flags, hashes, calculateHash);
var right = GetMatchedTransactionsCore(node.Right, flags, hashes, calculateHash); IEnumerable<uint256> right = GetMatchedTransactionsCore(node.Right, flags, hashes, calculateHash);
if(calculateHash) if(calculateHash)
node.UpdateHash(); node.UpdateHash();
return left.Concat(right); return left.Concat(right);
...@@ -201,15 +201,15 @@ namespace NBitcoin ...@@ -201,15 +201,15 @@ namespace NBitcoin
/// <returns></returns> /// <returns></returns>
public PartialMerkleTree Trim(params uint256[] matchedTransactions) public PartialMerkleTree Trim(params uint256[] matchedTransactions)
{ {
PartialMerkleTree trimmed = new PartialMerkleTree(); var trimmed = new PartialMerkleTree();
trimmed.TransactionCount = TransactionCount; trimmed.TransactionCount = this.TransactionCount;
var root = GetMerkleRoot(); MerkleNode root = GetMerkleRoot();
foreach(var leaf in root.GetLeafs()) foreach(MerkleNode leaf in root.GetLeafs())
{ {
MarkToTop(leaf, false); MarkToTop(leaf, false);
} }
BitWriter flags = new BitWriter(); var flags = new BitWriter();
foreach(var leaf in root.GetLeafs().Where(l => matchedTransactions.Contains(l.Hash))) foreach(MerkleNode leaf in root.GetLeafs().Where(l => matchedTransactions.Contains(l.Hash)))
{ {
MarkToTop(leaf, true); MarkToTop(leaf, true);
} }
......
...@@ -4,9 +4,9 @@ ...@@ -4,9 +4,9 @@
{ {
public PrecomputedTransactionData(Transaction tx) public PrecomputedTransactionData(Transaction tx)
{ {
HashOutputs = Script.GetHashOutputs(tx); this.HashOutputs = Script.GetHashOutputs(tx);
HashSequence = Script.GetHashSequence(tx); this.HashSequence = Script.GetHashSequence(tx);
HashPrevouts = Script.GetHashPrevouts(tx); this.HashPrevouts = Script.GetHashPrevouts(tx);
} }
public uint256 HashPrevouts public uint256 HashPrevouts
{ {
......
...@@ -2,21 +2,18 @@ ...@@ -2,21 +2,18 @@
using System.Text; using System.Text;
using NBitcoin.Crypto; using NBitcoin.Crypto;
#if !USEBC
#endif
namespace NBitcoin namespace NBitcoin
{ {
public class UnsecureRandom : IRandom public class UnsecureRandom : IRandom
{ {
Random _Rand = new Random(); private Random _Rand = new Random();
#region IRandom Members #region IRandom Members
public void GetBytes(byte[] output) public void GetBytes(byte[] output)
{ {
lock (_Rand) lock (this._Rand)
{ {
_Rand.NextBytes(output); this._Rand.NextBytes(output);
} }
} }
...@@ -40,7 +37,7 @@ namespace NBitcoin ...@@ -40,7 +37,7 @@ namespace NBitcoin
public static byte[] GetBytes(int length) public static byte[] GetBytes(int length)
{ {
byte[] data = new byte[length]; var data = new byte[length];
if (Random == null) if (Random == null)
throw new InvalidOperationException("You must set the RNG (RandomUtils.Random) before generating random numbers"); throw new InvalidOperationException("You must set the RNG (RandomUtils.Random) before generating random numbers");
Random.GetBytes(data); Random.GetBytes(data);
...@@ -53,7 +50,7 @@ namespace NBitcoin ...@@ -53,7 +50,7 @@ namespace NBitcoin
if (additionalEntropy == null || data.Length == 0) if (additionalEntropy == null || data.Length == 0)
return; return;
int pos = entropyIndex; int pos = entropyIndex;
var entropy = additionalEntropy; byte[] entropy = additionalEntropy;
for (int i = 0; i < data.Length; i++) for (int i = 0; i < data.Length; i++)
{ {
data[i] ^= entropy[pos % 32]; data[i] ^= entropy[pos % 32];
...@@ -68,8 +65,8 @@ namespace NBitcoin ...@@ -68,8 +65,8 @@ namespace NBitcoin
entropyIndex = pos % 32; entropyIndex = pos % 32;
} }
static volatile byte[] additionalEntropy = null; private static volatile byte[] additionalEntropy = null;
static volatile int entropyIndex = 0; private static volatile int entropyIndex = 0;
public static void AddEntropy(string data) public static void AddEntropy(string data)
{ {
...@@ -82,7 +79,7 @@ namespace NBitcoin ...@@ -82,7 +79,7 @@ namespace NBitcoin
{ {
if (data == null) if (data == null)
throw new ArgumentNullException("data"); throw new ArgumentNullException("data");
var entropy = Hashes.SHA256(data); byte[] entropy = Hashes.SHA256(data);
if (additionalEntropy == null) if (additionalEntropy == null)
additionalEntropy = entropy; additionalEntropy = entropy;
else else
......
#if WIN using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace NBitcoin
{
public class RNGCryptoServiceProviderRandom : IRandom
{
readonly RNGCryptoServiceProvider _Instance;
public RNGCryptoServiceProviderRandom()
{
_Instance = new RNGCryptoServiceProvider();
}
#region IRandom Members
public void GetBytes(byte[] output)
{
_Instance.GetBytes(output);
}
#endregion
}
public partial class RandomUtils
{
static RandomUtils()
{
//Thread safe http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider(v=vs.110).aspx
Random = new RNGCryptoServiceProviderRandom();
AddEntropy(Guid.NewGuid().ToByteArray());
}
}
}
#endif
#if !WIN && !NODEFAULTRNG
using System;
using System.Security.Cryptography; using System.Security.Cryptography;
namespace NBitcoin namespace NBitcoin
{ {
public class RandomNumberGeneratorRandom : IRandom public class RandomNumberGeneratorRandom : IRandom
{ {
readonly RandomNumberGenerator _Instance; private readonly RandomNumberGenerator _Instance;
public RandomNumberGeneratorRandom() public RandomNumberGeneratorRandom()
{ {
_Instance = RandomNumberGenerator.Create(); this._Instance = RandomNumberGenerator.Create();
} }
#region IRandom Members #region IRandom Members
public void GetBytes(byte[] output) public void GetBytes(byte[] output)
{ {
_Instance.GetBytes(output); this._Instance.GetBytes(output);
} }
#endregion #endregion
...@@ -70,23 +30,3 @@ namespace NBitcoin ...@@ -70,23 +30,3 @@ namespace NBitcoin
} }
} }
} }
#endif
#if DEBUG && NODEFAULTRNG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBitcoin
{
public partial class RandomUtils
{
static RandomUtils()
{
Random = new UnsecureRandom();
}
}
}
#endif
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
...@@ -60,39 +60,39 @@ namespace NBitcoin ...@@ -60,39 +60,39 @@ namespace NBitcoin
internal const int SEQUENCE_LOCKTIME_GRANULARITY = 9; internal const int SEQUENCE_LOCKTIME_GRANULARITY = 9;
uint _ValueInv; private uint _ValueInv;
public uint Value public uint Value
{ {
get get
{ {
return 0xFFFFFFFF - _ValueInv; return 0xFFFFFFFF - this._ValueInv;
} }
} }
public Sequence(uint value) public Sequence(uint value)
{ {
_ValueInv = 0xFFFFFFFF - value; this._ValueInv = 0xFFFFFFFF - value;
} }
public Sequence(int lockHeight) public Sequence(int lockHeight)
{ {
if(lockHeight > 0xFFFF || lockHeight < 0) if(lockHeight > 0xFFFF || lockHeight < 0)
throw new ArgumentOutOfRangeException("Relative lock height must be positive and lower or equals to 0xFFFF (65535 blocks)"); throw new ArgumentOutOfRangeException("Relative lock height must be positive and lower or equals to 0xFFFF (65535 blocks)");
_ValueInv = 0xFFFFFFFF - (uint)lockHeight; this._ValueInv = 0xFFFFFFFF - (uint)lockHeight;
} }
public Sequence(TimeSpan period) public Sequence(TimeSpan period)
{ {
if(period.TotalSeconds > (0xFFFF * 512) || period.TotalSeconds < 0) if(period.TotalSeconds > (0xFFFF * 512) || period.TotalSeconds < 0)
throw new ArgumentOutOfRangeException("Relative lock time must be positive and lower or equals to " + (0xFFFF * 512) + " seconds (approx 388 days)"); throw new ArgumentOutOfRangeException("Relative lock time must be positive and lower or equals to " + (0xFFFF * 512) + " seconds (approx 388 days)");
var value = (uint)(period.TotalSeconds / (1 << Sequence.SEQUENCE_LOCKTIME_GRANULARITY)); uint value = (uint)(period.TotalSeconds / (1 << SEQUENCE_LOCKTIME_GRANULARITY));
value |= SEQUENCE_LOCKTIME_TYPE_FLAG; value |= SEQUENCE_LOCKTIME_TYPE_FLAG;
_ValueInv = 0xFFFFFFFF - (uint)value; this._ValueInv = 0xFFFFFFFF - (uint)value;
} }
public bool IsRelativeLock public bool IsRelativeLock
{ {
get get
{ {
return (Value & SEQUENCE_LOCKTIME_DISABLE_FLAG) == 0; return (this.Value & SEQUENCE_LOCKTIME_DISABLE_FLAG) == 0;
} }
} }
...@@ -100,7 +100,7 @@ namespace NBitcoin ...@@ -100,7 +100,7 @@ namespace NBitcoin
{ {
get get
{ {
return Value < 0xffffffff - 1; return this.Value < 0xffffffff - 1;
} }
} }
...@@ -109,7 +109,7 @@ namespace NBitcoin ...@@ -109,7 +109,7 @@ namespace NBitcoin
get get
{ {
AssertRelativeLock(); AssertRelativeLock();
return (Value & SEQUENCE_LOCKTIME_TYPE_FLAG) != 0 ? SequenceLockType.Time : SequenceLockType.Height; return (this.Value & SEQUENCE_LOCKTIME_TYPE_FLAG) != 0 ? SequenceLockType.Time : SequenceLockType.Height;
} }
} }
...@@ -124,23 +124,23 @@ namespace NBitcoin ...@@ -124,23 +124,23 @@ namespace NBitcoin
private void AssertRelativeLock() private void AssertRelativeLock()
{ {
if(!IsRelativeLock) if(!this.IsRelativeLock)
throw new InvalidOperationException("This sequence is not a relative lock"); throw new InvalidOperationException("This sequence is not a relative lock");
} }
public override string ToString() public override string ToString()
{ {
if(IsRelativeLock) if(this.IsRelativeLock)
{ {
StringBuilder builder = new StringBuilder(); var builder = new StringBuilder();
builder.Append("Relative lock (" + LockType + "): "); builder.Append("Relative lock (" + this.LockType + "): ");
if(LockType == SequenceLockType.Height) if(this.LockType == SequenceLockType.Height)
builder.Append(LockHeight + " blocks"); builder.Append(this.LockHeight + " blocks");
else else
builder.Append(LockPeriod); builder.Append(this.LockPeriod);
return builder.ToString(); return builder.ToString();
} }
return Value.ToString(); return this.Value.ToString();
} }
public int LockHeight public int LockHeight
...@@ -148,9 +148,9 @@ namespace NBitcoin ...@@ -148,9 +148,9 @@ namespace NBitcoin
get get
{ {
AssertRelativeLock(); AssertRelativeLock();
if(LockType != SequenceLockType.Height) if(this.LockType != SequenceLockType.Height)
throw new InvalidOperationException("This sequence is a time based relative lock"); throw new InvalidOperationException("This sequence is a time based relative lock");
return (int)(Value & SEQUENCE_LOCKTIME_MASK); return (int)(this.Value & SEQUENCE_LOCKTIME_MASK);
} }
} }
public TimeSpan LockPeriod public TimeSpan LockPeriod
...@@ -158,9 +158,9 @@ namespace NBitcoin ...@@ -158,9 +158,9 @@ namespace NBitcoin
get get
{ {
AssertRelativeLock(); AssertRelativeLock();
if(LockType != SequenceLockType.Time) if(this.LockType != SequenceLockType.Time)
throw new InvalidOperationException("This sequence is a height based relative lock"); throw new InvalidOperationException("This sequence is a height based relative lock");
return TimeSpan.FromSeconds((int)(Value & SEQUENCE_LOCKTIME_MASK) * (1 << Sequence.SEQUENCE_LOCKTIME_GRANULARITY)); return TimeSpan.FromSeconds((int)(this.Value & SEQUENCE_LOCKTIME_MASK) * (1 << SEQUENCE_LOCKTIME_GRANULARITY));
} }
} }
} }
......
...@@ -6,8 +6,8 @@ namespace NBitcoin ...@@ -6,8 +6,8 @@ namespace NBitcoin
{ {
public SequenceLock(int minHeight, DateTimeOffset minTime) public SequenceLock(int minHeight, DateTimeOffset minTime)
{ {
MinHeight = minHeight; this.MinHeight = minHeight;
MinTime = minTime; this.MinTime = minTime;
} }
public SequenceLock(int minHeight, long minTime) public SequenceLock(int minHeight, long minTime)
: this(minHeight, Utils.UnixTimeToDateTime(minTime)) : this(minHeight, Utils.UnixTimeToDateTime(minTime))
...@@ -26,7 +26,7 @@ namespace NBitcoin ...@@ -26,7 +26,7 @@ namespace NBitcoin
public bool Evaluate(ChainedHeader block) public bool Evaluate(ChainedHeader block)
{ {
var nBlockTime = block.Previous == null ? Utils.UnixTimeToDateTime(0) : block.Previous.GetMedianTimePast(); DateTimeOffset nBlockTime = block.Previous == null ? Utils.UnixTimeToDateTime(0) : block.Previous.GetMedianTimePast();
return this.MinHeight < block.Height && this.MinTime < nBlockTime; return this.MinHeight < block.Height && this.MinTime < nBlockTime;
} }
} }
......
...@@ -10,7 +10,7 @@ namespace NBitcoin ...@@ -10,7 +10,7 @@ namespace NBitcoin
/// </summary> /// </summary>
public class Target public class Target
{ {
static Target _Difficulty1 = new Target(new byte[] { 0x1d, 0x00, 0xff, 0xff }); private static Target _Difficulty1 = new Target(new byte[] { 0x1d, 0x00, 0xff, 0xff });
public static Target Difficulty1 public static Target Difficulty1
{ {
get get
...@@ -37,16 +37,15 @@ namespace NBitcoin ...@@ -37,16 +37,15 @@ namespace NBitcoin
} }
private BigInteger _Target;
BigInteger _Target;
public Target(byte[] compact) public Target(byte[] compact)
{ {
if(compact.Length == 4) if(compact.Length == 4)
{ {
var exp = compact[0]; byte exp = compact[0];
var val = new BigInteger(compact.SafeSubarray(1, 3)); var val = new BigInteger(compact.SafeSubarray(1, 3));
_Target = val.ShiftLeft(8 * (exp - 3)); this._Target = val.ShiftLeft(8 * (exp - 3));
} }
else else
throw new FormatException("Invalid number of bytes"); throw new FormatException("Invalid number of bytes");
...@@ -54,13 +53,13 @@ namespace NBitcoin ...@@ -54,13 +53,13 @@ namespace NBitcoin
public Target(BigInteger target) public Target(BigInteger target)
{ {
_Target = target; this._Target = target;
_Target = new Target(this.ToCompact())._Target; this._Target = new Target(ToCompact())._Target;
} }
public Target(uint256 target) public Target(uint256 target)
{ {
_Target = new BigInteger(target.ToBytes(false)); this._Target = new BigInteger(target.ToBytes(false));
_Target = new Target(this.ToCompact())._Target; this._Target = new Target(ToCompact())._Target;
} }
public static implicit operator Target(uint a) public static implicit operator Target(uint a)
...@@ -69,11 +68,11 @@ namespace NBitcoin ...@@ -69,11 +68,11 @@ namespace NBitcoin
} }
public static implicit operator uint(Target a) public static implicit operator uint(Target a)
{ {
var bytes = a._Target.ToByteArray(); byte[] bytes = a._Target.ToByteArray();
var val = bytes.SafeSubarray(0, Math.Min(bytes.Length, 3)); byte[] val = bytes.SafeSubarray(0, Math.Min(bytes.Length, 3));
Array.Reverse(val); Array.Reverse(val);
var exp = (byte)(bytes.Length); byte exp = (byte)(bytes.Length);
var missing = 4 - val.Length; int missing = 4 - val.Length;
if(missing > 0) if(missing > 0)
val = val.Concat(new byte[missing]).ToArray(); val = val.Concat(new byte[missing]).ToArray();
if(missing < 0) if(missing < 0)
...@@ -81,34 +80,35 @@ namespace NBitcoin ...@@ -81,34 +80,35 @@ namespace NBitcoin
return (uint)val[0] + (uint)(val[1] << 8) + (uint)(val[2] << 16) + (uint)(exp << 24); return (uint)val[0] + (uint)(val[1] << 8) + (uint)(val[2] << 16) + (uint)(exp << 24);
} }
double? _Difficulty; private double? _Difficulty;
public double Difficulty public double Difficulty
{ {
get get
{ {
if(_Difficulty == null) if(this._Difficulty == null)
{ {
var qr = Difficulty1._Target.DivideAndRemainder(_Target); BigInteger[] qr = Difficulty1._Target.DivideAndRemainder(this._Target);
var quotient = qr[0]; BigInteger quotient = qr[0];
var remainder = qr[1]; BigInteger remainder = qr[1];
var decimalPart = BigInteger.Zero; BigInteger decimalPart = BigInteger.Zero;
for(int i = 0; i < 12; i++) for(int i = 0; i < 12; i++)
{ {
var div = (remainder.Multiply(BigInteger.Ten)).Divide(_Target); BigInteger div = (remainder.Multiply(BigInteger.Ten)).Divide(this._Target);
decimalPart = decimalPart.Multiply(BigInteger.Ten); decimalPart = decimalPart.Multiply(BigInteger.Ten);
decimalPart = decimalPart.Add(div); decimalPart = decimalPart.Add(div);
remainder = remainder.Multiply(BigInteger.Ten).Subtract(div.Multiply(_Target)); remainder = remainder.Multiply(BigInteger.Ten).Subtract(div.Multiply(this._Target));
} }
_Difficulty = double.Parse(quotient.ToString() + "." + decimalPart.ToString(), new NumberFormatInfo()
this._Difficulty = double.Parse(quotient.ToString() + "." + decimalPart.ToString(), new NumberFormatInfo()
{ {
NegativeSign = "-", NegativeSign = "-",
NumberDecimalSeparator = "." NumberDecimalSeparator = "."
}); });
} }
return _Difficulty.Value; return this._Difficulty.Value;
} }
} }
...@@ -116,14 +116,14 @@ namespace NBitcoin ...@@ -116,14 +116,14 @@ namespace NBitcoin
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
Target item = obj as Target; var item = obj as Target;
if(item == null) if(item == null)
return false; return false;
return _Target.Equals(item._Target); return this._Target.Equals(item._Target);
} }
public static bool operator ==(Target a, Target b) public static bool operator ==(Target a, Target b)
{ {
if(System.Object.ReferenceEquals(a, b)) if(ReferenceEquals(a, b))
return true; return true;
if(((object)a == null) || ((object)b == null)) if(((object)a == null) || ((object)b == null))
return false; return false;
...@@ -137,12 +137,12 @@ namespace NBitcoin ...@@ -137,12 +137,12 @@ namespace NBitcoin
public override int GetHashCode() public override int GetHashCode()
{ {
return _Target.GetHashCode(); return this._Target.GetHashCode();
} }
public BigInteger ToBigInteger() public BigInteger ToBigInteger()
{ {
return _Target; return this._Target;
} }
public uint ToCompact() public uint ToCompact()
...@@ -152,14 +152,14 @@ namespace NBitcoin ...@@ -152,14 +152,14 @@ namespace NBitcoin
public uint256 ToUInt256() public uint256 ToUInt256()
{ {
return ToUInt256(_Target); return ToUInt256(this._Target);
} }
internal static uint256 ToUInt256(BigInteger input) internal static uint256 ToUInt256(BigInteger input)
{ {
var array = input.ToByteArray(); byte[] array = input.ToByteArray();
var missingZero = 32 - array.Length; int missingZero = 32 - array.Length;
if(missingZero < 0) if(missingZero < 0)
throw new InvalidOperationException("Awful bug, this should never happen"); throw new InvalidOperationException("Awful bug, this should never happen");
if(missingZero != 0) if(missingZero != 0)
......
This diff is collapsed.
...@@ -19,7 +19,7 @@ namespace NBitcoin ...@@ -19,7 +19,7 @@ namespace NBitcoin
public TransactionNotFoundException(string message, uint256 txId, Exception inner) public TransactionNotFoundException(string message, uint256 txId, Exception inner)
: base(message ?? "Transaction " + txId + " not found", inner) : base(message ?? "Transaction " + txId + " not found", inner)
{ {
TxId = txId; this.TxId = txId;
} }
public uint256 TxId public uint256 TxId
{ {
......
This diff is collapsed.
...@@ -14,7 +14,7 @@ namespace NBitcoin ...@@ -14,7 +14,7 @@ namespace NBitcoin
{ {
if(parent == null) if(parent == null)
throw new ArgumentNullException("parent"); throw new ArgumentNullException("parent");
Transaction = parent; this.Transaction = parent;
} }
public Transaction Transaction public Transaction Transaction
......
using Newtonsoft.Json; using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace NBitcoin namespace NBitcoin
{ {
......
...@@ -32,6 +32,6 @@ using System.Runtime.InteropServices; ...@@ -32,6 +32,6 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers // You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below: // by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")] // [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.2.0")] [assembly: AssemblyVersion("1.1.12.0")]
[assembly: AssemblyFileVersion("1.1.2.0")] [assembly: AssemblyFileVersion("1.1.12.0")]
[assembly: InternalsVisibleTo("Stratis.Bitcoin.Tests")] [assembly: InternalsVisibleTo("Stratis.Bitcoin.Tests")]
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
"profiles": { "profiles": {
"Stratis.StratisD": { "Stratis.StratisD": {
"commandName": "Project", "commandName": "Project",
"commandLineArgs": "-testnode" "commandLineArgs": "-testnet -addnode=192.168.31.142:26178"
}, },
"Stratis.StratisD Test": { "Stratis.StratisD Test": {
"commandName": "Project", "commandName": "Project",
......
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