void IInteroperable.FromStackItem(StackItem stackItem)
        {
            Struct @struct = (Struct)stackItem;

            PubKey    = ECPoint.DecodePoint(@struct[0].GetSpan(), ECCurve.Secp256r1);
            Signature = @struct[1].GetSpan().ToArray();
        }
Exemple #2
0
        public void TestConstructor()
        {
            Random random = new Random();

            byte[] privateKey = new byte[32];
            for (int i = 0; i < privateKey.Length; i++)
            {
                privateKey[i] = (byte)random.Next(256);
            }
            KeyPair keyPair   = new KeyPair(privateKey);
            ECPoint publicKey = ECCurve.Secp256r1.G * privateKey;

            keyPair.PrivateKey.Should().BeEquivalentTo(privateKey);
            keyPair.PublicKey.Should().Be(publicKey);

            byte[] privateKey96 = new byte[96];
            for (int i = 0; i < privateKey96.Length; i++)
            {
                privateKey96[i] = (byte)random.Next(256);
            }
            keyPair   = new KeyPair(privateKey96);
            publicKey = ECPoint.DecodePoint(new byte[] { 0x04 }.Concat(privateKey96.Skip(privateKey96.Length - 96).Take(64)).ToArray(), ECCurve.Secp256r1);
            keyPair.PrivateKey.Should().BeEquivalentTo(privateKey96.Skip(64).Take(32));
            keyPair.PublicKey.Should().Be(publicKey);

            byte[] privateKey31 = new byte[31];
            for (int i = 0; i < privateKey31.Length; i++)
            {
                privateKey31[i] = (byte)random.Next(256);
            }
            Action action = () => new KeyPair(privateKey31);

            action.Should().Throw <ArgumentException>();
        }
Exemple #3
0
        private bool Account_SetVotes(ExecutionEngine engine)
        {
            AccountState account = engine.EvaluationStack.Pop().GetInterface <AccountState>();

            if (account == null)
            {
                return(false);
            }
            account = accounts[account.ScriptHash];
            if (account.IsFrozen)
            {
                return(false);
            }
            if (!account.Balances.ContainsKey(Blockchain.SystemShare.Hash) || account.Balances[Blockchain.SystemShare.Hash].Equals(Fixed8.Zero))
            {
                return(false);
            }
            if (!GetScriptHashesForVerifying(engine).Contains(account.ScriptHash))
            {
                return(false);
            }
            account       = accounts.GetAndChange(account.ScriptHash);
            account.Votes = engine.EvaluationStack.Pop().GetArray().Select(p => ECPoint.DecodePoint(p.GetByteArray(), ECCurve.Secp256r1)).ToArray();
            return(true);
        }
    public bool VerifySignature(byte[] message, byte[] signature, byte[] pubkey)
    {
      if (pubkey.Length == 33 && (pubkey[0] == 0x02 || pubkey[0] == 0x03))
      {
        try
        {
          pubkey = ECPoint.DecodePoint(pubkey, ECCurve.Secp256r1).EncodePoint(false).Skip(1).ToArray();
        }
        catch
        {
          return false;
        }
      }
      else if (pubkey.Length == 65 && pubkey[0] == 0x04)
      {
        pubkey = pubkey.Skip(1).ToArray();
      }
      else if (pubkey.Length != 64)
      {
        throw new ArgumentException();
      }

      BigInteger x = new BigInteger(1, pubkey.Take(32).ToArray());
      BigInteger y = new BigInteger(1, pubkey.Skip(32).ToArray());

      X9ECParameters ecParams = NistNamedCurves.GetByName("P-256");
      ECDomainParameters domainParameters = new ECDomainParameters(ecParams.Curve, ecParams.G, ecParams.N,
        ecParams.H, ecParams.GetSeed());
      var G = ecParams.G;
      Org.BouncyCastle.Math.EC.ECCurve curve = ecParams.Curve;
      Org.BouncyCastle.Math.EC.ECPoint q = curve.CreatePoint(x, y);

      ECPublicKeyParameters pubkeyParam = new ECPublicKeyParameters(q, domainParameters);

      var verifier = SignerUtilities.GetSigner("SHA-256withECDSA");
      
      verifier.Init(false, pubkeyParam);
      verifier.BlockUpdate(message, 0, message.Length);
      // expected format is SEQUENCE {INTEGER r, INTEGER s}
      var derSignature = new DerSequence(
          // first 32 bytes is "r" number
          new DerInteger(new BigInteger(1, signature.Take(32).ToArray())),
          // last 32 bytes is "s" number
          new DerInteger(new BigInteger(1, signature.Skip(32).ToArray())))
          .GetDerEncoded();

      ///old verify method
      ///
      /*
      const int ECDSA_PUBLIC_P256_MAGIC = 0x31534345;
      pubkey = BitConverter.GetBytes(ECDSA_PUBLIC_P256_MAGIC).Concat(BitConverter.GetBytes(32)).Concat(pubkey).ToArray();
      using (CngKey key = CngKey.Import(pubkey, CngKeyBlobFormat.EccPublicBlob))
      using (ECDsaCng ecdsa = new ECDsaCng(key))
      {
        var result = ecdsa.VerifyData(message, signature, HashAlgorithmName.SHA256);
      }
      */
      ///////////////////
      return verifier.VerifySignature(derSignature);
    }
