Commit 2ec9c439 authored by Pavel Pavlov's avatar Pavel Pavlov

Merge with Stratis (commit #1643 SHA-1: f5ae4bb67c7f3c1639225922976fa075272887d8)

parent 8b7233de
......@@ -51,11 +51,11 @@
{
get
{
return vchData.Length == 74;
return this.vchData.Length == 74;
}
}
ExtKey _Key;
private ExtKey _Key;
/// <summary>
/// Gets the extended key, converting from the Base58 representation.
......@@ -64,12 +64,12 @@
{
get
{
if(_Key == null)
if(this._Key == null)
{
_Key = new ExtKey();
_Key.ReadWrite(vchData);
this._Key = new ExtKey();
this._Key.ReadWrite(this.vchData);
}
return _Key;
return this._Key;
}
}
......@@ -92,7 +92,7 @@
{
get
{
return ExtKey.ScriptPubKey;
return this.ExtKey.ScriptPubKey;
}
}
......@@ -101,7 +101,7 @@
/// </summary>
public BitcoinExtPubKey Neuter()
{
return ExtKey.Neuter().GetWif(Network);
return this.ExtKey.Neuter().GetWif(this.Network);
}
#region ISecret Members
......@@ -113,7 +113,7 @@
{
get
{
return ExtKey.PrivateKey;
return this.ExtKey.PrivateKey;
}
}
......@@ -151,7 +151,7 @@
{
}
ExtPubKey _PubKey;
private ExtPubKey _PubKey;
/// <summary>
/// Gets the extended public key, converting from the Base58 representation.
......@@ -160,12 +160,12 @@
{
get
{
if(_PubKey == null)
if(this._PubKey == null)
{
_PubKey = new ExtPubKey();
_PubKey.ReadWrite(vchData);
this._PubKey = new ExtPubKey();
this._PubKey.ReadWrite(this.vchData);
}
return _PubKey;
return this._PubKey;
}
}
......@@ -187,7 +187,7 @@
{
get
{
return ExtPubKey.ScriptPubKey;
return this.ExtPubKey.ScriptPubKey;
}
}
......
......@@ -23,13 +23,13 @@ namespace NBitcoin
private const int FingerprintLength = 4;
private const int ChainCodeLength = 32;
Key key;
byte[] vchChainCode = new byte[ChainCodeLength];
uint nChild;
byte nDepth;
byte[] vchFingerprint = new byte[FingerprintLength];
private Key key;
private byte[] vchChainCode = new byte[ChainCodeLength];
private uint nChild;
private byte nDepth;
private byte[] vchFingerprint = new byte[FingerprintLength];
static readonly byte[] hashkey = Encoders.ASCII.DecodeData("Bitcoin seed");
private static readonly byte[] hashkey = Encoders.ASCII.DecodeData("Bitcoin seed");
/// <summary>
/// Gets the depth of this extended key from the root key.
......@@ -38,7 +38,7 @@ namespace NBitcoin
{
get
{
return nDepth;
return this.nDepth;
}
}
......@@ -49,7 +49,7 @@ namespace NBitcoin
{
get
{
return nChild;
return this.nChild;
}
}
......@@ -57,8 +57,8 @@ namespace NBitcoin
{
get
{
byte[] chainCodeCopy = new byte[ChainCodeLength];
Buffer.BlockCopy(vchChainCode, 0, chainCodeCopy, 0, ChainCodeLength);
var chainCodeCopy = new byte[ChainCodeLength];
Buffer.BlockCopy(this.vchChainCode, 0, chainCodeCopy, 0, ChainCodeLength);
return chainCodeCopy;
}
......@@ -113,8 +113,8 @@ namespace NBitcoin
this.key = key;
this.nDepth = depth;
this.nChild = child;
Buffer.BlockCopy(fingerprint, 0, vchFingerprint, 0, FingerprintLength);
Buffer.BlockCopy(chainCode, 0, vchChainCode, 0, ChainCodeLength);
Buffer.BlockCopy(fingerprint, 0, this.vchFingerprint, 0, FingerprintLength);
Buffer.BlockCopy(chainCode, 0, this.vchChainCode, 0, ChainCodeLength);
}
/// <summary>
......@@ -130,7 +130,7 @@ namespace NBitcoin
if(chainCode.Length != ChainCodeLength)
throw new ArgumentException(string.Format("The chain code must be {0} bytes.", ChainCodeLength), "chainCode");
this.key = masterKey;
Buffer.BlockCopy(chainCode, 0, vchChainCode, 0, ChainCodeLength);
Buffer.BlockCopy(chainCode, 0, this.vchChainCode, 0, ChainCodeLength);
}
/// <summary>
......@@ -160,10 +160,10 @@ namespace NBitcoin
private void SetMaster(byte[] seed)
{
var hashMAC = Hashes.HMACSHA512(hashkey, seed);
key = new Key(hashMAC.SafeSubarray(0, 32));
byte[] hashMAC = Hashes.HMACSHA512(hashkey, seed);
this.key = new Key(hashMAC.SafeSubarray(0, 32));
Buffer.BlockCopy(hashMAC, 32, vchChainCode, 0, ChainCodeLength);
Buffer.BlockCopy(hashMAC, 32, this.vchChainCode, 0, ChainCodeLength);
}
/// <summary>
......@@ -173,7 +173,7 @@ namespace NBitcoin
{
get
{
return key;
return this.key;
}
}
......@@ -182,22 +182,22 @@ namespace NBitcoin
/// </summary>
public ExtPubKey Neuter()
{
ExtPubKey ret = new ExtPubKey
var ret = new ExtPubKey
{
nDepth = nDepth,
vchFingerprint = vchFingerprint.ToArray(),
nChild = nChild,
pubkey = key.PubKey,
vchChainCode = vchChainCode.ToArray()
nDepth = this.nDepth,
vchFingerprint = this.vchFingerprint.ToArray(),
nChild = this.nChild,
pubkey = this.key.PubKey,
vchChainCode = this.vchChainCode.ToArray()
};
return ret;
}
public bool IsChildOf(ExtKey parentKey)
{
if(Depth != parentKey.Depth + 1)
if(this.Depth != parentKey.Depth + 1)
return false;
return parentKey.CalculateChildFingerprint().SequenceEqual(Fingerprint);
return parentKey.CalculateChildFingerprint().SequenceEqual(this.Fingerprint);
}
public bool IsParentOf(ExtKey childKey)
{
......@@ -205,14 +205,14 @@ namespace NBitcoin
}
private byte[] CalculateChildFingerprint()
{
return key.PubKey.Hash.ToBytes().SafeSubarray(0, FingerprintLength);
return this.key.PubKey.Hash.ToBytes().SafeSubarray(0, FingerprintLength);
}
public byte[] Fingerprint
{
get
{
return vchFingerprint;
return this.vchFingerprint;
}
}
......@@ -223,11 +223,11 @@ namespace NBitcoin
{
var result = new ExtKey
{
nDepth = (byte)(nDepth + 1),
nDepth = (byte)(this.nDepth + 1),
vchFingerprint = CalculateChildFingerprint(),
nChild = index
};
result.key = key.Derivate(this.vchChainCode, index, out result.vchChainCode);
result.key = this.key.Derivate(this.vchChainCode, index, out result.vchChainCode);
return result;
}
......@@ -268,13 +268,13 @@ namespace NBitcoin
{
using(stream.BigEndianScope())
{
stream.ReadWrite(ref nDepth);
stream.ReadWrite(ref vchFingerprint);
stream.ReadWrite(ref nChild);
stream.ReadWrite(ref vchChainCode);
stream.ReadWrite(ref this.nDepth);
stream.ReadWrite(ref this.vchFingerprint);
stream.ReadWrite(ref this.nChild);
stream.ReadWrite(ref this.vchChainCode);
byte b = 0;
stream.ReadWrite(ref b);
stream.ReadWrite(ref key);
stream.ReadWrite(ref this.key);
}
}
......@@ -297,7 +297,7 @@ namespace NBitcoin
{
get
{
return PrivateKey.PubKey.Hash.ScriptPubKey;
return this.PrivateKey.PubKey.Hash.ScriptPubKey;
}
}
......@@ -310,7 +310,7 @@ namespace NBitcoin
{
get
{
return (nChild & 0x80000000u) != 0;
return (this.nChild & 0x80000000u) != 0;
}
}
......@@ -323,35 +323,35 @@ namespace NBitcoin
{
if(parent == null)
throw new ArgumentNullException("parent");
if(Depth == 0)
if(this.Depth == 0)
throw new InvalidOperationException("This ExtKey is the root key of the HD tree");
if(IsHardened)
if(this.IsHardened)
throw new InvalidOperationException("This private key is hardened, so you can't get its parent");
var expectedFingerPrint = parent.CalculateChildFingerprint();
if(parent.Depth != this.Depth - 1 || !expectedFingerPrint.SequenceEqual(vchFingerprint))
byte[] expectedFingerPrint = parent.CalculateChildFingerprint();
if(parent.Depth != this.Depth - 1 || !expectedFingerPrint.SequenceEqual(this.vchFingerprint))
throw new ArgumentException("The parent ExtPubKey is not the immediate parent of this ExtKey", "parent");
byte[] l = null;
byte[] ll = new byte[32];
byte[] lr = new byte[32];
var ll = new byte[32];
var lr = new byte[32];
var pubKey = parent.PubKey.ToBytes();
l = Hashes.BIP32Hash(parent.vchChainCode, nChild, pubKey[0], pubKey.SafeSubarray(1));
byte[] pubKey = parent.PubKey.ToBytes();
l = Hashes.BIP32Hash(parent.vchChainCode, this.nChild, pubKey[0], pubKey.SafeSubarray(1));
Array.Copy(l, ll, 32);
Array.Copy(l, 32, lr, 0, 32);
var ccChild = lr;
byte[] ccChild = lr;
BigInteger parse256LL = new BigInteger(1, ll);
var parse256LL = new BigInteger(1, ll);
BigInteger N = ECKey.CURVE.N;
if(!ccChild.SequenceEqual(vchChainCode))
if(!ccChild.SequenceEqual(this.vchChainCode))
throw new InvalidOperationException("The derived chain code of the parent is not equal to this child chain code");
var keyBytes = PrivateKey.ToBytes();
byte[] keyBytes = this.PrivateKey.ToBytes();
var key = new BigInteger(1, keyBytes);
BigInteger kPar = key.Add(parse256LL.Negate()).Mod(N);
var keyParentBytes = kPar.ToByteArrayUnsigned();
byte[] keyParentBytes = kPar.ToByteArrayUnsigned();
if(keyParentBytes.Length < 32)
keyParentBytes = new byte[32 - keyParentBytes.Length].Concat(keyParentBytes).ToArray();
......
......@@ -18,7 +18,7 @@ namespace NBitcoin
private const int FingerprintLength = 4;
private const int ChainCodeLength = 32;
static readonly byte[] validPubKey = Encoders.Hex.DecodeData("0374ef3990e387b5a2992797f14c031a64efd80e5cb843d7c1d4a0274a9bc75e55");
private static readonly byte[] validPubKey = Encoders.Hex.DecodeData("0374ef3990e387b5a2992797f14c031a64efd80e5cb843d7c1d4a0274a9bc75e55");
internal byte nDepth;
internal byte[] vchFingerprint = new byte[FingerprintLength];
internal uint nChild;
......@@ -31,7 +31,7 @@ namespace NBitcoin
{
get
{
return nDepth;
return this.nDepth;
}
}
......@@ -39,7 +39,7 @@ namespace NBitcoin
{
get
{
return nChild;
return this.nChild;
}
}
......@@ -47,22 +47,22 @@ namespace NBitcoin
{
get
{
return (nChild & 0x80000000u) != 0;
return (this.nChild & 0x80000000u) != 0;
}
}
public PubKey PubKey
{
get
{
return pubkey;
return this.pubkey;
}
}
public byte[] ChainCode
{
get
{
byte[] chainCodeCopy = new byte[ChainCodeLength];
Buffer.BlockCopy(vchChainCode, 0, chainCodeCopy, 0, ChainCodeLength);
var chainCodeCopy = new byte[ChainCodeLength];
Buffer.BlockCopy(this.vchChainCode, 0, chainCodeCopy, 0, ChainCodeLength);
return chainCodeCopy;
}
......@@ -94,8 +94,8 @@ namespace NBitcoin
this.pubkey = pubkey;
this.nDepth = depth;
this.nChild = child;
Buffer.BlockCopy(fingerprint, 0, vchFingerprint, 0, FingerprintLength);
Buffer.BlockCopy(chainCode, 0, vchChainCode, 0, ChainCodeLength);
Buffer.BlockCopy(fingerprint, 0, this.vchFingerprint, 0, FingerprintLength);
Buffer.BlockCopy(chainCode, 0, this.vchChainCode, 0, ChainCodeLength);
}
public ExtPubKey(PubKey masterKey, byte[] chainCode)
......@@ -107,15 +107,15 @@ namespace NBitcoin
if(chainCode.Length != ChainCodeLength)
throw new ArgumentException(string.Format("The chain code must be {0} bytes.", ChainCodeLength), "chainCode");
this.pubkey = masterKey;
Buffer.BlockCopy(chainCode, 0, vchChainCode, 0, ChainCodeLength);
Buffer.BlockCopy(chainCode, 0, this.vchChainCode, 0, ChainCodeLength);
}
public bool IsChildOf(ExtPubKey parentKey)
{
if(Depth != parentKey.Depth + 1)
if(this.Depth != parentKey.Depth + 1)
return false;
return parentKey.CalculateChildFingerprint().SequenceEqual(Fingerprint);
return parentKey.CalculateChildFingerprint().SequenceEqual(this.Fingerprint);
}
public bool IsParentOf(ExtPubKey childKey)
{
......@@ -123,14 +123,14 @@ namespace NBitcoin
}
public byte[] CalculateChildFingerprint()
{
return pubkey.Hash.ToBytes().SafeSubarray(0, FingerprintLength);
return this.pubkey.Hash.ToBytes().SafeSubarray(0, FingerprintLength);
}
public byte[] Fingerprint
{
get
{
return vchFingerprint;
return this.vchFingerprint;
}
}
......@@ -138,11 +138,11 @@ namespace NBitcoin
{
var result = new ExtPubKey
{
nDepth = (byte)(nDepth + 1),
nDepth = (byte)(this.nDepth + 1),
vchFingerprint = CalculateChildFingerprint(),
nChild = index
};
result.pubkey = pubkey.Derivate(this.vchChainCode, index, out result.vchChainCode);
result.pubkey = this.pubkey.Derivate(this.vchChainCode, index, out result.vchChainCode);
return result;
}
......@@ -172,11 +172,11 @@ namespace NBitcoin
{
using(stream.BigEndianScope())
{
stream.ReadWrite(ref nDepth);
stream.ReadWrite(ref vchFingerprint);
stream.ReadWrite(ref nChild);
stream.ReadWrite(ref vchChainCode);
stream.ReadWrite(ref pubkey);
stream.ReadWrite(ref this.nDepth);
stream.ReadWrite(ref this.vchFingerprint);
stream.ReadWrite(ref this.nChild);
stream.ReadWrite(ref this.vchChainCode);
stream.ReadWrite(ref this.pubkey);
}
}
......@@ -191,14 +191,14 @@ namespace NBitcoin
public override bool Equals(object obj)
{
ExtPubKey item = obj as ExtPubKey;
var item = obj as ExtPubKey;
if(item == null)
return false;
return Hash.Equals(item.Hash);
return this.Hash.Equals(item.Hash);
}
public static bool operator ==(ExtPubKey a, ExtPubKey b)
{
if(System.Object.ReferenceEquals(a, b))
if(ReferenceEquals(a, b))
return true;
if(((object)a == null) || ((object)b == null))
return false;
......@@ -212,7 +212,7 @@ namespace NBitcoin
public override int GetHashCode()
{
return Hash.GetHashCode();
return this.Hash.GetHashCode();
}
#endregion
......@@ -230,7 +230,7 @@ namespace NBitcoin
{
get
{
return PubKey.Hash.ScriptPubKey;
return this.PubKey.Hash.ScriptPubKey;
}
}
......
......@@ -12,7 +12,7 @@ namespace NBitcoin
{
public KeyPath()
{
_Indexes = new uint[0];
this._Indexes = new uint[0];
}
/// <summary>
......@@ -22,7 +22,7 @@ namespace NBitcoin
/// <returns></returns>
public static KeyPath Parse(string path)
{
var parts = path
uint[] parts = path
.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries)
.Where(p => p != "m")
.Select(ParseCore)
......@@ -32,7 +32,7 @@ namespace NBitcoin
public KeyPath(string path)
{
_Indexes =
this._Indexes =
path
.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries)
.Where(p => p != "m")
......@@ -43,22 +43,22 @@ namespace NBitcoin
private static uint ParseCore(string i)
{
bool hardened = i.EndsWith("'");
var nonhardened = hardened ? i.Substring(0, i.Length - 1) : i;
var index = uint.Parse(nonhardened);
string nonhardened = hardened ? i.Substring(0, i.Length - 1) : i;
uint index = uint.Parse(nonhardened);
return hardened ? index | 0x80000000u : index;
}
public KeyPath(params uint[] indexes)
{
_Indexes = indexes;
this._Indexes = indexes;
}
readonly uint[] _Indexes;
private readonly uint[] _Indexes;
public uint this[int index]
{
get
{
return _Indexes[index];
return this._Indexes[index];
}
}
......@@ -66,7 +66,7 @@ namespace NBitcoin
{
get
{
return _Indexes.ToArray();
return this._Indexes.ToArray();
}
}
......@@ -86,8 +86,7 @@ namespace NBitcoin
public KeyPath Derive(KeyPath derivation)
{
return new KeyPath(
_Indexes
return new KeyPath(this._Indexes
.Concat(derivation._Indexes)
.ToArray());
}
......@@ -96,24 +95,24 @@ namespace NBitcoin
{
get
{
if(_Indexes.Length == 0)
if(this._Indexes.Length == 0)
return null;
return new KeyPath(_Indexes.Take(_Indexes.Length - 1).ToArray());
return new KeyPath(this._Indexes.Take(this._Indexes.Length - 1).ToArray());
}
}
public KeyPath Increment()
{
if(_Indexes.Length == 0)
if(this._Indexes.Length == 0)
return null;
var indices = _Indexes.ToArray();
uint[] indices = this._Indexes.ToArray();
indices[indices.Length - 1]++;
return new KeyPath(indices);
}
public override bool Equals(object obj)
{
KeyPath item = obj as KeyPath;
var item = obj as KeyPath;
if(item == null)
return false;
return ToString().Equals(item.ToString());
......@@ -137,16 +136,16 @@ namespace NBitcoin
return ToString().GetHashCode();
}
string _Path;
private string _Path;
public override string ToString()
{
return _Path ?? (_Path = string.Join("/", _Indexes.Select(ToString).ToArray()));
return this._Path ?? (this._Path = string.Join("/", this._Indexes.Select(ToString).ToArray()));
}
private static string ToString(uint i)
{
var hardened = (i & 0x80000000u) != 0;
var nonhardened = (i & ~0x80000000u);
bool hardened = (i & 0x80000000u) != 0;
uint nonhardened = (i & ~0x80000000u);
return hardened ? nonhardened + "'" : nonhardened.ToString(CultureInfo.InvariantCulture);
}
......@@ -154,9 +153,9 @@ namespace NBitcoin
{
get
{
if(_Indexes.Length == 0)
if(this._Indexes.Length == 0)
throw new InvalidOperationException("No indice found in this KeyPath");
return (_Indexes[_Indexes.Length - 1] & 0x80000000u) != 0;
return (this._Indexes[this._Indexes.Length - 1] & 0x80000000u) != 0;
}
}
}
......
using System;
using System.Linq;
using NBitcoin.BouncyCastle.Asn1.X9;
using NBitcoin.BouncyCastle.Math;
using NBitcoin.BouncyCastle.Math.EC;
using NBitcoin.Crypto;
......@@ -18,51 +19,54 @@ namespace NBitcoin
{
}
byte[] _AddressHash;
private byte[] _AddressHash;
public byte[] AddressHash
{
get
{
return _AddressHash ?? (_AddressHash = vchData.SafeSubarray(1, 4));
return this._AddressHash ?? (this._AddressHash = this.vchData.SafeSubarray(1, 4));
}
}
public bool IsCompressed
{
get
{
return (vchData[0] & 0x20) != 0;
return (this.vchData[0] & 0x20) != 0;
}
}
byte[] _OwnerEntropy;
private byte[] _OwnerEntropy;
public byte[] OwnerEntropy
{
get
{
return _OwnerEntropy ?? (_OwnerEntropy = vchData.SafeSubarray(5, 8));
return this._OwnerEntropy ?? (this._OwnerEntropy = this.vchData.SafeSubarray(5, 8));
}
}
LotSequence _LotSequence;
private LotSequence _LotSequence;
public LotSequence LotSequence
{
get
{
var hasLotSequence = (vchData[0] & 0x04) != 0;
bool hasLotSequence = (this.vchData[0] & 0x04) != 0;
if(!hasLotSequence)
return null;
if(_LotSequence == null)
if(this._LotSequence == null)
{
_LotSequence = new LotSequence(OwnerEntropy.SafeSubarray(4, 4));
this._LotSequence = new LotSequence(this.OwnerEntropy.SafeSubarray(4, 4));
}
return _LotSequence;
return this._LotSequence;
}
}
byte[] _EncryptedPointB;
byte[] EncryptedPointB
private byte[] _EncryptedPointB;
private byte[] EncryptedPointB
{
get
{
return _EncryptedPointB ?? (_EncryptedPointB = vchData.SafeSubarray(13));
return this._EncryptedPointB ?? (this._EncryptedPointB = this.vchData.SafeSubarray(13));
}
}
......@@ -78,7 +82,7 @@ namespace NBitcoin
{
get
{
return vchData.Length == 1 + 4 + 8 + 33;
return this.vchData.Length == 1 + 4 + 8 + 33;
}
}
......@@ -86,23 +90,23 @@ namespace NBitcoin
public bool Check(string passphrase, BitcoinAddress expectedAddress)
{
//Derive passfactor using scrypt with ownerentropy and the user's passphrase and use it to recompute passpoint
byte[] passfactor = BitcoinEncryptedSecretEC.CalculatePassFactor(passphrase, LotSequence, OwnerEntropy);
byte[] passfactor = BitcoinEncryptedSecretEC.CalculatePassFactor(passphrase, this.LotSequence, this.OwnerEntropy);
//Derive decryption key for pointb using scrypt with passpoint, addresshash, and ownerentropy
byte[] passpoint = BitcoinEncryptedSecretEC.CalculatePassPoint(passfactor);
byte[] derived = BitcoinEncryptedSecretEC.CalculateDecryptionKey(passpoint, AddressHash, OwnerEntropy);
byte[] derived = BitcoinEncryptedSecretEC.CalculateDecryptionKey(passpoint, this.AddressHash, this.OwnerEntropy);
//Decrypt encryptedpointb to yield pointb
var pointbprefix = EncryptedPointB[0];
byte pointbprefix = this.EncryptedPointB[0];
pointbprefix = (byte)(pointbprefix ^ (byte)(derived[63] & (byte)0x01));
//Optional since ArithmeticException will catch it, but it saves some times
if(pointbprefix != 0x02 && pointbprefix != 0x03)
return false;
var pointb = BitcoinEncryptedSecret.DecryptKey(EncryptedPointB.Skip(1).ToArray(), derived);
byte[] pointb = BitcoinEncryptedSecret.DecryptKey(this.EncryptedPointB.Skip(1).ToArray(), derived);
pointb = new byte[] { pointbprefix }.Concat(pointb).ToArray();
//4.ECMultiply pointb by passfactor. Use the resulting EC point as a public key
var curve = ECKey.Secp256k1;
X9ECParameters curve = ECKey.Secp256k1;
ECPoint pointbec;
try
{
......@@ -116,13 +120,13 @@ namespace NBitcoin
{
return false;
}
PubKey pubkey = new PubKey(pointbec.Multiply(new BigInteger(1, passfactor)).GetEncoded());
var pubkey = new PubKey(pointbec.Multiply(new BigInteger(1, passfactor)).GetEncoded());
//and hash it into address using either compressed or uncompressed public key methodology as specifid in flagbyte.
pubkey = IsCompressed ? pubkey.Compress() : pubkey.Decompress();
pubkey = this.IsCompressed ? pubkey.Compress() : pubkey.Decompress();
var actualhash = BitcoinEncryptedSecretEC.HashAddress(pubkey.GetAddress(Network));
var expectedhash = BitcoinEncryptedSecretEC.HashAddress(expectedAddress);
byte[] actualhash = BitcoinEncryptedSecretEC.HashAddress(pubkey.GetAddress(this.Network));
byte[] expectedhash = BitcoinEncryptedSecretEC.HashAddress(expectedAddress);
return Utils.ArrayEqual(actualhash, expectedhash);
}
......
......@@ -11,7 +11,7 @@ namespace NBitcoin
public class HardcodedWordlistSource : IWordlistSource
{
static Dictionary<string, string> _WordLists;
private static Dictionary<string, string> _WordLists;
static HardcodedWordlistSource()
{
var dico = new Dictionary<string, string>();
......@@ -29,7 +29,7 @@ namespace NBitcoin
public Task<Wordlist> Load(string name)
{
var list = _WordLists.TryGet(name);
string list = _WordLists.TryGet(name);
if(list == null)
return null;
return Task.FromResult(new Wordlist(list.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries),
......
This diff is collapsed.
......@@ -5,9 +5,6 @@ using System.Text;
using NBitcoin.BouncyCastle.Crypto.Parameters;
using NBitcoin.Crypto;
#if !WINDOWS_UWP && !USEBC
#endif
namespace NBitcoin
{
/// <summary>
......@@ -24,20 +21,21 @@ namespace NBitcoin
{
if(mnemonic == null)
throw new ArgumentNullException("mnemonic");
_Mnemonic = mnemonic.Trim();
this._Mnemonic = mnemonic.Trim();
if(wordlist == null)
wordlist = Wordlist.AutoDetect(mnemonic) ?? Wordlist.English;
var words = mnemonic.Split(new char[] { ' ', ' ' }, StringSplitOptions.RemoveEmptyEntries);
string[] words = mnemonic.Split(new char[] { ' ', ' ' }, StringSplitOptions.RemoveEmptyEntries);
//if the sentence is not at least 12 characters or cleanly divisible by 3, it is bad!
if(!CorrectWordCount(words.Length))
{
throw new FormatException("Word count should be equals to 12,15,18,21 or 24");
}
_Words = words;
_WordList = wordlist;
_Indices = wordlist.ToIndices(words);
this._Words = words;
this._WordList = wordlist;
this._Indices = wordlist.ToIndices(words);
}
/// <summary>
......@@ -48,23 +46,23 @@ namespace NBitcoin
public Mnemonic(Wordlist wordList, byte[] entropy = null)
{
wordList = wordList ?? Wordlist.English;
_WordList = wordList;
this._WordList = wordList;
if(entropy == null)
entropy = RandomUtils.GetBytes(32);
var i = Array.IndexOf(entArray, entropy.Length * 8);
int i = Array.IndexOf(entArray, entropy.Length * 8);
if(i == -1)
throw new ArgumentException("The length for entropy should be : " + String.Join(",", entArray), "entropy");
int cs = csArray[i];
byte[] checksum = Hashes.SHA256(entropy);
BitWriter entcsResult = new BitWriter();
var entcsResult = new BitWriter();
entcsResult.Write(entropy);
entcsResult.Write(checksum, cs);
_Indices = entcsResult.ToIntegers();
_Words = _WordList.GetWords(_Indices);
_Mnemonic = _WordList.GetSentence(_Indices);
this._Indices = entcsResult.ToIntegers();
this._Words = this._WordList.GetWords(this._Indices);
this._Mnemonic = this._WordList.GetSentence(this._Indices);
}
public Mnemonic(Wordlist wordList, WordCount wordCount)
......@@ -75,39 +73,39 @@ namespace NBitcoin
private static byte[] GenerateEntropy(WordCount wordCount)
{
var ms = (int)wordCount;
int ms = (int)wordCount;
if(!CorrectWordCount(ms))
throw new ArgumentException("Word count should be equal to 12,15,18,21 or 24", "wordCount");
int i = Array.IndexOf(msArray, (int)wordCount);
return RandomUtils.GetBytes(entArray[i] / 8);
}
static readonly int[] msArray = new[] { 12, 15, 18, 21, 24 };
static readonly int[] csArray = new[] { 4, 5, 6, 7, 8 };
static readonly int[] entArray = new[] { 128, 160, 192, 224, 256 };
private static readonly int[] msArray = new[] { 12, 15, 18, 21, 24 };
private static readonly int[] csArray = new[] { 4, 5, 6, 7, 8 };
private static readonly int[] entArray = new[] { 128, 160, 192, 224, 256 };
bool? _IsValidChecksum;
private bool? _IsValidChecksum;
public bool IsValidChecksum
{
get
{
if(_IsValidChecksum == null)
if(this._IsValidChecksum == null)
{
int i = Array.IndexOf(msArray, _Indices.Length);
int i = Array.IndexOf(msArray, this._Indices.Length);
int cs = csArray[i];
int ent = entArray[i];
BitWriter writer = new BitWriter();
var bits = Wordlist.ToBits(_Indices);
var writer = new BitWriter();
BitArray bits = Wordlist.ToBits(this._Indices);
writer.Write(bits, ent);
var entropy = writer.ToBytes();
var checksum = Hashes.SHA256(entropy);
byte[] entropy = writer.ToBytes();
byte[] checksum = Hashes.SHA256(entropy);
writer.Write(checksum, cs);
var expectedIndices = writer.ToIntegers();
_IsValidChecksum = expectedIndices.SequenceEqual(_Indices);
int[] expectedIndices = writer.ToIntegers();
this._IsValidChecksum = expectedIndices.SequenceEqual(this._Indices);
}
return _IsValidChecksum.Value;
return this._IsValidChecksum.Value;
}
}
......@@ -116,38 +114,12 @@ namespace NBitcoin
return msArray.Any(_ => _ == ms);
}
// FIXME: this method is not used. Shouldn't we delete it?
private int ToInt(BitArray bits)
{
if(bits.Length != 11)
{
throw new InvalidOperationException("should never happen, bug in nbitcoin");
}
int number = 0;
int base2Divide = 1024; //it's all downhill from here...literally we halve this for each bit we move to.
//literally picture this loop as going from the most significant bit across to the least in the 11 bits, dividing by 2 for each bit as per binary/base 2
foreach(bool b in bits)
{
if(b)
{
number = number + base2Divide;
}
base2Divide = base2Divide / 2;
}
return number;
}
private readonly Wordlist _WordList;
public Wordlist WordList
{
get
{
return _WordList;
return this._WordList;
}
}
......@@ -156,7 +128,7 @@ namespace NBitcoin
{
get
{
return _Indices;
return this._Indices;
}
}
private readonly string[] _Words;
......@@ -164,17 +136,17 @@ namespace NBitcoin
{
get
{
return _Words;
return this._Words;
}
}
public byte[] DeriveSeed(string passphrase = null)
{
passphrase = passphrase ?? "";
var salt = Concat(Encoding.UTF8.GetBytes("mnemonic"), Normalize(passphrase));
var bytes = Normalize(_Mnemonic);
byte[] salt = Concat(Encoding.UTF8.GetBytes("mnemonic"), Normalize(passphrase));
byte[] bytes = Normalize(this._Mnemonic);
#if USEBC || WINDOWS_UWP || NETCORE
#if NETCORE
var mac = new NBitcoin.BouncyCastle.Crypto.Macs.HMac(new NBitcoin.BouncyCastle.Crypto.Digests.Sha512Digest());
mac.Init(new KeyParameter(bytes));
return Pbkdf2.ComputeDerivedKey(mac, salt, 2048, 64);
......@@ -191,65 +163,29 @@ namespace NBitcoin
internal static string NormalizeString(string word)
{
#if !NOSTRNORMALIZE
if(!SupportOsNormalization())
{
return KDTable.NormalizeKD(word);
}
else
{
return word.Normalize(NormalizationForm.FormKD);
}
#else
return KDTable.NormalizeKD(word);
#endif
}
#if !NOSTRNORMALIZE
static bool? _SupportOSNormalization;
internal static bool SupportOsNormalization()
{
if(_SupportOSNormalization == null)
{
var notNormalized = "あおぞら";
var normalized = "あおぞら";
if(notNormalized.Equals(normalized, StringComparison.Ordinal))
{
_SupportOSNormalization = false;
}
else
{
try
{
_SupportOSNormalization = notNormalized.Normalize(NormalizationForm.FormKD).Equals(normalized, StringComparison.Ordinal);
}
catch { _SupportOSNormalization = false; }
}
}
return _SupportOSNormalization.Value;
}
#endif
public ExtKey DeriveExtKey(string passphrase = null)
{
return new ExtKey(DeriveSeed(passphrase));
}
static Byte[] Concat(Byte[] source1, Byte[] source2)
private static Byte[] Concat(Byte[] source1, Byte[] source2)
{
//Most efficient way to merge two arrays this according to http://stackoverflow.com/questions/415291/best-way-to-combine-two-or-more-byte-arrays-in-c-sharp
Byte[] buffer = new Byte[source1.Length + source2.Length];
System.Buffer.BlockCopy(source1, 0, buffer, 0, source1.Length);
System.Buffer.BlockCopy(source2, 0, buffer, source1.Length, source2.Length);
var buffer = new Byte[source1.Length + source2.Length];
Buffer.BlockCopy(source1, 0, buffer, 0, source1.Length);
Buffer.BlockCopy(source2, 0, buffer, source1.Length, source2.Length);
return buffer;
}
string _Mnemonic;
private string _Mnemonic;
public override string ToString()
{
return _Mnemonic;
return this._Mnemonic;
}
......
......@@ -113,7 +113,7 @@ namespace NBitcoin
return name;
}
static Dictionary<string, Wordlist> _LoadedLists = new Dictionary<string, Wordlist>();
private static Dictionary<string, Wordlist> _LoadedLists = new Dictionary<string, Wordlist>();
public static async Task<Wordlist> LoadWordList(string name)
{
if(name == null)
......@@ -131,10 +131,13 @@ namespace NBitcoin
throw new InvalidOperationException("Wordlist.WordlistSource is not set, impossible to fetch word list.");
result = await WordlistSource.Load(name).ConfigureAwait(false);
if(result != null)
{
lock(_LoadedLists)
{
_LoadedLists.AddOrReplace(name, result);
}
}
return result;
}
......@@ -152,11 +155,11 @@ namespace NBitcoin
/// <param name="words">The words to be used in the wordlist</param>
public Wordlist(String[] words, char space, string name)
{
_words = words
this._words = words
.Select(w => Mnemonic.NormalizeString(w))
.ToArray();
_Space = space;
_Name = name;
this._Space = space;
this._Name = name;
}
private readonly string _Name;
......@@ -164,7 +167,7 @@ namespace NBitcoin
{
get
{
return _Name;
return this._Name;
}
}
private readonly char _Space;
......@@ -172,7 +175,7 @@ namespace NBitcoin
{
get
{
return _Space;
return this._Space;
}
}
......@@ -184,9 +187,9 @@ namespace NBitcoin
public bool WordExists(string word, out int index)
{
word = Mnemonic.NormalizeString(word);
if(_words.Contains(word))
if(this._words.Contains(word))
{
index = Array.IndexOf(_words, word);
index = Array.IndexOf(this._words, word);
return true;
}
......@@ -202,7 +205,7 @@ namespace NBitcoin
/// <returns>Word</returns>
public string GetWordAtIndex(int index)
{
return _words[index];
return this._words[index];
}
/// <summary>
......@@ -212,7 +215,7 @@ namespace NBitcoin
{
get
{
return _words.Length;
return this._words.Length;
}
}
......@@ -227,41 +230,41 @@ namespace NBitcoin
}
public static Language AutoDetectLanguage(string[] words)
{
List<int> languageCount = new List<int>(new int[] { 0, 0, 0, 0, 0, 0 });
var languageCount = new List<int>(new int[] { 0, 0, 0, 0, 0, 0 });
int index;
foreach(string s in words)
{
if(Wordlist.English.WordExists(s, out index))
if(English.WordExists(s, out index))
{
//english is at 0
languageCount[0]++;
}
if(Wordlist.Japanese.WordExists(s, out index))
if(Japanese.WordExists(s, out index))
{
//japanese is at 1
languageCount[1]++;
}
if(Wordlist.Spanish.WordExists(s, out index))
if(Spanish.WordExists(s, out index))
{
//spanish is at 2
languageCount[2]++;
}
if(Wordlist.ChineseSimplified.WordExists(s, out index))
if(ChineseSimplified.WordExists(s, out index))
{
//chinese simplified is at 3
languageCount[3]++;
}
if(Wordlist.ChineseTraditional.WordExists(s, out index) && !Wordlist.ChineseSimplified.WordExists(s, out index))
if(ChineseTraditional.WordExists(s, out index) && !ChineseSimplified.WordExists(s, out index))
{
//chinese traditional is at 4
languageCount[4]++;
}
if(Wordlist.French.WordExists(s, out index))
if(French.WordExists(s, out index))
{
languageCount[5]++;
}
......@@ -314,12 +317,12 @@ namespace NBitcoin
public string[] Split(string mnemonic)
{
return mnemonic.Split(new char[] { Space }, StringSplitOptions.RemoveEmptyEntries);
return mnemonic.Split(new char[] {this.Space }, StringSplitOptions.RemoveEmptyEntries);
}
public override string ToString()
{
return _Name;
return this._Name;
}
public string[] GetWords(int[] indices)
......@@ -332,7 +335,7 @@ namespace NBitcoin
public string GetSentence(int[] indices)
{
return String.Join(Space.ToString(), GetWords(indices));
return String.Join(this.Space.ToString(), GetWords(indices));
}
......@@ -361,13 +364,13 @@ namespace NBitcoin
{
if(values.Any(v => v >= 2048))
throw new ArgumentException("values should be between 0 and 2048", "values");
BitArray result = new BitArray(values.Length * 11);
var result = new BitArray(values.Length * 11);
int i = 0;
foreach(var val in values)
foreach(int val in values)
{
for(int p = 0; p < 11; p++)
{
var v = (val & (1 << (10 - p))) != 0;
bool v = (val & (1 << (10 - p))) != 0;
result.Set(i, v);
i++;
}
......
......@@ -26,13 +26,13 @@ namespace NBitcoin
{
get
{
return _Network;
return this._Network;
}
}
protected Base58Data(string base64, Network expectedNetwork = null)
{
_Network = expectedNetwork;
this._Network = expectedNetwork;
SetString(base64);
}
......@@ -40,32 +40,32 @@ namespace NBitcoin
{
if(network == null)
throw new ArgumentNullException("network");
_Network = network;
this._Network = network;
SetData(rawBytes);
}
private void SetString(string psz)
{
if(_Network == null)
if(this._Network == null)
{
_Network = Network.GetNetworkFromBase58Data(psz, Type);
if(_Network == null)
throw new FormatException("Invalid " + this.GetType().Name);
this._Network = NetworksContainer.GetNetworkFromBase58Data(psz, this.Type);
if(this._Network == null)
throw new FormatException("Invalid " + GetType().Name);
}
byte[] vchTemp = Encoders.Base58Check.DecodeData(psz);
var expectedVersion = _Network.GetVersionBytes(Type, true);
byte[] expectedVersion = this._Network.GetVersionBytes(this.Type, true);
vchVersion = vchTemp.SafeSubarray(0, expectedVersion.Length);
if(!Utils.ArrayEqual(vchVersion, expectedVersion))
this.vchVersion = vchTemp.SafeSubarray(0, expectedVersion.Length);
if(!Utils.ArrayEqual(this.vchVersion, expectedVersion))
throw new FormatException("The version prefix does not match the expected one " + String.Join(",", expectedVersion));
vchData = vchTemp.SafeSubarray(expectedVersion.Length);
wifData = psz;
this.vchData = vchTemp.SafeSubarray(expectedVersion.Length);
this.wifData = psz;
if(!IsValid)
throw new FormatException("Invalid " + this.GetType().Name);
if(!this.IsValid)
throw new FormatException("Invalid " + GetType().Name);
}
......@@ -73,11 +73,11 @@ namespace NBitcoin
private void SetData(byte[] vchData)
{
this.vchData = vchData;
this.vchVersion = _Network.GetVersionBytes(Type, true);
wifData = Encoders.Base58Check.EncodeData(vchVersion.Concat(vchData).ToArray());
this.vchVersion = this._Network.GetVersionBytes(this.Type, true);
this.wifData = Encoders.Base58Check.EncodeData(this.vchVersion.Concat(vchData).ToArray());
if(!IsValid)
throw new FormatException("Invalid " + this.GetType().Name);
if(!this.IsValid)
throw new FormatException("Invalid " + GetType().Name);
}
......@@ -98,27 +98,27 @@ namespace NBitcoin
public string ToWif()
{
return wifData;
return this.wifData;
}
public byte[] ToBytes()
{
return vchData.ToArray();
return this.vchData.ToArray();
}
public override string ToString()
{
return wifData;
return this.wifData;
}
public override bool Equals(object obj)
{
Base58Data item = obj as Base58Data;
var item = obj as Base58Data;
if(item == null)
return false;
return ToString().Equals(item.ToString());
}
public static bool operator ==(Base58Data a, Base58Data b)
{
if(System.Object.ReferenceEquals(a, b))
if(ReferenceEquals(a, b))
return true;
if(((object)a == null) || ((object)b == null))
return false;
......
......@@ -94,7 +94,7 @@ namespace NBitcoin.BitcoinCore
{
this.Value = this.Outputs
.Where(o => !this.IsNull(o))
.Sum(o=> o.Value);
.Sum(o => o.Value);
}
private bool IsNull(TxOut o) => o.Value.Satoshi == -1;
......@@ -102,10 +102,10 @@ namespace NBitcoin.BitcoinCore
private void Cleanup()
{
var count = this.Outputs.Count;
int count = this.Outputs.Count;
// Remove spent outputs at the end of vout.
for(int i = count - 1; i >= 0; i--)
for (int i = count - 1; i >= 0; i--)
{
if (this.IsNull(this.Outputs[i]))
this.Outputs.RemoveAt(i);
......@@ -140,8 +140,10 @@ namespace NBitcoin.BitcoinCore
{
byte chAvail = 0;
for (uint i = 0; i < 8 && 2 + b * 8 + i < this.Outputs.Count; i++)
if(!this.IsNull(this.Outputs[2 + (int)b * 8 + (int)i]))
{
if (!this.IsNull(this.Outputs[2 + (int)b * 8 + (int)i]))
chAvail |= (byte)(1 << (int)i);
}
stream.ReadWrite(ref chAvail);
}
......@@ -175,7 +177,7 @@ namespace NBitcoin.BitcoinCore
stream.ReadWriteAsVarInt(ref nCode);
this.CoinBase = (nCode & 1) != 0;
List<bool> vAvail = new List<bool>() { false, false };
var vAvail = new List<bool>() { false, false };
vAvail[0] = (nCode & 2) != 0;
vAvail[1] = (nCode & 4) != 0;
......@@ -204,7 +206,7 @@ namespace NBitcoin.BitcoinCore
{
if (vAvail[(int)i])
{
TxOutCompressor compressed = new TxOutCompressor();
var compressed = new TxOutCompressor();
stream.ReadWrite(ref compressed);
this.Outputs[(int)i] = compressed.TxOut;
}
......@@ -236,7 +238,7 @@ namespace NBitcoin.BitcoinCore
bool fZero = true;
for (uint i = 0; i < 8 && 2 + b * 8 + i < this.Outputs.Count; i++)
{
if (!this.IsNull(this.Outputs[2 + (int)b * 8 + (int)i]))
if (!IsNull(this.Outputs[2 + (int)b * 8 + (int)i]))
{
fZero = false;
continue;
......@@ -256,7 +258,7 @@ namespace NBitcoin.BitcoinCore
// check whether a particular output is still available
public bool IsAvailable(uint position)
{
return position <= int.MaxValue && position < this.Outputs.Count && !this.IsNull(this.Outputs[(int)position]);
return position <= int.MaxValue && position < this.Outputs.Count && !IsNull(this.Outputs[(int)position]);
}
public TxOut TryGetOutput(uint position)
......@@ -275,7 +277,7 @@ namespace NBitcoin.BitcoinCore
public void ClearUnspendable()
{
for(int i = 0; i < this.Outputs.Count; i++)
for (int i = 0; i < this.Outputs.Count; i++)
{
TxOut o = this.Outputs[i];
if (o.ScriptPubKey.IsUnspendable)
......@@ -287,10 +289,12 @@ namespace NBitcoin.BitcoinCore
public void MergeFrom(Coins otherCoin)
{
var diff = otherCoin.Outputs.Count - this.Outputs.Count;
int diff = otherCoin.Outputs.Count - this.Outputs.Count;
if (diff > 0)
{
for (int i = 0; i < diff; i++)
this.Outputs.Add(NullTxOut);
}
for (int i = 0; i < otherCoin.Outputs.Count; i++)
this.Outputs[i] = otherCoin.Outputs[i];
......
......@@ -6,39 +6,31 @@ namespace NBitcoin.BitcoinCore
{
public class CoinsView
{
private readonly NoSqlRepository index;
public CoinsView(NoSqlRepository index)
public CoinsView(NoSqlRepository noSqlRepository)
{
this.index = index ?? throw new ArgumentNullException("index");
this.NoSqlRepository = noSqlRepository ?? throw new ArgumentNullException(nameof(noSqlRepository));
}
public CoinsView()
: this(new InMemoryNoSqlRepository())
public CoinsView(Network network)
: this(new InMemoryNoSqlRepository(network))
{
}
public NoSqlRepository Index
{
get
{
return this.index;
}
}
public NoSqlRepository NoSqlRepository { get; }
public Coins GetCoins(uint256 txId)
{
return this.Index.GetAsync<Coins>(txId.ToString()).GetAwaiter().GetResult();
return this.NoSqlRepository.GetAsync<Coins>(txId.ToString()).GetAwaiter().GetResult();
}
public Task<Coins> GetCoinsAsync(uint256 txId)
{
return this.Index.GetAsync<Coins>(txId.ToString());
return this.NoSqlRepository.GetAsync<Coins>(txId.ToString());
}
public void SetCoins(uint256 txId, Coins coins)
{
this.Index.PutAsync(txId.ToString(), coins);
this.NoSqlRepository.PutAsync(txId.ToString(), coins);
}
public bool HaveCoins(uint256 txId)
......@@ -53,13 +45,13 @@ namespace NBitcoin.BitcoinCore
public async Task<uint256> GetBestBlockAsync()
{
uint256.MutableUint256 block = await this.Index.GetAsync<uint256.MutableUint256>("B").ConfigureAwait(false);
uint256.MutableUint256 block = await this.NoSqlRepository.GetAsync<uint256.MutableUint256>("B").ConfigureAwait(false);
return block == null ? uint256.Zero : block.Value;
}
public void SetBestBlock(uint256 blockId)
{
this.Index.PutAsync("B", blockId.AsBitcoinSerializable());
this.NoSqlRepository.PutAsync("B", blockId.AsBitcoinSerializable());
}
public bool HaveInputs(Transaction tx)
......@@ -67,7 +59,7 @@ namespace NBitcoin.BitcoinCore
if (!tx.IsCoinBase)
{
// first check whether information about the prevout hash is available
foreach(TxIn input in tx.Inputs)
foreach (TxIn input in tx.Inputs)
{
OutPoint prevout = input.PrevOut;
if (!HaveCoins(prevout.Hash))
......@@ -103,7 +95,7 @@ namespace NBitcoin.BitcoinCore
public CoinsView CreateCached()
{
return new CoinsView(new CachedNoSqlRepository(this.Index));
return new CoinsView(new CachedNoSqlRepository(this.NoSqlRepository));
}
public void AddTransaction(Consensus consensus, Transaction tx, int height)
......@@ -111,4 +103,4 @@ namespace NBitcoin.BitcoinCore
SetCoins(tx.GetHash(), new Coins(tx, height));
}
}
}
}
\ No newline at end of file
This diff is collapsed.
using System;
using NBitcoin.BouncyCastle.Math;
using NBitcoin.Crypto;
namespace NBitcoin
{
/// <summary>
/// Nodes collect new transactions into a block, hash them into a hash tree,
/// and scan through nonce values to make the block's hash satisfy proof-of-work
/// requirements. When they solve the proof-of-work, they broadcast the block
/// to everyone and the block is added to the block chain. The first transaction
/// in the block is a special one that creates a new coin owned by the creator
/// of the block.
/// </summary>
public class BlockHeader : IBitcoinSerializable
{
public const int Size = 80;
/// <summary>Current header version.</summary>
public virtual int CurrentVersion => 3;
private static BigInteger Pow256 = BigInteger.ValueOf(2).Pow(256);
private uint256 hashPrevBlock;
public uint256 HashPrevBlock { get { return this.hashPrevBlock; } set { this.hashPrevBlock = value; } }
private uint time;
public uint Time { get { return this.time; } set { this.time = value; } }
private uint bits;
public Target Bits { get { return this.bits; } set { this.bits = value; } }
protected int version;
public int Version { get { return this.version; } set { this.version = value; } }
private uint nonce;
public uint Nonce { get { return this.nonce; } set { this.nonce = value; } }
private uint256 hashMerkleRoot;
public uint256 HashMerkleRoot { get { return this.hashMerkleRoot; } set { this.hashMerkleRoot = value; } }
public bool IsNull { get { return (this.bits == 0); } }
protected uint256[] hashes;
public DateTimeOffset BlockTime
{
get
{
return Utils.UnixTimeToDateTime(this.time);
}
set
{
this.time = Utils.DateTimeToUnixTime(value);
}
}
internal BlockHeader()
{
this.version = this.CurrentVersion;
this.hashPrevBlock = 0;
this.hashMerkleRoot = 0;
this.time = 0;
this.bits = 0;
this.nonce = 0;
}
public static BlockHeader Load(byte[] hex, Network network)
{
if (hex == null)
throw new ArgumentNullException(nameof(hex));
if (network == null)
throw new ArgumentNullException(nameof(network));
BlockHeader blockHeader = network.Consensus.ConsensusFactory.CreateBlockHeader();
blockHeader.ReadWrite(hex, network.Consensus.ConsensusFactory);
return blockHeader;
}
#region IBitcoinSerializable Members
public virtual void ReadWrite(BitcoinStream stream)
{
stream.ReadWrite(ref this.version);
stream.ReadWrite(ref this.hashPrevBlock);
stream.ReadWrite(ref this.hashMerkleRoot);
stream.ReadWrite(ref this.time);
stream.ReadWrite(ref this.bits);
stream.ReadWrite(ref this.nonce);
}
#endregion
/// <summary>
/// Generates the hash of a <see cref="BlockHeader"/>.
/// </summary>
/// <returns>A hash.</returns>
public virtual uint256 GetHash()
{
uint256 hash = null;
uint256[] hashes = this.hashes;
if (hashes != null)
hash = hashes[0];
if (hash != null)
return hash;
using (var hs = new HashStream())
{
this.ReadWrite(new BitcoinStream(hs, true));
hash = hs.GetHash();
}
hashes = this.hashes;
if (hashes != null)
{
hashes[0] = hash;
}
return hash;
}
/// <summary>
/// Generates a hash for a proof-of-work block header.
/// </summary>
/// <returns>A hash.</returns>
public virtual uint256 GetPoWHash()
{
return this.GetHash();
}
[Obsolete("Call PrecomputeHash(true, true) instead")]
public void CacheHashes()
{
this.PrecomputeHash(true, true);
}
/// <summary>
/// Precompute the block header hash so that later calls to <see cref="GetHash()"/> will returns the precomputed hash.
/// </summary>
/// <param name="invalidateExisting">If true, the previous precomputed hash is thrown away, else it is reused.</param>
/// <param name="lazily">If <c>true</c>, the hash will be calculated and cached at the first call to GetHash(), else it will be immediately.</param>
public void PrecomputeHash(bool invalidateExisting = false, bool lazily = false)
{
if (this.hashes == null || invalidateExisting)
this.hashes = new uint256[1];
if (!lazily && this.hashes[0] == null)
this.hashes[0] = this.GetHash();
}
public bool CheckProofOfWork()
{
BigInteger bits = this.Bits.ToBigInteger();
if ((bits.CompareTo(BigInteger.Zero) <= 0) || (bits.CompareTo(Pow256) >= 0))
return false;
return this.GetPoWHash() <= this.Bits.ToUInt256();
}
public override string ToString()
{
return this.GetHash().ToString();
}
/// <summary>
/// Set time to consensus acceptable value.
/// </summary>
/// <param name="now">The expected date.</param>
/// <param name="consensus">Consensus.</param>
/// <param name="prev">Previous block.</param>
public void UpdateTime(DateTimeOffset now, Consensus consensus, ChainedHeader prev)
{
DateTimeOffset nOldTime = this.BlockTime;
DateTimeOffset mtp = prev.GetMedianTimePast() + TimeSpan.FromSeconds(1);
DateTimeOffset nNewTime = mtp > now ? mtp : now;
if (nOldTime < nNewTime)
this.BlockTime = nNewTime;
// Updating time can change work required on testnet.
if (consensus.PowAllowMinDifficultyBlocks)
this.Bits = this.GetWorkRequired(consensus, prev);
}
/// <summary>
/// Set time to consensus acceptable value.
/// </summary>
/// <param name="now">The expected date.</param>
/// <param name="network">Network.</param>
/// <param name="prev">Previous block.</param>
public void UpdateTime(DateTimeOffset now, Network network, ChainedHeader prev)
{
this.UpdateTime(now, network.Consensus, prev);
}
public Target GetWorkRequired(Network network, ChainedHeader prev)
{
return this.GetWorkRequired(network.Consensus, prev);
}
public Target GetWorkRequired(Consensus consensus, ChainedHeader prev)
{
return new ChainedHeader(this, this.GetHash(), prev).GetWorkRequired(consensus);
}
}
}
......@@ -7,7 +7,6 @@ namespace NBitcoin
{
[Flags]
public enum BlockFlag //block index flags
{
BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
......@@ -34,24 +33,6 @@ namespace NBitcoin
{
}
public BlockStake(byte[] bytes)
{
this.ReadWrite(bytes);
}
public BlockStake(Block block)
{
this.StakeModifierV2 = uint256.Zero;
this.HashProof = uint256.Zero;
if (IsProofOfStake(block))
{
this.SetProofOfStake();
this.StakeTime = block.Transactions[1].Time;
this.PrevoutStake = block.Transactions[1].Inputs[0].PrevOut;
}
}
public BlockFlag Flags
{
get
......@@ -116,6 +97,37 @@ namespace NBitcoin
return true;
}
/// <summary>
/// Constructs a stake block from a given block.
/// </summary>
public static BlockStake Load(Block block)
{
var blockStake = new BlockStake
{
StakeModifierV2 = uint256.Zero,
HashProof = uint256.Zero
};
if (IsProofOfStake(block))
{
blockStake.SetProofOfStake();
blockStake.StakeTime = block.Transactions[1].Time;
blockStake.PrevoutStake = block.Transactions[1].Inputs[0].PrevOut;
}
return blockStake;
}
/// <summary>
/// Constructs a stake block from a set bytes and the given network.
/// </summary>
public static BlockStake Load(byte[] bytes, Network network)
{
var blockStake = new BlockStake();
blockStake.ReadWrite(bytes, network.Consensus.ConsensusFactory);
return blockStake;
}
/// <summary>
/// Check PoW and that the blocks connect correctly
/// </summary>
......@@ -126,12 +138,14 @@ namespace NBitcoin
{
if (network == null)
throw new ArgumentNullException("network");
if (chainedHeader.Height != 0 && chainedHeader.Previous == null)
return false;
var heightCorrect = chainedHeader.Height == 0 || chainedHeader.Height == chainedHeader.Previous.Height + 1;
var genesisCorrect = chainedHeader.Height != 0 || chainedHeader.HashBlock == network.GetGenesis().GetHash();
var hashPrevCorrect = chainedHeader.Height == 0 || chainedHeader.Header.HashPrevBlock == chainedHeader.Previous.HashBlock;
var hashCorrect = chainedHeader.HashBlock == chainedHeader.Header.GetHash();
bool heightCorrect = chainedHeader.Height == 0 || chainedHeader.Height == chainedHeader.Previous.Height + 1;
bool genesisCorrect = chainedHeader.Height != 0 || chainedHeader.HashBlock == network.GetGenesis().GetHash();
bool hashPrevCorrect = chainedHeader.Height == 0 || chainedHeader.Header.HashPrevBlock == chainedHeader.Previous.HashBlock;
bool hashCorrect = chainedHeader.HashBlock == chainedHeader.Header.GetHash();
return heightCorrect && genesisCorrect && hashPrevCorrect && hashCorrect;
}
......@@ -166,6 +180,11 @@ namespace NBitcoin
/// </summary>
public class PosConsensusFactory : ConsensusFactory
{
public PosConsensusFactory()
: base()
{
}
/// <inheritdoc />
public override Block CreateBlock()
{
......@@ -183,6 +202,18 @@ namespace NBitcoin
{
return new PosTransaction();
}
/// <inheritdoc />
public override Transaction CreateTransaction(string hex)
{
return new PosTransaction(hex);
}
/// <inheritdoc />
public override Transaction CreateTransaction(byte[] bytes)
{
return new PosTransaction(bytes);
}
}
/// <summary>
......@@ -190,7 +221,7 @@ namespace NBitcoin
/// </summary>
public class PosBlockHeader : BlockHeader
{
/// <summary>Current header version.</summary>
/// <inheritdoc />
public override int CurrentVersion => 7;
/// <inheritdoc />
......@@ -219,10 +250,7 @@ namespace NBitcoin
return hash;
}
/// <summary>
/// Generate a has based on the X13 algorithms.
/// </summary>
/// <returns></returns>
/// /// <inheritdoc />
public override uint256 GetPoWHash()
{
return HashX13.Instance.Hash(this.ToBytes());
......@@ -259,6 +287,8 @@ namespace NBitcoin
{
base.ReadWrite(stream);
stream.ReadWrite(ref this.blockSignature);
this.BlockSize = stream.Serializing ? stream.Counter.WrittenBytes : stream.Counter.ReadBytes;
}
}
}
\ No newline at end of file
......@@ -9,14 +9,14 @@ namespace NBitcoin.BouncyCastle.Asn1
protected Asn1Generator(
Stream outStream)
{
_out = outStream;
this._out = outStream;
}
protected Stream Out
{
get
{
return _out;
return this._out;
}
}
......
......@@ -17,7 +17,7 @@ namespace NBitcoin.BouncyCastle.Asn1
if(obj == this)
return true;
IAsn1Convertible other = obj as IAsn1Convertible;
var other = obj as IAsn1Convertible;
if(other == null)
return false;
......
......@@ -12,7 +12,7 @@ namespace NBitcoin.BouncyCastle.Asn1
public static Asn1EncodableVector FromEnumerable(
IEnumerable e)
{
Asn1EncodableVector v = new Asn1EncodableVector();
var v = new Asn1EncodableVector();
foreach(Asn1Encodable obj in e)
{
v.Add(obj);
......@@ -41,7 +41,7 @@ namespace NBitcoin.BouncyCastle.Asn1
{
foreach(Asn1Encodable obj in objs)
{
v.Add(obj);
this.v.Add(obj);
}
}
......@@ -54,7 +54,7 @@ namespace NBitcoin.BouncyCastle.Asn1
{
if(obj != null)
{
v.Add(obj);
this.v.Add(obj);
}
}
}
......@@ -65,7 +65,7 @@ namespace NBitcoin.BouncyCastle.Asn1
{
get
{
return (Asn1Encodable)v[index];
return (Asn1Encodable) this.v[index];
}
}
......@@ -81,7 +81,7 @@ namespace NBitcoin.BouncyCastle.Asn1
{
get
{
return v.Count;
return this.v.Count;
}
}
......@@ -89,13 +89,13 @@ namespace NBitcoin.BouncyCastle.Asn1
{
get
{
return v.Count;
return this.v.Count;
}
}
public IEnumerator GetEnumerator()
{
return v.GetEnumerator();
return this.v.GetEnumerator();
}
}
}
......@@ -25,7 +25,7 @@ namespace NBitcoin.BouncyCastle.Asn1
}
else if(input is MemoryStream)
{
MemoryStream mem = (MemoryStream)input;
var mem = (MemoryStream)input;
return (int)(mem.Length - mem.Position);
}
......@@ -75,7 +75,7 @@ namespace NBitcoin.BouncyCastle.Asn1
{
bool isConstructed = (tag & Asn1Tags.Constructed) != 0;
DefiniteLengthInputStream defIn = new DefiniteLengthInputStream(this.s, length);
var defIn = new DefiniteLengthInputStream(this.s, length);
if((tag & Asn1Tags.Application) != 0)
{
......@@ -98,12 +98,12 @@ namespace NBitcoin.BouncyCastle.Asn1
}
}
return CreatePrimitiveDerObject(tagNo, defIn, tmpBuffers);
return CreatePrimitiveDerObject(tagNo, defIn, this.tmpBuffers);
}
internal Asn1EncodableVector BuildEncodableVector()
{
Asn1EncodableVector v = new Asn1EncodableVector();
var v = new Asn1EncodableVector();
Asn1Object o;
while((o = ReadObject()) != null)
......@@ -147,7 +147,7 @@ namespace NBitcoin.BouncyCastle.Asn1
//
// calculate length
//
int length = ReadLength(this.s, limit);
int length = ReadLength(this.s, this.limit);
if(length < 0) // indefinite length method
{
......
......@@ -15,8 +15,8 @@ namespace NBitcoin.BouncyCastle.Asn1
{
try
{
MemoryStream input = new MemoryStream(data, false);
Asn1InputStream asn1 = new Asn1InputStream(input, data.Length);
var input = new MemoryStream(data, false);
var asn1 = new Asn1InputStream(input, data.Length);
Asn1Object result = asn1.ReadObject();
if(input.Position != input.Length)
throw new IOException("extra data found after object");
......
......@@ -23,7 +23,7 @@ namespace NBitcoin.BouncyCastle.Asn1
public Stream GetOctetStream()
{
return new MemoryStream(str, false);
return new MemoryStream(this.str, false);
}
public Asn1OctetStringParser Parser
......@@ -36,7 +36,7 @@ namespace NBitcoin.BouncyCastle.Asn1
public virtual byte[] GetOctets()
{
return str;
return this.str;
}
protected override int Asn1GetHashCode()
......@@ -47,7 +47,7 @@ namespace NBitcoin.BouncyCastle.Asn1
protected override bool Asn1Equals(
Asn1Object asn1Object)
{
DerOctetString other = asn1Object as DerOctetString;
var other = asn1Object as DerOctetString;
if(other == null)
return false;
......
......@@ -25,13 +25,13 @@ namespace NBitcoin.BouncyCastle.Asn1
}
else if(obj is Asn1SequenceParser)
{
return Asn1Sequence.GetInstance(((Asn1SequenceParser)obj).ToAsn1Object());
return GetInstance(((Asn1SequenceParser)obj).ToAsn1Object());
}
else if(obj is byte[])
{
try
{
return Asn1Sequence.GetInstance(FromByteArray((byte[])obj));
return GetInstance(FromByteArray((byte[])obj));
}
catch(IOException e)
{
......@@ -54,12 +54,12 @@ namespace NBitcoin.BouncyCastle.Asn1
protected internal Asn1Sequence(
int capacity)
{
seq = Platform.CreateArrayList(capacity);
this.seq = Platform.CreateArrayList(capacity);
}
public virtual IEnumerator GetEnumerator()
{
return seq.GetEnumerator();
return this.seq.GetEnumerator();
}
[Obsolete("Use GetEnumerator() instead")]
......@@ -84,10 +84,10 @@ namespace NBitcoin.BouncyCastle.Asn1
public IAsn1Convertible ReadObject()
{
if(index == max)
if(this.index == this.max)
return null;
Asn1Encodable obj = outer[index++];
Asn1Encodable obj = this.outer[this.index++];
if(obj is Asn1Sequence)
return ((Asn1Sequence)obj).Parser;
......@@ -101,7 +101,7 @@ namespace NBitcoin.BouncyCastle.Asn1
public Asn1Object ToAsn1Object()
{
return outer;
return this.outer;
}
}
......@@ -123,7 +123,7 @@ namespace NBitcoin.BouncyCastle.Asn1
{
get
{
return (Asn1Encodable)seq[index];
return (Asn1Encodable) this.seq[index];
}
}
......@@ -139,7 +139,7 @@ namespace NBitcoin.BouncyCastle.Asn1
{
get
{
return Count;
return this.Count;
}
}
......@@ -147,13 +147,13 @@ namespace NBitcoin.BouncyCastle.Asn1
{
get
{
return seq.Count;
return this.seq.Count;
}
}
protected override int Asn1GetHashCode()
{
int hc = Count;
int hc = this.Count;
foreach(object o in this)
{
......@@ -174,12 +174,12 @@ namespace NBitcoin.BouncyCastle.Asn1
protected override bool Asn1Equals(
Asn1Object asn1Object)
{
Asn1Sequence other = asn1Object as Asn1Sequence;
var other = asn1Object as Asn1Sequence;
if(other == null)
return false;
if(Count != other.Count)
if(this.Count != other.Count)
return false;
IEnumerator s1 = GetEnumerator();
......@@ -199,7 +199,7 @@ namespace NBitcoin.BouncyCastle.Asn1
private Asn1Encodable GetCurrent(IEnumerator e)
{
Asn1Encodable encObj = (Asn1Encodable)e.Current;
var encObj = (Asn1Encodable)e.Current;
// unfortunately null was allowed as a substitute for DER null
if(encObj == null)
......@@ -211,7 +211,7 @@ namespace NBitcoin.BouncyCastle.Asn1
protected internal void AddObject(
Asn1Encodable obj)
{
seq.Add(obj);
this.seq.Add(obj);
}
}
}
......@@ -22,9 +22,9 @@ namespace NBitcoin.BouncyCastle.Asn1
bool isExplicit)
: base(outStream)
{
_tagged = true;
_isExplicit = isExplicit;
_tagNo = tagNo;
this._tagged = true;
this._isExplicit = isExplicit;
this._tagNo = tagNo;
}
private static void WriteLength(
......@@ -68,16 +68,16 @@ namespace NBitcoin.BouncyCastle.Asn1
int tag,
byte[] bytes)
{
if(_tagged)
if(this._tagged)
{
int tagNum = _tagNo | Asn1Tags.Tagged;
int tagNum = this._tagNo | Asn1Tags.Tagged;
if(_isExplicit)
if(this._isExplicit)
{
int newTag = _tagNo | Asn1Tags.Constructed | Asn1Tags.Tagged;
MemoryStream bOut = new MemoryStream();
int newTag = this._tagNo | Asn1Tags.Constructed | Asn1Tags.Tagged;
var bOut = new MemoryStream();
WriteDerEncoded(bOut, tag, bytes);
WriteDerEncoded(Out, newTag, bOut.ToArray());
WriteDerEncoded(this.Out, newTag, bOut.ToArray());
}
else
{
......@@ -86,12 +86,12 @@ namespace NBitcoin.BouncyCastle.Asn1
tagNum |= Asn1Tags.Constructed;
}
WriteDerEncoded(Out, tagNum, bytes);
WriteDerEncoded(this.Out, tagNum, bytes);
}
}
else
{
WriteDerEncoded(Out, tag, bytes);
WriteDerEncoded(this.Out, tag, bytes);
}
}
......
......@@ -24,17 +24,17 @@ namespace NBitcoin.BouncyCastle.Asn1
public override void AddObject(
Asn1Encodable obj)
{
new DerOutputStream(_bOut).WriteObject(obj);
new DerOutputStream(this._bOut).WriteObject(obj);
}
public override Stream GetRawOutputStream()
{
return _bOut;
return this._bOut;
}
public override void Close()
{
WriteDerEncoded(Asn1Tags.Constructed | Asn1Tags.Sequence, _bOut.ToArray());
WriteDerEncoded(Asn1Tags.Constructed | Asn1Tags.Sequence, this._bOut.ToArray());
}
}
}
......@@ -33,21 +33,21 @@ namespace NBitcoin.BouncyCastle.Asn1
{
get
{
return _remaining;
return this._remaining;
}
}
public override int ReadByte()
{
if(_remaining == 0)
if(this._remaining == 0)
return -1;
int b = _in.ReadByte();
int b = this._in.ReadByte();
if(b < 0)
throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining);
throw new EndOfStreamException("DEF length " + this._originalLength + " object truncated by " + this._remaining);
if(--_remaining == 0)
if(--this._remaining == 0)
{
SetParentEofDetect(true);
}
......@@ -60,16 +60,16 @@ namespace NBitcoin.BouncyCastle.Asn1
int off,
int len)
{
if(_remaining == 0)
if(this._remaining == 0)
return 0;
int toRead = System.Math.Min(len, _remaining);
int numRead = _in.Read(buf, off, toRead);
int toRead = System.Math.Min(len, this._remaining);
int numRead = this._in.Read(buf, off, toRead);
if(numRead < 1)
throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining);
throw new EndOfStreamException("DEF length " + this._originalLength + " object truncated by " + this._remaining);
if((_remaining -= numRead) == 0)
if((this._remaining -= numRead) == 0)
{
SetParentEofDetect(true);
}
......@@ -79,22 +79,22 @@ namespace NBitcoin.BouncyCastle.Asn1
internal void ReadAllIntoByteArray(byte[] buf)
{
if(_remaining != buf.Length)
if(this._remaining != buf.Length)
throw new ArgumentException("buffer length not right for data");
if((_remaining -= Streams.ReadFully(_in, buf)) != 0)
throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining);
if((this._remaining -= Streams.ReadFully(this._in, buf)) != 0)
throw new EndOfStreamException("DEF length " + this._originalLength + " object truncated by " + this._remaining);
SetParentEofDetect(true);
}
internal byte[] ToArray()
{
if(_remaining == 0)
if(this._remaining == 0)
return EmptyBytes;
byte[] bytes = new byte[_remaining];
if((_remaining -= Streams.ReadFully(_in, bytes)) != 0)
throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining);
var bytes = new byte[this._remaining];
if((this._remaining -= Streams.ReadFully(this._in, bytes)) != 0)
throw new EndOfStreamException("DEF length " + this._originalLength + " object truncated by " + this._remaining);
SetParentEofDetect(true);
return bytes;
}
......
......@@ -28,7 +28,7 @@ namespace NBitcoin.BouncyCastle.Asn1
public DerInteger(
int value)
{
bytes = BigInteger.ValueOf(value).ToByteArray();
this.bytes = BigInteger.ValueOf(value).ToByteArray();
}
public DerInteger(
......@@ -37,7 +37,7 @@ namespace NBitcoin.BouncyCastle.Asn1
if(value == null)
throw new ArgumentNullException("value");
bytes = value.ToByteArray();
this.bytes = value.ToByteArray();
}
public DerInteger(
......@@ -50,7 +50,7 @@ namespace NBitcoin.BouncyCastle.Asn1
{
get
{
return new BigInteger(bytes);
return new BigInteger(this.bytes);
}
}
......@@ -62,25 +62,25 @@ namespace NBitcoin.BouncyCastle.Asn1
{
get
{
return new BigInteger(1, bytes);
return new BigInteger(1, this.bytes);
}
}
internal override void Encode(
DerOutputStream derOut)
{
derOut.WriteEncoded(Asn1Tags.Integer, bytes);
derOut.WriteEncoded(Asn1Tags.Integer, this.bytes);
}
protected override int Asn1GetHashCode()
{
return Arrays.GetHashCode(bytes);
return Arrays.GetHashCode(this.bytes);
}
protected override bool Asn1Equals(
Asn1Object asn1Object)
{
DerInteger other = asn1Object as DerInteger;
var other = asn1Object as DerInteger;
if(other == null)
return false;
......@@ -90,7 +90,7 @@ namespace NBitcoin.BouncyCastle.Asn1
public override string ToString()
{
return Value.ToString();
return this.Value.ToString();
}
}
}
......@@ -10,7 +10,7 @@ namespace NBitcoin.BouncyCastle.Asn1
{
public static readonly DerNull Instance = new DerNull(0);
byte[] zeroBytes = new byte[0];
private byte[] zeroBytes = new byte[0];
[Obsolete("Use static Instance object")]
public DerNull()
......@@ -24,7 +24,7 @@ namespace NBitcoin.BouncyCastle.Asn1
internal override void Encode(
DerOutputStream derOut)
{
derOut.WriteEncoded(Asn1Tags.Null, zeroBytes);
derOut.WriteEncoded(Asn1Tags.Null, this.zeroBytes);
}
protected override bool Asn1Equals(
......
......@@ -37,7 +37,7 @@ namespace NBitcoin.BouncyCastle.Asn1
{
get
{
return identifier;
return this.identifier;
}
}
......@@ -53,7 +53,7 @@ namespace NBitcoin.BouncyCastle.Asn1
*/
public virtual bool On(DerObjectIdentifier stem)
{
string id = Id, stemId = stem.Id;
string id = this.Id, stemId = stem.Id;
return id.Length > stemId.Length && id[stemId.Length] == '.' && Platform.StartsWith(id, stemId);
}
......@@ -67,7 +67,7 @@ namespace NBitcoin.BouncyCastle.Asn1
Stream outputStream,
long fieldValue)
{
byte[] result = new byte[9];
var result = new byte[9];
int pos = 8;
result[pos] = (byte)(fieldValue & 0x7f);
while(fieldValue >= (1L << 7))
......@@ -90,7 +90,7 @@ namespace NBitcoin.BouncyCastle.Asn1
else
{
BigInteger tmpValue = fieldValue;
byte[] tmp = new byte[byteCount];
var tmp = new byte[byteCount];
for(int i = byteCount - 1; i >= 0; i--)
{
tmp[i] = (byte)((tmpValue.IntValue & 0x7f) | 0x80);
......@@ -103,13 +103,13 @@ namespace NBitcoin.BouncyCastle.Asn1
protected override int Asn1GetHashCode()
{
return identifier.GetHashCode();
return this.identifier.GetHashCode();
}
protected override bool Asn1Equals(
Asn1Object asn1Object)
{
DerObjectIdentifier other = asn1Object as DerObjectIdentifier;
var other = asn1Object as DerObjectIdentifier;
if(other == null)
return false;
......@@ -119,7 +119,7 @@ namespace NBitcoin.BouncyCastle.Asn1
public override string ToString()
{
return identifier;
return this.identifier;
}
private static bool IsValidBranchID(
......@@ -171,7 +171,7 @@ namespace NBitcoin.BouncyCastle.Asn1
private static string MakeOidStringFromBytes(
byte[] bytes)
{
StringBuilder objId = new StringBuilder();
var objId = new StringBuilder();
long value = 0;
BigInteger bigValue = null;
bool first = true;
......
......@@ -13,7 +13,7 @@ namespace NBitcoin.BouncyCastle.Asn1
internal override void Encode(
DerOutputStream derOut)
{
derOut.WriteEncoded(Asn1Tags.OctetString, str);
derOut.WriteEncoded(Asn1Tags.OctetString, this.str);
}
internal static void Encode(
......
......@@ -86,7 +86,7 @@ namespace NBitcoin.BouncyCastle.Asn1
}
else
{
byte[] stack = new byte[5];
var stack = new byte[5];
int pos = stack.Length;
stack[--pos] = (byte)(tagNo & 0x7F);
......
......@@ -67,8 +67,8 @@ namespace NBitcoin.BouncyCastle.Asn1
DerOutputStream derOut)
{
// TODO Intermediate buffer could be avoided if we could calculate expected length
MemoryStream bOut = new MemoryStream();
DerOutputStream dOut = new DerOutputStream(bOut);
var bOut = new MemoryStream();
var dOut = new DerOutputStream(bOut);
foreach(Asn1Encodable obj in this)
{
......
......@@ -20,7 +20,7 @@ namespace NBitcoin.BouncyCastle.Asn1
internal virtual int GetRemaining()
{
// TODO: maybe one day this can become more accurate
return _limit;
return this._limit;
}
protected virtual void SetParentEofDetect(bool on)
......
......@@ -57,21 +57,21 @@ namespace NBitcoin.BouncyCastle.Asn1.X9
this.fieldIdentifier = fieldID.Identifier;
if(fieldIdentifier.Equals(X9ObjectIdentifiers.PrimeField))
if(this.fieldIdentifier.Equals(X9ObjectIdentifiers.PrimeField))
{
BigInteger q = ((DerInteger)fieldID.Parameters).Value;
X9FieldElement x9A = new X9FieldElement(q, (Asn1OctetString)seq[0]);
X9FieldElement x9B = new X9FieldElement(q, (Asn1OctetString)seq[1]);
curve = new FpCurve(q, x9A.Value.ToBigInteger(), x9B.Value.ToBigInteger());
var x9A = new X9FieldElement(q, (Asn1OctetString)seq[0]);
var x9B = new X9FieldElement(q, (Asn1OctetString)seq[1]);
this.curve = new FpCurve(q, x9A.Value.ToBigInteger(), x9B.Value.ToBigInteger());
}
else
{
if(fieldIdentifier.Equals(X9ObjectIdentifiers.CharacteristicTwoField))
if(this.fieldIdentifier.Equals(X9ObjectIdentifiers.CharacteristicTwoField))
{
// Characteristic two field
DerSequence parameters = (DerSequence)fieldID.Parameters;
var parameters = (DerSequence)fieldID.Parameters;
int m = ((DerInteger)parameters[0]).Value.IntValue;
DerObjectIdentifier representation
var representation
= (DerObjectIdentifier)parameters[1];
int k1 = 0;
......@@ -85,15 +85,15 @@ namespace NBitcoin.BouncyCastle.Asn1.X9
else
{
// Pentanomial basis representation
DerSequence pentanomial = (DerSequence)parameters[2];
var pentanomial = (DerSequence)parameters[2];
k1 = ((DerInteger)pentanomial[0]).Value.IntValue;
k2 = ((DerInteger)pentanomial[1]).Value.IntValue;
k3 = ((DerInteger)pentanomial[2]).Value.IntValue;
}
X9FieldElement x9A = new X9FieldElement(m, k1, k2, k3, (Asn1OctetString)seq[0]);
X9FieldElement x9B = new X9FieldElement(m, k1, k2, k3, (Asn1OctetString)seq[1]);
var x9A = new X9FieldElement(m, k1, k2, k3, (Asn1OctetString)seq[0]);
var x9B = new X9FieldElement(m, k1, k2, k3, (Asn1OctetString)seq[1]);
// TODO Is it possible to get the order (n) and cofactor(h) too?
curve = new F2mCurve(m, k1, k2, k3, x9A.Value.ToBigInteger(), x9B.Value.ToBigInteger());
this.curve = new F2mCurve(m, k1, k2, k3, x9A.Value.ToBigInteger(), x9B.Value.ToBigInteger());
}
}
}
......@@ -102,13 +102,13 @@ namespace NBitcoin.BouncyCastle.Asn1.X9
{
get
{
return curve;
return this.curve;
}
}
public byte[] GetSeed()
{
return Arrays.Clone(seed);
return Arrays.Clone(this.seed);
}
/**
......@@ -123,13 +123,13 @@ namespace NBitcoin.BouncyCastle.Asn1.X9
*/
public override Asn1Object ToAsn1Object()
{
Asn1EncodableVector v = new Asn1EncodableVector();
var v = new Asn1EncodableVector();
if(fieldIdentifier.Equals(X9ObjectIdentifiers.PrimeField)
|| fieldIdentifier.Equals(X9ObjectIdentifiers.CharacteristicTwoField))
if(this.fieldIdentifier.Equals(X9ObjectIdentifiers.PrimeField)
|| this.fieldIdentifier.Equals(X9ObjectIdentifiers.CharacteristicTwoField))
{
v.Add(new X9FieldElement(curve.A).ToAsn1Object());
v.Add(new X9FieldElement(curve.B).ToAsn1Object());
v.Add(new X9FieldElement(this.curve.A).ToAsn1Object());
v.Add(new X9FieldElement(this.curve.B).ToAsn1Object());
}
return new DerSequence(v);
......
......@@ -74,7 +74,7 @@ namespace NBitcoin.BouncyCastle.Asn1.X9
}
else if(ECAlgorithms.IsF2mCurve(curve))
{
IPolynomialExtensionField field = (IPolynomialExtensionField)curve.Field;
var field = (IPolynomialExtensionField)curve.Field;
int[] exponents = field.MinimalPolynomial.GetExponentsPresent();
if(exponents.Length == 3)
{
......@@ -99,7 +99,7 @@ namespace NBitcoin.BouncyCastle.Asn1.X9
{
get
{
return curve;
return this.curve;
}
}
......@@ -107,7 +107,7 @@ namespace NBitcoin.BouncyCastle.Asn1.X9
{
get
{
return g.Point;
return this.g.Point;
}
}
......@@ -115,7 +115,7 @@ namespace NBitcoin.BouncyCastle.Asn1.X9
{
get
{
return n;
return this.n;
}
}
......@@ -123,13 +123,13 @@ namespace NBitcoin.BouncyCastle.Asn1.X9
{
get
{
return h;
return this.h;
}
}
public byte[] GetSeed()
{
return seed;
return this.seed;
}
/**
......@@ -141,7 +141,7 @@ namespace NBitcoin.BouncyCastle.Asn1.X9
{
get
{
return new X9Curve(curve, seed);
return new X9Curve(this.curve, this.seed);
}
}
......@@ -154,7 +154,7 @@ namespace NBitcoin.BouncyCastle.Asn1.X9
{
get
{
return fieldID;
return this.fieldID;
}
}
......@@ -167,7 +167,7 @@ namespace NBitcoin.BouncyCastle.Asn1.X9
{
get
{
return g;
return this.g;
}
}
......@@ -186,16 +186,14 @@ namespace NBitcoin.BouncyCastle.Asn1.X9
*/
public override Asn1Object ToAsn1Object()
{
Asn1EncodableVector v = new Asn1EncodableVector(
new DerInteger(BigInteger.One),
fieldID,
new X9Curve(curve, seed),
g,
new DerInteger(n));
if(h != null)
var v = new Asn1EncodableVector(
new DerInteger(BigInteger.One), this.fieldID,
new X9Curve(this.curve, this.seed), this.g,
new DerInteger(this.n));
if(this.h != null)
{
v.Add(new DerInteger(h));
v.Add(new DerInteger(this.h));
}
return new DerSequence(v);
......
......@@ -10,12 +10,12 @@ namespace NBitcoin.BouncyCastle.Asn1.X9
{
lock(this)
{
if(parameters == null)
if(this.parameters == null)
{
parameters = CreateParameters();
this.parameters = CreateParameters();
}
return parameters;
return this.parameters;
}
}
}
......
......@@ -38,19 +38,19 @@ namespace NBitcoin.BouncyCastle.Asn1.X9
public byte[] GetPointEncoding()
{
return Arrays.Clone(encoding.GetOctets());
return Arrays.Clone(this.encoding.GetOctets());
}
public ECPoint Point
{
get
{
if(p == null)
if(this.p == null)
{
p = c.DecodePoint(encoding.GetOctets()).Normalize();
this.p = this.c.DecodePoint(this.encoding.GetOctets()).Normalize();
}
return p;
return this.p;
}
}
......@@ -58,7 +58,7 @@ namespace NBitcoin.BouncyCastle.Asn1.X9
{
get
{
byte[] octets = encoding.GetOctets();
byte[] octets = this.encoding.GetOctets();
return octets != null && octets.Length > 0 && (octets[0] == 2 || octets[0] == 3);
}
}
......@@ -73,7 +73,7 @@ namespace NBitcoin.BouncyCastle.Asn1.X9
*/
public override Asn1Object ToAsn1Object()
{
return encoding;
return this.encoding;
}
}
}
......@@ -40,7 +40,7 @@ namespace NBitcoin.BouncyCastle.Asn1.X9
{
get
{
return f;
return this.f;
}
}
......@@ -63,8 +63,8 @@ namespace NBitcoin.BouncyCastle.Asn1.X9
*/
public override Asn1Object ToAsn1Object()
{
int byteCount = X9IntegerConverter.GetByteLength(f);
byte[] paddedBigInteger = X9IntegerConverter.IntegerToBytes(f.ToBigInteger(), byteCount);
int byteCount = X9IntegerConverter.GetByteLength(this.f);
byte[] paddedBigInteger = X9IntegerConverter.IntegerToBytes(this.f.ToBigInteger(), byteCount);
return new DerOctetString(paddedBigInteger);
}
......
......@@ -62,7 +62,7 @@ namespace NBitcoin.BouncyCastle.Asn1.X9
{
this.id = X9ObjectIdentifiers.CharacteristicTwoField;
Asn1EncodableVector fieldIdParams = new Asn1EncodableVector(new DerInteger(m));
var fieldIdParams = new Asn1EncodableVector(new DerInteger(m));
if(k2 == 0)
{
......@@ -93,7 +93,7 @@ namespace NBitcoin.BouncyCastle.Asn1.X9
{
get
{
return id;
return this.id;
}
}
......@@ -101,7 +101,7 @@ namespace NBitcoin.BouncyCastle.Asn1.X9
{
get
{
return parameters;
return this.parameters;
}
}
......@@ -116,7 +116,7 @@ namespace NBitcoin.BouncyCastle.Asn1.X9
*/
public override Asn1Object ToAsn1Object()
{
return new DerSequence(id, parameters);
return new DerSequence(this.id, this.parameters);
}
}
}
......@@ -22,13 +22,13 @@ namespace NBitcoin.BouncyCastle.Asn1.X9
if(qLength < bytes.Length)
{
byte[] tmp = new byte[qLength];
var tmp = new byte[qLength];
Array.Copy(bytes, bytes.Length - tmp.Length, tmp, 0, tmp.Length);
return tmp;
}
else if(qLength > bytes.Length)
{
byte[] tmp = new byte[qLength];
var tmp = new byte[qLength];
Array.Copy(bytes, 0, tmp, tmp.Length - bytes.Length, bytes.Length);
return tmp;
}
......
......@@ -15,14 +15,14 @@ namespace NBitcoin.BouncyCastle.Crypto
{
get
{
return privateKey;
return this.privateKey;
}
}
public override bool Equals(
object obj)
{
AsymmetricKeyParameter other = obj as AsymmetricKeyParameter;
var other = obj as AsymmetricKeyParameter;
if(other == null)
{
......@@ -35,12 +35,12 @@ namespace NBitcoin.BouncyCastle.Crypto
protected bool Equals(
AsymmetricKeyParameter other)
{
return privateKey == other.privateKey;
return this.privateKey == other.privateKey;
}
public override int GetHashCode()
{
return privateKey.GetHashCode();
return this.privateKey.GetHashCode();
}
}
}
......@@ -39,15 +39,15 @@ namespace NBitcoin.BouncyCastle.Crypto
throw new ArgumentNullException("cipher");
this.cipher = cipher;
buf = new byte[cipher.GetBlockSize()];
bufOff = 0;
this.buf = new byte[cipher.GetBlockSize()];
this.bufOff = 0;
}
public override string AlgorithmName
{
get
{
return cipher.AlgorithmName;
return this.cipher.AlgorithmName;
}
}
......@@ -69,7 +69,7 @@ namespace NBitcoin.BouncyCastle.Crypto
Reset();
cipher.Init(forEncryption, parameters);
this.cipher.Init(forEncryption, parameters);
}
/**
......@@ -79,7 +79,7 @@ namespace NBitcoin.BouncyCastle.Crypto
*/
public override int GetBlockSize()
{
return cipher.GetBlockSize();
return this.cipher.GetBlockSize();
}
/**
......@@ -93,8 +93,8 @@ namespace NBitcoin.BouncyCastle.Crypto
public override int GetUpdateOutputSize(
int length)
{
int total = length + bufOff;
int leftOver = total % buf.Length;
int total = length + this.bufOff;
int leftOver = total % this.buf.Length;
return total - leftOver;
}
......@@ -110,7 +110,7 @@ namespace NBitcoin.BouncyCastle.Crypto
int length)
{
// Note: Can assume IsPartialBlockOkay is true for purposes of this calculation
return length + bufOff;
return length + this.bufOff;
}
/**
......@@ -128,15 +128,15 @@ namespace NBitcoin.BouncyCastle.Crypto
byte[] output,
int outOff)
{
buf[bufOff++] = input;
this.buf[this.bufOff++] = input;
if(bufOff == buf.Length)
if(this.bufOff == this.buf.Length)
{
if((outOff + buf.Length) > output.Length)
if((outOff + this.buf.Length) > output.Length)
throw new DataLengthException("output buffer too short");
bufOff = 0;
return cipher.ProcessBlock(buf, 0, output, outOff);
this.bufOff = 0;
return this.cipher.ProcessBlock(this.buf, 0, output, outOff);
}
return 0;
......@@ -153,7 +153,7 @@ namespace NBitcoin.BouncyCastle.Crypto
if(outLength > 0 && pos < outLength)
{
byte[] tmp = new byte[pos];
var tmp = new byte[pos];
Array.Copy(outBytes, 0, tmp, 0, pos);
outBytes = tmp;
}
......@@ -179,7 +179,7 @@ namespace NBitcoin.BouncyCastle.Crypto
if(outLength > 0 && pos < outLength)
{
byte[] tmp = new byte[pos];
var tmp = new byte[pos];
Array.Copy(outBytes, 0, tmp, 0, pos);
outBytes = tmp;
}
......@@ -223,27 +223,27 @@ namespace NBitcoin.BouncyCastle.Crypto
}
int resultLen = 0;
int gapLen = buf.Length - bufOff;
int gapLen = this.buf.Length - this.bufOff;
if(length > gapLen)
{
Array.Copy(input, inOff, buf, bufOff, gapLen);
resultLen += cipher.ProcessBlock(buf, 0, output, outOff);
bufOff = 0;
Array.Copy(input, inOff, this.buf, this.bufOff, gapLen);
resultLen += this.cipher.ProcessBlock(this.buf, 0, output, outOff);
this.bufOff = 0;
length -= gapLen;
inOff += gapLen;
while(length > buf.Length)
while(length > this.buf.Length)
{
resultLen += cipher.ProcessBlock(input, inOff, output, outOff + resultLen);
resultLen += this.cipher.ProcessBlock(input, inOff, output, outOff + resultLen);
length -= blockSize;
inOff += blockSize;
}
}
Array.Copy(input, inOff, buf, bufOff, length);
bufOff += length;
if(bufOff == buf.Length)
Array.Copy(input, inOff, this.buf, this.bufOff, length);
this.bufOff += length;
if(this.bufOff == this.buf.Length)
{
resultLen += cipher.ProcessBlock(buf, 0, output, outOff + resultLen);
bufOff = 0;
resultLen += this.cipher.ProcessBlock(this.buf, 0, output, outOff + resultLen);
this.bufOff = 0;
}
return resultLen;
}
......@@ -260,7 +260,7 @@ namespace NBitcoin.BouncyCastle.Crypto
int pos = DoFinal(outBytes, 0);
if(pos < outBytes.Length)
{
byte[] tmp = new byte[pos];
var tmp = new byte[pos];
Array.Copy(outBytes, 0, tmp, 0, pos);
outBytes = tmp;
}
......@@ -297,7 +297,7 @@ namespace NBitcoin.BouncyCastle.Crypto
if(pos < outBytes.Length)
{
byte[] tmp = new byte[pos];
var tmp = new byte[pos];
Array.Copy(outBytes, 0, tmp, 0, pos);
outBytes = tmp;
}
......@@ -330,17 +330,17 @@ namespace NBitcoin.BouncyCastle.Crypto
{
try
{
if(bufOff != 0)
if(this.bufOff != 0)
{
Check.DataLength(!cipher.IsPartialBlockOkay, "data not block size aligned");
Check.OutputLength(output, outOff, bufOff, "output buffer too short for DoFinal()");
Check.DataLength(!this.cipher.IsPartialBlockOkay, "data not block size aligned");
Check.OutputLength(output, outOff, this.bufOff, "output buffer too short for DoFinal()");
// NB: Can't copy directly, or we may write too much output
cipher.ProcessBlock(buf, 0, buf, 0);
Array.Copy(buf, 0, output, outOff, bufOff);
this.cipher.ProcessBlock(this.buf, 0, this.buf, 0);
Array.Copy(this.buf, 0, output, outOff, this.bufOff);
}
return bufOff;
return this.bufOff;
}
finally
{
......@@ -354,10 +354,10 @@ namespace NBitcoin.BouncyCastle.Crypto
*/
public override void Reset()
{
Array.Clear(buf, 0, buf.Length);
bufOff = 0;
Array.Clear(this.buf, 0, this.buf.Length);
this.bufOff = 0;
cipher.Reset();
this.cipher.Reset();
}
}
}
......@@ -19,34 +19,34 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
internal GeneralDigest()
{
xBuf = new byte[4];
this.xBuf = new byte[4];
}
internal GeneralDigest(GeneralDigest t)
{
xBuf = new byte[t.xBuf.Length];
this.xBuf = new byte[t.xBuf.Length];
CopyIn(t);
}
protected void CopyIn(GeneralDigest t)
{
Array.Copy(t.xBuf, 0, xBuf, 0, t.xBuf.Length);
Array.Copy(t.xBuf, 0, this.xBuf, 0, t.xBuf.Length);
xBufOff = t.xBufOff;
byteCount = t.byteCount;
this.xBufOff = t.xBufOff;
this.byteCount = t.byteCount;
}
public void Update(byte input)
{
xBuf[xBufOff++] = input;
this.xBuf[this.xBufOff++] = input;
if(xBufOff == xBuf.Length)
if(this.xBufOff == this.xBuf.Length)
{
ProcessWord(xBuf, 0);
xBufOff = 0;
ProcessWord(this.xBuf, 0);
this.xBufOff = 0;
}
byteCount++;
this.byteCount++;
}
public void BlockUpdate(
......@@ -60,15 +60,15 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
// fill the current word
//
int i = 0;
if(xBufOff != 0)
if(this.xBufOff != 0)
{
while(i < length)
{
xBuf[xBufOff++] = input[inOff + i++];
if(xBufOff == 4)
this.xBuf[this.xBufOff++] = input[inOff + i++];
if(this.xBufOff == 4)
{
ProcessWord(xBuf, 0);
xBufOff = 0;
ProcessWord(this.xBuf, 0);
this.xBufOff = 0;
break;
}
}
......@@ -88,22 +88,22 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
//
while(i < length)
{
xBuf[xBufOff++] = input[inOff + i++];
this.xBuf[this.xBufOff++] = input[inOff + i++];
}
byteCount += length;
this.byteCount += length;
}
public void Finish()
{
long bitLength = (byteCount << 3);
long bitLength = (this.byteCount << 3);
//
// add the pad bytes.
//
Update((byte)128);
while(xBufOff != 0)
while(this.xBufOff != 0)
Update((byte)0);
ProcessLength(bitLength);
ProcessBlock();
......@@ -111,9 +111,9 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
public virtual void Reset()
{
byteCount = 0;
xBufOff = 0;
Array.Clear(xBuf, 0, xBuf.Length);
this.byteCount = 0;
this.xBufOff = 0;
Array.Clear(this.xBuf, 0, this.xBuf.Length);
}
public int GetByteLength()
......
......@@ -28,7 +28,7 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
*/
internal LongDigest()
{
xBuf = new byte[8];
this.xBuf = new byte[8];
Reset();
}
......@@ -41,44 +41,44 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
internal LongDigest(
LongDigest t)
{
xBuf = new byte[t.xBuf.Length];
this.xBuf = new byte[t.xBuf.Length];
CopyIn(t);
}
protected void CopyIn(LongDigest t)
{
Array.Copy(t.xBuf, 0, xBuf, 0, t.xBuf.Length);
xBufOff = t.xBufOff;
byteCount1 = t.byteCount1;
byteCount2 = t.byteCount2;
H1 = t.H1;
H2 = t.H2;
H3 = t.H3;
H4 = t.H4;
H5 = t.H5;
H6 = t.H6;
H7 = t.H7;
H8 = t.H8;
Array.Copy(t.W, 0, W, 0, t.W.Length);
wOff = t.wOff;
Array.Copy(t.xBuf, 0, this.xBuf, 0, t.xBuf.Length);
this.xBufOff = t.xBufOff;
this.byteCount1 = t.byteCount1;
this.byteCount2 = t.byteCount2;
this.H1 = t.H1;
this.H2 = t.H2;
this.H3 = t.H3;
this.H4 = t.H4;
this.H5 = t.H5;
this.H6 = t.H6;
this.H7 = t.H7;
this.H8 = t.H8;
Array.Copy(t.W, 0, this.W, 0, t.W.Length);
this.wOff = t.wOff;
}
public void Update(
byte input)
{
xBuf[xBufOff++] = input;
this.xBuf[this.xBufOff++] = input;
if(xBufOff == xBuf.Length)
if(this.xBufOff == this.xBuf.Length)
{
ProcessWord(xBuf, 0);
xBufOff = 0;
ProcessWord(this.xBuf, 0);
this.xBufOff = 0;
}
byteCount1++;
this.byteCount1++;
}
public void BlockUpdate(
......@@ -89,7 +89,7 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
//
// fill the current word
//
while((xBufOff != 0) && (length > 0))
while((this.xBufOff != 0) && (length > 0))
{
Update(input[inOff]);
......@@ -100,13 +100,13 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
//
// process whole words.
//
while(length > xBuf.Length)
while(length > this.xBuf.Length)
{
ProcessWord(input, inOff);
inOff += xBuf.Length;
length -= xBuf.Length;
byteCount1 += xBuf.Length;
inOff += this.xBuf.Length;
length -= this.xBuf.Length;
this.byteCount1 += this.xBuf.Length;
}
//
......@@ -125,15 +125,15 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
{
AdjustByteCounts();
long lowBitLength = byteCount1 << 3;
long hiBitLength = byteCount2;
long lowBitLength = this.byteCount1 << 3;
long hiBitLength = this.byteCount2;
//
// add the pad bytes.
//
Update((byte)128);
while(xBufOff != 0)
while(this.xBufOff != 0)
{
Update((byte)0);
}
......@@ -145,26 +145,26 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
public virtual void Reset()
{
byteCount1 = 0;
byteCount2 = 0;
this.byteCount1 = 0;
this.byteCount2 = 0;
xBufOff = 0;
for(int i = 0; i < xBuf.Length; i++)
this.xBufOff = 0;
for(int i = 0; i < this.xBuf.Length; i++)
{
xBuf[i] = 0;
this.xBuf[i] = 0;
}
wOff = 0;
Array.Clear(W, 0, W.Length);
this.wOff = 0;
Array.Clear(this.W, 0, this.W.Length);
}
internal void ProcessWord(
byte[] input,
int inOff)
{
W[wOff] = Pack.BE_To_UInt64(input, inOff);
this.W[this.wOff] = Pack.BE_To_UInt64(input, inOff);
if(++wOff == 16)
if(++this.wOff == 16)
{
ProcessBlock();
}
......@@ -176,10 +176,10 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
*/
private void AdjustByteCounts()
{
if(byteCount1 > 0x1fffffffffffffffL)
if(this.byteCount1 > 0x1fffffffffffffffL)
{
byteCount2 += (long)((ulong)byteCount1 >> 61);
byteCount1 &= 0x1fffffffffffffffL;
this.byteCount2 += (long)((ulong) this.byteCount1 >> 61);
this.byteCount1 &= 0x1fffffffffffffffL;
}
}
......@@ -187,13 +187,13 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
long lowW,
long hiW)
{
if(wOff > 14)
if(this.wOff > 14)
{
ProcessBlock();
}
W[14] = (ulong)hiW;
W[15] = (ulong)lowW;
this.W[14] = (ulong)hiW;
this.W[15] = (ulong)lowW;
}
internal void ProcessBlock()
......@@ -205,79 +205,79 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
//
for(int ti = 16; ti <= 79; ++ti)
{
W[ti] = Sigma1(W[ti - 2]) + W[ti - 7] + Sigma0(W[ti - 15]) + W[ti - 16];
this.W[ti] = Sigma1(this.W[ti - 2]) + this.W[ti - 7] + Sigma0(this.W[ti - 15]) + this.W[ti - 16];
}
//
// set up working variables.
//
ulong a = H1;
ulong b = H2;
ulong c = H3;
ulong d = H4;
ulong e = H5;
ulong f = H6;
ulong g = H7;
ulong h = H8;
ulong a = this.H1;
ulong b = this.H2;
ulong c = this.H3;
ulong d = this.H4;
ulong e = this.H5;
ulong f = this.H6;
ulong g = this.H7;
ulong h = this.H8;
int t = 0;
for(int i = 0; i < 10; i++)
{
// t = 8 * i
h += Sum1(e) + Ch(e, f, g) + K[t] + W[t++];
h += Sum1(e) + Ch(e, f, g) + K[t] + this.W[t++];
d += h;
h += Sum0(a) + Maj(a, b, c);
// t = 8 * i + 1
g += Sum1(d) + Ch(d, e, f) + K[t] + W[t++];
g += Sum1(d) + Ch(d, e, f) + K[t] + this.W[t++];
c += g;
g += Sum0(h) + Maj(h, a, b);
// t = 8 * i + 2
f += Sum1(c) + Ch(c, d, e) + K[t] + W[t++];
f += Sum1(c) + Ch(c, d, e) + K[t] + this.W[t++];
b += f;
f += Sum0(g) + Maj(g, h, a);
// t = 8 * i + 3
e += Sum1(b) + Ch(b, c, d) + K[t] + W[t++];
e += Sum1(b) + Ch(b, c, d) + K[t] + this.W[t++];
a += e;
e += Sum0(f) + Maj(f, g, h);
// t = 8 * i + 4
d += Sum1(a) + Ch(a, b, c) + K[t] + W[t++];
d += Sum1(a) + Ch(a, b, c) + K[t] + this.W[t++];
h += d;
d += Sum0(e) + Maj(e, f, g);
// t = 8 * i + 5
c += Sum1(h) + Ch(h, a, b) + K[t] + W[t++];
c += Sum1(h) + Ch(h, a, b) + K[t] + this.W[t++];
g += c;
c += Sum0(d) + Maj(d, e, f);
// t = 8 * i + 6
b += Sum1(g) + Ch(g, h, a) + K[t] + W[t++];
b += Sum1(g) + Ch(g, h, a) + K[t] + this.W[t++];
f += b;
b += Sum0(c) + Maj(c, d, e);
// t = 8 * i + 7
a += Sum1(f) + Ch(f, g, h) + K[t] + W[t++];
a += Sum1(f) + Ch(f, g, h) + K[t] + this.W[t++];
e += a;
a += Sum0(b) + Maj(b, c, d);
}
H1 += a;
H2 += b;
H3 += c;
H4 += d;
H5 += e;
H6 += f;
H7 += g;
H8 += h;
this.H1 += a;
this.H2 += b;
this.H3 += c;
this.H4 += d;
this.H5 += e;
this.H6 += f;
this.H7 += g;
this.H8 += h;
//
// reset the offset and clean out the word buffer.
//
wOff = 0;
Array.Clear(W, 0, 16);
this.wOff = 0;
Array.Clear(this.W, 0, 16);
}
/* SHA-384 and SHA-512 functions (as for SHA-256 but for longs) */
......@@ -341,7 +341,7 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
public int GetByteLength()
{
return MyByteLength;
return this.MyByteLength;
}
public abstract string AlgorithmName
......
......@@ -40,14 +40,14 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
{
base.CopyIn(t);
H1 = t.H1;
H2 = t.H2;
H3 = t.H3;
H4 = t.H4;
H5 = t.H5;
Array.Copy(t.X, 0, X, 0, t.X.Length);
xOff = t.xOff;
this.H1 = t.H1;
this.H2 = t.H2;
this.H3 = t.H3;
this.H4 = t.H4;
this.H5 = t.H5;
Array.Copy(t.X, 0, this.X, 0, t.X.Length);
this.xOff = t.xOff;
}
public override string AlgorithmName
......@@ -67,9 +67,9 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
byte[] input,
int inOff)
{
X[xOff] = Pack.BE_To_UInt32(input, inOff);
this.X[this.xOff] = Pack.BE_To_UInt32(input, inOff);
if(++xOff == 16)
if(++this.xOff == 16)
{
ProcessBlock();
}
......@@ -77,13 +77,13 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
internal override void ProcessLength(long bitLength)
{
if(xOff > 14)
if(this.xOff > 14)
{
ProcessBlock();
}
X[14] = (uint)((ulong)bitLength >> 32);
X[15] = (uint)((ulong)bitLength);
this.X[14] = (uint)((ulong)bitLength >> 32);
this.X[15] = (uint)((ulong)bitLength);
}
public override int DoFinal(
......@@ -92,11 +92,11 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
{
Finish();
Pack.UInt32_To_BE(H1, output, outOff);
Pack.UInt32_To_BE(H2, output, outOff + 4);
Pack.UInt32_To_BE(H3, output, outOff + 8);
Pack.UInt32_To_BE(H4, output, outOff + 12);
Pack.UInt32_To_BE(H5, output, outOff + 16);
Pack.UInt32_To_BE(this.H1, output, outOff);
Pack.UInt32_To_BE(this.H2, output, outOff + 4);
Pack.UInt32_To_BE(this.H3, output, outOff + 8);
Pack.UInt32_To_BE(this.H4, output, outOff + 12);
Pack.UInt32_To_BE(this.H5, output, outOff + 16);
Reset();
......@@ -110,14 +110,14 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
{
base.Reset();
H1 = 0x67452301;
H2 = 0xefcdab89;
H3 = 0x98badcfe;
H4 = 0x10325476;
H5 = 0xc3d2e1f0;
this.H1 = 0x67452301;
this.H2 = 0xefcdab89;
this.H3 = 0x98badcfe;
this.H4 = 0x10325476;
this.H5 = 0xc3d2e1f0;
xOff = 0;
Array.Clear(X, 0, X.Length);
this.xOff = 0;
Array.Clear(this.X, 0, this.X.Length);
}
//
......@@ -150,18 +150,18 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
//
for(int i = 16; i < 80; i++)
{
uint t = X[i - 3] ^ X[i - 8] ^ X[i - 14] ^ X[i - 16];
X[i] = t << 1 | t >> 31;
uint t = this.X[i - 3] ^ this.X[i - 8] ^ this.X[i - 14] ^ this.X[i - 16];
this.X[i] = t << 1 | t >> 31;
}
//
// set up working variables.
//
uint A = H1;
uint B = H2;
uint C = H3;
uint D = H4;
uint E = H5;
uint A = this.H1;
uint B = this.H2;
uint C = this.H3;
uint D = this.H4;
uint E = this.H5;
//
// round 1
......@@ -172,19 +172,19 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
{
// E = rotateLeft(A, 5) + F(B, C, D) + E + X[idx++] + Y1
// B = rotateLeft(B, 30)
E += (A << 5 | (A >> 27)) + F(B, C, D) + X[idx++] + Y1;
E += (A << 5 | (A >> 27)) + F(B, C, D) + this.X[idx++] + Y1;
B = B << 30 | (B >> 2);
D += (E << 5 | (E >> 27)) + F(A, B, C) + X[idx++] + Y1;
D += (E << 5 | (E >> 27)) + F(A, B, C) + this.X[idx++] + Y1;
A = A << 30 | (A >> 2);
C += (D << 5 | (D >> 27)) + F(E, A, B) + X[idx++] + Y1;
C += (D << 5 | (D >> 27)) + F(E, A, B) + this.X[idx++] + Y1;
E = E << 30 | (E >> 2);
B += (C << 5 | (C >> 27)) + F(D, E, A) + X[idx++] + Y1;
B += (C << 5 | (C >> 27)) + F(D, E, A) + this.X[idx++] + Y1;
D = D << 30 | (D >> 2);
A += (B << 5 | (B >> 27)) + F(C, D, E) + X[idx++] + Y1;
A += (B << 5 | (B >> 27)) + F(C, D, E) + this.X[idx++] + Y1;
C = C << 30 | (C >> 2);
}
......@@ -195,19 +195,19 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
{
// E = rotateLeft(A, 5) + H(B, C, D) + E + X[idx++] + Y2
// B = rotateLeft(B, 30)
E += (A << 5 | (A >> 27)) + H(B, C, D) + X[idx++] + Y2;
E += (A << 5 | (A >> 27)) + H(B, C, D) + this.X[idx++] + Y2;
B = B << 30 | (B >> 2);
D += (E << 5 | (E >> 27)) + H(A, B, C) + X[idx++] + Y2;
D += (E << 5 | (E >> 27)) + H(A, B, C) + this.X[idx++] + Y2;
A = A << 30 | (A >> 2);
C += (D << 5 | (D >> 27)) + H(E, A, B) + X[idx++] + Y2;
C += (D << 5 | (D >> 27)) + H(E, A, B) + this.X[idx++] + Y2;
E = E << 30 | (E >> 2);
B += (C << 5 | (C >> 27)) + H(D, E, A) + X[idx++] + Y2;
B += (C << 5 | (C >> 27)) + H(D, E, A) + this.X[idx++] + Y2;
D = D << 30 | (D >> 2);
A += (B << 5 | (B >> 27)) + H(C, D, E) + X[idx++] + Y2;
A += (B << 5 | (B >> 27)) + H(C, D, E) + this.X[idx++] + Y2;
C = C << 30 | (C >> 2);
}
......@@ -218,19 +218,19 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
{
// E = rotateLeft(A, 5) + G(B, C, D) + E + X[idx++] + Y3
// B = rotateLeft(B, 30)
E += (A << 5 | (A >> 27)) + G(B, C, D) + X[idx++] + Y3;
E += (A << 5 | (A >> 27)) + G(B, C, D) + this.X[idx++] + Y3;
B = B << 30 | (B >> 2);
D += (E << 5 | (E >> 27)) + G(A, B, C) + X[idx++] + Y3;
D += (E << 5 | (E >> 27)) + G(A, B, C) + this.X[idx++] + Y3;
A = A << 30 | (A >> 2);
C += (D << 5 | (D >> 27)) + G(E, A, B) + X[idx++] + Y3;
C += (D << 5 | (D >> 27)) + G(E, A, B) + this.X[idx++] + Y3;
E = E << 30 | (E >> 2);
B += (C << 5 | (C >> 27)) + G(D, E, A) + X[idx++] + Y3;
B += (C << 5 | (C >> 27)) + G(D, E, A) + this.X[idx++] + Y3;
D = D << 30 | (D >> 2);
A += (B << 5 | (B >> 27)) + G(C, D, E) + X[idx++] + Y3;
A += (B << 5 | (B >> 27)) + G(C, D, E) + this.X[idx++] + Y3;
C = C << 30 | (C >> 2);
}
......@@ -241,33 +241,33 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
{
// E = rotateLeft(A, 5) + H(B, C, D) + E + X[idx++] + Y4
// B = rotateLeft(B, 30)
E += (A << 5 | (A >> 27)) + H(B, C, D) + X[idx++] + Y4;
E += (A << 5 | (A >> 27)) + H(B, C, D) + this.X[idx++] + Y4;
B = B << 30 | (B >> 2);
D += (E << 5 | (E >> 27)) + H(A, B, C) + X[idx++] + Y4;
D += (E << 5 | (E >> 27)) + H(A, B, C) + this.X[idx++] + Y4;
A = A << 30 | (A >> 2);
C += (D << 5 | (D >> 27)) + H(E, A, B) + X[idx++] + Y4;
C += (D << 5 | (D >> 27)) + H(E, A, B) + this.X[idx++] + Y4;
E = E << 30 | (E >> 2);
B += (C << 5 | (C >> 27)) + H(D, E, A) + X[idx++] + Y4;
B += (C << 5 | (C >> 27)) + H(D, E, A) + this.X[idx++] + Y4;
D = D << 30 | (D >> 2);
A += (B << 5 | (B >> 27)) + H(C, D, E) + X[idx++] + Y4;
A += (B << 5 | (B >> 27)) + H(C, D, E) + this.X[idx++] + Y4;
C = C << 30 | (C >> 2);
}
H1 += A;
H2 += B;
H3 += C;
H4 += D;
H5 += E;
this.H1 += A;
this.H2 += B;
this.H3 += C;
this.H4 += D;
this.H5 += E;
//
// reset start of the buffer.
//
xOff = 0;
Array.Clear(X, 0, 16);
this.xOff = 0;
Array.Clear(this.X, 0, 16);
}
public override IMemoable Copy()
......@@ -277,7 +277,7 @@ namespace NBitcoin.BouncyCastle.Crypto.Digests
public override void Reset(IMemoable other)
{
Sha1Digest d = (Sha1Digest)other;
var d = (Sha1Digest)other;
CopyIn(d);
}
......
......@@ -41,7 +41,7 @@ namespace NBitcoin.BouncyCastle.Crypto.EC
protected override X9ECParameters CreateParameters()
{
byte[] S = null;
GlvTypeBParameters glv = new GlvTypeBParameters(
var glv = new GlvTypeBParameters(
new BigInteger("7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee", 16),
new BigInteger("5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72", 16),
new BigInteger[]{
......@@ -54,7 +54,7 @@ namespace NBitcoin.BouncyCastle.Crypto.EC
new BigInteger("e4437ed6010e88286f547fa90abfe4c42212", 16),
272);
ECCurve curve = ConfigureCurveGlv(new SecP256K1Curve(), glv);
X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04"
var G = new X9ECPoint(curve, Hex.Decode("04"
+ "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798"
+ "483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8"));
return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
......
......@@ -34,7 +34,7 @@ namespace NBitcoin.BouncyCastle.Crypto.Parameters
public byte[] GetKey()
{
return (byte[])key.Clone();
return (byte[]) this.key.Clone();
}
}
......
......@@ -31,14 +31,14 @@ namespace NBitcoin.BouncyCastle.Crypto.Signers
public virtual BigInteger NextK()
{
int qBitLength = q.BitLength;
int qBitLength = this.q.BitLength;
BigInteger k;
do
{
k = new BigInteger(qBitLength, random);
k = new BigInteger(qBitLength, this.random);
}
while(k.SignValue < 1 || k.CompareTo(q) >= 0);
while(k.SignValue < 1 || k.CompareTo(this.q) >= 0);
return k;
}
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment