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
......
This diff is collapsed.
......@@ -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)
{
......
#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);
}
}
}
This diff is collapsed.
......@@ -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
This diff is collapsed.
This diff is collapsed.
......@@ -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)
......
This diff is collapsed.
......@@ -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
{
......
This diff is collapsed.
......@@ -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
{
......
......@@ -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