Exemple #5
0
        private bool AppChain_ChangeSeedList(ExecutionEngine engine)
        {
            if (Trigger != TriggerType.Application)
            {
                return(false);
            }

            UInt160 hash = new UInt160(engine.CurrentContext.EvaluationStack.Pop().GetByteArray());

            AppChainState state = Snapshot.AppChains.TryGet(hash);

            if (state == null)
            {
                return(false);
            }

            int validatorCount = (int)engine.CurrentContext.EvaluationStack.Pop().GetBigInteger();

            ECPoint[] validators = new ECPoint[validatorCount];
            for (int i = 0; i < validatorCount; i++)
            {
                validators[i] = ECPoint.DecodePoint(engine.CurrentContext.EvaluationStack.Pop().GetByteArray(), ECCurve.Secp256r1);
            }

            state.StandbyValidators = validators;

            Blockchain appchain = Blockchain.GetBlockchain(hash);

            if (appchain != null)
            {
                appchain.StandbyValidators = (ECPoint[])validators.Clone();
            }

            return(true);
        }
Exemple #6
0
        public static bool VerifySignature(byte[] message, byte[] signature, byte[] pubkey)
        {
            //unity dotnet不完整,不能用dotnet自带的ecdsa
            var PublicKey = ECPoint.DecodePoint(pubkey, ECCurve.Secp256r1);
            var ecdsa     = new ECDsa(PublicKey);
            var b1        = signature.Take(32).Reverse().Concat(new byte[] { 0x00 }).ToArray();
            var b2        = signature.Skip(32).Reverse().Concat(new byte[] { 0x00 }).ToArray();
            var num1      = new BigInteger(b1);
            var num2      = new BigInteger(b2);
            var hash      = sha256.ComputeHash(message);

            return(ecdsa.VerifySignature(hash, num1, num2));
            //var PublicKey = ThinNeo.Cryptography.ECC.ECPoint.DecodePoint(pubkey, ThinNeo.Cryptography.ECC.ECCurve.Secp256r1);
            //var usepk = PublicKey.EncodePoint(false).Skip(1).ToArray();

            ////byte[] first = { 0x45, 0x43, 0x53, 0x31, 0x20, 0x00, 0x00, 0x00 };
            ////usepk = first.Concat(usepk).ToArray();

            ////using (System.Security.Cryptography.CngKey key = System.Security.Cryptography.CngKey.Import(usepk, System.Security.Cryptography.CngKeyBlobFormat.EccPublicBlob))
            ////using (System.Security.Cryptography.ECDsaCng ecdsa = new System.Security.Cryptography.ECDsaCng(key))

            //using (var ecdsa = System.Security.Cryptography.ECDsa.Create(new System.Security.Cryptography.ECParameters
            //{
            //    Curve = System.Security.Cryptography.ECCurve.NamedCurves.nistP256,
            //    Q = new System.Security.Cryptography.ECPoint
            //    {
            //        X = usepk.Take(32).ToArray(),
            //        Y = usepk.Skip(32).ToArray()
            //    }
            //}))
            //{
            //    var hash = sha256.ComputeHash(message);
            //    return ecdsa.VerifyHash(hash, signature);
            //}
        }
