Commit c0331514 authored by Pavel Pavlov's avatar Pavel Pavlov

Bug fix after merge.

parent 0191a5d6
......@@ -2,7 +2,7 @@
"profiles": {
"Stratis.StratisD": {
"commandName": "Project",
"commandLineArgs": "-testnet -debug -loglevel=trace"
"commandLineArgs": "-testnet -debug -loglevel=trace -addnode=192.168.31.142:56849"
},
"Stratis.StratisD Test": {
"commandName": "Project",
......
......@@ -16,9 +16,9 @@ namespace NBitcoin
public BIP9DeploymentsParameters(int bit, DateTimeOffset startTime, DateTimeOffset timeout)
{
Bit = bit;
StartTime = startTime;
Timeout = timeout;
this.Bit = bit;
this.StartTime = startTime;
this.Timeout = timeout;
}
public BIP9DeploymentsParameters(int bit, long startTime, long timeout)
......
......@@ -5,14 +5,14 @@ using System.Text;
namespace NBitcoin
{
class BitReader
internal class BitReader
{
BitArray array;
private BitArray array;
public BitReader(byte[] data, int bitCount)
{
BitWriter writer = new BitWriter();
var writer = new BitWriter();
writer.Write(data, bitCount);
array = writer.ToBitArray();
this.array = writer.ToBitArray();
}
public BitReader(BitArray array)
......@@ -24,8 +24,8 @@ namespace NBitcoin
public bool Read()
{
var v = array.Get(Position);
Position++;
bool v = this.array.Get(this.Position);
this.Position++;
return v;
}
......@@ -40,7 +40,7 @@ namespace NBitcoin
uint value = 0;
for(int i = 0; i < bitCount; i++)
{
var v = Read() ? 1U : 0U;
uint v = Read() ? 1U : 0U;
value += (v << i);
}
return value;
......@@ -50,36 +50,36 @@ namespace NBitcoin
{
get
{
return array.Length;
return this.array.Length;
}
}
public BitArray ToBitArray()
{
BitArray result = new BitArray(array.Length);
for(int i = 0; i < array.Length; i++)
result.Set(i, array.Get(i));
var result = new BitArray(this.array.Length);
for(int i = 0; i < this.array.Length; i++)
result.Set(i, this.array.Get(i));
return result;
}
public BitWriter ToWriter()
{
var writer = new BitWriter();
writer.Write(array);
writer.Write(this.array);
return writer;
}
public void Consume(int count)
{
Position += count;
this.Position += count;
}
public bool Same(BitReader b)
{
while(Position != Count && b.Position != b.Count)
while(this.Position != this.Count && b.Position != b.Count)
{
var valuea = Read();
var valueb = b.Read();
bool valuea = Read();
bool valueb = b.Read();
if(valuea != valueb)
return false;
}
......@@ -88,30 +88,31 @@ namespace NBitcoin
public override string ToString()
{
StringBuilder builder = new StringBuilder(array.Length);
for(int i = 0; i < Count; i++)
var builder = new StringBuilder(this.array.Length);
for(int i = 0; i < this.Count; i++)
{
if(i != 0 && i % 8 == 0)
builder.Append(' ');
builder.Append(array.Get(i) ? "1" : "0");
builder.Append(this.array.Get(i) ? "1" : "0");
}
return builder.ToString();
}
}
class BitWriter
internal class BitWriter
{
List<bool> values = new List<bool>();
private List<bool> values = new List<bool>();
public int Count
{
get
{
return values.Count;
return this.values.Count;
}
}
public void Write(bool value)
{
values.Insert(Position, value);
_Position++;
this.values.Insert(this.Position, value);
this._Position++;
}
internal void Write(byte[] bytes)
......@@ -122,26 +123,26 @@ namespace NBitcoin
public void Write(byte[] bytes, int bitCount)
{
bytes = SwapEndianBytes(bytes);
BitArray array = new BitArray(bytes);
values.InsertRange(Position, array.OfType<bool>().Take(bitCount));
_Position += bitCount;
var array = new BitArray(bytes);
this.values.InsertRange(this.Position, array.OfType<bool>().Take(bitCount));
this._Position += bitCount;
}
public byte[] ToBytes()
{
var array = ToBitArray();
var bytes = ToByteArray(array);
BitArray array = ToBitArray();
byte[] bytes = ToByteArray(array);
bytes = SwapEndianBytes(bytes);
return bytes;
}
//BitArray.CopyTo do not exist in portable lib
static byte[] ToByteArray(BitArray bits)
private static byte[] ToByteArray(BitArray bits)
{
int arrayLength = bits.Length / 8;
if(bits.Length % 8 != 0)
arrayLength++;
byte[] array = new byte[arrayLength];
var array = new byte[arrayLength];
for(int i = 0; i < bits.Length; i++)
{
......@@ -155,19 +156,19 @@ namespace NBitcoin
public BitArray ToBitArray()
{
return new BitArray(values.ToArray());
return new BitArray(this.values.ToArray());
}
public int[] ToIntegers()
{
var array = new BitArray(values.ToArray());
var array = new BitArray(this.values.ToArray());
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++)
{
byte newByte = 0;
......@@ -191,16 +192,16 @@ namespace NBitcoin
}
}
int _Position;
private int _Position;
public int Position
{
get
{
return _Position;
return this._Position;
}
set
{
_Position = value;
this._Position = value;
}
}
......@@ -236,12 +237,12 @@ namespace NBitcoin
public override string ToString()
{
StringBuilder builder = new StringBuilder(values.Count);
for(int i = 0; i < Count; i++)
var builder = new StringBuilder(this.values.Count);
for(int i = 0; i < this.Count; i++)
{
if(i != 0 && i % 8 == 0)
builder.Append(' ');
builder.Append(values[i] ? "1" : "0");
builder.Append(this.values[i] ? "1" : "0");
}
return builder.ToString();
}
......
......@@ -12,8 +12,8 @@ namespace NBitcoin
public BitcoinScriptAddress(string base58, Network expectedNetwork)
: base(Validate(base58, ref expectedNetwork), expectedNetwork)
{
var decoded = Encoders.Base58Check.DecodeData(base58);
_Hash = new ScriptId(new uint160(decoded.Skip(expectedNetwork.GetVersionBytes(Base58Type.SCRIPT_ADDRESS, true).Length).ToArray()));
byte[] decoded = Encoders.Base58Check.DecodeData(base58);
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)
......@@ -27,8 +27,8 @@ namespace NBitcoin
{
if (base58 == null)
throw new ArgumentNullException("base58");
var data = Encoders.Base58Check.DecodeData(base58);
var versionBytes = expectedNetwork.GetVersionBytes(Base58Type.SCRIPT_ADDRESS, false);
byte[] data = Encoders.Base58Check.DecodeData(base58);
byte[] versionBytes = expectedNetwork.GetVersionBytes(Base58Type.SCRIPT_ADDRESS, false);
if (versionBytes != null && data.StartWith(versionBytes))
{
if (data.Length == versionBytes.Length + 20)
......@@ -42,7 +42,7 @@ namespace NBitcoin
public BitcoinScriptAddress(ScriptId scriptId, 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)
......@@ -52,12 +52,12 @@ namespace NBitcoin
return null;
}
ScriptId _Hash;
private ScriptId _Hash;
public ScriptId Hash
{
get
{
return _Hash;
return this._Hash;
}
}
......@@ -71,7 +71,7 @@ namespace NBitcoin
protected override Script GeneratePaymentScript()
{
return PayToScriptHashTemplate.Instance.GenerateScriptPubKey((ScriptId)Hash);
return PayToScriptHashTemplate.Instance.GenerateScriptPubKey((ScriptId) this.Hash);
}
}
......@@ -100,22 +100,22 @@ namespace NBitcoin
throw new ArgumentNullException("network");
if(str == null)
throw new ArgumentNullException("str");
_Str = str;
_Network = network;
this._Str = str;
this._Network = network;
}
string _Str;
private string _Str;
Script _ScriptPubKey;
private Script _ScriptPubKey;
public Script ScriptPubKey
{
get
{
if(_ScriptPubKey == null)
if(this._ScriptPubKey == null)
{
_ScriptPubKey = GeneratePaymentScript();
this._ScriptPubKey = GeneratePaymentScript();
}
return _ScriptPubKey;
return this._ScriptPubKey;
}
}
......@@ -127,7 +127,7 @@ namespace NBitcoin
if(bitcoinScriptAddress != null)
return bitcoinScriptAddress;
return new BitcoinScriptAddress(this.ScriptPubKey.Hash, Network);
return new BitcoinScriptAddress(this.ScriptPubKey.Hash, this.Network);
}
public BitcoinColoredAddress ToColoredAddress()
......@@ -141,26 +141,26 @@ namespace NBitcoin
{
get
{
return _Network;
return this._Network;
}
}
public override string ToString()
{
return _Str;
return this._Str;
}
public override bool Equals(object obj)
{
BitcoinAddress item = obj as BitcoinAddress;
var item = obj as BitcoinAddress;
if(item == null)
return false;
return _Str.Equals(item._Str);
return this._Str.Equals(item._Str);
}
public static bool operator ==(BitcoinAddress a, BitcoinAddress b)
{
if(System.Object.ReferenceEquals(a, b))
if(ReferenceEquals(a, b))
return true;
if(((object)a == null) || ((object)b == null))
return false;
......@@ -174,7 +174,7 @@ namespace NBitcoin
public override int GetHashCode()
{
return _Str.GetHashCode();
return this._Str.GetHashCode();
}
}
}
......@@ -12,8 +12,8 @@ namespace NBitcoin
public BitcoinPubKeyAddress(string base58, Network expectedNetwork)
: base(Validate(base58, ref expectedNetwork), expectedNetwork)
{
var decoded = Encoders.Base58Check.DecodeData(base58);
_KeyId = new KeyId(new uint160(decoded.Skip(expectedNetwork.GetVersionBytes(Base58Type.PUBKEY_ADDRESS, true).Length).ToArray()));
byte[] decoded = Encoders.Base58Check.DecodeData(base58);
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)
......@@ -27,8 +27,8 @@ namespace NBitcoin
{
if (base58 == null)
throw new ArgumentNullException("base58");
var data = Encoders.Base58Check.DecodeData(base58);
var versionBytes = expectedNetwork.GetVersionBytes(Base58Type.PUBKEY_ADDRESS, false);
byte[] data = Encoders.Base58Check.DecodeData(base58);
byte[] versionBytes = expectedNetwork.GetVersionBytes(Base58Type.PUBKEY_ADDRESS, false);
if (versionBytes != null && data.StartWith(versionBytes))
{
if (data.Length == versionBytes.Length + 20)
......@@ -42,7 +42,7 @@ namespace NBitcoin
public BitcoinPubKeyAddress(KeyId keyId, 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)
......@@ -54,16 +54,16 @@ namespace NBitcoin
public bool VerifyMessage(string message, string signature)
{
var key = PubKey.RecoverFromMessage(message, signature);
return key.Hash == Hash;
PubKey key = PubKey.RecoverFromMessage(message, signature);
return key.Hash == this.Hash;
}
KeyId _KeyId;
private KeyId _KeyId;
public KeyId Hash
{
get
{
return _KeyId;
return this._KeyId;
}
}
......
using System.Linq;
using System.Collections.Generic;
using System.Linq;
using NBitcoin.DataEncoders;
namespace NBitcoin
......@@ -12,7 +13,7 @@ namespace NBitcoin
private static byte[] ToBytes(Key key)
{
var keyBytes = key.ToBytes();
byte[] keyBytes = key.ToBytes();
if(!key.IsCompressed)
return keyBytes;
else
......@@ -27,14 +28,14 @@ namespace NBitcoin
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
{
get
{
return PrivateKey.PubKey.Hash;
return this.PrivateKey.PubKey.Hash;
}
}
......@@ -42,17 +43,18 @@ namespace NBitcoin
{
get
{
return PrivateKey.PubKey;
return this.PrivateKey.PubKey;
}
}
#region ISecret Members
Key _Key;
private Key _Key;
public Key PrivateKey
{
get
{
return _Key ?? (_Key = new Key(vchData, 32, IsCompressed));
return this._Key ?? (this._Key = new Key(this.vchData, 32, this.IsCompressed));
}
}
#endregion
......@@ -61,12 +63,12 @@ namespace NBitcoin
{
get
{
if(vchData.Length != 33 && vchData.Length != 32)
if(this.vchData.Length != 33 && this.vchData.Length != 32)
return false;
if(vchData.Length == 33 && IsCompressed)
if(this.vchData.Length == 33 && this.IsCompressed)
return true;
if(vchData.Length == 32 && !IsCompressed)
if(this.vchData.Length == 32 && !this.IsCompressed)
return true;
return false;
}
......@@ -74,23 +76,23 @@ namespace NBitcoin
public BitcoinEncryptedSecret Encrypt(string password)
{
return PrivateKey.GetEncryptedBitcoinSecret(password, Network);
return this.PrivateKey.GetEncryptedBitcoinSecret(password, this.Network);
}
public BitcoinSecret Copy(bool? compressed)
{
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
{
byte[] result = Encoders.Base58Check.DecodeData(wifData);
var resultList = result.ToList();
byte[] result = Encoders.Base58Check.DecodeData(this.wifData);
List<byte> resultList = result.ToList();
if(compressed.Value)
{
......@@ -100,7 +102,7 @@ namespace NBitcoin
{
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
{
get
{
return vchData.Length > 32 && vchData[32] == 1;
return this.vchData.Length > 32 && this.vchData[32] == 1;
}
}
......
......@@ -8,10 +8,10 @@ namespace NBitcoin
public BitcoinWitPubKeyAddress(string bech32, Network 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;
var decoded = encoder.Decode(bech32, out witVersion);
_Hash = new WitKeyId(decoded);
byte[] decoded = encoder.Decode(bech32, out witVersion);
this._Hash = new WitKeyId(decoded);
}
private static string Validate(string bech32, ref Network expectedNetwork)
......@@ -37,14 +37,14 @@ namespace NBitcoin
return false;
}
var encoder = expectedNetwork.GetBech32Encoder(Bech32Type.WITNESS_PUBKEY_ADDRESS, false);
Bech32Encoder encoder = expectedNetwork.GetBech32Encoder(Bech32Type.WITNESS_PUBKEY_ADDRESS, false);
if (encoder == null)
return false;
try
{
byte witVersion;
var data = encoder.Decode(bech32, out witVersion);
byte[] data = encoder.Decode(bech32, out witVersion);
if (data.Length == 20 && witVersion == 0)
{
return true;
......@@ -68,7 +68,7 @@ namespace NBitcoin
public BitcoinWitPubKeyAddress(WitKeyId segwitKeyId, 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)
......@@ -80,23 +80,23 @@ namespace NBitcoin
public bool VerifyMessage(string message, string signature)
{
var key = PubKey.RecoverFromMessage(message, signature);
PubKey key = PubKey.RecoverFromMessage(message, signature);
return key.WitHash == this.Hash;
}
WitKeyId _Hash;
private WitKeyId _Hash;
public WitKeyId Hash
{
get
{
return _Hash;
return this._Hash;
}
}
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
......@@ -113,10 +113,10 @@ namespace NBitcoin
public BitcoinWitScriptAddress(string bech32, Network expectedNetwork = null)
: 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;
var decoded = encoder.Decode(bech32, out witVersion);
_Hash = new WitScriptId(decoded);
byte[] decoded = encoder.Decode(bech32, out witVersion);
this._Hash = new WitScriptId(decoded);
}
private static string Validate(string bech32, ref Network expectedNetwork)
......@@ -142,13 +142,13 @@ namespace NBitcoin
return false;
}
var encoder = expectedNetwork.GetBech32Encoder(Bech32Type.WITNESS_SCRIPT_ADDRESS, false);
Bech32Encoder encoder = expectedNetwork.GetBech32Encoder(Bech32Type.WITNESS_SCRIPT_ADDRESS, false);
if (encoder == null)
return false;
try
{
byte witVersion;
var data = encoder.Decode(bech32, out witVersion);
byte[] data = encoder.Decode(bech32, out witVersion);
if (data.Length == 32 && witVersion == 0)
{
return true;
......@@ -172,7 +172,7 @@ namespace NBitcoin
public BitcoinWitScriptAddress(WitScriptId segwitScriptId, 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
return null;
}
WitScriptId _Hash;
private WitScriptId _Hash;
public WitScriptId Hash
{
get
{
return _Hash;
return this._Hash;
}
}
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
......
......@@ -9,19 +9,19 @@ namespace NBitcoin
{
public partial class BitcoinStream
{
VarInt _VarInt = new VarInt(0);
private VarInt _VarInt = new VarInt(0);
private void ReadWriteArray<T>(ref T[] data) where T : IBitcoinSerializable
{
if(data == null && Serializing)
if(data == null && this.Serializing)
throw new ArgumentNullException("Impossible to serialize a null array");
_VarInt.SetValue(data == null ? 0 : (ulong)data.Length);
ReadWrite(ref _VarInt);
this._VarInt.SetValue(data == null ? 0 : (ulong)data.Length);
ReadWrite(ref this._VarInt);
if(_VarInt.ToLong() > (uint)MaxArraySize)
if(this._VarInt.ToLong() > (uint) this.MaxArraySize)
throw new ArgumentOutOfRangeException("Array size too big");
if(!Serializing)
data = new T[_VarInt.ToLong()];
if(!this.Serializing)
data = new T[this._VarInt.ToLong()];
for(int i = 0 ; i < data.Length ; i++)
{
T obj = data[i];
......@@ -33,15 +33,15 @@ namespace NBitcoin
private void ReadWriteArray(ref ulong[] data)
{
if(data == null && Serializing)
if(data == null && this.Serializing)
throw new ArgumentNullException("Impossible to serialize a null array");
_VarInt.SetValue(data == null ? 0 : (ulong)data.Length);
ReadWrite(ref _VarInt);
this._VarInt.SetValue(data == null ? 0 : (ulong)data.Length);
ReadWrite(ref this._VarInt);
if(_VarInt.ToLong() > (uint)MaxArraySize)
if(this._VarInt.ToLong() > (uint) this.MaxArraySize)
throw new ArgumentOutOfRangeException("Array size not big");
if(!Serializing)
data = new ulong[_VarInt.ToLong()];
if(!this.Serializing)
data = new ulong[this._VarInt.ToLong()];
for(int i = 0 ; i < data.Length ; i++)
{
ulong obj = data[i];
......@@ -53,15 +53,15 @@ namespace NBitcoin
private void ReadWriteArray(ref ushort[] data)
{
if(data == null && Serializing)
if(data == null && this.Serializing)
throw new ArgumentNullException("Impossible to serialize a null array");
_VarInt.SetValue(data == null ? 0 : (ulong)data.Length);
ReadWrite(ref _VarInt);
this._VarInt.SetValue(data == null ? 0 : (ulong)data.Length);
ReadWrite(ref this._VarInt);
if(_VarInt.ToLong() > (uint)MaxArraySize)
if(this._VarInt.ToLong() > (uint) this.MaxArraySize)
throw new ArgumentOutOfRangeException("Array size not big");
if(!Serializing)
data = new ushort[_VarInt.ToLong()];
if(!this.Serializing)
data = new ushort[this._VarInt.ToLong()];
for(int i = 0 ; i < data.Length ; i++)
{
ushort obj = data[i];
......@@ -73,15 +73,15 @@ namespace NBitcoin
private void ReadWriteArray(ref uint[] data)
{
if(data == null && Serializing)
if(data == null && this.Serializing)
throw new ArgumentNullException("Impossible to serialize a null array");
_VarInt.SetValue(data == null ? 0 : (ulong)data.Length);
ReadWrite(ref _VarInt);
this._VarInt.SetValue(data == null ? 0 : (ulong)data.Length);
ReadWrite(ref this._VarInt);
if(_VarInt.ToLong() > (uint)MaxArraySize)
if(this._VarInt.ToLong() > (uint) this.MaxArraySize)
throw new ArgumentOutOfRangeException("Array size not big");
if(!Serializing)
data = new uint[_VarInt.ToLong()];
if(!this.Serializing)
data = new uint[this._VarInt.ToLong()];
for(int i = 0 ; i < data.Length ; i++)
{
uint obj = data[i];
......@@ -90,38 +90,17 @@ namespace NBitcoin
}
}
private void ReadWriteArray(ref byte[] data)
{
if(data == null && Serializing)
throw new ArgumentNullException("Impossible to serialize a null array");
_VarInt.SetValue(data == null ? 0 : (ulong)data.Length);
ReadWrite(ref _VarInt);
if(_VarInt.ToLong() > (uint)MaxArraySize)
throw new ArgumentOutOfRangeException("Array size not big");
if(!Serializing)
data = new byte[_VarInt.ToLong()];
for(int i = 0 ; i < data.Length ; i++)
{
byte obj = data[i];
ReadWrite(ref obj);
data[i] = obj;
}
}
private void ReadWriteArray(ref long[] data)
{
if(data == null && Serializing)
if(data == null && this.Serializing)
throw new ArgumentNullException("Impossible to serialize a null array");
_VarInt.SetValue(data == null ? 0 : (ulong)data.Length);
ReadWrite(ref _VarInt);
this._VarInt.SetValue(data == null ? 0 : (ulong)data.Length);
ReadWrite(ref this._VarInt);
if(_VarInt.ToLong() > (uint)MaxArraySize)
if(this._VarInt.ToLong() > (uint) this.MaxArraySize)
throw new ArgumentOutOfRangeException("Array size not big");
if(!Serializing)
data = new long[_VarInt.ToLong()];
if(!this.Serializing)
data = new long[this._VarInt.ToLong()];
for(int i = 0 ; i < data.Length ; i++)
{
long obj = data[i];
......@@ -133,15 +112,15 @@ namespace NBitcoin
private void ReadWriteArray(ref short[] data)
{
if(data == null && Serializing)
if(data == null && this.Serializing)
throw new ArgumentNullException("Impossible to serialize a null array");
_VarInt.SetValue(data == null ? 0 : (ulong)data.Length);
ReadWrite(ref _VarInt);
this._VarInt.SetValue(data == null ? 0 : (ulong)data.Length);
ReadWrite(ref this._VarInt);
if(_VarInt.ToLong() > (uint)MaxArraySize)
if(this._VarInt.ToLong() > (uint) this.MaxArraySize)
throw new ArgumentOutOfRangeException("Array size not big");
if(!Serializing)
data = new short[_VarInt.ToLong()];
if(!this.Serializing)
data = new short[this._VarInt.ToLong()];
for(int i = 0 ; i < data.Length ; i++)
{
short obj = data[i];
......@@ -153,15 +132,15 @@ namespace NBitcoin
private void ReadWriteArray(ref int[] data)
{
if(data == null && Serializing)
if(data == null && this.Serializing)
throw new ArgumentNullException("Impossible to serialize a null array");
_VarInt.SetValue(data == null ? 0 : (ulong)data.Length);
ReadWrite(ref _VarInt);
this._VarInt.SetValue(data == null ? 0 : (ulong)data.Length);
ReadWrite(ref this._VarInt);
if(_VarInt.ToLong() > (uint)MaxArraySize)
if(this._VarInt.ToLong() > (uint) this.MaxArraySize)
throw new ArgumentOutOfRangeException("Array size not big");
if(!Serializing)
data = new int[_VarInt.ToLong()];
if(!this.Serializing)
data = new int[this._VarInt.ToLong()];
for(int i = 0 ; i < data.Length ; i++)
{
int obj = data[i];
......@@ -207,66 +186,67 @@ namespace NBitcoin
ReadWriteArray(ref data);
}
uint256.MutableUint256 _MutableUint256 = new uint256.MutableUint256(uint256.Zero);
private uint256.MutableUint256 _MutableUint256 = new uint256.MutableUint256(uint256.Zero);
public void ReadWrite(ref uint256 value)
{
value = value ?? uint256.Zero;
_MutableUint256.Value = value;
this.ReadWrite(ref _MutableUint256);
value = _MutableUint256.Value;
this._MutableUint256.Value = value;
ReadWrite(ref this._MutableUint256);
value = this._MutableUint256.Value;
}
public void ReadWrite(uint256 value)
{
value = value ?? uint256.Zero;
_MutableUint256.Value = value;
this.ReadWrite(ref _MutableUint256);
value = _MutableUint256.Value;
this._MutableUint256.Value = value;
ReadWrite(ref this._MutableUint256);
value = this._MutableUint256.Value;
}
public void ReadWrite(ref List<uint256> value)
{
if(Serializing)
if(this.Serializing)
{
var list = value == null ? null : value.Select(v=>v.AsBitcoinSerializable()).ToList();
this.ReadWrite(ref list);
List<uint256.MutableUint256> list = value == null ? null : value.Select(v=>v.AsBitcoinSerializable()).ToList();
ReadWrite(ref list);
}
else
{
List<uint256.MutableUint256> list = null;
this.ReadWrite(ref list);
ReadWrite(ref list);
value = list.Select(l=>l.Value).ToList();
}
}
uint160.MutableUint160 _MutableUint160 = new uint160.MutableUint160(uint160.Zero);
private uint160.MutableUint160 _MutableUint160 = new uint160.MutableUint160(uint160.Zero);
public void ReadWrite(ref uint160 value)
{
value = value ?? uint160.Zero;
_MutableUint160.Value = value;
this.ReadWrite(ref _MutableUint160);
value = _MutableUint160.Value;
this._MutableUint160.Value = value;
ReadWrite(ref this._MutableUint160);
value = this._MutableUint160.Value;
}
public void ReadWrite(uint160 value)
{
value = value ?? uint160.Zero;
_MutableUint160.Value = value;
this.ReadWrite(ref _MutableUint160);
value = _MutableUint160.Value;
this._MutableUint160.Value = value;
ReadWrite(ref this._MutableUint160);
value = this._MutableUint160.Value;
}
public void ReadWrite(ref List<uint160> value)
{
if(Serializing)
if(this.Serializing)
{
var list = value == null ? null : value.Select(v=>v.AsBitcoinSerializable()).ToList();
this.ReadWrite(ref list);
List<uint160.MutableUint160> list = value == null ? null : value.Select(v=>v.AsBitcoinSerializable()).ToList();
ReadWrite(ref list);
}
else
{
List<uint160.MutableUint160> list = null;
this.ReadWrite(ref list);
ReadWrite(ref list);
value = list.Select(l=>l.Value).ToList();
}
}
......@@ -276,7 +256,7 @@ namespace NBitcoin
{
ulong l = (ulong)data;
ReadWriteNumber(ref l, sizeof(ulong));
if(!Serializing)
if(!this.Serializing)
data = (ulong)l;
}
......@@ -291,7 +271,7 @@ namespace NBitcoin
{
ulong l = (ulong)data;
ReadWriteNumber(ref l, sizeof(ushort));
if(!Serializing)
if(!this.Serializing)
data = (ushort)l;
}
......@@ -306,7 +286,7 @@ namespace NBitcoin
{
ulong l = (ulong)data;
ReadWriteNumber(ref l, sizeof(uint));
if(!Serializing)
if(!this.Serializing)
data = (uint)l;
}
......@@ -323,7 +303,7 @@ namespace NBitcoin
{
long l = (long)data;
ReadWriteNumber(ref l, sizeof(long));
if(!Serializing)
if(!this.Serializing)
data = (long)l;
}
......@@ -338,7 +318,7 @@ namespace NBitcoin
{
long l = (long)data;
ReadWriteNumber(ref l, sizeof(short));
if(!Serializing)
if(!this.Serializing)
data = (short)l;
}
......@@ -353,7 +333,7 @@ namespace NBitcoin
{
long l = (long)data;
ReadWriteNumber(ref l, sizeof(int));
if(!Serializing)
if(!this.Serializing)
data = (int)l;
}
......
......@@ -10,20 +10,20 @@ namespace NBitcoin
{
protected bool Equals(BlockSignature other)
{
return Equals(signature, other.signature);
return Equals(this.signature, other.signature);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
if (obj.GetType() != GetType()) return false;
return Equals((BlockSignature) obj);
}
public override int GetHashCode()
{
return (signature?.GetHashCode() ?? 0);
return (this.signature?.GetHashCode() ?? 0);
}
public BlockSignature()
......@@ -37,17 +37,17 @@ namespace NBitcoin
{
get
{
return signature;
return this.signature;
}
set
{
signature = value;
this.signature = value;
}
}
internal void SetNull()
{
signature = new byte[0];
this.signature = new byte[0];
}
public bool IsEmpty()
......@@ -57,7 +57,7 @@ namespace NBitcoin
public static bool operator ==(BlockSignature a, BlockSignature b)
{
if (System.Object.ReferenceEquals(a, b))
if (ReferenceEquals(a, b))
return true;
if (((object)a == null) || ((object)b == null))
......@@ -75,7 +75,7 @@ namespace NBitcoin
public void ReadWrite(BitcoinStream stream)
{
stream.ReadWriteAsVarString(ref signature);
stream.ReadWriteAsVarString(ref this.signature);
}
#endregion
......
......@@ -6,18 +6,18 @@ namespace NBitcoin
{
public class CachedTransactionRepository : ITransactionRepository
{
ITransactionRepository _Inner;
Dictionary<uint256, Transaction> _Transactions = new Dictionary<uint256, Transaction>();
Queue<uint256> _EvictionQueue = new Queue<uint256>();
ReaderWriterLock @lock = new ReaderWriterLock();
private ITransactionRepository _Inner;
private Dictionary<uint256, Transaction> _Transactions = new Dictionary<uint256, Transaction>();
private Queue<uint256> _EvictionQueue = new Queue<uint256>();
private ReaderWriterLock @lock = new ReaderWriterLock();
public CachedTransactionRepository(ITransactionRepository inner)
{
if(inner == null)
throw new ArgumentNullException("inner");
ReadThrough = true;
WriteThrough = true;
_Inner = inner;
MaxCachedTransactions = 100;
this.ReadThrough = true;
this.WriteThrough = true;
this._Inner = inner;
this.MaxCachedTransactions = 100;
}
public int MaxCachedTransactions
......@@ -28,9 +28,9 @@ namespace NBitcoin
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
{
bool found = false;
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)
{
result = await _Inner.GetAsync(txId).ConfigureAwait(false);
if(ReadThrough)
result = await this._Inner.GetAsync(txId).ConfigureAwait(false);
if(this.ReadThrough)
{
using(@lock.LockWrite())
using(this.@lock.LockWrite())
{
_Transactions.AddOrReplace(txId, result);
this._Transactions.AddOrReplace(txId, result);
EvictIfNecessary(txId);
}
}
......@@ -63,29 +62,27 @@ namespace NBitcoin
private void EvictIfNecessary(uint256 txId)
{
_EvictionQueue.Enqueue(txId);
while(_Transactions.Count > MaxCachedTransactions && _EvictionQueue.Count > 0)
_Transactions.Remove(_EvictionQueue.Dequeue());
this._EvictionQueue.Enqueue(txId);
while(this._Transactions.Count > this.MaxCachedTransactions && this._EvictionQueue.Count > 0) this._Transactions.Remove(this._EvictionQueue.Dequeue());
}
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))
{
_Transactions.AddOrReplace(txId, tx);
this._Transactions.AddOrReplace(txId, tx);
EvictIfNecessary(txId);
}
else
_Transactions[txId] = tx;
this._Transactions[txId] = tx;
}
}
return _Inner.PutAsync(txId, tx);
return this._Inner.PutAsync(txId, tx);
}
#endregion
......
......@@ -43,7 +43,7 @@ namespace NBitcoin
public abstract ChainedHeader SetTip(ChainedHeader chainedHeader);
/// <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>
/// Gets an enumerable iterator for the chain.
......@@ -59,7 +59,7 @@ namespace NBitcoin
}
else
{
foreach (ChainedHeader block in this.EnumerateFromStart())
foreach (ChainedHeader block in EnumerateFromStart())
yield return block;
}
}
......@@ -74,7 +74,7 @@ namespace NBitcoin
if (otherChain == null)
throw new ArgumentNullException("otherChain");
return this.SetTip(otherChain.Tip);
return SetTip(otherChain.Tip);
}
/// <summary>
......@@ -85,7 +85,7 @@ namespace NBitcoin
public bool SetTip(BlockHeader header)
{
ChainedHeader chainedHeader;
return this.TrySetTip(header, out chainedHeader);
return TrySetTip(header, out chainedHeader);
}
/// <summary>
......@@ -102,12 +102,12 @@ namespace NBitcoin
throw new ArgumentNullException("header");
chainedHeader = null;
ChainedHeader prev = this.GetBlock(header.HashPrevBlock);
ChainedHeader prev = GetBlock(header.HashPrevBlock);
if (prev == null)
return false;
chainedHeader = new ChainedHeader(header, header.GetHash(), this.GetBlock(header.HashPrevBlock));
this.SetTip(chainedHeader);
chainedHeader = new ChainedHeader(header, header.GetHash(), GetBlock(header.HashPrevBlock));
SetTip(chainedHeader);
return true;
}
......@@ -118,7 +118,7 @@ namespace NBitcoin
/// <returns>Whether the chain contains the chained block header.</returns>
public bool Contains(uint256 hash)
{
ChainedHeader block = this.GetBlock(hash);
ChainedHeader block = GetBlock(hash);
return block != null;
}
......@@ -143,7 +143,7 @@ namespace NBitcoin
/// <returns>The required work.</returns>
public Target GetWorkRequired(Network network, int height)
{
return this.GetBlock(height).GetWorkRequired(network);
return GetBlock(height).GetWorkRequired(network);
}
/// <summary>
......@@ -159,7 +159,7 @@ namespace NBitcoin
// Find the first block the caller has in the main chain.
foreach (uint256 hash in hashes)
{
ChainedHeader mi = this.GetBlock(hash);
ChainedHeader mi = GetBlock(hash);
if (mi != null)
return mi;
}
......@@ -177,7 +177,7 @@ namespace NBitcoin
if (locator == null)
throw new ArgumentNullException("locator");
return this.FindFork(locator.Blocks);
return FindFork(locator.Blocks);
}
/// <summary>
......@@ -187,12 +187,12 @@ namespace NBitcoin
/// <returns>Enumeration of chained block headers after given block hash.</returns>
public IEnumerable<ChainedHeader> EnumerateAfter(uint256 blockHash)
{
ChainedHeader block = this.GetBlock(blockHash);
ChainedHeader block = GetBlock(blockHash);
if (block == null)
return new ChainedHeader[0];
return this.EnumerateAfter(block);
return EnumerateAfter(block);
}
/// <summary>
......@@ -205,7 +205,7 @@ namespace NBitcoin
if (block == null)
throw new ArgumentNullException("block");
return this.EnumerateToTip(block.HashBlock);
return EnumerateToTip(block.HashBlock);
}
/// <summary>
......@@ -215,13 +215,13 @@ namespace NBitcoin
/// <returns>Enumeration of chained block headers from the given block hash to tip.</returns>
public IEnumerable<ChainedHeader> EnumerateToTip(uint256 blockHash)
{
ChainedHeader block = this.GetBlock(blockHash);
ChainedHeader block = GetBlock(blockHash);
if (block == null)
yield break;
yield return block;
foreach (ChainedHeader chainedBlock in this.EnumerateAfter(blockHash))
foreach (ChainedHeader chainedBlock in EnumerateAfter(blockHash))
yield return chainedBlock;
}
......@@ -237,7 +237,7 @@ namespace NBitcoin
while (true)
{
ChainedHeader b = this.GetBlock(i);
ChainedHeader b = GetBlock(i);
if ((b == null) || (b.Previous != prev))
yield break;
......
......@@ -28,7 +28,7 @@ namespace NBitcoin
public ConcurrentChain(BlockHeader genesisHeader, Network network = null) // TODO: Remove the null default
{
this.network = network ?? Network.Main;
this.SetTip(new ChainedHeader(genesisHeader, genesisHeader.GetHash(), 0));
SetTip(new ChainedHeader(genesisHeader, genesisHeader.GetHash(), 0));
}
public ConcurrentChain(Network network)
......@@ -39,17 +39,17 @@ namespace NBitcoin
public ConcurrentChain(byte[] bytes, Network network = null) // TODO: Remove the null default
: this(network ?? Network.Main)
{
this.Load(bytes);
Load(bytes);
}
public void Load(byte[] chain)
{
this.Load(new MemoryStream(chain));
Load(new MemoryStream(chain));
}
public void Load(Stream stream)
{
this.Load(new BitcoinStream(stream, false));
Load(new BitcoinStream(stream, false));
}
public void Load(BitcoinStream stream)
......@@ -72,10 +72,10 @@ namespace NBitcoin
this.blocksByHeight.Clear();
this.blocksById.Clear();
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))
this.SetTipLocked(new ChainedHeader(header, id.Value, this.Tip));
SetTipLocked(new ChainedHeader(header, id.Value, this.Tip));
else
break;
......@@ -90,14 +90,14 @@ namespace NBitcoin
public byte[] ToBytes()
{
MemoryStream ms = new MemoryStream();
this.WriteTo(ms);
var ms = new MemoryStream();
WriteTo(ms);
return ms.ToArray();
}
public void WriteTo(Stream stream)
{
this.WriteTo(new BitcoinStream(stream, true));
WriteTo(new BitcoinStream(stream, true));
}
public void WriteTo(BitcoinStream stream)
......@@ -117,7 +117,7 @@ namespace NBitcoin
public ConcurrentChain Clone()
{
ConcurrentChain chain = new ConcurrentChain();
var chain = new ConcurrentChain();
chain.network = this.network;
chain.tip = this.tip;
using (this.lockObject.LockRead())
......@@ -140,7 +140,7 @@ namespace NBitcoin
{
using (this.lockObject.LockWrite())
{
return this.SetTipLocked(block);
return SetTipLocked(block);
}
}
......@@ -155,7 +155,7 @@ namespace NBitcoin
{
if ((this.tip == null) || (block.ChainWork > this.tip.ChainWork))
{
this.SetTipLocked(block);
SetTipLocked(block);
return true;
}
}
......@@ -166,14 +166,14 @@ namespace NBitcoin
private ChainedHeader SetTipLocked(ChainedHeader block)
{
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.blocksByHeight.Remove(orphaned.Height);
height--;
}
ChainedHeader fork = this.GetBlockLocked(height);
ChainedHeader fork = GetBlockLocked(height);
foreach (ChainedHeader newBlock in block.EnumerateToGenesis().TakeWhile(c => c != fork))
{
this.blocksById.AddOrReplace(newBlock.HashBlock, newBlock);
......@@ -192,7 +192,7 @@ namespace NBitcoin
ChainedHeader tip = this.tip;
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");
if (tip.Height > block.Height)
......@@ -240,7 +240,7 @@ namespace NBitcoin
{
using (this.lockObject.LockRead())
{
return this.GetBlockLocked(height);
return GetBlockLocked(height);
}
}
......@@ -254,7 +254,7 @@ namespace NBitcoin
{
using (this.lockObject.LockRead())
{
block = this.GetBlockLocked(i);
block = GetBlockLocked(i);
if (block == null)
yield break;
}
......
......@@ -12,11 +12,11 @@ namespace NBitcoin
{
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
{
get
......@@ -31,7 +31,7 @@ namespace NBitcoin
throw new ArgumentNullException("feePerK");
if(feePerK.Satoshi < 0)
throw new ArgumentOutOfRangeException("feePerK");
_FeePerK = feePerK;
this._FeePerK = feePerK;
}
public FeeRate(Money feePaid, int size)
......@@ -41,9 +41,9 @@ namespace NBitcoin
if(feePaid.Satoshi < 0)
throw new ArgumentOutOfRangeException("feePaid");
if(size > 0)
_FeePerK = feePaid * 1000 / size;
this._FeePerK = feePaid * 1000 / size;
else
_FeePerK = 0;
this._FeePerK = 0;
}
/// <summary>
......@@ -53,9 +53,9 @@ namespace NBitcoin
/// <returns></returns>
public Money GetFee(int virtualSize)
{
Money nFee = _FeePerK.Satoshi * virtualSize / 1000;
if(nFee == 0 && _FeePerK.Satoshi > 0)
nFee = _FeePerK.Satoshi;
Money nFee = this._FeePerK.Satoshi * virtualSize / 1000;
if(nFee == 0 && this._FeePerK.Satoshi > 0)
nFee = this._FeePerK.Satoshi;
return nFee;
}
public Money GetFee(Transaction tx)
......@@ -65,11 +65,11 @@ namespace NBitcoin
public override bool Equals(object obj)
{
if(Object.ReferenceEquals(this, obj))
if(ReferenceEquals(this, obj))
return true;
if(((object)this == null) || (obj == null))
return false;
var left = this;
FeeRate left = this;
var right = obj as FeeRate;
if(right == null)
return false;
......@@ -78,21 +78,21 @@ namespace NBitcoin
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
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)
{
return other == null
? 1
: _FeePerK.CompareTo(other._FeePerK);
: this._FeePerK.CompareTo(other._FeePerK);
}
#endregion
......@@ -105,11 +105,11 @@ namespace NBitcoin
return 1;
var m = obj as FeeRate;
if (m != null)
return _FeePerK.CompareTo(m._FeePerK);
#if !(PORTABLE || NETCORE)
return this._FeePerK.CompareTo(m._FeePerK);
#if !NETCORE
return _FeePerK.CompareTo(obj);
#else
return _FeePerK.CompareTo((long)obj);
return this._FeePerK.CompareTo((long)obj);
#endif
}
......@@ -150,7 +150,7 @@ namespace NBitcoin
public static bool operator ==(FeeRate left, FeeRate right)
{
if (Object.ReferenceEquals(left, right))
if (ReferenceEquals(left, right))
return true;
if (((object)left == null) || ((object)right == null))
return false;
......@@ -164,7 +164,7 @@ namespace NBitcoin
public override int GetHashCode()
{
return _FeePerK.GetHashCode();
return this._FeePerK.GetHashCode();
}
public static FeeRate Min(FeeRate left, FeeRate right)
......
#if !NOFILEIO
using System;
using System;
using System.IO;
using System.Threading;
......@@ -12,12 +11,13 @@ namespace NBitcoin
}
public class FileLock : IDisposable
{
FileStream _Fs = null;
private FileStream _Fs = null;
public FileLock(string filePath, FileLockType lockType)
{
if(filePath == null)
throw new ArgumentNullException("filePath");
if(!File.Exists(filePath))
{
try
{
File.Create(filePath).Dispose();
......@@ -25,16 +25,16 @@ namespace NBitcoin
catch
{
}
CancellationTokenSource source = new CancellationTokenSource();
}
var source = new CancellationTokenSource();
source.CancelAfter(20000);
while(true)
{
try
{
if(lockType == FileLockType.Read)
_Fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
if(lockType == FileLockType.ReadWrite)
_Fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
if(lockType == FileLockType.Read) this._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);
break;
}
catch(IOException)
......@@ -48,7 +48,7 @@ namespace NBitcoin
public void Dispose()
{
_Fs.Dispose();
this._Fs.Dispose();
}
......@@ -68,4 +68,3 @@ namespace NBitcoin
//}
}
}
#endif
\ No newline at end of file
......@@ -6,16 +6,16 @@ namespace NBitcoin
{
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)
:base(network ?? Network.Main)
public InMemoryNoSqlRepository(Network network)
:base(network)
{
}
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)
{
......@@ -34,4 +34,4 @@ namespace NBitcoin
return Task.FromResult(result);
}
}
}
}
\ No newline at end of file
#if !NOSOCKET
using System;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
......@@ -8,53 +7,10 @@ namespace NBitcoin
{
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)
{
address = address.EnsureIPv6();
var bytes = address.GetAddressBytes();
byte[] bytes = address.GetAddressBytes();
return address.IsIPv4() && (
bytes[15 - 3] == 10 ||
(bytes[15 - 3] == 192 && bytes[15 - 2] == 168) ||
......@@ -64,76 +20,76 @@ namespace NBitcoin
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)
{
address = address.EnsureIPv6();
var bytes = address.GetAddressBytes();
byte[] bytes = address.GetAddressBytes();
return address.IsIPv4() && (bytes[15 - 3] == 169 && bytes[15 - 2] == 254);
}
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;
}
public static bool IsRFC3964(this IPAddress address)
{
var bytes = address.GetAddressBytes();
byte[] bytes = address.GetAddressBytes();
return (bytes[15 - 15] == 0x20 && bytes[15 - 14] == 0x02);
}
public static bool IsRFC6052(this IPAddress address)
{
var bytes = address.GetAddressBytes();
byte[] pchRFC6052 = new byte[] { 0, 0x64, 0xFF, 0x9B, 0, 0, 0, 0, 0, 0, 0, 0 };
byte[] bytes = address.GetAddressBytes();
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);
}
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);
}
public static bool IsRFC4862(this IPAddress address)
{
var bytes = address.GetAddressBytes();
byte[] pchRFC4862 = new byte[] { 0xFE, 0x80, 0, 0, 0, 0, 0, 0 };
byte[] bytes = address.GetAddressBytes();
var pchRFC4862 = new byte[] { 0xFE, 0x80, 0, 0, 0, 0, 0, 0 };
return ((Utils.ArrayEqual(bytes, 0, pchRFC4862, 0, pchRFC4862.Length) ? 0 : 1) == 0);
}
public static bool IsRFC4193(this IPAddress address)
{
var bytes = address.GetAddressBytes();
byte[] bytes = address.GetAddressBytes();
return ((bytes[15 - 15] & 0xFE) == 0xFC);
}
public static bool IsRFC6145(this IPAddress address)
{
var bytes = address.GetAddressBytes();
byte[] pchRFC6145 = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0, 0 };
byte[] bytes = address.GetAddressBytes();
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);
}
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);
}
public static byte[] GetGroup(this IPAddress address)
{
List<byte> vchRet = new List<byte>();
var vchRet = new List<byte>();
int nClass = 2;
int nStartByte = 0;
int nBits = 16;
address = address.EnsureIPv6();
var bytes = address.GetAddressBytes();
byte[] bytes = address.GetAddressBytes();
// all local addresses belong to the same group
if(address.IsLocal())
......@@ -196,10 +152,10 @@ namespace NBitcoin
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)
{
var bytes = address.GetAddressBytes();
byte[] bytes = address.GetAddressBytes();
return ((Utils.ArrayEqual(bytes, 0, pchOnionCat, 0, pchOnionCat.Length) ? 0 : 1) == 0);
}
public static IPAddress EnsureIPv6(this IPAddress address)
......@@ -209,7 +165,7 @@ namespace NBitcoin
return address.MapToIPv6Ex();
}
static bool? _IsRunningOnMono;
private static bool? _IsRunningOnMono;
public static bool IsRunningOnMono()
{
if(_IsRunningOnMono == null)
......@@ -219,32 +175,24 @@ namespace NBitcoin
public static IPAddress MapToIPv6Ex(this IPAddress address)
{
#if WIN
return Compatibility.MapToIPv6(address);
#else
return Utils.MapToIPv6(address);
#endif
}
public static bool IsIPv4MappedToIPv6Ex(this IPAddress address)
{
#if WIN
return Compatibility.IsIPv4MappedToIPv6(address);
#else
return Utils.IsIPv4MappedToIPv6(address);
#endif
}
public static bool IsLocal(this IPAddress address)
{
address = address.EnsureIPv6();
var bytes = address.GetAddressBytes();
byte[] bytes = address.GetAddressBytes();
// IPv4 loopback
if(address.IsIPv4() && (bytes[15 - 3] == 127 || bytes[15 - 3] == 0))
return true;
// 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)
return true;
......@@ -254,7 +202,7 @@ namespace NBitcoin
public static bool IsMulticast(this IPAddress address)
{
address = address.EnsureIPv6();
var bytes = address.GetAddressBytes();
byte[] bytes = address.GetAddressBytes();
return (address.IsIPv4() && (bytes[15 - 3] & 0xF0) == 0xE0)
|| (bytes[15 - 15] == 0xFF);
}
......@@ -277,9 +225,9 @@ namespace NBitcoin
public static bool IsValid(this IPAddress address)
{
address = address.EnsureIPv6();
var ip = address.GetAddressBytes();
byte[] ip = address.GetAddressBytes();
// 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)
return false;
......@@ -302,4 +250,3 @@ namespace NBitcoin
}
}
}
#endif
\ No newline at end of file
using System;
using System.Linq;
using System.Text;
using NBitcoin.BouncyCastle.Asn1.X9;
using NBitcoin.BouncyCastle.Math;
using NBitcoin.Crypto;
......@@ -21,7 +22,7 @@ namespace NBitcoin
return Network.Parse<BitcoinEncryptedSecret>(wif, network).GetKey(password);
}
byte[] vch = new byte[0];
private byte[] vch = new byte[0];
internal ECKey _ECKey;
public bool IsCompressed
{
......@@ -63,9 +64,9 @@ namespace NBitcoin
private void SetBytes(byte[] data, int count, bool fCompressedIn)
{
vch = data.SafeSubarray(0, count);
IsCompressed = fCompressedIn;
_ECKey = new ECKey(vch, true);
this.vch = data.SafeSubarray(0, count);
this.IsCompressed = fCompressedIn;
this._ECKey = new ECKey(this.vch, true);
}
private static bool Check(byte[] vch)
......@@ -74,24 +75,24 @@ namespace NBitcoin
return candidateKey > 0 && candidateKey < N;
}
PubKey _PubKey;
private PubKey _PubKey;
public PubKey PubKey
{
get
{
if(_PubKey == null)
if(this._PubKey == null)
{
ECKey key = new ECKey(vch, true);
_PubKey = key.GetPubKey(IsCompressed);
var key = new ECKey(this.vch, true);
this._PubKey = key.GetPubKey(this.IsCompressed);
}
return _PubKey;
return this._PubKey;
}
}
public ECDSASignature Sign(uint256 hash)
{
return _ECKey.Sign(hash);
return this._ECKey.Sign(hash);
}
......@@ -102,20 +103,20 @@ namespace NBitcoin
public string SignMessage(byte[] messageBytes)
{
byte[] data = Utils.FormatMessageForSigning(messageBytes);
var hash = Hashes.Hash256(data);
uint256 hash = Hashes.Hash256(data);
return Convert.ToBase64String(SignCompact(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.
int recId = -1;
for(int i = 0; i < 4; i++)
{
ECKey k = ECKey.RecoverFromSignature(i, sig, hash, IsCompressed);
if(k != null && k.GetPubKey(IsCompressed).ToHex() == PubKey.ToHex())
ECKey k = ECKey.RecoverFromSignature(i, sig, hash, this.IsCompressed);
if(k != null && k.GetPubKey(this.IsCompressed).ToHex() == this.PubKey.ToHex())
{
recId = i;
break;
......@@ -125,9 +126,9 @@ namespace NBitcoin
if(recId == -1)
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;
......@@ -140,10 +141,10 @@ namespace NBitcoin
public void ReadWrite(BitcoinStream stream)
{
stream.ReadWrite(ref vch);
stream.ReadWrite(ref this.vch);
if(!stream.Serializing)
{
_ECKey = new ECKey(vch, true);
this._ECKey = new ECKey(this.vch, true);
}
}
......@@ -154,29 +155,29 @@ namespace NBitcoin
byte[] l = null;
if((nChild >> 31) == 0)
{
var pubKey = PubKey.ToBytes();
byte[] pubKey = this.PubKey.ToBytes();
l = Hashes.BIP32Hash(cc, nChild, pubKey[0], pubKey.SafeSubarray(1));
}
else
{
l = Hashes.BIP32Hash(cc, nChild, 0, this.ToBytes());
}
var ll = l.SafeSubarray(0, 32);
var lr = l.SafeSubarray(32, 32);
byte[] ll = l.SafeSubarray(0, 32);
byte[] lr = l.SafeSubarray(32, 32);
ccChild = lr;
var parse256LL = new BigInteger(1, ll);
var kPar = new BigInteger(1, vch);
var N = ECKey.CURVE.N;
var kPar = new BigInteger(1, this.vch);
BigInteger N = ECKey.CURVE.N;
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.");
var key = parse256LL.Add(kPar).Mod(N);
BigInteger key = parse256LL.Add(kPar).Mod(N);
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.");
var keyBytes = key.ToByteArrayUnsigned();
byte[] keyBytes = key.ToByteArrayUnsigned();
if(keyBytes.Length < 32)
keyBytes = new byte[32 - keyBytes.Length].Concat(keyBytes).ToArray();
return new Key(keyBytes);
......@@ -184,8 +185,8 @@ namespace NBitcoin
public Key Uncover(Key scan, PubKey ephem)
{
var curve = ECKey.Secp256k1;
var priv = new BigInteger(1, PubKey.GetStealthSharedSecret(scan, ephem))
X9ECParameters curve = ECKey.Secp256k1;
byte[] priv = new BigInteger(1, PubKey.GetStealthSharedSecret(scan, ephem))
.Add(new BigInteger(1, this.ToBytes()))
.Mod(curve.N)
.ToByteArrayUnsigned();
......@@ -228,7 +229,7 @@ namespace NBitcoin
{
get
{
return PubKey.Hash.ScriptPubKey;
return this.PubKey.Hash.ScriptPubKey;
}
}
......@@ -242,14 +243,14 @@ namespace NBitcoin
public override bool Equals(object obj)
{
Key item = obj as Key;
var item = obj as Key;
if(item == null)
return false;
return PubKey.Equals(item.PubKey);
return this.PubKey.Equals(item.PubKey);
}
public static bool operator ==(Key a, Key b)
{
if(System.Object.ReferenceEquals(a, b))
if(ReferenceEquals(a, b))
return true;
if(((object)a == null) || ((object)b == null))
return false;
......@@ -263,7 +264,7 @@ namespace NBitcoin
public override int GetHashCode()
{
return PubKey.GetHashCode();
return this.PubKey.GetHashCode();
}
}
}
......@@ -10,20 +10,20 @@ namespace NBitcoin
public TxDestination()
{
_DestBytes = new byte[] { 0 };
this._DestBytes = new byte[] { 0 };
}
public TxDestination(byte[] value)
{
if(value == null)
throw new ArgumentNullException("value");
_DestBytes = value;
this._DestBytes = value;
}
public TxDestination(string value)
{
_DestBytes = Encoders.Hex.DecodeData(value);
_Str = value;
this._DestBytes = Encoders.Hex.DecodeData(value);
this._Str = value;
}
public abstract BitcoinAddress GetAddress(Network network);
......@@ -45,22 +45,22 @@ namespace NBitcoin
public byte[] ToBytes(bool @unsafe)
{
if(@unsafe)
return _DestBytes;
var array = new byte[_DestBytes.Length];
Array.Copy(_DestBytes, array, _DestBytes.Length);
return this._DestBytes;
var array = new byte[this._DestBytes.Length];
Array.Copy(this._DestBytes, array, this._DestBytes.Length);
return array;
}
public override bool Equals(object obj)
{
TxDestination item = obj as TxDestination;
var item = obj as TxDestination;
if(item == null)
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)
{
if(System.Object.ReferenceEquals(a, b))
if(ReferenceEquals(a, b))
return true;
if(((object)a == null) || ((object)b == null))
return false;
......@@ -74,15 +74,14 @@ namespace NBitcoin
public override int GetHashCode()
{
return Utils.GetHashCode(_DestBytes);
return Utils.GetHashCode(this._DestBytes);
}
string _Str;
private string _Str;
public override string ToString()
{
if(_Str == null)
_Str = Encoders.Hex.EncodeData(_DestBytes);
return _Str;
if(this._Str == null) this._Str = Encoders.Hex.EncodeData(this._DestBytes);
return this._Str;
}
}
public class KeyId : TxDestination
......@@ -159,7 +158,7 @@ namespace NBitcoin
{
get
{
return PayToWitTemplate.Instance.GenerateScriptPubKey(OpcodeType.OP_0, _DestBytes);
return PayToWitTemplate.Instance.GenerateScriptPubKey(OpcodeType.OP_0, this._DestBytes);
}
}
......@@ -168,7 +167,7 @@ namespace NBitcoin
{
get
{
return new KeyId(_DestBytes).ScriptPubKey;
return new KeyId(this._DestBytes).ScriptPubKey;
}
}
......@@ -217,7 +216,7 @@ namespace NBitcoin
{
get
{
return PayToWitTemplate.Instance.GenerateScriptPubKey(OpcodeType.OP_0, _DestBytes);
return PayToWitTemplate.Instance.GenerateScriptPubKey(OpcodeType.OP_0, this._DestBytes);
}
}
......
......@@ -5,7 +5,7 @@ namespace NBitcoin
public struct LockTime : IBitcoinSerializable
{
internal const uint LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
uint _value;
private uint _value;
public static LockTime Zero
{
......@@ -16,17 +16,17 @@ namespace NBitcoin
}
public LockTime(DateTimeOffset dateTime)
{
_value = Utils.DateTimeToUnixTime(dateTime);
if(_value < LOCKTIME_THRESHOLD)
this._value = Utils.DateTimeToUnixTime(dateTime);
if(this._value < LOCKTIME_THRESHOLD)
throw new ArgumentOutOfRangeException("dateTime", "The minimum possible date is be Tue Nov 5 00:53:20 1985 UTC");
}
public LockTime(int valueOrHeight)
{
_value = (uint)valueOrHeight;
this._value = (uint)valueOrHeight;
}
public LockTime(uint valueOrHeight)
{
_value = valueOrHeight;
this._value = valueOrHeight;
}
......@@ -34,9 +34,9 @@ namespace NBitcoin
{
get
{
if(!IsTimeLock)
if(!this.IsTimeLock)
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
{
get
{
if(!IsHeightLock)
if(!this.IsHeightLock)
throw new InvalidOperationException("This is not a height based lock");
return (int)_value;
return (int) this._value;
}
}
......@@ -54,7 +54,7 @@ namespace NBitcoin
{
get
{
return _value;
return this._value;
}
}
......@@ -63,7 +63,7 @@ namespace NBitcoin
{
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
{
get
{
return !IsHeightLock;
return !this.IsHeightLock;
}
}
......@@ -80,14 +80,14 @@ namespace NBitcoin
public void ReadWrite(BitcoinStream stream)
{
stream.ReadWrite(ref _value);
stream.ReadWrite(ref this._value);
}
#endregion
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)
......@@ -129,7 +129,7 @@ namespace NBitcoin
if(!(obj is LockTime))
return false;
var item = (LockTime)obj;
return _value.Equals(item._value);
return this._value.Equals(item._value);
}
public static bool operator ==(LockTime a, LockTime b)
{
......@@ -143,7 +143,7 @@ namespace NBitcoin
public override int GetHashCode()
{
return _value.GetHashCode();
return this._value.GetHashCode();
}
}
}
......@@ -10,30 +10,31 @@ namespace NBitcoin
}
// Public only for unit testing
BlockHeader header;
private BlockHeader header;
public BlockHeader Header
{
get
{
return header;
return this.header;
}
set
{
header = value;
this.header = value;
}
}
PartialMerkleTree _PartialMerkleTree;
private PartialMerkleTree _PartialMerkleTree;
public PartialMerkleTree PartialMerkleTree
{
get
{
return _PartialMerkleTree;
return this._PartialMerkleTree;
}
set
{
_PartialMerkleTree = value;
this._PartialMerkleTree = value;
}
}
......@@ -42,10 +43,10 @@ namespace NBitcoin
// thus the filter will likely be modified.
public MerkleBlock(Block block, BloomFilter filter)
{
header = block.Header;
this.header = block.Header;
List<bool> vMatch = new List<bool>();
List<uint256> vHashes = new List<uint256>();
var vMatch = new List<bool>();
var vHashes = new List<uint256>();
for(uint i = 0; i < block.Transactions.Count; i++)
......@@ -55,30 +56,31 @@ namespace NBitcoin
vHashes.Add(hash);
}
_PartialMerkleTree = new PartialMerkleTree(vHashes.ToArray(), vMatch.ToArray());
this._PartialMerkleTree = new PartialMerkleTree(vHashes.ToArray(), vMatch.ToArray());
}
public MerkleBlock(Block block, uint256[] txIds)
{
header = block.Header;
this.header = block.Header;
List<bool> vMatch = new List<bool>();
List<uint256> vHashes = new List<uint256>();
var vMatch = new List<bool>();
var vHashes = new List<uint256>();
for(int i = 0; i < block.Transactions.Count; i++)
{
var hash = block.Transactions[i].GetHash();
uint256 hash = block.Transactions[i].GetHash();
vHashes.Add(hash);
vMatch.Add(txIds.Contains(hash));
}
_PartialMerkleTree = new PartialMerkleTree(vHashes.ToArray(), vMatch.ToArray());
this._PartialMerkleTree = new PartialMerkleTree(vHashes.ToArray(), vMatch.ToArray());
}
#region IBitcoinSerializable Members
public void ReadWrite(BitcoinStream stream)
{
stream.ReadWrite(ref header);
stream.ReadWrite(ref _PartialMerkleTree);
stream.ReadWrite(ref this.header);
stream.ReadWrite(ref this._PartialMerkleTree);
}
#endregion
......
......@@ -10,7 +10,7 @@ namespace NBitcoin
{
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)
return new MerkleNode(uint256.Zero);
while(row.Count != 1)
......@@ -18,8 +18,8 @@ namespace NBitcoin
var parentRow = new List<MerkleNode>();
for(int i = 0; i < row.Count; i += 2)
{
var left = row[i];
var right = i + 1 < row.Count ? row[i + 1] : null;
MerkleNode left = row[i];
MerkleNode right = i + 1 < row.Count ? row[i + 1] : null;
var parent = new MerkleNode(left, right);
parentRow.Add(parent);
}
......@@ -37,14 +37,14 @@ namespace NBitcoin
public MerkleNode(uint256 hash)
{
_Hash = hash;
IsLeaf = true;
this._Hash = hash;
this.IsLeaf = true;
}
public MerkleNode(MerkleNode left, MerkleNode right)
{
Left = left;
Right = right;
this.Left = left;
this.Right = right;
if(left != null)
left.Parent = this;
if(right != null)
......@@ -56,19 +56,18 @@ namespace NBitcoin
{
get
{
return _Hash;
return this._Hash;
}
set
{
_Hash = value;
this._Hash = value;
}
}
public void UpdateHash()
{
var right = Right ?? Left;
if(Left != null && Left.Hash != null && right.Hash != null)
_Hash = Hashes.Hash256(Left.Hash.ToBytes().Concat(right.Hash.ToBytes()).ToArray());
MerkleNode right = this.Right ?? this.Left;
if(this.Left != null && this.Left.Hash != null && right.Hash != null) this._Hash = Hashes.Hash256(this.Left.Hash.ToBytes().Concat(right.Hash.ToBytes()).ToArray());
}
public bool IsLeaf
......@@ -76,7 +75,8 @@ namespace NBitcoin
get;
private set;
}
uint256 _Hash;
private uint256 _Hash;
public MerkleNode Parent
{
get;
......@@ -96,10 +96,10 @@ namespace NBitcoin
public IEnumerable<MerkleNode> EnumerateDescendants()
{
IEnumerable<MerkleNode> result = new MerkleNode[] { this };
if(Right != null)
result = Right.EnumerateDescendants().Concat(result);
if(Left != null)
result = Left.EnumerateDescendants().Concat(result);
if(this.Right != null)
result = this.Right.EnumerateDescendants().Concat(result);
if(this.Left != null)
result = this.Left.EnumerateDescendants().Concat(result);
return result;
}
......@@ -121,7 +121,7 @@ namespace NBitcoin
public IEnumerable<MerkleNode> Ancestors()
{
var n = Parent;
MerkleNode n = this.Parent;
while(n != null)
{
yield return n;
......@@ -131,27 +131,25 @@ namespace NBitcoin
public override string ToString()
{
return Hash == null ? "???" : Hash.ToString();
return this.Hash == null ? "???" : this.Hash.ToString();
}
public string ToString(bool hierachy)
{
if(!hierachy)
return ToString();
StringBuilder builder = new StringBuilder();
var builder = new StringBuilder();
ToString(builder, 0);
return builder.ToString();
}
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.AppendLine(ToString());
if(Left != null)
Left.ToString(builder, indent + 1);
if(Right != null)
Right.ToString(builder, indent + 1);
if(this.Left != null) this.Left.ToString(builder, indent + 1);
if(this.Right != null) this.Right.ToString(builder, indent + 1);
}
}
}
......@@ -14,7 +14,7 @@ namespace NBitcoin
if(moneys == null)
throw new ArgumentNullException("moneys");
long result = 0;
foreach(var money in moneys)
foreach(Money money in moneys)
{
result = checked(result + money.Satoshi);
}
......@@ -28,7 +28,7 @@ namespace NBitcoin
if(zero == null)
throw new ArgumentNullException("zero");
IMoney result = zero;
foreach(var money in moneys)
foreach(IMoney money in moneys)
{
result = result.Add(money);
}
......@@ -44,7 +44,7 @@ namespace NBitcoin
throw new ArgumentNullException("assetId");
long result = 0;
AssetId id = null;
foreach(var money in moneys)
foreach(AssetMoney money in moneys)
{
result = checked(result + money.Quantity);
if(id == null)
......@@ -96,7 +96,7 @@ namespace NBitcoin
private MoneyBag(IEnumerable<IMoney> bag)
{
foreach(var money in bag)
foreach(IMoney money in bag)
{
AppendMoney(money);
}
......@@ -104,7 +104,7 @@ namespace NBitcoin
private void AppendMoney(MoneyBag money)
{
foreach(var m in money._bag)
foreach(IMoney m in money._bag)
{
AppendMoney(m);
}
......@@ -119,18 +119,17 @@ namespace NBitcoin
return;
}
var firstCompatible = _bag.FirstOrDefault(x => x.IsCompatible(money));
IMoney firstCompatible = this._bag.FirstOrDefault(x => x.IsCompatible(money));
if(firstCompatible == null)
{
_bag.Add(money);
this._bag.Add(money);
}
else
{
_bag.Remove(firstCompatible);
var zero = firstCompatible.Sub(firstCompatible);
var total = firstCompatible.Add(money);
if(!zero.Equals(total))
_bag.Add(total);
this._bag.Remove(firstCompatible);
IMoney zero = firstCompatible.Sub(firstCompatible);
IMoney total = firstCompatible.Add(money);
if(!zero.Equals(total)) this._bag.Add(total);
}
}
......@@ -152,7 +151,7 @@ namespace NBitcoin
if(other == null)
return false;
var m = new MoneyBag(other);
return m._bag.SequenceEqual(_bag);
return m._bag.SequenceEqual(this._bag);
}
public static MoneyBag operator -(MoneyBag left, IMoney right)
......@@ -175,7 +174,7 @@ namespace NBitcoin
IMoney IMoney.Add(IMoney money)
{
var m = new MoneyBag(_bag);
var m = new MoneyBag(this._bag);
m.AppendMoney(money);
return m;
}
......@@ -187,7 +186,7 @@ namespace NBitcoin
IMoney IMoney.Negate()
{
return new MoneyBag(_bag.Select(x => x.Negate()));
return new MoneyBag(this._bag.Select(x => x.Negate()));
}
bool IMoney.IsCompatible(IMoney money)
......@@ -211,7 +210,7 @@ namespace NBitcoin
public override string ToString()
{
var sb = new StringBuilder();
foreach(var money in _bag)
foreach(IMoney money in this._bag)
{
sb.AppendFormat("{0} ", money);
}
......@@ -220,12 +219,12 @@ namespace NBitcoin
public IEnumerator<IMoney> GetEnumerator()
{
return _bag.GetEnumerator();
return this._bag.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _bag.GetEnumerator();
return this._bag.GetEnumerator();
}
/// <summary>
......@@ -237,16 +236,16 @@ namespace NBitcoin
{
if(parts <= 0)
throw new ArgumentOutOfRangeException("Parts should be more than 0", "parts");
List<List<IMoney>> splits = new List<List<IMoney>>();
foreach(var money in this)
var splits = new List<List<IMoney>>();
foreach(IMoney money in this)
{
splits.Add(money.Split(parts).ToList());
}
for(int i = 0; i < parts; i++)
{
MoneyBag bag = new MoneyBag();
foreach(var split in splits)
var bag = new MoneyBag();
foreach(List<IMoney> split in splits)
{
bag += split[i];
}
......@@ -316,18 +315,18 @@ namespace NBitcoin
throw new FormatException("Impossible to parse the string in a bitcoin amount");
}
long _Satoshis;
private long _Satoshis;
public long Satoshi
{
get
{
return _Satoshis;
return this._Satoshis;
}
// used as a central point where long.MinValue checking can be enforced
private set
{
CheckLongMinValue(value);
_Satoshis = value;
this._Satoshis = value;
}
}
......@@ -337,25 +336,25 @@ namespace NBitcoin
/// <returns></returns>
public Money Abs()
{
var a = this;
if(a < Money.Zero)
Money a = this;
if(a < Zero)
a = -a;
return a;
}
public Money(int satoshis)
{
Satoshi = satoshis;
this.Satoshi = satoshis;
}
public Money(uint satoshis)
{
Satoshi = satoshis;
this.Satoshi = satoshis;
}
public Money(long satoshis)
{
Satoshi = satoshis;
this.Satoshi = satoshis;
}
public Money(ulong satoshis)
......@@ -364,7 +363,7 @@ namespace NBitcoin
// ulong.MaxValue is greater than long.MaxValue
checked
{
Satoshi = (long)satoshis;
this.Satoshi = (long)satoshis;
}
}
......@@ -374,8 +373,8 @@ namespace NBitcoin
CheckMoneyUnit(unit, "unit");
checked
{
var satoshi = amount * (int)unit;
Satoshi = (long)satoshi;
decimal satoshi = amount * (int)unit;
this.Satoshi = (long)satoshi;
}
}
......@@ -390,11 +389,11 @@ namespace NBitcoin
if(parts <= 0)
throw new ArgumentOutOfRangeException("Parts should be more than 0", "parts");
long remain;
long result = DivRem(_Satoshis, parts, out remain);
long result = DivRem(this._Satoshis, parts, out remain);
for(int i = 0; i < parts; i++)
{
yield return Money.Satoshis(result + (remain > 0 ? 1 : 0));
yield return Satoshis(result + (remain > 0 ? 1 : 0));
remain--;
}
}
......@@ -420,7 +419,7 @@ namespace NBitcoin
CheckMoneyUnit(unit, "unit");
// overflow safe because (long / int) always fit in decimal
// decimal operations are checked by default
return (decimal)Satoshi / (int)unit;
return (decimal) this.Satoshi / (int)unit;
}
/// <summary>
/// Convert Money to decimal (same as ToUnit)
......@@ -474,14 +473,14 @@ namespace NBitcoin
{
if(other == null)
return false;
return _Satoshis.Equals(other._Satoshis);
return this._Satoshis.Equals(other._Satoshis);
}
public int CompareTo(Money other)
{
if(other == null)
return 1;
return _Satoshis.CompareTo(other._Satoshis);
return this._Satoshis.CompareTo(other._Satoshis);
}
#endregion
......@@ -492,13 +491,13 @@ namespace NBitcoin
{
if(obj == null)
return 1;
Money m = obj as Money;
var m = obj as Money;
if(m != null)
return _Satoshis.CompareTo(m._Satoshis);
#if !(PORTABLE || NETCORE)
return this._Satoshis.CompareTo(m._Satoshis);
#if !NETCORE
return _Satoshis.CompareTo(obj);
#else
return _Satoshis.CompareTo((long)obj);
return this._Satoshis.CompareTo((long)obj);
#endif
}
......@@ -530,26 +529,26 @@ namespace NBitcoin
{
if(right == null)
throw new ArgumentNullException("right");
return Money.Satoshis(checked(left * right._Satoshis));
return Satoshis(checked(left * right._Satoshis));
}
public static Money operator *(Money right, int left)
{
if(right == null)
throw new ArgumentNullException("right");
return Money.Satoshis(checked(right._Satoshis * left));
return Satoshis(checked(right._Satoshis * left));
}
public static Money operator *(long left, Money right)
{
if(right == null)
throw new ArgumentNullException("right");
return Money.Satoshis(checked(left * right._Satoshis));
return Satoshis(checked(left * right._Satoshis));
}
public static Money operator *(Money right, long left)
{
if(right == null)
throw new ArgumentNullException("right");
return Money.Satoshis(checked(left * right._Satoshis));
return Satoshis(checked(left * right._Satoshis));
}
public static Money operator /(Money left, long right)
......@@ -623,19 +622,19 @@ namespace NBitcoin
public static implicit operator Money(string value)
{
return Money.Parse(value);
return Parse(value);
}
public override bool Equals(object obj)
{
Money item = obj as Money;
var item = obj as Money;
if(item == null)
return false;
return _Satoshis.Equals(item._Satoshis);
return this._Satoshis.Equals(item._Satoshis);
}
public static bool operator ==(Money a, Money b)
{
if(Object.ReferenceEquals(a, b))
if(ReferenceEquals(a, b))
return true;
if(((object)a == null) || ((object)b == null))
return false;
......@@ -649,7 +648,7 @@ namespace NBitcoin
public override int GetHashCode()
{
return _Satoshis.GetHashCode();
return this._Satoshis.GetHashCode();
}
......@@ -670,14 +669,14 @@ namespace NBitcoin
/// <returns></returns>
public string ToString(bool fplus, bool trimExcessZero = true)
{
var fmt = string.Format("{{0:{0}{1}B}}",
string fmt = string.Format("{{0:{0}{1}B}}",
(fplus ? "+" : null),
(trimExcessZero ? "2" : "8"));
return string.Format(BitcoinFormatter.Formatter, fmt, _Satoshis);
return string.Format(BitcoinFormatter.Formatter, fmt, this._Satoshis);
}
static Money _Zero = new Money(0);
private static Money _Zero = new Money(0);
public static Money Zero
{
get
......@@ -713,7 +712,7 @@ namespace NBitcoin
throw new ArgumentNullException("amount");
if(margin < 0.0m || margin > 1.0m)
throw new ArgumentOutOfRangeException("margin", "margin should be between 0 and 1");
var dust = Money.Satoshis((decimal)this.Satoshi * margin);
Money dust = Satoshis((decimal)this.Satoshi * margin);
return Almost(amount, dust);
}
......@@ -747,7 +746,7 @@ namespace NBitcoin
private static void CheckMoneyUnit(MoneyUnit value, string paramName)
{
var typeOfMoneyUnit = typeof(MoneyUnit);
Type typeOfMoneyUnit = typeof(MoneyUnit);
if(!Enum.IsDefined(typeOfMoneyUnit, value))
{
throw new ArgumentException("Invalid value for MoneyUnit", paramName);
......@@ -777,7 +776,7 @@ namespace NBitcoin
int IComparable.CompareTo(object obj)
{
return this.CompareTo(obj);
return CompareTo(obj);
}
#endregion
......@@ -786,7 +785,7 @@ namespace NBitcoin
int IComparable<IMoney>.CompareTo(IMoney other)
{
return this.CompareTo(other);
return CompareTo(other);
}
#endregion
......@@ -795,7 +794,7 @@ namespace NBitcoin
bool IEquatable<IMoney>.Equals(IMoney other)
{
return this.Equals(other);
return Equals(other);
}
bool IMoney.IsCompatible(IMoney money)
......@@ -823,7 +822,7 @@ namespace NBitcoin
#endregion
}
static class CharExtensions
internal static class CharExtensions
{
// .NET Char class already provides an static IsDigit method however
// it behaves differently depending on if char is a Latin or not.
......@@ -844,12 +843,12 @@ namespace NBitcoin
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if(!this.Equals(formatProvider))
if(!Equals(formatProvider))
{
return null;
}
var i = 0;
var plus = format[i] == '+';
int i = 0;
bool plus = format[i] == '+';
if(plus)
i++;
int decPos = 0;
......@@ -857,7 +856,7 @@ namespace NBitcoin
{
i++;
}
var unit = format[i];
char unit = format[i];
var unitToUseInCalc = MoneyUnit.BTC;
switch(unit)
{
......@@ -865,10 +864,10 @@ namespace NBitcoin
unitToUseInCalc = MoneyUnit.BTC;
break;
}
var val = Convert.ToDecimal(arg) / (int)unitToUseInCalc;
var zeros = new string('0', decPos);
var rest = new string('#', 10 - decPos);
var fmt = plus && val > 0 ? "+" : string.Empty;
decimal val = Convert.ToDecimal(arg) / (int)unitToUseInCalc;
string zeros = new string('0', decPos);
string rest = new string('#', 10 - decPos);
string fmt = plus && val > 0 ? "+" : string.Empty;
fmt += "{0:0" + (decPos > 0 ? "." + zeros + rest : string.Empty) + "}";
return string.Format(CultureInfo.InvariantCulture, fmt, val);
......
......@@ -5,31 +5,21 @@ namespace NBitcoin
{
public class NoSqlTransactionRepository : ITransactionRepository
{
private readonly NoSqlRepository repository;
public NoSqlRepository Repository
{
get
{
return this.repository;
}
}
public NoSqlRepository Repository { get; }
public NoSqlTransactionRepository(Network network = null)
public NoSqlTransactionRepository(Network network)
:this(new InMemoryNoSqlRepository(network))
{
}
public NoSqlTransactionRepository(NoSqlRepository repository)
{
if(repository == null)
throw new ArgumentNullException("repository");
this.repository = repository;
this.Repository = repository ?? throw new ArgumentNullException("repository");
}
#region ITransactionRepository Members
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)
......@@ -39,9 +29,7 @@ namespace NBitcoin
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
{
}
uint _TransactionCount;
private uint _TransactionCount;
public uint TransactionCount
{
get
{
return _TransactionCount;
return this._TransactionCount;
}
set
{
_TransactionCount = value;
this._TransactionCount = value;
}
}
List<uint256> _Hashes = new List<uint256>();
private List<uint256> _Hashes = new List<uint256>();
public List<uint256> Hashes
{
get
{
return _Hashes;
return this._Hashes;
}
}
BitArray _Flags = new BitArray(0);
private BitArray _Flags = new BitArray(0);
public BitArray Flags
{
get
{
return _Flags;
return this._Flags;
}
set
{
_Flags = value;
this._Flags = value;
}
}
......@@ -51,22 +52,22 @@ namespace NBitcoin
public void ReadWrite(BitcoinStream stream)
{
stream.ReadWrite(ref _TransactionCount);
stream.ReadWrite(ref _Hashes);
stream.ReadWrite(ref this._TransactionCount);
stream.ReadWrite(ref this._Hashes);
byte[] vBytes = null;
if(!stream.Serializing)
{
stream.ReadWriteAsVarString(ref vBytes);
BitWriter writer = new BitWriter();
var writer = new BitWriter();
for(int p = 0; p < vBytes.Length * 8; p++)
writer.Write((vBytes[p / 8] & (1 << (p % 8))) != 0);
_Flags = writer.ToBitArray();
this._Flags = writer.ToBitArray();
}
else
{
vBytes = new byte[(_Flags.Length + 7) / 8];
for(int p = 0; p < _Flags.Length; p++)
vBytes[p / 8] |= (byte)(ToByte(_Flags.Get(p)) << (p % 8));
vBytes = new byte[(this._Flags.Length + 7) / 8];
for(int p = 0; p < this._Flags.Length; p++)
vBytes[p / 8] |= (byte)(ToByte(this._Flags.Get(p)) << (p % 8));
stream.ReadWriteAsVarString(ref vBytes);
}
}
......@@ -82,21 +83,21 @@ namespace NBitcoin
{
if(vMatch.Length != vTxid.Length)
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);
BitWriter flags = new BitWriter();
var flags = new BitWriter();
MarkNodes(root, vMatch);
BuildCore(root, flags);
Flags = flags.ToBitArray();
this.Flags = flags.ToBitArray();
}
private static void MarkNodes(MerkleNode root, bool[] vMatch)
{
BitReader matches = new BitReader(new BitArray(vMatch));
foreach(var leaf in root.GetLeafs())
var matches = new BitReader(new BitArray(vMatch));
foreach(MerkleNode leaf in root.GetLeafs())
{
if(matches.Read())
{
......@@ -108,7 +109,7 @@ namespace NBitcoin
private static void MarkToTop(MerkleNode leaf, bool value)
{
leaf.IsMarked = value;
foreach(var ancestor in leaf.Ancestors())
foreach(MerkleNode ancestor in leaf.Ancestors())
{
ancestor.IsMarked = value;
}
......@@ -116,9 +117,9 @@ namespace NBitcoin
public MerkleNode GetMerkleRoot()
{
MerkleNode node = MerkleNode.GetRoot((int)TransactionCount);
BitReader flags = new BitReader(Flags);
var hashes = Hashes.GetEnumerator();
MerkleNode node = MerkleNode.GetRoot((int) this.TransactionCount);
var flags = new BitReader(this.Flags);
List<uint256>.Enumerator hashes = this.Hashes.GetEnumerator();
GetMatchedTransactionsCore(node, flags, hashes, true).AsEnumerable();
return node;
}
......@@ -126,7 +127,7 @@ namespace NBitcoin
{
try
{
var hash = GetMerkleRoot().Hash;
uint256 hash = GetMerkleRoot().Hash;
return expectedMerkleRootHash == null || hash == expectedMerkleRootHash;
}
catch(Exception)
......@@ -142,8 +143,7 @@ namespace NBitcoin
if(node == null)
return;
flags.Write(node.IsMarked);
if(node.IsLeaf || !node.IsMarked)
Hashes.Add(node.Hash);
if(node.IsLeaf || !node.IsMarked) this.Hashes.Add(node.Hash);
if(node.IsMarked)
{
......@@ -154,9 +154,9 @@ namespace NBitcoin
public IEnumerable<uint256> GetMatchedTransactions()
{
BitReader flags = new BitReader(Flags);
MerkleNode root = MerkleNode.GetRoot((int)TransactionCount);
var hashes = Hashes.GetEnumerator();
var flags = new BitReader(this.Flags);
MerkleNode root = MerkleNode.GetRoot((int) this.TransactionCount);
List<uint256>.Enumerator hashes = this.Hashes.GetEnumerator();
return GetMatchedTransactionsCore(root, flags, hashes, false);
}
......@@ -175,8 +175,8 @@ namespace NBitcoin
return new uint256[0];
if(node.IsLeaf)
return new uint256[] { node.Hash };
var left = GetMatchedTransactionsCore(node.Left, flags, hashes, calculateHash);
var right = GetMatchedTransactionsCore(node.Right, flags, hashes, calculateHash);
IEnumerable<uint256> left = GetMatchedTransactionsCore(node.Left, flags, hashes, calculateHash);
IEnumerable<uint256> right = GetMatchedTransactionsCore(node.Right, flags, hashes, calculateHash);
if(calculateHash)
node.UpdateHash();
return left.Concat(right);
......@@ -201,15 +201,15 @@ namespace NBitcoin
/// <returns></returns>
public PartialMerkleTree Trim(params uint256[] matchedTransactions)
{
PartialMerkleTree trimmed = new PartialMerkleTree();
trimmed.TransactionCount = TransactionCount;
var root = GetMerkleRoot();
foreach(var leaf in root.GetLeafs())
var trimmed = new PartialMerkleTree();
trimmed.TransactionCount = this.TransactionCount;
MerkleNode root = GetMerkleRoot();
foreach(MerkleNode leaf in root.GetLeafs())
{
MarkToTop(leaf, false);
}
BitWriter flags = new BitWriter();
foreach(var leaf in root.GetLeafs().Where(l => matchedTransactions.Contains(l.Hash)))
var flags = new BitWriter();
foreach(MerkleNode leaf in root.GetLeafs().Where(l => matchedTransactions.Contains(l.Hash)))
{
MarkToTop(leaf, true);
}
......
......@@ -4,9 +4,9 @@
{
public PrecomputedTransactionData(Transaction tx)
{
HashOutputs = Script.GetHashOutputs(tx);
HashSequence = Script.GetHashSequence(tx);
HashPrevouts = Script.GetHashPrevouts(tx);
this.HashOutputs = Script.GetHashOutputs(tx);
this.HashSequence = Script.GetHashSequence(tx);
this.HashPrevouts = Script.GetHashPrevouts(tx);
}
public uint256 HashPrevouts
{
......
......@@ -2,21 +2,18 @@
using System.Text;
using NBitcoin.Crypto;
#if !USEBC
#endif
namespace NBitcoin
{
public class UnsecureRandom : IRandom
{
Random _Rand = new Random();
private Random _Rand = new Random();
#region IRandom Members
public void GetBytes(byte[] output)
{
lock (_Rand)
lock (this._Rand)
{
_Rand.NextBytes(output);
this._Rand.NextBytes(output);
}
}
......@@ -40,7 +37,7 @@ namespace NBitcoin
public static byte[] GetBytes(int length)
{
byte[] data = new byte[length];
var data = new byte[length];
if (Random == null)
throw new InvalidOperationException("You must set the RNG (RandomUtils.Random) before generating random numbers");
Random.GetBytes(data);
......@@ -53,7 +50,7 @@ namespace NBitcoin
if (additionalEntropy == null || data.Length == 0)
return;
int pos = entropyIndex;
var entropy = additionalEntropy;
byte[] entropy = additionalEntropy;
for (int i = 0; i < data.Length; i++)
{
data[i] ^= entropy[pos % 32];
......@@ -68,8 +65,8 @@ namespace NBitcoin
entropyIndex = pos % 32;
}
static volatile byte[] additionalEntropy = null;
static volatile int entropyIndex = 0;
private static volatile byte[] additionalEntropy = null;
private static volatile int entropyIndex = 0;
public static void AddEntropy(string data)
{
......@@ -82,7 +79,7 @@ namespace NBitcoin
{
if (data == null)
throw new ArgumentNullException("data");
var entropy = Hashes.SHA256(data);
byte[] entropy = Hashes.SHA256(data);
if (additionalEntropy == null)
additionalEntropy = entropy;
else
......
#if WIN
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;
using System.Security.Cryptography;
namespace NBitcoin
{
public class RandomNumberGeneratorRandom : IRandom
{
readonly RandomNumberGenerator _Instance;
private readonly RandomNumberGenerator _Instance;
public RandomNumberGeneratorRandom()
{
_Instance = RandomNumberGenerator.Create();
this._Instance = RandomNumberGenerator.Create();
}
#region IRandom Members
public void GetBytes(byte[] output)
{
_Instance.GetBytes(output);
this._Instance.GetBytes(output);
}
#endregion
......@@ -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
......@@ -69,18 +69,18 @@ namespace NBitcoin
{
if(tx == null)
throw new ArgumentNullException("tx");
_Transaction = tx;
_Index = index;
_Amount = amount;
_PrecomputedTransactionData = precomputedTransactionData;
this._Transaction = tx;
this._Index = index;
this._Amount = amount;
this._PrecomputedTransactionData = precomputedTransactionData;
}
public TransactionChecker(Transaction tx, int index, Money amount = null)
{
if(tx == null)
throw new ArgumentNullException("tx");
_Transaction = tx;
_Index = index;
_Amount = amount;
this._Transaction = tx;
this._Index = index;
this._Amount = amount;
}
......@@ -89,7 +89,7 @@ namespace NBitcoin
{
get
{
return _PrecomputedTransactionData;
return this._PrecomputedTransactionData;
}
}
......@@ -98,7 +98,7 @@ namespace NBitcoin
{
get
{
return _Transaction;
return this._Transaction;
}
}
......@@ -106,7 +106,7 @@ namespace NBitcoin
{
get
{
return Transaction.Inputs[_Index];
return this.Transaction.Inputs[this._Index];
}
}
......@@ -115,7 +115,7 @@ namespace NBitcoin
{
get
{
return _Index;
return this._Index;
}
}
......@@ -124,7 +124,7 @@ namespace NBitcoin
{
get
{
return _Amount;
return this._Amount;
}
}
}
......@@ -159,9 +159,9 @@ namespace NBitcoin
{
public Network Network { get; }
class CScriptNum
private class CScriptNum
{
const long nMaxNumSize = 4;
private const long nMaxNumSize = 4;
/**
* Numeric opcodes (OP_1ADD, etc) are restricted to operating on 4-byte integers.
* The semantics are subtle, though: operands must be in the range [-2^31 +1...2^31 -1],
......@@ -173,7 +173,7 @@ namespace NBitcoin
public CScriptNum(long n)
{
m_value = n;
this.m_value = n;
}
private long m_value;
......@@ -209,7 +209,8 @@ namespace NBitcoin
}
}
}
m_value = set_vch(vch);
this.m_value = set_vch(vch);
}
public override int GetHashCode()
......@@ -220,8 +221,8 @@ namespace NBitcoin
{
if(obj == null || !(obj is CScriptNum))
return false;
CScriptNum item = (CScriptNum)obj;
return m_value == item.m_value;
var item = (CScriptNum)obj;
return this.m_value == item.m_value;
}
public static bool operator ==(CScriptNum num, long rhs)
{
......@@ -332,19 +333,19 @@ namespace NBitcoin
public int getint()
{
if(m_value > int.MaxValue)
if(this.m_value > int.MaxValue)
return int.MaxValue;
else if(m_value < int.MinValue)
else if(this.m_value < int.MinValue)
return int.MinValue;
return (int)m_value;
return (int) this.m_value;
}
public byte[] getvch()
{
return serialize(m_value);
return serialize(this.m_value);
}
static byte[] serialize(long value)
private static byte[] serialize(long value)
{
if(value == 0)
return new byte[0];
......@@ -377,7 +378,7 @@ namespace NBitcoin
return result.ToArray();
}
static long set_vch(byte[] vch)
private static long set_vch(byte[] vch)
{
if(vch.Length == 0)
return 0;
......@@ -390,7 +391,7 @@ namespace NBitcoin
// the result's msb and return a negative.
if((vch[vch.Length - 1] & 0x80) != 0)
{
var temp = ~(0x80UL << (8 * (vch.Length - 1)));
ulong temp = ~(0x80UL << (8 * (vch.Length - 1)));
return -((long)((ulong)result & temp));
}
......@@ -398,21 +399,21 @@ namespace NBitcoin
}
}
ContextStack<byte[]> _stack = new ContextStack<byte[]>();
private ContextStack<byte[]> _stack = new ContextStack<byte[]>();
public ContextStack<byte[]> Stack
{
get
{
return _stack;
return this._stack;
}
}
public ScriptEvaluationContext(Network network)
{
this.Network = network;
this.ScriptVerify = NBitcoin.ScriptVerify.Standard;
this.SigHash = NBitcoin.SigHash.Undefined;
this.ScriptVerify = ScriptVerify.Standard;
this.SigHash = SigHash.Undefined;
this.Error = ScriptError.UnknownError;
}
......@@ -437,29 +438,29 @@ namespace NBitcoin
{
WitScript witness = checker.Input.WitScript;
SetError(ScriptError.UnknownError);
if((ScriptVerify & ScriptVerify.SigPushOnly) != 0 && !scriptSig.IsPushOnly)
if((this.ScriptVerify & ScriptVerify.SigPushOnly) != 0 && !scriptSig.IsPushOnly)
return SetError(ScriptError.SigPushOnly);
ScriptEvaluationContext evaluationCopy = null;
if(!EvalScript(scriptSig, checker, 0))
return false;
if((ScriptVerify & ScriptVerify.P2SH) != 0)
if((this.ScriptVerify & ScriptVerify.P2SH) != 0)
{
evaluationCopy = Clone();
}
if(!EvalScript(scriptPubKey, checker, 0))
return false;
if(!Result)
if(!this.Result)
return SetError(ScriptError.EvalFalse);
bool hadWitness = false;
// Bare witness programs
if((ScriptVerify & ScriptVerify.Witness) != 0)
if((this.ScriptVerify & ScriptVerify.Witness) != 0)
{
var wit = PayToWitTemplate.Instance.ExtractScriptPubKeyParameters2(this.Network, scriptPubKey);
WitProgramParameters wit = PayToWitTemplate.Instance.ExtractScriptPubKeyParameters2(this.Network, scriptPubKey);
if(wit != null)
{
hadWitness = true;
......@@ -474,13 +475,13 @@ namespace NBitcoin
}
// Bypass the cleanstack check at the end. The actual stack is obviously not clean
// for witness programs.
Stack.Clear();
Stack.Push(new byte[0]);
this.Stack.Clear();
this.Stack.Push(new byte[0]);
}
}
// Additional validation for spend-to-script-hash transactions:
if(((ScriptVerify & ScriptVerify.P2SH) != 0) && scriptPubKey.IsPayToScriptHash(this.Network))
if(((this.ScriptVerify & ScriptVerify.P2SH) != 0) && scriptPubKey.IsPayToScriptHash(this.Network))
{
Load(evaluationCopy);
evaluationCopy = this;
......@@ -502,9 +503,9 @@ namespace NBitcoin
return SetError(ScriptError.EvalFalse);
// P2SH witness program
if((ScriptVerify & ScriptVerify.Witness) != 0)
if((this.ScriptVerify & ScriptVerify.Witness) != 0)
{
var wit = PayToWitTemplate.Instance.ExtractScriptPubKeyParameters2(this.Network, redeem);
WitProgramParameters wit = PayToWitTemplate.Instance.ExtractScriptPubKeyParameters2(this.Network, redeem);
if(wit != null)
{
hadWitness = true;
......@@ -520,8 +521,8 @@ namespace NBitcoin
}
// Bypass the cleanstack check at the end. The actual stack is obviously not clean
// for witness programs.
Stack.Clear();
Stack.Push(new byte[0]);
this.Stack.Clear();
this.Stack.Push(new byte[0]);
}
}
}
......@@ -529,24 +530,24 @@ namespace NBitcoin
// The CLEANSTACK check is only performed after potential P2SH evaluation,
// as the non-P2SH evaluation of a P2SH script will obviously not result in
// a clean stack (the P2SH inputs remain).
if((ScriptVerify & ScriptVerify.CleanStack) != 0)
if((this.ScriptVerify & ScriptVerify.CleanStack) != 0)
{
// Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK
// would be possible, which is not a softfork (and P2SH should be one).
if((ScriptVerify & ScriptVerify.P2SH) == 0)
if((this.ScriptVerify & ScriptVerify.P2SH) == 0)
throw new InvalidOperationException("ScriptVerify : CleanStack without P2SH is not allowed");
if((ScriptVerify & ScriptVerify.Witness) == 0)
if((this.ScriptVerify & ScriptVerify.Witness) == 0)
throw new InvalidOperationException("ScriptVerify : CleanStack without Witness is not allowed");
if(Stack.Count != 1)
if(this.Stack.Count != 1)
return SetError(ScriptError.CleanStack);
}
if((ScriptVerify & ScriptVerify.Witness) != 0)
if((this.ScriptVerify & ScriptVerify.Witness) != 0)
{
// We can't check for correct unexpected witness data if P2SH was off, so require
// that WITNESS implies P2SH. Otherwise, going from WITNESS->P2SH+WITNESS would be
// possible, which is not a softfork.
if((ScriptVerify & ScriptVerify.P2SH) == 0)
if((this.ScriptVerify & ScriptVerify.P2SH) == 0)
throw new InvalidOperationException("ScriptVerify : Witness without P2SH is not allowed");
if(!hadWitness && witness.PushCount != 0)
{
......@@ -559,7 +560,7 @@ namespace NBitcoin
private bool VerifyWitnessProgram(WitScript witness, WitProgramParameters wit, TransactionChecker checker)
{
List<byte[]> stack = new List<byte[]>();
var stack = new List<byte[]>();
Script scriptPubKey;
if(wit.Version == 0)
......@@ -576,7 +577,7 @@ namespace NBitcoin
{
stack.Add(witness.GetUnsafePush(i));
}
var hashScriptPubKey = Hashes.SHA256(scriptPubKey.ToBytes(true));
byte[] hashScriptPubKey = Hashes.SHA256(scriptPubKey.ToBytes(true));
if(!Utils.ArrayEqual(hashScriptPubKey, wit.Program))
{
return SetError(ScriptError.WitnessProgramMissmatch);
......@@ -597,7 +598,7 @@ namespace NBitcoin
return SetError(ScriptError.WitnessProgramWrongLength);
}
}
else if((ScriptVerify & ScriptVerify.DiscourageUpgradableWitnessProgram) != 0)
else if((this.ScriptVerify & ScriptVerify.DiscourageUpgradableWitnessProgram) != 0)
{
return SetError(ScriptError.DiscourageUpgradableWitnessProgram);
}
......@@ -607,9 +608,9 @@ namespace NBitcoin
return true;
}
var ctx = this.Clone();
ScriptEvaluationContext ctx = Clone();
ctx.Stack.Clear();
foreach(var item in stack)
foreach(byte[] item in stack)
ctx.Stack.Push(item);
// Disallow stack item size > MAX_SCRIPT_ELEMENT_SIZE in witness stack
......@@ -631,9 +632,9 @@ namespace NBitcoin
}
static readonly byte[] vchFalse = new byte[0];
static readonly byte[] vchZero = new byte[0];
static readonly byte[] vchTrue = new byte[] { 1 };
private static readonly byte[] vchFalse = new byte[0];
private static readonly byte[] vchZero = new byte[0];
private static readonly byte[] vchTrue = new byte[] { 1 };
private const int MAX_SCRIPT_ELEMENT_SIZE = 520;
......@@ -645,20 +646,21 @@ namespace NBitcoin
{
return EvalScript(script, checker, (int)hashVersion);
}
bool EvalScript(Script s, TransactionChecker checker, int hashversion)
private bool EvalScript(Script s, TransactionChecker checker, int hashversion)
{
if(s.Length > 10000)
return SetError(ScriptError.ScriptSize);
SetError(ScriptError.UnknownError);
var pbegincodehash = 0;
int pbegincodehash = 0;
var vfExec = new Stack<bool>();
var altstack = new ContextStack<byte[]>();
var nOpCount = 0;
var fRequireMinimal = (ScriptVerify & ScriptVerify.MinimalData) != 0;
int nOpCount = 0;
bool fRequireMinimal = (this.ScriptVerify & ScriptVerify.MinimalData) != 0;
try
{
......@@ -706,7 +708,7 @@ namespace NBitcoin
if(fRequireMinimal && !CheckMinimalPush(opcode.PushData, opcode.Code))
return SetError(ScriptError.MinimalData);
_stack.Push(opcode.PushData);
this._stack.Push(opcode.PushData);
}
//if(fExec && opcode.PushData != null)
......@@ -738,7 +740,7 @@ namespace NBitcoin
{
// ( -- value)
var num = new CScriptNum((int)opcode.Code - (int)(OpcodeType.OP_1 - 1));
_stack.Push(num.getvch());
this._stack.Push(num.getvch());
break;
}
//
......@@ -749,17 +751,17 @@ namespace NBitcoin
case OpcodeType.OP_NOP1:
case OpcodeType.OP_CHECKLOCKTIMEVERIFY:
{
if((ScriptVerify & ScriptVerify.CheckLockTimeVerify) == 0)
if((this.ScriptVerify & ScriptVerify.CheckLockTimeVerify) == 0)
{
// not enabled; treat as a NOP2
if((ScriptVerify & ScriptVerify.DiscourageUpgradableNops) != 0)
if((this.ScriptVerify & ScriptVerify.DiscourageUpgradableNops) != 0)
{
return SetError(ScriptError.DiscourageUpgradableNops);
}
break;
}
if(Stack.Count < 1)
if(this.Stack.Count < 1)
return SetError(ScriptError.InvalidStackOperation);
// Note that elsewhere numeric opcodes are limited to
......@@ -776,7 +778,7 @@ namespace NBitcoin
// Thus as a special case we tell CScriptNum to accept up
// to 5-byte bignums, which are good until 2**39-1, well
// beyond the 2**32-1 limit of the nLockTime field itself.
CScriptNum nLockTime = new CScriptNum(_stack.Top(-1), fRequireMinimal, 5);
var nLockTime = new CScriptNum(this._stack.Top(-1), fRequireMinimal, 5);
// In the rare event that the argument may be < 0 due to
// some arithmetic being done first, you can always use
......@@ -792,23 +794,23 @@ namespace NBitcoin
}
case OpcodeType.OP_CHECKSEQUENCEVERIFY:
{
if((ScriptVerify & ScriptVerify.CheckSequenceVerify) == 0)
if((this.ScriptVerify & ScriptVerify.CheckSequenceVerify) == 0)
{
// not enabled; treat as a NOP3
if((ScriptVerify & ScriptVerify.DiscourageUpgradableNops) != 0)
if((this.ScriptVerify & ScriptVerify.DiscourageUpgradableNops) != 0)
{
return SetError(ScriptError.DiscourageUpgradableNops);
}
break;
}
if(Stack.Count < 1)
if(this.Stack.Count < 1)
return SetError(ScriptError.InvalidStackOperation);
// nSequence, like nLockTime, is a 32-bit unsigned integer
// field. See the comment in CHECKLOCKTIMEVERIFY regarding
// 5-byte numeric operands.
CScriptNum nSequence = new CScriptNum(Stack.Top(-1), fRequireMinimal, 5);
var nSequence = new CScriptNum(this.Stack.Top(-1), fRequireMinimal, 5);
// In the rare event that the argument may be < 0 due to
// some arithmetic being done first, you can always use
......@@ -836,7 +838,7 @@ namespace NBitcoin
case OpcodeType.OP_NOP8:
case OpcodeType.OP_NOP9:
case OpcodeType.OP_NOP10:
if((ScriptVerify & ScriptVerify.DiscourageUpgradableNops) != 0)
if((this.ScriptVerify & ScriptVerify.DiscourageUpgradableNops) != 0)
{
return SetError(ScriptError.DiscourageUpgradableNops);
}
......@@ -846,15 +848,15 @@ namespace NBitcoin
case OpcodeType.OP_NOTIF:
{
// <expression> if [statements] [else [statements]] endif
var bValue = false;
bool bValue = false;
if(fExec)
{
if(_stack.Count < 1)
if(this._stack.Count < 1)
return SetError(ScriptError.UnbalancedConditional);
var vch = _stack.Top(-1);
byte[] vch = this._stack.Top(-1);
if(hashversion == (int)HashVersion.Witness && (ScriptVerify & ScriptVerify.MinimalIf) != 0)
if(hashversion == (int)HashVersion.Witness && (this.ScriptVerify & ScriptVerify.MinimalIf) != 0)
{
if(vch.Length > 1)
return SetError(ScriptError.MinimalIf);
......@@ -865,7 +867,7 @@ namespace NBitcoin
bValue = CastToBool(vch);
if(opcode.Code == OpcodeType.OP_NOTIF)
bValue = !bValue;
_stack.Pop();
this._stack.Pop();
}
vfExec.Push(bValue);
break;
......@@ -875,7 +877,7 @@ namespace NBitcoin
if(vfExec.Count == 0)
return SetError(ScriptError.UnbalancedConditional);
var v = vfExec.Pop();
bool v = vfExec.Pop();
vfExec.Push(!v);
break;
}
......@@ -891,13 +893,13 @@ namespace NBitcoin
{
// (true -- ) or
// (false -- false) and return
if(_stack.Count < 1)
if(this._stack.Count < 1)
return SetError(ScriptError.InvalidStackOperation);
if(!CastToBool(_stack.Top(-1)))
if(!CastToBool(this._stack.Top(-1)))
return SetError(ScriptError.Verify);
_stack.Pop();
this._stack.Pop();
break;
}
case OpcodeType.OP_RETURN:
......@@ -909,11 +911,11 @@ namespace NBitcoin
//
case OpcodeType.OP_TOALTSTACK:
{
if(_stack.Count < 1)
if(this._stack.Count < 1)
return SetError(ScriptError.InvalidStackOperation);
altstack.Push(_stack.Top(-1));
_stack.Pop();
altstack.Push(this._stack.Top(-1));
this._stack.Pop();
break;
}
case OpcodeType.OP_FROMALTSTACK:
......@@ -921,135 +923,134 @@ namespace NBitcoin
if(altstack.Count < 1)
return SetError(ScriptError.InvalidAltStackOperation);
_stack.Push(altstack.Top(-1));
this._stack.Push(altstack.Top(-1));
altstack.Pop();
break;
}
case OpcodeType.OP_2DROP:
{
// (x1 x2 -- )
if(_stack.Count < 2)
if(this._stack.Count < 2)
return SetError(ScriptError.InvalidStackOperation);
_stack.Pop();
_stack.Pop();
this._stack.Pop();
this._stack.Pop();
break;
}
case OpcodeType.OP_2DUP:
{
// (x1 x2 -- x1 x2 x1 x2)
if(_stack.Count < 2)
if(this._stack.Count < 2)
return SetError(ScriptError.InvalidStackOperation);
var vch1 = _stack.Top(-2);
var vch2 = _stack.Top(-1);
_stack.Push(vch1);
_stack.Push(vch2);
byte[] vch1 = this._stack.Top(-2);
byte[] vch2 = this._stack.Top(-1);
this._stack.Push(vch1);
this._stack.Push(vch2);
break;
}
case OpcodeType.OP_3DUP:
{
// (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
if(_stack.Count < 3)
if(this._stack.Count < 3)
return SetError(ScriptError.InvalidStackOperation);
var vch1 = _stack.Top(-3);
var vch2 = _stack.Top(-2);
var vch3 = _stack.Top(-1);
_stack.Push(vch1);
_stack.Push(vch2);
_stack.Push(vch3);
byte[] vch1 = this._stack.Top(-3);
byte[] vch2 = this._stack.Top(-2);
byte[] vch3 = this._stack.Top(-1);
this._stack.Push(vch1);
this._stack.Push(vch2);
this._stack.Push(vch3);
break;
}
case OpcodeType.OP_2OVER:
{
// (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
if(_stack.Count < 4)
if(this._stack.Count < 4)
return SetError(ScriptError.InvalidStackOperation);
var vch1 = _stack.Top(-4);
var vch2 = _stack.Top(-3);
_stack.Push(vch1);
_stack.Push(vch2);
byte[] vch1 = this._stack.Top(-4);
byte[] vch2 = this._stack.Top(-3);
this._stack.Push(vch1);
this._stack.Push(vch2);
break;
}
case OpcodeType.OP_2ROT:
{
// (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
if(_stack.Count < 6)
if(this._stack.Count < 6)
return SetError(ScriptError.InvalidStackOperation);
var vch1 = _stack.Top(-6);
var vch2 = _stack.Top(-5);
_stack.Remove(-6, -4);
_stack.Push(vch1);
_stack.Push(vch2);
byte[] vch1 = this._stack.Top(-6);
byte[] vch2 = this._stack.Top(-5);
this._stack.Remove(-6, -4);
this._stack.Push(vch1);
this._stack.Push(vch2);
break;
}
case OpcodeType.OP_2SWAP:
{
// (x1 x2 x3 x4 -- x3 x4 x1 x2)
if(_stack.Count < 4)
if(this._stack.Count < 4)
return SetError(ScriptError.InvalidStackOperation);
_stack.Swap(-4, -2);
_stack.Swap(-3, -1);
this._stack.Swap(-4, -2);
this._stack.Swap(-3, -1);
break;
}
case OpcodeType.OP_IFDUP:
{
// (x - 0 | x x)
if(_stack.Count < 1)
if(this._stack.Count < 1)
return SetError(ScriptError.InvalidStackOperation);
var vch = _stack.Top(-1);
if(CastToBool(vch))
_stack.Push(vch);
byte[] vch = this._stack.Top(-1);
if(CastToBool(vch)) this._stack.Push(vch);
break;
}
case OpcodeType.OP_DEPTH:
{
// -- stacksize
var bn = new CScriptNum(_stack.Count);
_stack.Push(bn.getvch());
var bn = new CScriptNum(this._stack.Count);
this._stack.Push(bn.getvch());
break;
}
case OpcodeType.OP_DROP:
{
// (x -- )
if(_stack.Count < 1)
if(this._stack.Count < 1)
return SetError(ScriptError.InvalidStackOperation);
_stack.Pop();
this._stack.Pop();
break;
}
case OpcodeType.OP_DUP:
{
// (x -- x x)
if(_stack.Count < 1)
if(this._stack.Count < 1)
return SetError(ScriptError.InvalidStackOperation);
var vch = _stack.Top(-1);
_stack.Push(vch);
byte[] vch = this._stack.Top(-1);
this._stack.Push(vch);
break;
}
case OpcodeType.OP_NIP:
{
// (x1 x2 -- x2)
if(_stack.Count < 2)
if(this._stack.Count < 2)
return SetError(ScriptError.InvalidStackOperation);
_stack.Remove(-2);
this._stack.Remove(-2);
break;
}
case OpcodeType.OP_OVER:
{
// (x1 x2 -- x1 x2 x1)
if(_stack.Count < 2)
if(this._stack.Count < 2)
return SetError(ScriptError.InvalidStackOperation);
var vch = _stack.Top(-2);
_stack.Push(vch);
byte[] vch = this._stack.Top(-2);
this._stack.Push(vch);
break;
}
case OpcodeType.OP_PICK:
......@@ -1057,18 +1058,17 @@ namespace NBitcoin
{
// (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
// (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
if(_stack.Count < 2)
if(this._stack.Count < 2)
return SetError(ScriptError.InvalidStackOperation);
int n = new CScriptNum(_stack.Top(-1), fRequireMinimal).getint();
_stack.Pop();
if(n < 0 || n >= _stack.Count)
int n = new CScriptNum(this._stack.Top(-1), fRequireMinimal).getint();
this._stack.Pop();
if(n < 0 || n >= this._stack.Count)
return SetError(ScriptError.InvalidStackOperation);
var vch = _stack.Top(-n - 1);
if(opcode.Code == OpcodeType.OP_ROLL)
_stack.Remove(-n - 1);
_stack.Push(vch);
byte[] vch = this._stack.Top(-n - 1);
if(opcode.Code == OpcodeType.OP_ROLL) this._stack.Remove(-n - 1);
this._stack.Push(vch);
break;
}
case OpcodeType.OP_ROT:
......@@ -1076,40 +1076,40 @@ namespace NBitcoin
// (x1 x2 x3 -- x2 x3 x1)
// x2 x1 x3 after first swap
// x2 x3 x1 after second swap
if(_stack.Count < 3)
if(this._stack.Count < 3)
return SetError(ScriptError.InvalidStackOperation);
_stack.Swap(-3, -2);
_stack.Swap(-2, -1);
this._stack.Swap(-3, -2);
this._stack.Swap(-2, -1);
break;
}
case OpcodeType.OP_SWAP:
{
// (x1 x2 -- x2 x1)
if(_stack.Count < 2)
if(this._stack.Count < 2)
return SetError(ScriptError.InvalidStackOperation);
_stack.Swap(-2, -1);
this._stack.Swap(-2, -1);
break;
}
case OpcodeType.OP_TUCK:
{
// (x1 x2 -- x2 x1 x2)
if(_stack.Count < 2)
if(this._stack.Count < 2)
return SetError(ScriptError.InvalidStackOperation);
var vch = _stack.Top(-1);
_stack.Insert(-3, vch);
byte[] vch = this._stack.Top(-1);
this._stack.Insert(-3, vch);
break;
}
case OpcodeType.OP_SIZE:
{
// (in -- in size)
if(_stack.Count < 1)
if(this._stack.Count < 1)
return SetError(ScriptError.InvalidStackOperation);
var bn = new CScriptNum(_stack.Top(-1).Length);
_stack.Push(bn.getvch());
var bn = new CScriptNum(this._stack.Top(-1).Length);
this._stack.Push(bn.getvch());
break;
}
//
......@@ -1120,26 +1120,26 @@ namespace NBitcoin
{
//case OpcodeType.OP_NOTEQUAL: // use OpcodeType.OP_NUMNOTEQUAL
// (x1 x2 - bool)
if(_stack.Count < 2)
if(this._stack.Count < 2)
return SetError(ScriptError.InvalidStackOperation);
var vch1 = _stack.Top(-2);
var vch2 = _stack.Top(-1);
byte[] vch1 = this._stack.Top(-2);
byte[] vch2 = this._stack.Top(-1);
bool fEqual = Utils.ArrayEqual(vch1, vch2);
// OpcodeType.OP_NOTEQUAL is disabled because it would be too easy to say
// something like n != 1 and have some wiseguy pass in 1 with extra
// zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
//if (opcode == OpcodeType.OP_NOTEQUAL)
// fEqual = !fEqual;
_stack.Pop();
_stack.Pop();
_stack.Push(fEqual ? vchTrue : vchFalse);
this._stack.Pop();
this._stack.Pop();
this._stack.Push(fEqual ? vchTrue : vchFalse);
if(opcode.Code == OpcodeType.OP_EQUALVERIFY)
{
if(!fEqual)
return SetError(ScriptError.EqualVerify);
_stack.Pop();
this._stack.Pop();
}
break;
}
......@@ -1154,10 +1154,10 @@ namespace NBitcoin
case OpcodeType.OP_0NOTEQUAL:
{
// (in -- out)
if(_stack.Count < 1)
if(this._stack.Count < 1)
return SetError(ScriptError.InvalidStackOperation);
var bn = new CScriptNum(_stack.Top(-1), fRequireMinimal);
var bn = new CScriptNum(this._stack.Top(-1), fRequireMinimal);
switch(opcode.Code)
{
case OpcodeType.OP_1ADD:
......@@ -1182,8 +1182,9 @@ namespace NBitcoin
default:
throw new NotSupportedException("invalid opcode");
}
_stack.Pop();
_stack.Push(bn.getvch());
this._stack.Pop();
this._stack.Push(bn.getvch());
break;
}
case OpcodeType.OP_ADD:
......@@ -1201,11 +1202,11 @@ namespace NBitcoin
case OpcodeType.OP_MAX:
{
// (x1 x2 -- out)
if(_stack.Count < 2)
if(this._stack.Count < 2)
return SetError(ScriptError.InvalidStackOperation);
var bn1 = new CScriptNum(_stack.Top(-2), fRequireMinimal);
var bn2 = new CScriptNum(_stack.Top(-1), fRequireMinimal);
var bn1 = new CScriptNum(this._stack.Top(-2), fRequireMinimal);
var bn2 = new CScriptNum(this._stack.Top(-1), fRequireMinimal);
var bn = new CScriptNum(0);
switch(opcode.Code)
{
......@@ -1253,32 +1254,33 @@ namespace NBitcoin
default:
throw new NotSupportedException("invalid opcode");
}
_stack.Pop();
_stack.Pop();
_stack.Push(bn.getvch());
this._stack.Pop();
this._stack.Pop();
this._stack.Push(bn.getvch());
if(opcode.Code == OpcodeType.OP_NUMEQUALVERIFY)
{
if(!CastToBool(_stack.Top(-1)))
if(!CastToBool(this._stack.Top(-1)))
return SetError(ScriptError.NumEqualVerify);
_stack.Pop();
this._stack.Pop();
}
break;
}
case OpcodeType.OP_WITHIN:
{
// (x min max -- out)
if(_stack.Count < 3)
if(this._stack.Count < 3)
return SetError(ScriptError.InvalidStackOperation);
var bn1 = new CScriptNum(_stack.Top(-3), fRequireMinimal);
var bn2 = new CScriptNum(_stack.Top(-2), fRequireMinimal);
var bn3 = new CScriptNum(_stack.Top(-1), fRequireMinimal);
var bn1 = new CScriptNum(this._stack.Top(-3), fRequireMinimal);
var bn2 = new CScriptNum(this._stack.Top(-2), fRequireMinimal);
var bn3 = new CScriptNum(this._stack.Top(-1), fRequireMinimal);
bool fValue = (bn2 <= bn1 && bn1 < bn3);
_stack.Pop();
_stack.Pop();
_stack.Pop();
_stack.Push(fValue ? vchTrue : vchFalse);
this._stack.Pop();
this._stack.Pop();
this._stack.Pop();
this._stack.Push(fValue ? vchTrue : vchFalse);
break;
}
//
......@@ -1291,10 +1293,10 @@ namespace NBitcoin
case OpcodeType.OP_HASH256:
{
// (in -- hash)
if(_stack.Count < 1)
if(this._stack.Count < 1)
return SetError(ScriptError.InvalidStackOperation);
var vch = _stack.Top(-1);
byte[] vch = this._stack.Top(-1);
byte[] vchHash = null; //((opcode == OpcodeType.OP_RIPEMD160 || opcode == OpcodeType.OP_SHA1 || opcode == OpcodeType.OP_HASH160) ? 20 : 32);
if(opcode.Code == OpcodeType.OP_RIPEMD160)
vchHash = Hashes.RIPEMD160(vch, 0, vch.Length);
......@@ -1306,8 +1308,8 @@ namespace NBitcoin
vchHash = Hashes.Hash160(vch, 0, vch.Length).ToBytes();
else if(opcode.Code == OpcodeType.OP_HASH256)
vchHash = Hashes.Hash256(vch, 0, vch.Length).ToBytes();
_stack.Pop();
_stack.Push(vchHash);
this._stack.Pop();
this._stack.Push(vchHash);
break;
}
case OpcodeType.OP_CODESEPARATOR:
......@@ -1320,11 +1322,11 @@ namespace NBitcoin
case OpcodeType.OP_CHECKSIGVERIFY:
{
// (sig pubkey -- bool)
if(_stack.Count < 2)
if(this._stack.Count < 2)
return SetError(ScriptError.InvalidStackOperation);
var vchSig = _stack.Top(-2);
var vchPubKey = _stack.Top(-1);
byte[] vchSig = this._stack.Top(-2);
byte[] vchPubKey = this._stack.Top(-1);
////// debug print
//PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
......@@ -1343,18 +1345,18 @@ namespace NBitcoin
}
bool fSuccess = CheckSig(vchSig, vchPubKey, scriptCode, checker, hashversion);
if(!fSuccess && (ScriptVerify & ScriptVerify.NullFail) != 0 && vchSig.Length != 0)
if(!fSuccess && (this.ScriptVerify & ScriptVerify.NullFail) != 0 && vchSig.Length != 0)
return SetError(ScriptError.NullFail);
_stack.Pop();
_stack.Pop();
_stack.Push(fSuccess ? vchTrue : vchFalse);
this._stack.Pop();
this._stack.Pop();
this._stack.Push(fSuccess ? vchTrue : vchFalse);
if(opcode.Code == OpcodeType.OP_CHECKSIGVERIFY)
{
if(!fSuccess)
return SetError(ScriptError.CheckSigVerify);
_stack.Pop();
this._stack.Pop();
}
break;
}
......@@ -1364,10 +1366,10 @@ namespace NBitcoin
// ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
int i = 1;
if(_stack.Count < i)
if(this._stack.Count < i)
return SetError(ScriptError.InvalidStackOperation);
int nKeysCount = new CScriptNum(_stack.Top(-i), fRequireMinimal).getint();
int nKeysCount = new CScriptNum(this._stack.Top(-i), fRequireMinimal).getint();
if(nKeysCount < 0 || nKeysCount > 20)
return SetError(ScriptError.PubkeyCount);
......@@ -1380,24 +1382,24 @@ namespace NBitcoin
// ikey2 is the position of last non-signature item in the stack. Top stack item = 1.
// With SCRIPT_VERIFY_NULLFAIL, this is used for cleanup if operation fails.
int ikey2 = nKeysCount + 2;
if(_stack.Count < i)
if(this._stack.Count < i)
return SetError(ScriptError.InvalidStackOperation);
int nSigsCount = new CScriptNum(_stack.Top(-i), fRequireMinimal).getint();
int nSigsCount = new CScriptNum(this._stack.Top(-i), fRequireMinimal).getint();
if(nSigsCount < 0 || nSigsCount > nKeysCount)
return SetError(ScriptError.SigCount);
int isig = ++i;
i += nSigsCount;
if(_stack.Count < i)
if(this._stack.Count < i)
return SetError(ScriptError.InvalidStackOperation);
// Subset of script starting at the most recent codeseparator
Script scriptCode = new Script(s._Script.Skip(pbegincodehash).ToArray());
var scriptCode = new Script(s._Script.Skip(pbegincodehash).ToArray());
// Drop the signatures, since there's no way for a signature to sign itself
for(int k = 0; k < nSigsCount; k++)
{
var vchSig = _stack.Top(-isig - k);
byte[] vchSig = this._stack.Top(-isig - k);
if(hashversion == (int)HashVersion.Original)
scriptCode.FindAndDelete(vchSig);
}
......@@ -1405,8 +1407,8 @@ namespace NBitcoin
bool fSuccess = true;
while(fSuccess && nSigsCount > 0)
{
var vchSig = _stack.Top(-isig);
var vchPubKey = _stack.Top(-ikey);
byte[] vchSig = this._stack.Top(-isig);
byte[] vchPubKey = this._stack.Top(-ikey);
// Note how this makes the exact order of pubkey/signature evaluation
// distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set.
......@@ -1437,11 +1439,11 @@ namespace NBitcoin
while(i-- > 1)
{
// If the operation failed, we require that all signatures must be empty vector
if(!fSuccess && (ScriptVerify & ScriptVerify.NullFail) != 0 && ikey2 == 0 && _stack.Top(-1).Length != 0)
if(!fSuccess && (this.ScriptVerify & ScriptVerify.NullFail) != 0 && ikey2 == 0 && this._stack.Top(-1).Length != 0)
return SetError(ScriptError.NullFail);
if(ikey2 > 0)
ikey2--;
_stack.Pop();
this._stack.Pop();
}
// A bug causes CHECKMULTISIG to consume one extra argument
......@@ -1450,22 +1452,22 @@ namespace NBitcoin
// Unfortunately this is a potential source of mutability,
// so optionally verify it is exactly equal to zero prior
// to removing it from the stack.
if(_stack.Count < 1)
if(this._stack.Count < 1)
return SetError(ScriptError.InvalidStackOperation);
if(((ScriptVerify & ScriptVerify.NullDummy) != 0) && _stack.Top(-1).Length != 0)
if(((this.ScriptVerify & ScriptVerify.NullDummy) != 0) && this._stack.Top(-1).Length != 0)
return SetError(ScriptError.SigNullDummy);
_stack.Pop();
this._stack.Pop();
_stack.Push(fSuccess ? vchTrue : vchFalse);
this._stack.Push(fSuccess ? vchTrue : vchFalse);
if(opcode.Code == OpcodeType.OP_CHECKMULTISIGVERIFY)
{
if(!fSuccess)
return SetError(ScriptError.CheckMultiSigVerify);
_stack.Pop();
this._stack.Pop();
}
break;
}
......@@ -1474,14 +1476,14 @@ namespace NBitcoin
}
}
// Size limits
if(_stack.Count + altstack.Count > 1000)
if(this._stack.Count + altstack.Count > 1000)
return SetError(ScriptError.StackSize);
}
}
}
catch(Exception ex)
{
ThrownException = ex;
this.ThrownException = ex;
return SetError(ScriptError.UnknownError);
}
......@@ -1491,10 +1493,10 @@ namespace NBitcoin
return SetSuccess(ScriptError.OK);
}
bool CheckSequence(CScriptNum nSequence, TransactionChecker checker)
private bool CheckSequence(CScriptNum nSequence, TransactionChecker checker)
{
var txTo = checker.Transaction;
var nIn = checker.Index;
Transaction txTo = checker.Transaction;
int nIn = checker.Index;
// Relative lock times are supported by comparing the passed
// in operand to the sequence number of the input.
long txToSequence = (long)txTo.Inputs[nIn].Sequence;
......@@ -1513,8 +1515,8 @@ namespace NBitcoin
// Mask off any bits that do not have consensus-enforced meaning
// before doing the integer comparisons
var nLockTimeMask = Sequence.SEQUENCE_LOCKTIME_TYPE_FLAG | Sequence.SEQUENCE_LOCKTIME_MASK;
var txToSequenceMasked = txToSequence & nLockTimeMask;
uint nLockTimeMask = Sequence.SEQUENCE_LOCKTIME_TYPE_FLAG | Sequence.SEQUENCE_LOCKTIME_MASK;
long txToSequenceMasked = txToSequence & nLockTimeMask;
CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
// There are two kinds of nSequence: lock-by-blockheight
......@@ -1541,10 +1543,10 @@ namespace NBitcoin
}
bool CheckLockTime(CScriptNum nLockTime, TransactionChecker checker)
private bool CheckLockTime(CScriptNum nLockTime, TransactionChecker checker)
{
var txTo = checker.Transaction;
var nIn = checker.Index;
Transaction txTo = checker.Transaction;
int nIn = checker.Index;
// There are two kinds of nLockTime: lock-by-blockheight
// and lock-by-blocktime, distinguished by whether
// nLockTime < LOCKTIME_THRESHOLD.
......@@ -1581,13 +1583,13 @@ namespace NBitcoin
private bool SetSuccess(ScriptError scriptError)
{
Error = ScriptError.OK;
this.Error = ScriptError.OK;
return true;
}
private bool SetError(ScriptError scriptError)
{
Error = scriptError;
this.Error = scriptError;
return false;
}
......@@ -1630,19 +1632,19 @@ namespace NBitcoin
{
return true;
}
if((ScriptVerify & (ScriptVerify.DerSig | ScriptVerify.LowS | ScriptVerify.StrictEnc)) != 0 && !IsValidSignatureEncoding(vchSig))
if((this.ScriptVerify & (ScriptVerify.DerSig | ScriptVerify.LowS | ScriptVerify.StrictEnc)) != 0 && !IsValidSignatureEncoding(vchSig))
{
Error = ScriptError.SigDer;
this.Error = ScriptError.SigDer;
return false;
}
if((ScriptVerify & ScriptVerify.LowS) != 0 && !IsLowDERSignature(vchSig))
if((this.ScriptVerify & ScriptVerify.LowS) != 0 && !IsLowDERSignature(vchSig))
{
// serror is set
return false;
}
if((ScriptVerify & ScriptVerify.StrictEnc) != 0 && !IsDefinedHashtypeSignature(vchSig))
if((this.ScriptVerify & ScriptVerify.StrictEnc) != 0 && !IsDefinedHashtypeSignature(vchSig))
{
Error = ScriptError.SigHashType;
this.Error = ScriptError.SigHashType;
return false;
}
return true;
......@@ -1650,19 +1652,19 @@ namespace NBitcoin
private bool CheckPubKeyEncoding(byte[] vchPubKey, int sigversion)
{
if((ScriptVerify & ScriptVerify.StrictEnc) != 0 && !IsCompressedOrUncompressedPubKey(vchPubKey))
if((this.ScriptVerify & ScriptVerify.StrictEnc) != 0 && !IsCompressedOrUncompressedPubKey(vchPubKey))
{
Error = ScriptError.PubKeyType;
this.Error = ScriptError.PubKeyType;
return false;
}
if((ScriptVerify & ScriptVerify.WitnessPubkeyType) != 0 && sigversion == (int)HashVersion.Witness && !IsCompressedPubKey(vchPubKey))
if((this.ScriptVerify & ScriptVerify.WitnessPubkeyType) != 0 && sigversion == (int)HashVersion.Witness && !IsCompressedPubKey(vchPubKey))
{
return SetError(ScriptError.WitnessPubkeyType);
}
return true;
}
static bool IsCompressedPubKey(byte[] vchPubKey)
private static bool IsCompressedPubKey(byte[] vchPubKey)
{
if(vchPubKey.Length != 33)
{
......@@ -1685,7 +1687,7 @@ namespace NBitcoin
}
int nLenR = vchSig[3];
int nLenS = vchSig[5 + nLenR];
var S = 6 + nLenR;
int S = 6 + nLenR;
// If the S value is above the order of the curve divided by two, its
// complement modulo the order could have been used instead, which is
// one byte shorter when encoded correctly.
......@@ -1697,14 +1699,14 @@ namespace NBitcoin
return true;
}
static bool IsDefinedHashtypeSignature(byte[] vchSig)
private static bool IsDefinedHashtypeSignature(byte[] vchSig)
{
if(vchSig.Length == 0)
{
return false;
}
var temp = ~(SigHash.AnyoneCanPay);
SigHash temp = ~(SigHash.AnyoneCanPay);
byte nHashType = (byte)(vchSig[vchSig.Length - 1] & (byte)temp);
if(nHashType < (byte)SigHash.All || nHashType > (byte)SigHash.Single)
return false;
......@@ -1716,18 +1718,18 @@ namespace NBitcoin
{
if(!IsValidSignatureEncoding(vchSig))
{
Error = ScriptError.SigDer;
this.Error = ScriptError.SigDer;
return false;
}
int nLenR = vchSig[3];
int nLenS = vchSig[5 + nLenR];
var S = 6 + nLenR;
int S = 6 + nLenR;
// If the S value is above the order of the curve divided by two, its
// complement modulo the order could have been used instead, which is
// one byte shorter when encoded correctly.
if(!CheckSignatureElement(vchSig, S, nLenS, true))
{
Error = ScriptError.SigHighS;
this.Error = ScriptError.SigHighS;
return false;
}
......@@ -1740,7 +1742,7 @@ namespace NBitcoin
set;
}
static byte[] vchMaxModOrder = new byte[]
private static byte[] vchMaxModOrder = new byte[]
{
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,
......@@ -1748,7 +1750,7 @@ namespace NBitcoin
0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40
};
static byte[] vchMaxModHalfOrder = new byte[]
private static byte[] vchMaxModHalfOrder = new byte[]
{
0x7F,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
......@@ -1809,7 +1811,7 @@ namespace NBitcoin
// * sighash: 1-byte value indicating what data is hashed (not part of the DER
// signature)
var signLen = sig.Length;
int signLen = sig.Length;
// Minimum and maximum size constraints.
if(signLen < 9 || signLen > 73)
......@@ -1876,7 +1878,7 @@ namespace NBitcoin
}
bool CheckMinimalPush(byte[] data, OpcodeType opcode)
private bool CheckMinimalPush(byte[] data, OpcodeType opcode)
{
if(data.Length == 0)
{
......@@ -1926,12 +1928,12 @@ namespace NBitcoin
return false;
}
List<SignedHash> _SignedHashes = new List<SignedHash>();
private List<SignedHash> _SignedHashes = new List<SignedHash>();
public IEnumerable<SignedHash> SignedHashes
{
get
{
return _SignedHashes;
return this._SignedHashes;
}
}
......@@ -1954,7 +1956,8 @@ namespace NBitcoin
{
return CheckSig(vchSig, vchPubKey, scriptCode, new TransactionChecker(txTo, nIn), 0);
}
bool CheckSig(byte[] vchSig, byte[] vchPubKey, Script scriptCode, TransactionChecker checker, int sigversion)
private bool CheckSig(byte[] vchSig, byte[] vchPubKey, Script scriptCode, TransactionChecker checker, int sigversion)
{
PubKey pubkey = null;
try
......@@ -1978,7 +1981,7 @@ namespace NBitcoin
}
catch(Exception)
{
if((ScriptVerify.DerSig & ScriptVerify) != 0)
if((ScriptVerify.DerSig & this.ScriptVerify) != 0)
throw;
return false;
}
......@@ -1987,7 +1990,7 @@ namespace NBitcoin
return false;
uint256 sighash = Script.SignatureHash(this.Network, scriptCode, checker.Transaction, checker.Index, scriptSig.SigHash, checker.Amount, (HashVersion)sigversion, checker.PrecomputedTransactionData);
_SignedHashes.Add(new SignedHash()
this._SignedHashes.Add(new SignedHash()
{
ScriptCode = scriptCode,
HashVersion = (HashVersion)sigversion,
......@@ -1996,14 +1999,14 @@ namespace NBitcoin
});
if(!pubkey.Verify(sighash, scriptSig.Signature))
{
if((ScriptVerify & ScriptVerify.StrictEnc) != 0)
if((this.ScriptVerify & ScriptVerify.StrictEnc) != 0)
return false;
//Replicate OpenSSL bug on 23b397edccd3740a74adb603c9756370fafcde9bcc4483eb271ecad09a94dd63 (http://r6.ca/blog/20111119T211504Z.html)
var nLenR = vchSig[3];
var nLenS = vchSig[5 + nLenR];
var R = 4;
var S = 6 + nLenR;
byte nLenR = vchSig[3];
byte nLenS = vchSig[5 + nLenR];
int R = 4;
int S = 6 + nLenR;
var newS = new NBitcoin.BouncyCastle.Math.BigInteger(1, vchSig, S, nLenS);
var newR = new NBitcoin.BouncyCastle.Math.BigInteger(1, vchSig, R, nLenR);
var sig2 = new ECDSASignature(newR, newS);
......@@ -2020,27 +2023,27 @@ namespace NBitcoin
public bool IsAllowedSignature(SigHash sigHash)
{
if(SigHash == NBitcoin.SigHash.Undefined)
if(this.SigHash == SigHash.Undefined)
return true;
return SigHash == sigHash;
return this.SigHash == sigHash;
}
private void Load(ScriptEvaluationContext other)
{
_stack = new ContextStack<byte[]>(other._stack);
ScriptVerify = other.ScriptVerify;
SigHash = other.SigHash;
this._stack = new ContextStack<byte[]>(other._stack);
this.ScriptVerify = other.ScriptVerify;
this.SigHash = other.SigHash;
}
public ScriptEvaluationContext Clone()
{
return new ScriptEvaluationContext(this.Network)
{
_stack = new ContextStack<byte[]>(_stack),
ScriptVerify = ScriptVerify,
SigHash = SigHash,
_SignedHashes = _SignedHashes
_stack = new ContextStack<byte[]>(this._stack),
ScriptVerify = this.ScriptVerify,
SigHash = this.SigHash,
_SignedHashes = this._SignedHashes
};
}
......@@ -2048,9 +2051,9 @@ namespace NBitcoin
{
get
{
if(Stack.Count == 0)
if(this.Stack.Count == 0)
return false;
return CastToBool(_stack.Top(-1));
return CastToBool(this._stack.Top(-1));
}
}
......@@ -2078,8 +2081,8 @@ namespace NBitcoin
/// </summary>
public ContextStack()
{
_position = -1;
_array = new T[16];
this._position = -1;
this._array = new T[16];
}
/// <summary>
......@@ -2089,9 +2092,9 @@ namespace NBitcoin
/// <param name="stack">The stack.</param>
public ContextStack(ContextStack<T> stack)
{
_position = stack._position;
_array = new T[stack._array.Length];
stack._array.CopyTo(_array, 0);
this._position = stack._position;
this._array = new T[stack._array.Length];
stack._array.CopyTo(this._array, 0);
}
/// <summary>
......@@ -2101,7 +2104,7 @@ namespace NBitcoin
{
get
{
return _position + 1;
return this._position + 1;
}
}
......@@ -2112,7 +2115,7 @@ namespace NBitcoin
public void Push(T item)
{
EnsureSize();
_array[++_position] = item;
this._array[++this._position] = item;
}
/// <summary>
......@@ -2121,7 +2124,7 @@ namespace NBitcoin
/// <returns>The element in top of the stack</returns>
public T Pop()
{
return _array[_position--];
return this._array[this._position--];
}
/// <summary>
......@@ -2131,9 +2134,9 @@ namespace NBitcoin
/// <exception cref="System.ArgumentOutOfRangeException">Cannot remove more elements</exception>
public void Clear(int n)
{
if(n > Count)
if(n > this.Count)
throw new ArgumentOutOfRangeException("n", "Cannot remove more elements");
_position -= n;
this._position -= n;
}
/// <summary>
......@@ -2144,9 +2147,9 @@ namespace NBitcoin
/// <exception cref="System.IndexOutOfRangeException">topIndex</exception>
public T Top(int i)
{
if(i > 0 || -i > Count)
if(i > 0 || -i > this.Count)
throw new IndexOutOfRangeException("topIndex");
return _array[Count + i];
return this._array[this.Count + i];
}
/// <summary>
......@@ -2159,14 +2162,14 @@ namespace NBitcoin
/// </exception>
public void Swap(int i, int j)
{
if(i > 0 || -i > Count)
if(i > 0 || -i > this.Count)
throw new IndexOutOfRangeException("i");
if(i > 0 || -j > Count)
if(i > 0 || -j > this.Count)
throw new IndexOutOfRangeException("j");
var t = _array[Count + i];
_array[Count + i] = _array[Count + j];
_array[Count + j] = t;
T t = this._array[this.Count + i];
this._array[this.Count + i] = this._array[this.Count + j];
this._array[this.Count + j] = t;
}
/// <summary>
......@@ -2178,13 +2181,14 @@ namespace NBitcoin
{
EnsureSize();
position = Count + position;
for(int i = _position; i >= position + 1; i--)
position = this.Count + position;
for(int i = this._position; i >= position + 1; i--)
{
_array[i + 1] = _array[i];
this._array[i + 1] = this._array[i];
}
_array[position + 1] = value;
_position++;
this._array[position + 1] = value;
this._position++;
}
/// <summary>
......@@ -2204,19 +2208,19 @@ namespace NBitcoin
public void Remove(int from, int to)
{
int toRemove = to - from;
for(int i = Count + from; i < Count + from + toRemove; i++)
for(int i = this.Count + from; i < this.Count + from + toRemove; i++)
{
for(int y = Count + from; y < Count; y++)
_array[y] = _array[y + 1];
for(int y = this.Count + from; y < this.Count; y++) this._array[y] = this._array[y + 1];
}
_position -= toRemove;
this._position -= toRemove;
}
private void EnsureSize()
{
if(_position < _array.Length - 1)
if(this._position < this._array.Length - 1)
return;
Array.Resize(ref _array, 2 * _array.Length);
Array.Resize(ref this._array, 2 * this._array.Length);
}
/// <summary>
......@@ -2225,8 +2229,8 @@ namespace NBitcoin
/// <returns>A copy of the internal array</returns>
public T[] AsInternalArray()
{
var array = new T[Count];
Array.Copy(_array, 0, array, 0, Count);
var array = new T[this.Count];
Array.Copy(this._array, 0, array, 0, this.Count);
return array;
}
......@@ -2252,19 +2256,19 @@ namespace NBitcoin
public Enumerator(ContextStack<T> stack)
{
_stack = stack;
_index = stack._position + 1;
this._stack = stack;
this._index = stack._position + 1;
}
public T Current
{
get
{
if(_index == -1)
if(this._index == -1)
{
throw new InvalidOperationException("Enumeration has ended");
}
return _stack._array[_index];
return this._stack._array[this._index];
}
}
......@@ -2272,18 +2276,18 @@ namespace NBitcoin
{
get
{
return Current;
return this.Current;
}
}
public bool MoveNext()
{
return --_index >= 0;
return --this._index >= 0;
}
public void Reset()
{
_index = _stack._position + 1;
this._index = this._stack._position + 1;
}
public void Dispose()
......@@ -2294,7 +2298,7 @@ namespace NBitcoin
internal void Clear()
{
Clear(Count);
Clear(this.Count);
}
}
}
......@@ -269,9 +269,9 @@ namespace NBitcoin
{
_ValidOpCode = GetValidOpCode();
_OpcodeByName = new Dictionary<string, OpcodeType>();
foreach(var code in Enum.GetValues(typeof(OpcodeType)).Cast<OpcodeType>().Distinct())
foreach(OpcodeType code in Enum.GetValues(typeof(OpcodeType)).Cast<OpcodeType>().Distinct())
{
var name = GetOpName(code);
string name = GetOpName(code);
if(name != "OP_UNKNOWN")
_OpcodeByName.AddOrReplace(name, code);
}
......@@ -283,7 +283,7 @@ namespace NBitcoin
_OpcodeByName.AddOrReplace("OP_CHECKSEQUENCEVERIFY", OpcodeType.OP_CHECKSEQUENCEVERIFY);
_OpcodeByName.AddOrReplace("OP_NOP3", OpcodeType.OP_CHECKSEQUENCEVERIFY);
foreach(var op in new[]
foreach(object[] op in new[]
{
new object[]{"OP_0", OpcodeType.OP_0},
new object[]{"OP_1", OpcodeType.OP_1},
......@@ -311,7 +311,7 @@ namespace NBitcoin
}
public static Op GetPushOp(byte[] data)
{
Op op = new Op();
var op = new Op();
op.PushData = data;
if(data.Length == 0)
op.Code = OpcodeType.OP_0;
......@@ -323,7 +323,7 @@ namespace NBitcoin
op.Code = (OpcodeType)(byte)data.Length;
else if(data.Length <= 0xFF)
op.Code = OpcodeType.OP_PUSHDATA1;
#if !(PORTABLE || NETCORE)
#if !NETCORE
else if(data.LongLength <= 0xFFFF)
op.Code = OpcodeType.OP_PUSHDATA2;
else if(data.LongLength <= 0xFFFFFFFF)
......@@ -341,24 +341,24 @@ namespace NBitcoin
{
}
string _Name;
private string _Name;
public string Name
{
get
{
if(_Name == null)
_Name = GetOpName(Code);
return _Name;
if(this._Name == null) this._Name = GetOpName(this.Code);
return this._Name;
}
}
OpcodeType _Code;
static readonly bool[] _ValidOpCode;
private OpcodeType _Code;
private static readonly bool[] _ValidOpCode;
private static bool[] GetValidOpCode()
{
var valid = new bool[256];
foreach(var val in Enum.GetValues(typeof(OpcodeType)))
foreach(object val in Enum.GetValues(typeof(OpcodeType)))
{
valid[(byte)val] = true;
}
......@@ -376,12 +376,12 @@ namespace NBitcoin
{
get
{
return _Code;
return this._Code;
}
set
{
_Code = value;
IsInvalid = !_ValidOpCode[(byte)value];
this._Code = value;
this.IsInvalid = !_ValidOpCode[(byte)value];
}
}
public byte[] PushData
......@@ -394,36 +394,36 @@ namespace NBitcoin
{
var bitStream = new BitcoinStream(result, true);
if(Code == OpcodeType.OP_0)
if(this.Code == OpcodeType.OP_0)
{
//OP_0 already pushed
return;
}
if(OpcodeType.OP_1 <= Code && Code <= OpcodeType.OP_16)
if(OpcodeType.OP_1 <= this.Code && this.Code <= OpcodeType.OP_16)
{
//OP_1 to OP_16 already pushed
return;
}
if(Code == OpcodeType.OP_1NEGATE)
if(this.Code == OpcodeType.OP_1NEGATE)
{
//OP_1Negate already pushed
return;
}
if(0x01 <= (byte)Code && (byte)Code <= 0x4b)
if(0x01 <= (byte) this.Code && (byte) this.Code <= 0x4b)
{
//Data length already pushed
}
else if(Code == OpcodeType.OP_PUSHDATA1)
else if(this.Code == OpcodeType.OP_PUSHDATA1)
{
bitStream.ReadWrite((byte)data.Length);
}
else if(Code == OpcodeType.OP_PUSHDATA2)
else if(this.Code == OpcodeType.OP_PUSHDATA2)
{
bitStream.ReadWrite((ushort)data.Length);
}
else if(Code == OpcodeType.OP_PUSHDATA4)
else if(this.Code == OpcodeType.OP_PUSHDATA4)
{
bitStream.ReadWrite((uint)data.Length);
}
......@@ -434,33 +434,33 @@ namespace NBitcoin
internal byte[] ReadData(Stream stream)
{
uint len = 0;
BitcoinStream bitStream = new BitcoinStream(stream, false);
if(Code == 0)
var bitStream = new BitcoinStream(stream, false);
if(this.Code == 0)
return new byte[0];
if((byte)OpcodeType.OP_1 <= (byte)Code && (byte)Code <= (byte)OpcodeType.OP_16)
if((byte)OpcodeType.OP_1 <= (byte) this.Code && (byte) this.Code <= (byte)OpcodeType.OP_16)
{
return new byte[] { (byte)(Code - OpcodeType.OP_1 + 1) };
return new byte[] { (byte)(this.Code - OpcodeType.OP_1 + 1) };
}
if(Code == OpcodeType.OP_1NEGATE)
if(this.Code == OpcodeType.OP_1NEGATE)
{
return new byte[] { 0x81 };
}
try
{
if(0x01 <= (byte)Code && (byte)Code <= 0x4b)
len = (uint)Code;
else if(Code == OpcodeType.OP_PUSHDATA1)
if(0x01 <= (byte) this.Code && (byte) this.Code <= 0x4b)
len = (uint) this.Code;
else if(this.Code == OpcodeType.OP_PUSHDATA1)
len = bitStream.ReadWrite((byte)0);
else if(Code == OpcodeType.OP_PUSHDATA2)
else if(this.Code == OpcodeType.OP_PUSHDATA2)
len = bitStream.ReadWrite((ushort)0);
else if(Code == OpcodeType.OP_PUSHDATA4)
else if(this.Code == OpcodeType.OP_PUSHDATA4)
len = bitStream.ReadWrite((uint)0);
else
{
IsInvalid = true;
this.IsInvalid = true;
return new byte[0];
}
......@@ -470,22 +470,22 @@ namespace NBitcoin
if(len <= MAX_SCRIPT_ELEMENT_SIZE) //Most of the time
{
data = new byte[len];
var readen = stream.Read(data, 0, data.Length);
int readen = stream.Read(data, 0, data.Length);
if(readen != data.Length)
{
IsInvalid = true;
this.IsInvalid = true;
return new byte[0];
}
}
else //Mitigate against a big array allocation
{
List<byte> bytes = new List<byte>();
var bytes = new List<byte>();
for(int i = 0; i < len; i++)
{
var b = stream.ReadByte();
int b = stream.ReadByte();
if(b < 0)
{
IsInvalid = true;
this.IsInvalid = true;
return new byte[0];
}
bytes.Add((byte)b);
......@@ -497,57 +497,57 @@ namespace NBitcoin
}
catch(EndOfStreamException)
{
IsInvalid = true;
this.IsInvalid = true;
return new byte[0];
}
}
public byte[] ToBytes()
{
MemoryStream ms = new MemoryStream();
var ms = new MemoryStream();
WriteTo(ms);
return ms.ToArray();
}
public override string ToString()
{
if(PushData != null)
if(this.PushData != null)
{
if(PushData.Length == 0)
if(this.PushData.Length == 0)
return "0";
var result = Encoders.Hex.EncodeData(PushData);
string result = Encoders.Hex.EncodeData(this.PushData);
return result.Length == 2 && result[0] == '0' ? result.Substring(1) : result;
}
else if(Name == "OP_UNKNOWN")
else if(this.Name == "OP_UNKNOWN")
{
return Name + "(" + string.Format("0x{0:x2}", (byte)Code) + ")";
return this.Name + "(" + string.Format("0x{0:x2}", (byte) this.Code) + ")";
}
else
{
return Name;
return this.Name;
}
}
public void WriteTo(Stream stream)
{
stream.WriteByte((byte)Code);
if(PushData != null)
stream.WriteByte((byte) this.Code);
if(this.PushData != null)
{
PushDataToStream(PushData, stream);
PushDataToStream(this.PushData, stream);
}
}
static string unknown = "OP_UNKNOWN(0x";
const int MAX_SCRIPT_ELEMENT_SIZE = 520;
private static string unknown = "OP_UNKNOWN(0x";
private const int MAX_SCRIPT_ELEMENT_SIZE = 520;
internal static Op Read(TextReader textReader)
{
var opname = ReadWord(textReader);
string opname = ReadWord(textReader);
OpcodeType opcode;
var isOpCode = GetOpCode(opname, out opcode);
bool isOpCode = GetOpCode(opname, out opcode);
if(
(!isOpCode || Op.IsPushCode(opcode))
(!isOpCode || IsPushCode(opcode))
&& !opname.StartsWith(unknown))
{
if(isOpCode && opcode == OpcodeType.OP_0)
......@@ -583,10 +583,12 @@ namespace NBitcoin
public static implicit operator Op(OpcodeType codeType)
{
if(!IsPushCode(codeType))
{
return new Op()
{
Code = codeType,
};
}
else
{
if(OpcodeType.OP_1 <= codeType && codeType <= OpcodeType.OP_16)
......@@ -622,11 +624,11 @@ namespace NBitcoin
private static string ReadWord(TextReader textReader)
{
StringBuilder builder = new StringBuilder();
var builder = new StringBuilder();
int r;
while((r = textReader.Read()) != -1)
{
var ch = (char)r;
char ch = (char)r;
bool isSpace = DataEncoder.IsSpace(ch);
if(isSpace && builder.Length == 0)
continue;
......@@ -648,21 +650,21 @@ namespace NBitcoin
{
get
{
return Code == OpcodeType.OP_0 ||
OpcodeType.OP_1 <= Code && Code <= OpcodeType.OP_16;
return this.Code == OpcodeType.OP_0 ||
OpcodeType.OP_1 <= this.Code && this.Code <= OpcodeType.OP_16;
}
}
public bool IsSmallInt
{
get
{
return IsSmallUInt || Code == OpcodeType.OP_1NEGATE;
return this.IsSmallUInt || this.Code == OpcodeType.OP_1NEGATE;
}
}
public int? GetInt()
{
var l = GetLong();
long? l = GetLong();
if(l == null)
return null;
if(l.Value > int.MaxValue)
......@@ -674,9 +676,9 @@ namespace NBitcoin
public long? GetLong()
{
if(PushData == null)
if(this.PushData == null)
return null;
var vch = PushData;
byte[] vch = this.PushData;
if(vch.Length == 0)
return 0;
......@@ -688,7 +690,7 @@ namespace NBitcoin
// the result's msb and return a negative.
if((vch[vch.Length - 1] & 0x80) != 0)
{
var temp = ~(0x80UL << (8 * (vch.Length - 1)));
ulong temp = ~(0x80UL << (8 * (vch.Length - 1)));
return -((long)((ulong)result & temp));
}
return result;
......@@ -719,7 +721,7 @@ namespace NBitcoin
public Op Read()
{
var b = this.Inner.ReadByte();
int b = this.Inner.ReadByte();
if(b == -1)
return null;
......@@ -727,7 +729,7 @@ namespace NBitcoin
if(Op.IsPushCode(opcode))
{
Op op = new Op();
var op = new Op();
op.Code = opcode;
op.PushData = op.ReadData(this.Inner);
return op;
......
......@@ -60,39 +60,39 @@ namespace NBitcoin
internal const int SEQUENCE_LOCKTIME_GRANULARITY = 9;
uint _ValueInv;
private uint _ValueInv;
public uint Value
{
get
{
return 0xFFFFFFFF - _ValueInv;
return 0xFFFFFFFF - this._ValueInv;
}
}
public Sequence(uint value)
{
_ValueInv = 0xFFFFFFFF - value;
this._ValueInv = 0xFFFFFFFF - value;
}
public Sequence(int lockHeight)
{
if(lockHeight > 0xFFFF || lockHeight < 0)
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)
{
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)");
var value = (uint)(period.TotalSeconds / (1 << Sequence.SEQUENCE_LOCKTIME_GRANULARITY));
uint value = (uint)(period.TotalSeconds / (1 << SEQUENCE_LOCKTIME_GRANULARITY));
value |= SEQUENCE_LOCKTIME_TYPE_FLAG;
_ValueInv = 0xFFFFFFFF - (uint)value;
this._ValueInv = 0xFFFFFFFF - (uint)value;
}
public bool IsRelativeLock
{
get
{
return (Value & SEQUENCE_LOCKTIME_DISABLE_FLAG) == 0;
return (this.Value & SEQUENCE_LOCKTIME_DISABLE_FLAG) == 0;
}
}
......@@ -100,7 +100,7 @@ namespace NBitcoin
{
get
{
return Value < 0xffffffff - 1;
return this.Value < 0xffffffff - 1;
}
}
......@@ -109,7 +109,7 @@ namespace NBitcoin
get
{
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
private void AssertRelativeLock()
{
if(!IsRelativeLock)
if(!this.IsRelativeLock)
throw new InvalidOperationException("This sequence is not a relative lock");
}
public override string ToString()
{
if(IsRelativeLock)
if(this.IsRelativeLock)
{
StringBuilder builder = new StringBuilder();
builder.Append("Relative lock (" + LockType + "): ");
if(LockType == SequenceLockType.Height)
builder.Append(LockHeight + " blocks");
var builder = new StringBuilder();
builder.Append("Relative lock (" + this.LockType + "): ");
if(this.LockType == SequenceLockType.Height)
builder.Append(this.LockHeight + " blocks");
else
builder.Append(LockPeriod);
builder.Append(this.LockPeriod);
return builder.ToString();
}
return Value.ToString();
return this.Value.ToString();
}
public int LockHeight
......@@ -148,9 +148,9 @@ namespace NBitcoin
get
{
AssertRelativeLock();
if(LockType != SequenceLockType.Height)
if(this.LockType != SequenceLockType.Height)
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
......@@ -158,9 +158,9 @@ namespace NBitcoin
get
{
AssertRelativeLock();
if(LockType != SequenceLockType.Time)
if(this.LockType != SequenceLockType.Time)
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
{
public SequenceLock(int minHeight, DateTimeOffset minTime)
{
MinHeight = minHeight;
MinTime = minTime;
this.MinHeight = minHeight;
this.MinTime = minTime;
}
public SequenceLock(int minHeight, long minTime)
: this(minHeight, Utils.UnixTimeToDateTime(minTime))
......@@ -26,7 +26,7 @@ namespace NBitcoin
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;
}
}
......
......@@ -10,7 +10,7 @@ namespace NBitcoin
/// </summary>
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
{
get
......@@ -37,16 +37,15 @@ namespace NBitcoin
}
BigInteger _Target;
private BigInteger _Target;
public Target(byte[] compact)
{
if(compact.Length == 4)
{
var exp = compact[0];
byte exp = compact[0];
var val = new BigInteger(compact.SafeSubarray(1, 3));
_Target = val.ShiftLeft(8 * (exp - 3));
this._Target = val.ShiftLeft(8 * (exp - 3));
}
else
throw new FormatException("Invalid number of bytes");
......@@ -54,13 +53,13 @@ namespace NBitcoin
public Target(BigInteger target)
{
_Target = target;
_Target = new Target(this.ToCompact())._Target;
this._Target = target;
this._Target = new Target(ToCompact())._Target;
}
public Target(uint256 target)
{
_Target = new BigInteger(target.ToBytes(false));
_Target = new Target(this.ToCompact())._Target;
this._Target = new BigInteger(target.ToBytes(false));
this._Target = new Target(ToCompact())._Target;
}
public static implicit operator Target(uint a)
......@@ -69,11 +68,11 @@ namespace NBitcoin
}
public static implicit operator uint(Target a)
{
var bytes = a._Target.ToByteArray();
var val = bytes.SafeSubarray(0, Math.Min(bytes.Length, 3));
byte[] bytes = a._Target.ToByteArray();
byte[] val = bytes.SafeSubarray(0, Math.Min(bytes.Length, 3));
Array.Reverse(val);
var exp = (byte)(bytes.Length);
var missing = 4 - val.Length;
byte exp = (byte)(bytes.Length);
int missing = 4 - val.Length;
if(missing > 0)
val = val.Concat(new byte[missing]).ToArray();
if(missing < 0)
......@@ -81,34 +80,35 @@ namespace NBitcoin
return (uint)val[0] + (uint)(val[1] << 8) + (uint)(val[2] << 16) + (uint)(exp << 24);
}
double? _Difficulty;
private double? _Difficulty;
public double Difficulty
{
get
{
if(_Difficulty == null)
if(this._Difficulty == null)
{
var qr = Difficulty1._Target.DivideAndRemainder(_Target);
var quotient = qr[0];
var remainder = qr[1];
var decimalPart = BigInteger.Zero;
BigInteger[] qr = Difficulty1._Target.DivideAndRemainder(this._Target);
BigInteger quotient = qr[0];
BigInteger remainder = qr[1];
BigInteger decimalPart = BigInteger.Zero;
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.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 = "-",
NumberDecimalSeparator = "."
});
}
return _Difficulty.Value;
return this._Difficulty.Value;
}
}
......@@ -116,14 +116,14 @@ namespace NBitcoin
public override bool Equals(object obj)
{
Target item = obj as Target;
var item = obj as Target;
if(item == null)
return false;
return _Target.Equals(item._Target);
return this._Target.Equals(item._Target);
}
public static bool operator ==(Target a, Target b)
{
if(System.Object.ReferenceEquals(a, b))
if(ReferenceEquals(a, b))
return true;
if(((object)a == null) || ((object)b == null))
return false;
......@@ -137,12 +137,12 @@ namespace NBitcoin
public override int GetHashCode()
{
return _Target.GetHashCode();
return this._Target.GetHashCode();
}
public BigInteger ToBigInteger()
{
return _Target;
return this._Target;
}
public uint ToCompact()
......@@ -152,14 +152,14 @@ namespace NBitcoin
public uint256 ToUInt256()
{
return ToUInt256(_Target);
return ToUInt256(this._Target);
}
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)
throw new InvalidOperationException("Awful bug, this should never happen");
if(missingZero != 0)
......
......@@ -3,12 +3,7 @@ using System.Diagnostics;
namespace NBitcoin
{
#if NOTRACESOURCE
internal
#else
public
#endif
class TraceCorrelationScope : IDisposable
public class TraceCorrelationScope : IDisposable
{
private Guid old;
......@@ -16,26 +11,26 @@ namespace NBitcoin
{
get
{
return old;
return this.old;
}
private set
{
old = value;
this.old = value;
}
}
bool _Transfered;
private bool _Transfered;
TraceSource _Source;
private TraceSource _Source;
public TraceCorrelationScope(Guid activity, TraceSource source, bool traceTransfer)
{
// NETSTDCONV
// this.old = Trace.CorrelationManager.ActivityId;
_Transfered = old != activity && traceTransfer;
if(_Transfered)
this._Transfered = this.old != activity && traceTransfer;
if(this._Transfered)
{
_Source = source;
this._Source = source;
// _Source.TraceTransfer(0, "t", activity);
}
// Trace.CorrelationManager.ActivityId = activity;
......@@ -46,7 +41,7 @@ namespace NBitcoin
public void Dispose()
{
if(_Transfered)
if(this._Transfered)
{
// NETSTDCONV
//_Source.TraceTransfer(0, "transfer", old);
......@@ -56,16 +51,10 @@ namespace NBitcoin
#endregion
}
#if NOTRACESOURCE
internal
#else
public
#endif
class TraceCorrelation
public class TraceCorrelation
{
TraceSource _Source;
string _ActivityName;
private TraceSource _Source;
private string _ActivityName;
public TraceCorrelation(TraceSource source, string activityName)
: this(Guid.NewGuid(), source, activityName)
{
......@@ -73,34 +62,34 @@ namespace NBitcoin
}
public TraceCorrelation(Guid activity, TraceSource source, string activityName)
{
_Source = source;
_ActivityName = activityName;
this._Source = source;
this._ActivityName = activityName;
this.activity = activity;
}
Guid activity;
private Guid activity;
public Guid Activity
{
get
{
return activity;
return this.activity;
}
private set
{
activity = value;
this.activity = value;
}
}
volatile bool _First = true;
private volatile bool _First = true;
public TraceCorrelationScope Open(bool traceTransfer = true)
{
var scope = new TraceCorrelationScope(activity, _Source, traceTransfer);
if(_First)
var scope = new TraceCorrelationScope(this.activity, this._Source, traceTransfer);
if(this._First)
{
_First = false;
this._First = false;
// NETSTDCONV
// _Source.TraceEvent(TraceEventType.Start, 0, _ActivityName);
_Source.TraceEvent(TraceEventType.Critical, 0, _ActivityName);
this._Source.TraceEvent(TraceEventType.Critical, 0, this._ActivityName);
}
return scope;
}
......@@ -122,7 +111,7 @@ namespace NBitcoin
public override string ToString()
{
return _ActivityName;
return this._ActivityName;
}
}
}
......@@ -19,7 +19,7 @@ namespace NBitcoin
public TransactionNotFoundException(string message, uint256 txId, Exception inner)
: base(message ?? "Transaction " + txId + " not found", inner)
{
TxId = txId;
this.TxId = txId;
}
public uint256 TxId
{
......
......@@ -6,7 +6,7 @@ namespace NBitcoin
{
public class TransactionSignature
{
static readonly TransactionSignature _Empty = new TransactionSignature(new ECDSASignature(NBitcoin.BouncyCastle.Math.BigInteger.ValueOf(0), NBitcoin.BouncyCastle.Math.BigInteger.ValueOf(0)), SigHash.All);
private static readonly TransactionSignature _Empty = new TransactionSignature(new ECDSASignature(BouncyCastle.Math.BigInteger.ValueOf(0), BouncyCastle.Math.BigInteger.ValueOf(0)), SigHash.All);
public static TransactionSignature Empty
{
get
......@@ -62,8 +62,8 @@ namespace NBitcoin
{
if(sigHash == SigHash.Undefined)
throw new ArgumentException("sigHash should not be Undefined");
_SigHash = sigHash;
_Signature = signature;
this._SigHash = sigHash;
this._Signature = signature;
}
public TransactionSignature(ECDSASignature signature)
: this(signature, SigHash.All)
......@@ -72,13 +72,13 @@ namespace NBitcoin
}
public TransactionSignature(byte[] sigSigHash)
{
_Signature = ECDSASignature.FromDER(sigSigHash);
_SigHash = (SigHash)sigSigHash[sigSigHash.Length - 1];
this._Signature = ECDSASignature.FromDER(sigSigHash);
this._SigHash = (SigHash)sigSigHash[sigSigHash.Length - 1];
}
public TransactionSignature(byte[] sig, SigHash sigHash)
{
_Signature = ECDSASignature.FromDER(sig);
_SigHash = sigHash;
this._Signature = ECDSASignature.FromDER(sig);
this._SigHash = sigHash;
}
private readonly ECDSASignature _Signature;
......@@ -86,7 +86,7 @@ namespace NBitcoin
{
get
{
return _Signature;
return this._Signature;
}
}
private readonly SigHash _SigHash;
......@@ -94,16 +94,16 @@ namespace NBitcoin
{
get
{
return _SigHash;
return this._SigHash;
}
}
public byte[] ToBytes()
{
var sig = _Signature.ToDER();
byte[] sig = this._Signature.ToDER();
var result = new byte[sig.Length + 1];
Array.Copy(sig, 0, result, 0, sig.Length);
result[result.Length - 1] = (byte)_SigHash;
result[result.Length - 1] = (byte) this._SigHash;
return result;
}
......@@ -114,7 +114,7 @@ namespace NBitcoin
public bool Check(Network network, PubKey pubKey, Script scriptPubKey, IndexedTxIn txIn, ScriptVerify verify = ScriptVerify.Standard)
{
return this.Check(network, pubKey, scriptPubKey, txIn.Transaction, txIn.Index, verify);
return Check(network, pubKey, scriptPubKey, txIn.Transaction, txIn.Index, verify);
}
public bool Check(Network network, PubKey pubKey, Script scriptPubKey, Transaction tx, uint nIndex, ScriptVerify verify = ScriptVerify.Standard)
......@@ -122,31 +122,30 @@ namespace NBitcoin
return new ScriptEvaluationContext(network)
{
ScriptVerify = verify,
SigHash = SigHash
SigHash = this.SigHash
}.CheckSig(this, pubKey, scriptPubKey, tx, nIndex);
}
string _Id;
private string _Id;
private string Id
{
get
{
if(_Id == null)
_Id = Encoders.Hex.EncodeData(ToBytes());
return _Id;
if(this._Id == null) this._Id = Encoders.Hex.EncodeData(ToBytes());
return this._Id;
}
}
public override bool Equals(object obj)
{
TransactionSignature item = obj as TransactionSignature;
var item = obj as TransactionSignature;
if(item == null)
return false;
return Id.Equals(item.Id);
return this.Id.Equals(item.Id);
}
public static bool operator ==(TransactionSignature a, TransactionSignature b)
{
if(System.Object.ReferenceEquals(a, b))
if(ReferenceEquals(a, b))
return true;
if(((object)a == null) || ((object)b == null))
return false;
......@@ -160,7 +159,7 @@ namespace NBitcoin
public override int GetHashCode()
{
return Id.GetHashCode();
return this.Id.GetHashCode();
}
public override string ToString()
......@@ -172,7 +171,7 @@ namespace NBitcoin
{
get
{
return Signature.IsLowS;
return this.Signature.IsLowS;
}
}
......@@ -182,9 +181,9 @@ namespace NBitcoin
/// </summary>
public TransactionSignature MakeCanonical()
{
if(IsLowS)
if(this.IsLowS)
return this;
return new TransactionSignature(Signature.MakeCanonical(), SigHash);
return new TransactionSignature(this.Signature.MakeCanonical(), this.SigHash);
}
}
}
......@@ -14,7 +14,7 @@ namespace NBitcoin
{
if(parent == null)
throw new ArgumentNullException("parent");
Transaction = parent;
this.Transaction = parent;
}
public Transaction Transaction
......
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace NBitcoin
{
......
......@@ -150,7 +150,7 @@ namespace Stratis.Bitcoin.P2P.Peer
this.MessageProducer.PushMessage(incomingMessage);
}
}
catch (OperationCanceledException ex)
catch (OperationCanceledException)
{
this.logger.LogTrace("Receiving cancelled.");
this.peer.Disconnect("Receiving cancelled.");
......@@ -340,7 +340,7 @@ namespace Stratis.Bitcoin.P2P.Peer
/// <exception cref="ProtocolViolationException">Thrown if the incoming message is too big.</exception>
private async Task<byte[]> ReadMessageAsync(ProtocolVersion protocolVersion, CancellationToken cancellation = default(CancellationToken))
{
//this.logger.LogTrace("({0}:{1})", nameof(protocolVersion), protocolVersion);
this.logger.LogTrace("({0}:{1})", nameof(protocolVersion), protocolVersion);
// First find and read the magic.
await this.ReadMagicAsync(this.network.MagicBytes, cancellation).ConfigureAwait(false);
......@@ -411,7 +411,7 @@ namespace Stratis.Bitcoin.P2P.Peer
this.logger.LogTrace("(-)");
}
static int _offset=0;
/// <summary>
/// Reads a specific number of bytes from the connection stream into a buffer.
/// </summary>
......@@ -423,20 +423,11 @@ namespace Stratis.Bitcoin.P2P.Peer
/// <exception cref="OperationCanceledException">Thrown if the operation was cancelled or the end of the stream was reached.</exception>
private async Task ReadBytesAsync(byte[] buffer, int offset, int bytesToRead, CancellationToken cancellation = default(CancellationToken))
{
//this.logger.LogTrace("({0}:{1},{2}:{3})", nameof(offset), offset, nameof(bytesToRead), bytesToRead);
this.logger.LogTrace("({0}:{1},{2}:{3})", nameof(offset), offset, nameof(bytesToRead), bytesToRead);
while (bytesToRead > 0)
{
int chunkSize = 0;
try
{
chunkSize = this.stream.Read(buffer, offset, bytesToRead);
//chunkSize = await this.stream.ReadAsync(buffer, offset, bytesToRead, cancellation).ConfigureAwait(false);
}catch(Exception ex)
{
int qwe = 1;
_offset = 0;
}
int chunkSize = await this.stream.ReadAsync(buffer, offset, bytesToRead, cancellation).ConfigureAwait(false);
if (chunkSize == 0)
{
this.logger.LogTrace("(-)[STREAM_END]");
......@@ -444,11 +435,10 @@ namespace Stratis.Bitcoin.P2P.Peer
}
offset += chunkSize;
_offset += offset;
bytesToRead -= chunkSize;
}
//this.logger.LogTrace("(-)");
this.logger.LogTrace("(-)");
}
/// <summary>
......@@ -466,7 +456,7 @@ namespace Stratis.Bitcoin.P2P.Peer
/// </remarks>
private async Task<Message> ReadAndParseMessageAsync(ProtocolVersion protocolVersion, CancellationToken cancellation)
{
//this.logger.LogTrace("({0}:{1})", nameof(protocolVersion), protocolVersion);
this.logger.LogTrace("({0}:{1})", nameof(protocolVersion), protocolVersion);
Message message = null;
......
......@@ -32,6 +32,6 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.2.0")]
[assembly: AssemblyFileVersion("1.1.2.0")]
[assembly: AssemblyVersion("1.1.12.0")]
[assembly: AssemblyFileVersion("1.1.12.0")]
[assembly: InternalsVisibleTo("Stratis.Bitcoin.Tests")]
......@@ -2,7 +2,7 @@
"profiles": {
"Stratis.StratisD": {
"commandName": "Project",
"commandLineArgs": "-testnode"
"commandLineArgs": "-testnet -addnode=192.168.31.142:26178"
},
"Stratis.StratisD Test": {
"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