Add license header.
[NovacoinLibrary.git] / Novacoin / CKeyPair.cs
index 885529b..6c7243c 100644 (file)
@@ -1,14 +1,30 @@
-\feffusing System.Collections.Generic;
-using System.Linq;
-using System;
+\feff/**
+ *  Novacoin classes library
+ *  Copyright (C) 2015 Alex D. (balthazar.ad@gmail.com)
 
-using Org.BouncyCastle.Math;
-using Org.BouncyCastle.Math.EC;
+ *  This program is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU Affero General Public License as
+ *  published by the Free Software Foundation, either version 3 of the
+ *  License, or (at your option) any later version.
+
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU Affero General Public License for more details.
+
+ *  You should have received a copy of the GNU Affero General Public License
+ *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
 
 using Org.BouncyCastle.Crypto;
 using Org.BouncyCastle.Crypto.Generators;
 using Org.BouncyCastle.Crypto.Parameters;
+using Org.BouncyCastle.Math;
+using Org.BouncyCastle.Math.EC;
 using Org.BouncyCastle.Security;
+using System;
+using System.Collections.Generic;
+using System.Linq;
 
 
 namespace Novacoin
@@ -40,10 +56,19 @@ namespace Novacoin
         /// Init key pair using secret sequence of bytes
         /// </summary>
         /// <param name="secretBytes">Byte sequence</param>
+        /// <param name="Compressed">Compression flag</param>
         public CKeyPair(IEnumerable<byte> secretBytes, bool Compressed=true)
         {
             // Deserialize secret value
-            BigInteger D = new BigInteger(secretBytes.ToArray());
+            BigInteger D = new BigInteger(secretBytes.Take(32).ToArray());
+
+            if (D.SignValue == -1)
+            {
+                List<byte> fixedKeyBytes = secretBytes.Take(32).ToList();
+                fixedKeyBytes.Insert(0, 0x00); // prepend with sign byte
+
+                D = new BigInteger(fixedKeyBytes.ToArray());
+            }
 
             // Calculate public key
             ECPoint Q = curve.G.Multiply(D);
@@ -57,21 +82,30 @@ namespace Novacoin
             }
         }
 
+        /// <summary>
+        /// Init key pair using secret sequence of bytes
+        /// </summary>
+        /// <param name="secretBytes">Byte sequence</param>
+        public CKeyPair(IEnumerable<byte> secretBytes) : 
+            this (secretBytes.Take(32), (secretBytes.Count() == 33 && secretBytes.Last() == 0x01))
+        {
+        }
+
         public CKeyPair(string strBase58)
         {
             List<byte> rawBytes = AddressTools.Base58DecodeCheck(strBase58).ToList();
             rawBytes.RemoveAt(0); // Remove key version byte
 
-            int nSecretLen = rawBytes[0] == 0x00 ? 33 : 32;
-            int nTaggedSecretLen = nSecretLen + 1;
+            // Deserialize secret value
+            BigInteger D = new BigInteger(rawBytes.Take(32).ToArray());
 
-            if (rawBytes.Count > nTaggedSecretLen || rawBytes.Count < nSecretLen)
+            if (D.SignValue == -1)
             {
-                throw new FormatException("Invalid private key");
-            }
+                List<byte> secretbytes = rawBytes.Take(32).ToList(); // Copy secret
+                secretbytes.Insert(0, 0x00); // Prepend with sign byte
 
-            // Deserialize secret value
-            BigInteger D = new BigInteger(rawBytes.Take(nSecretLen).ToArray());
+                D = new BigInteger(secretbytes.ToArray()); // Try decoding again
+            }
 
             // Calculate public key
             ECPoint Q = curve.G.Multiply(D);
@@ -79,65 +113,77 @@ namespace Novacoin
             _Private = new ECPrivateKeyParameters(D, domain);
             _Public = new ECPublicKeyParameters(Q, domain);
 
-            if (rawBytes.Count == nTaggedSecretLen && rawBytes.Last() == 0x01) // Check compression tag
+            if (rawBytes.Count == 33 && rawBytes.Last() == 0x01) // Check compression tag
             {
                 _Public = Compress(_Public);
             }
         }
 
         /// <summary>
+        /// Initialize a copy of CKeyPair instance
+        /// </summary>
+        /// <param name="pair">CKyPair instance</param>
+        public CKeyPair(CKeyPair pair)
+        {
+            _Public = pair._Public;
+            _Private = pair._Private;
+        }
+
+        /// <summary>
         /// Create signature for supplied data
         /// </summary>
-        /// <param name="data">Data bytes sequence</param>
+        /// <param name="data">Hash to sigh</param>
         /// <returns>Signature bytes sequence</returns>
-        public IEnumerable<byte> Sign(IEnumerable<byte> data)
+        public IEnumerable<byte> Sign(Hash sigHash)
         {
-            byte[] dataBytes = data.ToArray();
-
-            ISigner signer = SignerUtilities.GetSigner("SHA-256withECDSA");
+            ISigner signer = SignerUtilities.GetSigner("NONEwithECDSA");
             signer.Init(true, _Private);
-            signer.BlockUpdate(dataBytes, 0, dataBytes.Length);
+            signer.BlockUpdate(sigHash.hashBytes, 0, sigHash.hashSize);
 
             return signer.GenerateSignature();
         }
 
-        public CPubKey GetPubKey()
+        public CPubKey PubKey
         {
-            return new CPubKey(Public);
+            get { return new CPubKey(PublicBytes); }
         }
 
         /// <summary>
-        /// Secret part of key pair
+        /// SecretBytes part of key pair
         /// </summary>
-        public IEnumerable<byte> Secret
+        public IEnumerable<byte> SecretBytes
         {
-            get { return _Private.D.ToByteArray(); }
+            get
+            {
+                List<byte> secretBytes = new List<byte>(_Private.D.ToByteArray());
+
+                if (secretBytes[0] == 0x00)
+                {
+                    // Remove sign
+                    secretBytes.RemoveAt(0);
+                }
+
+                if (IsCompressed)
+                {
+                    // Set compression flag
+                    secretBytes.Add(0x01);
+                }
+
+                return secretBytes;
+            }
         }
 
         public string ToHex()
         {
-            List<byte> r = new List<byte>(Secret);
-            
-            if (IsCompressed)
-            {
-                r.Add(0x01);
-            }
-
-            return Interop.ToHex(r);
+            return Interop.ToHex(SecretBytes);
         }
 
         public override string ToString()
         {
             List<byte> r = new List<byte>();
 
-            r.Add((byte)(128 + AddrType.PUBKEY_ADDRESS));
-
-            r.AddRange(Secret);
-
-            if (IsCompressed)
-            {
-                r.Add(0x01);
-            }
+            r.Add((byte)(128 + AddrType.PUBKEY_ADDRESS)); // Key version
+            r.AddRange(SecretBytes); // Key data
 
             return AddressTools.Base58EncodeCheck(r);
         }