Exemple #7
0
        /// <summary>
        /// 从指定的json对象中解析出签名上下文
        /// </summary>
        /// <param name="json">json对象</param>
        /// <returns>返回上下文</returns>
        public static SignatureContext FromJson(JObject json)
        {
            ISignable signable = Assembly.GetExecutingAssembly().CreateInstance(json["type"].AsString()) as ISignable;

            using (MemoryStream ms = new MemoryStream(json["hex"].AsString().HexToBytes(), false))
                using (BinaryReader reader = new BinaryReader(ms, Encoding.UTF8))
                {
                    signable.DeserializeUnsigned(reader);
                }
            SignatureContext context = new SignatureContext(signable);
            JArray           scripts = (JArray)json["scripts"];

            for (int i = 0; i < scripts.Count; i++)
            {
                if (scripts[i] != null)
                {
                    context.redeemScripts[i] = scripts[i]["redeem_script"].AsString().HexToBytes();
                    context.signatures[i]    = new Dictionary <ECPoint, byte[]>();
                    JArray sigs = (JArray)scripts[i]["signatures"];
                    for (int j = 0; j < sigs.Count; j++)
                    {
                        ECPoint pubkey    = ECPoint.DecodePoint(sigs[j]["pubkey"].AsString().HexToBytes(), ECCurve.Secp256r1);
                        byte[]  signature = sigs[j]["signature"].AsString().HexToBytes();
                        context.signatures[i].Add(pubkey, signature);
                    }
                    context.completed[i] = scripts[i]["completed"].AsBoolean();
                }
            }
            return(context);
        }
Exemple #8
0
        private bool Account_SetVotes(ExecutionEngine engine)
        {
            AccountState account = engine.EvaluationStack.Pop().GetInterface <AccountState>();

            ECPoint[] votes = engine.EvaluationStack.Pop().GetArray().Select(p => ECPoint.DecodePoint(p.GetByteArray(), ECCurve.Secp256r1)).ToArray();
            if (account == null)
            {
                return(false);
            }
            if (votes.Length > 1024)
            {
                return(false);
            }
            account = accounts[account.ScriptHash];
            if (account.IsFrozen)
            {
                return(false);
            }
            if ((!account.Balances.TryGetValue(Blockchain.GoverningToken.Hash, out Fixed8 balance) || balance.Equals(Fixed8.Zero)) && votes.Length > 0)
            {
                return(false);
            }
            if (!CheckWitness(engine, account.ScriptHash))
            {
                return(false);
            }
            account       = accounts.GetAndChange(account.ScriptHash);
            account.Votes = votes.Distinct().ToArray();
            return(true);
        }
Exemple #9
0
        public static SignatureContext Parse(string value)
        {
            JObject   json     = JObject.Parse(value);
            string    typename = string.Format("{0}.{1}", typeof(SignatureContext).Namespace, json["type"].AsString());
            ISignable signable = Assembly.GetExecutingAssembly().CreateInstance(typename) as ISignable;

            using (MemoryStream ms = new MemoryStream(json["hex"].AsString().HexToBytes(), false))
                using (BinaryReader reader = new BinaryReader(ms, Encoding.UTF8))
                {
                    signable.DeserializeUnsigned(reader);
                }
            SignatureContext context = new SignatureContext(signable);
            JArray           scripts = (JArray)json["scripts"];

            for (int i = 0; i < scripts.Count; i++)
            {
                if (scripts[i] != null)
                {
                    context.redeemScripts[i] = scripts[i]["redeem_script"].AsString().HexToBytes();
                    context.signatures[i]    = new Dictionary <ECPoint, byte[]>();
                    JArray sigs = (JArray)scripts[i]["signatures"];
                    for (int j = 0; j < sigs.Count; j++)
                    {
                        ECPoint pubkey    = ECPoint.DecodePoint(sigs[j]["pubkey"].AsString().HexToBytes(), ECCurve.Secp256r1);
                        byte[]  signature = sigs[j]["signature"].AsString().HexToBytes();
                        context.signatures[i].Add(pubkey, signature);
                    }
                }
            }
            return(context);
        }
Exemple #10
0
        public void Serialize()
        {
            ECPoint val = ECPoint.DecodePoint("03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c".HexToBytes(), ECCurve.Secp256r1);

            uut.PublicKey  = val;
            uut.Registered = true;
            uut.Votes      = Fixed8.Zero;

            byte[] data;
            using (MemoryStream stream = new MemoryStream())
            {
                using (BinaryWriter writer = new BinaryWriter(stream, Encoding.ASCII, true))
                {
                    uut.Serialize(writer);
                    data = stream.ToArray();
                }
            }

            byte[] requiredData = new byte[] { 0, 3, 178, 9, 253, 79, 83, 167, 23, 14, 164, 68, 78, 12, 176, 166, 187, 106, 83, 194, 189, 1, 105, 38, 152, 156, 248, 95, 155, 15, 186, 23, 167, 12, 1, 0, 0, 0, 0, 0, 0, 0, 0 };

            data.Length.Should().Be(requiredData.Length);
            for (int i = 0; i < requiredData.Length; i++)
            {
                data[i].Should().Be(requiredData[i]);
            }
        }
        public void Deserialize(BinaryReader reader)
        {
            rangeSig = reader.ReadSerializable <RangeSigatureType>();
            C        = ECPoint.DecodePoint(reader.ReadVarBytes(), ECCurve.Secp256r1);
            mask     = reader.ReadVarBytes();

            CheckFields();
        }
Exemple #12
0
        public void Size_Get()
        {
            ECPoint val = ECPoint.DecodePoint("03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c".HexToBytes(), ECCurve.Secp256r1);

            uut.PublicKey = val;

            uut.Size.Should().Be(43); // 1 + 33 + 1 + 8
        }
Exemple #13
0
        public void Equals_DifferentKey()
        {
            ValidatorState newVs = new ValidatorState();

            newVs.PublicKey = ECPoint.DecodePoint("03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70b".HexToBytes(), ECCurve.Secp256r1);
            uut.PublicKey   = ECPoint.DecodePoint("03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c".HexToBytes(), ECCurve.Secp256r1);
            uut.Equals(newVs).Should().BeFalse();
        }
 /// <summary>
 /// The implementation of System.Runtime.CheckWitness.
 /// Determines whether the specified account has witnessed the current transaction.
 /// </summary>
 /// <param name="hashOrPubkey">The hash or public key of the account.</param>
 /// <returns><see langword="true"/> if the account has witnessed the current transaction; otherwise, <see langword="false"/>.</returns>
 protected internal bool CheckWitness(byte[] hashOrPubkey)
 {
     UInt160 hash = hashOrPubkey.Length switch
     {
         20 => new UInt160(hashOrPubkey),
         33 => Contract.CreateSignatureRedeemScript(ECPoint.DecodePoint(hashOrPubkey, ECCurve.Secp256r1)).ToScriptHash(),
         _ => throw new ArgumentException(null, nameof(hashOrPubkey))
     };
     return CheckWitnessInternal(hash);
 }
Exemple #15
0
        public bool Verify(byte[] publicKey, byte[] sig, IEnumerable <byte[]> data)
        {
            var r        = new BigInteger(((byte[])sig).Take(32).Reverse().Concat(new byte[1]).ToArray());
            var s        = new BigInteger(((byte[])sig).Skip(32).Reverse().Concat(new byte[1]).ToArray());
            var pubKey   = ECPoint.DecodePoint(publicKey, this.SelectedCurve);
            var dsa      = new ECDsa(pubKey);
            var dataHash = HashBytes(data);

            return(dsa.VerifySignature(dataHash, r, s));
        }
        public void Deserialize(BinaryReader reader)
        {
            AsnlSig = reader.ReadSerializable <ASNLSignatureType>();

            for (int i = 0; i < 64; i++)
            {
                Ci.Add(ECPoint.DecodePoint(reader.ReadVarBytes(), ECCurve.Secp256r1));
            }

            CheckFields();
        }
Exemple #17
0
 public static ECPoint[] StandbyValidators1()
 {
     ECPoint[] StandbyValidators1 = null;
     string[]  s = { "0327da12b5c40200e9f65569476bbff2218da4f32548ff43b6387ec1416a231ee8",
                     "026ce35b29147ad09e4afe4ec4a7319095f08198fa8babbe3c56e970b143528d22",
                     "0209e7fd41dfb5c2f8dc72eb30358ac100ea8c72da18847befe06eade68cebfcb9",
                     "039dafd8571a641058ccc832c5e2111ea39b09c0bde36050914384f7a48bce9bf9",
                     "038dddc06ce687677a53d54f096d2591ba2302068cf123c1f2d75c2dddc5425579",
                     "02d02b1873a0863cd042cc717da31cea0d7cf9db32b74d4c72c01b0011503e2e22",
                     "034ff5ceeac41acf22cd5ed2da17a6df4dd8358fcb2bfb1a43208ad0feaab2746b" };
     return(StandbyValidators1 = s.OfType <string>().Select(p => ECPoint.DecodePoint(p.HexToBytes(), ECCurve.Secp256r1)).ToArray());
 }
Exemple #18
0
        protected void ProcessValidatorStateDescriptor(StateDescriptor descriptor, DataCache <ECPoint, ValidatorState> validators)
        {
            ECPoint        pubkey    = ECPoint.DecodePoint(descriptor.Key, ECCurve.Secp256r1);
            ValidatorState validator = validators.GetAndChange(pubkey, () => new ValidatorState(pubkey));

            switch (descriptor.Field)
            {
            case "Registered":
                validator.Registered = BitConverter.ToBoolean(descriptor.Value, 0);
                break;
            }
        }
Exemple #19
0
        internal static void ProcessValidatorStateDescriptor(StateDescriptor descriptor, Snapshot snapshot)
        {
            ECPoint        pubkey    = ECPoint.DecodePoint(descriptor.Key, ECCurve.Secp256);
            ValidatorState validator = snapshot.Validators.GetAndChange(pubkey, () => new ValidatorState(pubkey));

            switch (descriptor.Field)
            {
            case "Registered":
                validator.Registered = BitConverter.ToBoolean(descriptor.Value, 0);
                break;
            }
        }
Exemple #20
0
        private IEnumerable <UInt160> GetScriptHashesForVerifying_Validator(StateDescriptor descriptor)
        {
            switch (descriptor.Field)
            {
            case "Registered":
                yield return(Contract.CreateSignatureRedeemScript(ECPoint.DecodePoint(descriptor.Key, ECCurve.Secp256r1)).ToScriptHash());

                break;

            default:
                throw new InvalidOperationException();
            }
        }
Exemple #21
0
 public Contract GetContract()
 {
     ECPoint[] publicKeys = listBox1.Items.OfType <string>().Select(p => ECPoint.DecodePoint(p.HexToBytes(), ECCurve.Secp256r1)).ToArray();
     foreach (ECPoint publicKey in publicKeys)
     {
         KeyPair key = Program.CurrentWallet.GetKey(publicKey.EncodePoint(true).ToScriptHash());
         if (key != null)
         {
             return(Contract.CreateMultiSigContract(key.PublicKeyHash, (int)numericUpDown2.Value, publicKeys));
         }
     }
     return(null);
 }
Exemple #22
0
        internal ContractPermissionDescriptor(ReadOnlySpan <byte> span)
        {
            switch (span.Length)
            {
            case UInt160.Length:
                Hash = new UInt160(span);
                break;

            case 33:
                Group = ECPoint.DecodePoint(span, ECCurve.Secp256r1);
                break;

            default:
                throw new ArgumentException(null, nameof(span));
            }
        }
Exemple #23
0
        private string[] GetSignersFromWitnesses(Witness[] witnesses)
        {
            List <ECPoint> pubKeys = new List <ECPoint>();

            try
            {
                foreach (var witness in witnesses)
                {
                    byte[] script = witness.VerificationScript;
                    if (script.IsSignatureContract())
                    {
                        pubKeys.Add(ECPoint.DecodePoint(script.Skip(1).Take(33).ToArray(), ECCurve.Secp256r1));
                    }
                    else if (script.IsMultiSigContract())
                    {
                        int i = 0;
                        switch (script[i++])
                        {
                        case 1:
                            ++i;
                            break;

                        case 2:
                            i += 2;
                            break;
                        }
                        while (script[i++] == 33)
                        {
                            pubKeys.Add(ECPoint.DecodePoint(script.Skip(i).Take(33).ToArray(), ECCurve.Secp256r1));
                            i += 33;
                        }
                    }
                    else
                    {
                        throw new NotSupportedException();
                    }
                }
            }
            catch (Exception)
            {
                return(null);
            }
            return(pubKeys.Select(p => ("21" + p.EncodePoint(true).ToHexString() + "ac").HexToBytes().ToScriptHash().ToAddress()).ToArray());
        }
Exemple #24
0
        private static bool VerifySignature(byte[] hash, byte[] signature, byte[] pubkey)
        {
            const int ECDSA_PUBLIC_P256_MAGIC = 0x31534345;

            try
            {
                pubkey = ECPoint.DecodePoint(pubkey, ECCurve.Secp256r1).EncodePoint(false).Skip(1).ToArray();
            }
            catch
            {
                return(false);
            }
            pubkey = BitConverter.GetBytes(ECDSA_PUBLIC_P256_MAGIC).Concat(BitConverter.GetBytes(32)).Concat(pubkey).ToArray();
            using (CngKey key = CngKey.Import(pubkey, CngKeyBlobFormat.EccPublicBlob))
                using (ECDsaCng ecdsa = new ECDsaCng(key))
                {
                    return(ecdsa.VerifyHash(hash, signature));
                }
        }
        protected virtual bool Runtime_CheckWitness(ExecutionEngine engine)
        {
            byte[] hashOrPubkey = engine.EvaluationStack.Pop().GetByteArray();
            bool   result;

            if (hashOrPubkey.Length == 20)
            {
                result = CheckWitness(engine, new UInt160(hashOrPubkey));
            }
            else if (hashOrPubkey.Length == 33)
            {
                result = CheckWitness(engine, ECPoint.DecodePoint(hashOrPubkey, ECCurve.Secp256r1));
            }
            else
            {
                return(false);
            }
            engine.EvaluationStack.Push(result);
            return(true);
        }
Exemple #26
0
        private static bool Runtime_CheckWitness(ApplicationEngine engine)
        {
            byte[] hashOrPubkey = engine.CurrentContext.EvaluationStack.Pop().GetByteArray();
            bool   result;

            if (hashOrPubkey.Length == 20)
            {
                result = CheckWitness(engine, new UInt160(hashOrPubkey));
            }
            else if (hashOrPubkey.Length == 33)
            {
                result = CheckWitness(engine, ECPoint.DecodePoint(hashOrPubkey, ECCurve.Secp256r1));
            }
            else
            {
                return(false);
            }
            engine.CurrentContext.EvaluationStack.Push(result);
            return(true);
        }
Exemple #27
0
        private bool Validator_Register(ExecutionEngine engine)
        {
            ECPoint pubkey = ECPoint.DecodePoint(engine.EvaluationStack.Pop().GetByteArray(), ECCurve.Secp256r1);

            if (pubkey.IsInfinity)
            {
                return(false);
            }
            if (!CheckWitness(engine, pubkey))
            {
                return(false);
            }
            ValidatorState validator = validators.GetOrAdd(pubkey, () => new ValidatorState
            {
                PublicKey = pubkey
            });

            engine.EvaluationStack.Push(StackItem.FromInterface(validator));
            return(true);
        }
Exemple #28
0
        private void setupAssetStateWithValues(AssetState assetState, out UInt256 assetId, out AssetType assetType, out string name, out Fixed8 amount, out Fixed8 available, out byte precision, out Fixed8 fee, out UInt160 feeAddress, out ECPoint owner, out UInt160 admin, out UInt160 issuer, out uint expiration, out bool isFrozen)
        {
            assetId            = new UInt256(TestUtils.GetByteArray(32, 0x20));
            assetState.AssetId = assetId;

            assetType            = AssetType.SystemCoin;
            assetState.AssetType = assetType;

            name            = "neo";
            assetState.Name = name;

            amount            = new Fixed8(42);
            assetState.Amount = amount;

            available            = new Fixed8(43);
            assetState.Available = available;

            precision            = 0x42;
            assetState.Precision = precision;

            fee            = new Fixed8(44);
            assetState.Fee = fee;

            feeAddress            = new UInt160(TestUtils.GetByteArray(20, 0x21));
            assetState.FeeAddress = feeAddress;

            owner            = ECPoint.DecodePoint(TestUtils.GetByteArray(1, 0x00), ECCurve.Secp256r1);
            assetState.Owner = owner;

            admin            = new UInt160(TestUtils.GetByteArray(20, 0x22));
            assetState.Admin = admin;

            issuer            = new UInt160(TestUtils.GetByteArray(20, 0x23));
            assetState.Issuer = issuer;

            expiration            = 42u;
            assetState.Expiration = expiration;

            isFrozen            = true;
            assetState.IsFrozen = isFrozen;
        }
        private static void UpdateResultFromFile(UInt160 hash)
        {
            string           address = Wallet.ToAddress(hash);
            X509Certificate2 cert;

            try
            {
                cert = new X509Certificate2(Path.Combine(Settings.Default.CertCachePath, $"{address}.cer"));
            }
            catch (CryptographicException)
            {
                results[hash].Type = CertificateQueryResultType.Missing;
                return;
            }
            if (cert.PublicKey.Oid.Value != "1.2.840.10045.2.1")
            {
                results[hash].Type = CertificateQueryResultType.Missing;
                return;
            }
            if (!hash.Equals(Contract.CreateSignatureRedeemScript(ECPoint.DecodePoint(cert.PublicKey.EncodedKeyValue.RawData, ECCurve.Secp256r1)).ToScriptHash()))
            {
                results[hash].Type = CertificateQueryResultType.Missing;
                return;
            }
            using (X509Chain chain = new X509Chain())
            {
                results[hash].Certificate = cert;
                if (chain.Build(cert))
                {
                    results[hash].Type = CertificateQueryResultType.Good;
                }
                else if (chain.ChainStatus.Length == 1 && chain.ChainStatus[0].Status == X509ChainStatusFlags.NotTimeValid)
                {
                    results[hash].Type = CertificateQueryResultType.Expired;
                }
                else
                {
                    results[hash].Type = CertificateQueryResultType.Invalid;
                }
            }
        }
Exemple #30
0
        private static bool VerifySignature(byte[] signature, byte[] pubKey, Transaction tx, uint inputIndex, byte[] scriptPubKey)
        {
            BigInteger r, s;

            using (MemoryStream ms = new MemoryStream(signature, false))
                using (BinaryReader reader = new BinaryReader(ms))
                {
                    if (reader.ReadByte() != 0x30)
                    {
                        return(false);
                    }
                    reader.ReadByte();
                    if (reader.ReadByte() != 0x02)
                    {
                        return(false);
                    }
                    r = new BigInteger(reader.ReadBytes(reader.ReadByte()).Reverse().ToArray());
                    if (reader.ReadByte() != 0x02)
                    {
                        return(false);
                    }
                    s = new BigInteger(reader.ReadBytes(reader.ReadByte()).Reverse().ToArray());
                }
            HashType hashType = (HashType)signature[signature.Length - 1];

            byte[]  hash = tx.GetHashForVerification(hashType, inputIndex, scriptPubKey);
            ECPoint pubKeyPoint;

            try
            {
                pubKeyPoint = ECPoint.DecodePoint(pubKey, ECCurve.Secp256k1);
            }
            catch
            {
                return(false);
            }
            ECDsa signer = new ECDsa(pubKeyPoint);

            return(signer.VerifySignature(hash, r, s));
        }