示例#1
0
        //Transfer Global Asset
        public static Transaction CreateGlobalTransfer(SignDelegate sign)
        {
            //交易输入是 1 GAS
            var inputs = new List <CoinReference> {
                //coin reference A
                new CoinReference()
                {
                    PrevHash  = new UInt256("0x21b64eb35881e7261c72c70f38bd6d5eb6aa18f232e08ba3022220b46c13d9a2".Remove(0, 2).HexToBytes().Reverse().ToArray()),
                    PrevIndex = 0
                }
            }.ToArray();
            //交易输出是 0.999 GAS,找回到原地址
            var outputs = new List <TransactionOutput> {
                new TransactionOutput()
                {
                    AssetId    = Blockchain.UtilityToken.Hash,                        //Asset Id, this is GAS
                    ScriptHash = "Ad1HKAATNmFT5buNgSxspbW68f4XVSssSw".ToScriptHash(), //Receiver
                    Value      = new Fixed8((long)(0.999 * (long)Math.Pow(10, 8)))    //Value (satoshi unit)
                }
            }.ToArray();
            //则手续费是 0.001 GAS

            var tx = new ContractTransaction()
            {
                Outputs    = outputs,
                Inputs     = inputs,
                Attributes = new TransactionAttribute[0],
                Witnesses  = new Witness[0],
            };

            return(sign.Invoke(tx));
        }
示例#2
0
        public static Transaction Claim(Wallet wallet, SignDelegate sign)
        {
            CoinReference[] claims = wallet.GetUnclaimedCoins().Select(p => p.Reference).ToArray();
            if (claims.Length == 0)
            {
                return(null);
            }

            using (Snapshot snapshot = Blockchain.Singleton.GetSnapshot())
            {
                ClaimTransaction tx = new ClaimTransaction
                {
                    Claims     = claims,
                    Attributes = new TransactionAttribute[0],
                    Inputs     = new CoinReference[0],
                    Outputs    = new[]
                    {
                        new TransactionOutput
                        {
                            AssetId    = Blockchain.UtilityToken.Hash,
                            Value      = snapshot.CalculateBonus(claims),
                            ScriptHash = wallet.GetChangeAddress()
                        }
                    }
                };

                return(sign.Invoke(tx));
            }
        }
示例#3
0
        static void Main(string[] args)
        {
            var system = new NeoSystem(new LevelDBStore("D:\\PrivateNet2\\NEO-GUI 2.9 release\\Chain_0001E240"));

            SignDelegate sign = new SignDelegate(SignWithWallet);

            var tx = CreateGlobalTransfer(sign);

            Console.ReadLine();
        }
        public static Transaction CreateGlobalTransfer(SignDelegate sign)
        {
            string      preTxId = "0x7866a1aae60e7e6a2da87a681edf8c265db200ba68f4a96b447f85bb60c3594b";
            UInt256     hash    = UInt256.Parse(preTxId);
            Transaction tx1     = Blockchain.Singleton.GetTransaction(hash);

            Fixed8 preOutVal     = tx1.Outputs[100].Value;
            Fixed8 currentOutVal = new Fixed8(1 * (long)Math.Pow(10, 8));

            if (preOutVal < currentOutVal)
            {
                Console.WriteLine("insufficient fund");
                return(null);
            }

            var inputs = new List <CoinReference>
            {
                new CoinReference()
                {
                    PrevHash  = new UInt256(preTxId.Remove(0, 2).HexToBytes().Reverse().ToArray()),
                    PrevIndex = 100
                }
            }.ToArray();

            var outputs = new List <TransactionOutput>();

            var output1 = new TransactionOutput()
            {
                AssetId    = UInt256.Parse(assetid),
                ScriptHash = "AYuApoS1MQvJMQF7J9GiMcCA9du7s6YBwo".ToScriptHash(),
                Value      = currentOutVal
            };

            outputs.Add(output1);
            if (preOutVal > currentOutVal)
            {
                var output2 = new TransactionOutput()
                {
                    AssetId    = UInt256.Parse(assetid),
                    ScriptHash = "AZi4EzuSSp4kiWCUvLZcWo8daymKf53ez6".ToScriptHash(),
                    Value      = preOutVal - currentOutVal
                };
                outputs.Add(output2);
            }

            var tx = new ContractTransaction()
            {
                Outputs    = outputs.ToArray(),
                Inputs     = inputs,
                Attributes = new TransactionAttribute[0],
                Witnesses  = new Witness[0]
            };

            return(sign.Invoke(tx));
        }
示例#5
0
        // This constructor will be used by NET45 for signing and for RSAKeyWrap
        internal AsymmetricAdapter(SecurityKey key, string algorithm, HashAlgorithm hashAlgorithm, bool requirePrivateKey)
        {
            HashAlgorithm = hashAlgorithm;

            // RsaSecurityKey has either Rsa OR RsaParameters.
            // If we use the RsaParameters, we create a new RSA object and will need to dispose.
            if (key is RsaSecurityKey rsaKey)
            {
                InitializeUsingRsaSecurityKey(rsaKey, algorithm);
            }
            else if (key is X509SecurityKey x509Key)
            {
                InitializeUsingX509SecurityKey(x509Key, algorithm, requirePrivateKey);
            }
            else if (key is JsonWebKey jsonWebKey)
            {
                if (JsonWebKeyConverter.TryConvertToSecurityKey(jsonWebKey, out SecurityKey securityKey))
                {
                    if (securityKey is RsaSecurityKey rsaSecurityKeyFromJsonWebKey)
                    {
                        InitializeUsingRsaSecurityKey(rsaSecurityKeyFromJsonWebKey, algorithm);
                    }
                    else if (securityKey is X509SecurityKey x509SecurityKeyFromJsonWebKey)
                    {
                        InitializeUsingX509SecurityKey(x509SecurityKeyFromJsonWebKey, algorithm, requirePrivateKey);
                    }
                    else if (securityKey is ECDsaSecurityKey edcsaSecurityKeyFromJsonWebKey)
                    {
                        InitializeUsingEcdsaSecurityKey(edcsaSecurityKeyFromJsonWebKey);
                    }
                    else
                    {
                        throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10684, algorithm, key)));
                    }
                }
            }
            else if (key is ECDsaSecurityKey ecdsaKey)
            {
                ECDsaSecurityKey  = ecdsaKey;
                SignatureFunction = SignWithECDsa;
                VerifyFunction    = VerifyWithECDsa;
            }
            else
            {
                throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10684, algorithm, key)));
            }
        }
示例#6
0
        //CGAS MintTokens
        public static void MintTokens()
        {
            var inputs = new List <CoinReference> {
                new CoinReference()
                {
                    PrevHash  = new UInt256("0xf5088ce508d86197c991ff0ef7651ddf01f3e555f257039c972082250e899210".Remove(0, 2).HexToBytes().Reverse().ToArray()),
                    PrevIndex = 0
                }
            }.ToArray();

            var outputs = new List <TransactionOutput> {
                new TransactionOutput()
                {
                    AssetId    = Blockchain.UtilityToken.Hash, //Asset Id, this is GAS
                    ScriptHash = ScriptHash,                   //CGAS 地址
                    Value      = new Fixed8((long)(1 * (long)Math.Pow(10, 8)))
                }
            }.ToArray();

            Transaction tx = null;

            using (ScriptBuilder sb = new ScriptBuilder())
            {
                sb.EmitAppCall(ScriptHash, "mintTokens");
                sb.Emit(OpCode.THROWIFNOT);

                byte[] nonce = new byte[8];
                Random rand  = new Random();
                rand.NextBytes(nonce);
                sb.Emit(OpCode.RET, nonce);
                tx = new InvocationTransaction
                {
                    Version    = 1,
                    Script     = sb.ToArray(),
                    Outputs    = outputs,
                    Inputs     = inputs,
                    Attributes = new TransactionAttribute[0],
                    Witnesses  = new Witness[0]
                };
            }
            var sign = new SignDelegate(SignWithWallet);

            sign.Invoke(tx, "1.json", "11111111");
            Verify(tx);
        }
示例#7
0
        public PackageBuilder SetIssuer(string id, string type = "", SignDelegate sign = null)
        {
            if (string.IsNullOrEmpty(type))
            {
                type = DerivationSecp256k1PKH.NAME;
            }

            if (CurrentClaim.Issuer == null)
            {
                CurrentClaim.Issuer = new IssuerIdentity();
            }

            CurrentClaim.Issuer.Type = type;
            CurrentClaim.Issuer.Id   = id;
            CurrentClaim.IssuerSign  = sign;

            return(this);
        }
示例#8
0
        public PackageBuilder SetServer(string id, string type = "", SignDelegate sign = null)
        {
            if (string.IsNullOrEmpty(type))
            {
                type = DerivationSecp256k1PKH.NAME;
            }

            if (Package.Server == null)
            {
                Package.Server = new ServerIdentity();
            }

            Package.Server.Id   = id;
            Package.Server.Type = type;
            Package.Server.Sign = sign;

            return(this);
        }
示例#9
0
        public PackageBuilder SignServer(Package package = null, SignDelegate sign = null)
        {
            if (package == null)
            {
                package = Package;
            }

            if (sign != null)
            {
                Package.SetSignature(sign(Package.Id));
            }
            else
            if (Package.Server.Sign != null)
            {
                Package.SetSignature(Package.Server.Sign(Package.Id));
            }
            return(this);
        }
示例#10
0
        public PackageBuilder SignIssuer(Claim claim = null, SignDelegate sign = null)
        {
            if (claim == null)
            {
                claim = CurrentClaim;
            }

            var source = _packageBinary.ClaimBinary.GetIdSource(claim);

            if (sign != null)
            {
                claim.Issuer.Proof = sign(source);
            }
            else
            {
                if (claim.IssuerSign != null)
                {
                    claim.Issuer.Proof = claim.IssuerSign(source);
                }
            }
            return(this);
        }
示例#11
0
        static void Test(string[] args)
        {
            timer.Interval = 15000;
            timer.Elapsed += Timer_Elapsed;
            timer.Start();
            var system = new BhpSystem(new LevelDBStore(@"D:\BHP\20181018\test-cli\bhp-cli-3\Chain_00F1A2E3"));

            system.StartNode(20555, 20556);

            Console.ReadKey();
            SignDelegate sign = new SignDelegate(SignWithoutWallet);
            var          tx   = CreateGlobalTransfer(sign);

            system.LocalNode.Tell(new LocalNode.Relay {
                Inventory = tx
            });

            Console.WriteLine("The End");
            timer.Stop();
            timer.Elapsed -= Timer_Elapsed;
            timer.Dispose();
            Console.ReadKey();
        }
示例#12
0
        public OrlpEd25519Context(string sharedLibPathOverride = null)
        {
            string os;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                os        = "windows";
                loadUtils = new SharedLibLoadUtilsWindows();
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                os        = "linux";
                loadUtils = new SharedLibLoadUtilsLinux();
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                os        = "mac";
                loadUtils = new SharedLibLoadUtilsMac();
            }
            else
            {
                throw new PlatformNotSupportedException("Unsupported OS");
            }

            if (!string.IsNullOrEmpty(sharedLibPathOverride))
            {
                LoadedLibraryPath = sharedLibPathOverride;
            }
            else
            {
                string cpu = RuntimeInformation.ProcessArchitecture switch
                {
                    Architecture.X64 => "x64",
                    Architecture.X86 => "x86",
                    Architecture.Arm => "armeabi-v7a",
                    Architecture.Arm64 => "arm64-v8a",
                    _ => throw new PlatformNotSupportedException("CPU Architecture not supported!")
                };

                string path = Path.Combine(Path.GetFullPath(Path.GetDirectoryName(Assembly.GetCallingAssembly().Location) ?? "."), "lib", cpu, os);

                if (!Directory.Exists(path))
                {
                    throw new PlatformNotSupportedException($"Shared library not found in {path} and/or unsupported CPU architecture. Please don't forget to copy the shared libraries/DLL into the 'lib/{{CPU_ARCHITECTURE}}/{{OS}}/{{SHARED_LIB_FILE}}' folder of your output build directory. ");
                }

                bool found = false;
                foreach (string file in Directory.GetFiles(path))
                {
                    if (file.ToLower().Contains("ed25519"))
                    {
                        LoadedLibraryPath = Path.GetFullPath(Path.Combine(path, file));
                        found             = true;
                        break;
                    }
                }

                if (!found)
                {
                    throw new FileLoadException($"Shared library not found in {path} and/or unsupported CPU architecture. Please don't forget to copy the shared libraries/DLL into the 'lib/{{CPU_ARCHITECTURE}}/{{OS}}/{{SHARED_LIB_FILE}}' folder of your output build directory. ");
                }
            }

            lib = loadUtils.LoadLibrary(LoadedLibraryPath);
            if (lib == IntPtr.Zero)
            {
                goto hell; // The gates of hell opened, and out came the beginning of marshalling, DLL hell and C# interop...
            }

            IntPtr createSeed = loadUtils.GetProcAddress(lib, "ed25519_create_seed");

            if (createSeed == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr createKeypair = loadUtils.GetProcAddress(lib, "ed25519_create_keypair");

            if (createKeypair == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr sign = loadUtils.GetProcAddress(lib, "ed25519_sign");

            if (sign == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr verify = loadUtils.GetProcAddress(lib, "ed25519_verify");

            if (verify == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr addScalar = loadUtils.GetProcAddress(lib, "ed25519_add_scalar");

            if (addScalar == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr keyExchange = loadUtils.GetProcAddress(lib, "ed25519_key_exchange");

            if (keyExchange == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr keyConvert = loadUtils.GetProcAddress(lib, "ed25519_key_convert_ref10_to_orlp");

            if (keyConvert == IntPtr.Zero)
            {
                goto hell;
            }

            createSeedDelegate         = Marshal.GetDelegateForFunctionPointer <CreateSeedDelegate>(createSeed);
            createKeypairDelegate      = Marshal.GetDelegateForFunctionPointer <CreateKeypairDelegate>(createKeypair);
            signDelegate               = Marshal.GetDelegateForFunctionPointer <SignDelegate>(sign);
            verifyDelegate             = Marshal.GetDelegateForFunctionPointer <VerifyDelegate>(verify);
            addScalarDelegate          = Marshal.GetDelegateForFunctionPointer <AddScalarDelegate>(addScalar);
            keyExchangeDelegate        = Marshal.GetDelegateForFunctionPointer <KeyExchangeDelegate>(keyExchange);
            ref10KeyConversionDelegate = Marshal.GetDelegateForFunctionPointer <Ref10KeyConversionDelegate>(keyConvert);

            return;

hell:
            throw new Exception($"Failed to load one or more functions from the orlp-ed25519 shared library \"{LoadedLibraryPath}\"!");
        }
示例#13
0
        private void InitializeUsingRsa(RSA rsa, string algorithm)
        {
#if NET461 || NETSTANDARD2_0
            if (algorithm.Equals(SecurityAlgorithms.RsaSsaPssSha256, StringComparison.Ordinal) ||
                algorithm.Equals(SecurityAlgorithms.RsaSsaPssSha256Signature, StringComparison.Ordinal) ||
                algorithm.Equals(SecurityAlgorithms.RsaSsaPssSha384, StringComparison.Ordinal) ||
                algorithm.Equals(SecurityAlgorithms.RsaSsaPssSha384Signature, StringComparison.Ordinal) ||
                algorithm.Equals(SecurityAlgorithms.RsaSsaPssSha512, StringComparison.Ordinal) ||
                algorithm.Equals(SecurityAlgorithms.RsaSsaPssSha512Signature, StringComparison.Ordinal))
            {
                RSASignaturePadding = RSASignaturePadding.Pss;
            }
            else
            {
                // default RSASignaturePadding for other supported RSA algorithms is Pkcs1
                RSASignaturePadding = RSASignaturePadding.Pkcs1;
            }
#endif

            // This case is the result of a calling
            // X509Certificate2.GetPrivateKey OR X509Certificate2.GetPublicKey.Key
            // These calls return an AsymmetricAlgorithm which doesn't have API's to do much and need to be cast.
            // RSACryptoServiceProvider is wrapped to support SHA2
            // RSACryptoServiceProviderProxy is only supported on Windows platform
#if DESKTOP
            _useRSAOeapPadding = algorithm.Equals(SecurityAlgorithms.RsaOAEP, StringComparison.Ordinal) ||
                                 algorithm.Equals(SecurityAlgorithms.RsaOaepKeyWrap, StringComparison.Ordinal);

            if (rsa is RSACryptoServiceProvider rsaCryptoServiceProvider)
            {
                RsaCryptoServiceProviderProxy = new RSACryptoServiceProviderProxy(rsaCryptoServiceProvider);
                SignatureFunction             = SignWithRsaCryptoServiceProviderProxy;
                VerifyFunction = VerifyWithRsaCryptoServiceProviderProxy;
                // RSACryptoServiceProviderProxy will keep track of if it creates a new RSA object.
                // Only if a new RSA was creaated, RSACryptoServiceProviderProxy will call RSA.Dispose().
                _disposeCryptoOperators = true;
                return;
            }
#endif

            // This case required the user to get a RSA object by calling
            // X509Certificate2.GetRSAPrivateKey() OR X509Certificate2.GetRSAPublicKey()
            // This requires 4.6+ to be installed. If a dependent library is targeting 4.5, 4.5.1, 4.5.2 or 4.6
            // they will use Net45, but the type is RSACng.
            // The 'lightup' code will bind to the correct operators.
#if NET45
            else if (rsa.GetType().ToString().Equals(_rsaCngTypeName, StringComparison.Ordinal) && IsRsaCngSupported())
            {
                _lightUpHashAlgorithmName = GetLightUpHashAlgorithmName();
                SignatureFunction         = Pkcs1SignData;
                VerifyFunction            = Pkcs1VerifyData;
                return;
            }
            else
            {
                // In NET45 we only support RSACryptoServiceProvider or "System.Security.Cryptography.RSACng"
                throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10687, typeof(RSACryptoServiceProvider).ToString(), _rsaCngTypeName, rsa.GetType().ToString())));
            }
#endif

#if NET461 || NETSTANDARD2_0
            // Here we can use RSA straight up.
            _rsaEncryptionPadding = (algorithm.Equals(SecurityAlgorithms.RsaOAEP, StringComparison.Ordinal) || algorithm.Equals(SecurityAlgorithms.RsaOaepKeyWrap, StringComparison.Ordinal))
                        ? RSAEncryptionPadding.OaepSHA1
                        : RSAEncryptionPadding.Pkcs1;
            RSA = rsa;
            SignatureFunction = SignWithRsa;
            VerifyFunction    = VerifyWithRsa;
#endif
        }
示例#14
0
 private void InitializeUsingEcdsaSecurityKey(ECDsaSecurityKey ecdsaSecurityKey)
 {
     ECDsaSecurityKey  = ecdsaSecurityKey;
     SignatureFunction = SignWithECDsa;
     VerifyFunction    = VerifyWithECDsa;
 }
示例#15
0
        // concat onli return new value TODO check
        static BigInteger DeterministicGenerateK(Curve curve, byte[] hash, BigInteger d, SignDelegate checkSign, uint nonce)
        {
            if (nonce > 0)
            {
                hash = SHA256.Create().HashAndDispose(hash.Concat(new byte[nonce]));
            }
            Assert.Equal(hash.Length, 32, "Hash must be 256 bit");

            var x     = d.ToBuffer(32);
            var key   = new byte[32].Fill(( byte )0);
            var value = new byte[32].Fill(( byte )1);

            // Step D
            key = new HMACSHA256(key).HashAndDispose(value.Add(( byte )0).Concat(x, hash));

            // Step E
            value = new HMACSHA256(key).HashAndDispose(value);

            // Step F
            key = new HMACSHA256(key).HashAndDispose(value.Add(( byte )1).Concat(x, hash));

            // Step G
            value = new HMACSHA256(key).HashAndDispose(value);

            // Step H1/H2a, ignored as tlen == qlen (256 bit)
            // Step H2b
            value = new HMACSHA256(key).HashAndDispose(value);

            var t = BigInteger.FromBuffer(value);

            // Step H3, repeat until t is within the interval [1, n - 1]
            while ((t.Sign <= 0) || (t.CompareTo(curve.N) >= 0) || !checkSign(t))
            {
                key   = new HMACSHA256(key).HashAndDispose(value.Add(( byte )0));
                value = new HMACSHA256(key).HashAndDispose(value);

                // Step H1/H2a, again, ignored as tlen == qlen (256 bit)
                // Step H2b again
                value = new HMACSHA256(key).HashAndDispose(value);

                t = BigInteger.FromBuffer(value);
            }

            return(t);
        }
示例#16
0
 public void SetSignerCallback(SignDelegate signer)
 {
     SignerCallback = signer;
 }
示例#17
0
        /// <summary>
        /// Creates a new qryptext instance. <para> </para>
        /// Make sure to create one only once and cache it as needed, since loading the DLLs into memory can negatively affect the performance.
        /// <param name="sharedLibPathOverride">[OPTIONAL] Don't look for a <c>lib/</c> folder and directly use this path as a pre-resolved, platform-specific shared lib/DLL file path. Pass this if you want to manually handle the various platform's paths yourself.</param>
        /// </summary>
        public QryptextSharpContext(string sharedLibPathOverride = null)
        {
            string os;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                os        = "windows";
                loadUtils = new SharedLibLoadUtilsWindows();
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                os        = "linux";
                loadUtils = new SharedLibLoadUtilsLinux();
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                os        = "mac";
                loadUtils = new SharedLibLoadUtilsMac();
            }
            else
            {
                throw new PlatformNotSupportedException("Unsupported OS");
            }

            if (string.IsNullOrEmpty(sharedLibPathOverride))
            {
                StringBuilder pathBuilder = new StringBuilder(256);
                pathBuilder.Append("lib/");

                switch (RuntimeInformation.ProcessArchitecture)
                {
                case Architecture.X64:
                    pathBuilder.Append("x64/");
                    break;

                case Architecture.X86:
                    pathBuilder.Append("x86/");
                    break;

                case Architecture.Arm:
                    pathBuilder.Append("armeabi-v7a/");
                    break;

                case Architecture.Arm64:
                    pathBuilder.Append("arm64-v8a/");
                    break;
                }

                if (!Directory.Exists(pathBuilder.ToString()))
                {
                    throw new PlatformNotSupportedException($"Qryptext shared library not found in {pathBuilder} and/or unsupported CPU architecture. Please don't forget to copy the Qryptext shared libraries/DLL into the 'lib/{{CPU_ARCHITECTURE}}/{{OS}}/{{SHARED_LIB_FILE}}' folder of your output build directory.  https://github.com/GlitchedPolygons/qryptext/tree/master/csharp/lib/");
                }

                pathBuilder.Append(os);
                pathBuilder.Append('/');

                string[] l = Directory.GetFiles(pathBuilder.ToString());
                if (l == null || l.Length != 1)
                {
                    throw new FileLoadException("There should only be exactly one shared library file per supported platform!");
                }

                pathBuilder.Append(Path.GetFileName(l[0]));
                LoadedLibraryPath = Path.GetFullPath(pathBuilder.ToString());
                pathBuilder.Clear();
            }
            else
            {
                LoadedLibraryPath = sharedLibPathOverride;
            }

            lib = loadUtils.LoadLibrary(LoadedLibraryPath);
            if (lib == IntPtr.Zero)
            {
                goto hell;
            }


            IntPtr enableFprintf = loadUtils.GetProcAddress(lib, "qryptext_enable_fprintf");

            if (enableFprintf == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr disableFprintf = loadUtils.GetProcAddress(lib, "qryptext_disable_fprintf");

            if (disableFprintf == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr isFprintfEnabled = loadUtils.GetProcAddress(lib, "qryptext_is_fprintf_enabled");

            if (isFprintfEnabled == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr getVersionNumber = loadUtils.GetProcAddress(lib, "qryptext_get_version_number");

            if (getVersionNumber == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr getVersionNumberString = loadUtils.GetProcAddress(lib, "qryptext_get_version_number_string");

            if (getVersionNumberString == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr devUrandom = loadUtils.GetProcAddress(lib, "qryptext_dev_urandom");

            if (devUrandom == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr calcEncryptionOutputLength = loadUtils.GetProcAddress(lib, "qryptext_calc_encryption_output_length");

            if (calcEncryptionOutputLength == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr calcBase64Length = loadUtils.GetProcAddress(lib, "qryptext_calc_base64_length");

            if (calcBase64Length == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr genKyber1K = loadUtils.GetProcAddress(lib, "qryptext_kyber1024_generate_keypair");

            if (genKyber1K == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr genFalcon1K = loadUtils.GetProcAddress(lib, "qryptext_falcon1024_generate_keypair");

            if (genFalcon1K == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr encrypt = loadUtils.GetProcAddress(lib, "qryptext_encrypt");

            if (encrypt == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr decrypt = loadUtils.GetProcAddress(lib, "qryptext_decrypt");

            if (decrypt == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr sign = loadUtils.GetProcAddress(lib, "qryptext_sign");

            if (sign == IntPtr.Zero)
            {
                goto hell;
            }

            IntPtr verify = loadUtils.GetProcAddress(lib, "qryptext_verify");

            if (verify == IntPtr.Zero)
            {
                goto hell;
            }

            enableFprintfDelegate              = Marshal.GetDelegateForFunctionPointer <EnableFprintfDelegate>(enableFprintf);
            disableFprintfDelegate             = Marshal.GetDelegateForFunctionPointer <DisableFprintfDelegate>(disableFprintf);
            isFprintfEnabledDelegate           = Marshal.GetDelegateForFunctionPointer <IsFprintfEnabledDelegate>(isFprintfEnabled);
            getVersionNumberDelegate           = Marshal.GetDelegateForFunctionPointer <GetVersionNumberDelegate>(getVersionNumber);
            getVersionNumberStringDelegate     = Marshal.GetDelegateForFunctionPointer <GetVersionNumberStringDelegate>(getVersionNumberString);
            devUrandomDelegate                 = Marshal.GetDelegateForFunctionPointer <DevUrandomDelegate>(devUrandom);
            calcEncryptionOutputLengthDelegate = Marshal.GetDelegateForFunctionPointer <CalcEncryptionOutputLengthDelegate>(calcEncryptionOutputLength);
            calcBase64LengthDelegate           = Marshal.GetDelegateForFunctionPointer <CalcBase64LengthDelegate>(calcBase64Length);
            generateKyber1024KeyPairDelegate   = Marshal.GetDelegateForFunctionPointer <GenerateKyber1024KeyPairDelegate>(genKyber1K);
            generateFalcon1024KeyPairDelegate  = Marshal.GetDelegateForFunctionPointer <GenerateFalcon1024KeyPairDelegate>(genFalcon1K);
            encryptDelegate = Marshal.GetDelegateForFunctionPointer <EncryptDelegate>(encrypt);
            decryptDelegate = Marshal.GetDelegateForFunctionPointer <DecryptDelegate>(decrypt);
            signDelegate    = Marshal.GetDelegateForFunctionPointer <SignDelegate>(sign);
            verifyDelegate  = Marshal.GetDelegateForFunctionPointer <VerifyDelegate>(verify);

            return;

hell:
            throw new Exception($"Failed to load one or more functions from the shared library \"{LoadedLibraryPath}\"!");
        }
示例#18
0
        //Transfer NEP-5 Asset
        public static Transaction CreateNep5Transfer(SignDelegate sign)
        {
            var from    = "AS8UDW7aLhrywLVHFL3ny5tSBaVhWTeZjT".ToScriptHash();
            var assetId = new UInt160("ceab719b8baa2310f232ee0d277c061704541cfb".HexToBytes().Reverse().ToArray());
            var to      = "AS8UDW7aLhrywLVHFL3ny5tSBaVhWTeZjT".ToScriptHash();
            var value   = 100;

            //交易输入是 1 GAS
            var inputs = new List <CoinReference> {
                //coin reference A
                new CoinReference()
                {
                    PrevHash  = new UInt256("0x51ac4f7f1662d8c9379ccce3fa7cd2085b9a865edfa53ad892352a41768dd1de".Remove(0, 2).HexToBytes().Reverse().ToArray()),
                    PrevIndex = 0
                }
            }.ToArray();
            //交易输出是 0.999 GAS,找回到原地址
            var outputs = new List <TransactionOutput> {
                new TransactionOutput()
                {
                    AssetId    = Blockchain.UtilityToken.Hash,                        //Asset Id, this is NEO
                    ScriptHash = "AJd31a8rYPEBkY1QSxpsGy8mdU4vTYTD4U".ToScriptHash(), //Receiver
                    Value      = new Fixed8((long)(0.999 * (long)Math.Pow(10, 8)))    //Value (satoshi unit)
                }
            }.ToArray();

            //则手续费是 0.001 GAS

            //Query Balances
            using (ScriptBuilder sb2 = new ScriptBuilder())
            {
                byte[] script;
                sb2.EmitAppCall(assetId, "balanceOf", from);
                sb2.Emit(OpCode.DEPTH, OpCode.PACK);
                script = sb2.ToArray();
                ApplicationEngine engine = ApplicationEngine.Run(script);
                if (engine.State.HasFlag(VMState.FAULT))
                {
                    return(null);
                }
                var        balances = ((VMArray)engine.ResultStack.Pop())[0];
                BigInteger sum      = balances.GetBigInteger();
                if (sum < value)
                {
                    Console.WriteLine("Insufficient balance");
                    return(null);
                }
            }

            //Transfer
            using (ScriptBuilder sb = new ScriptBuilder())
            {
                sb.EmitAppCall(assetId, "transfer", from, to, value);
                sb.Emit(OpCode.THROWIFNOT);

                byte[] nonce = new byte[8];
                Random rand  = new Random();
                rand.NextBytes(nonce);
                sb.Emit(OpCode.RET, nonce);
                var tx = new InvocationTransaction
                {
                    Version    = 1,
                    Script     = sb.ToArray(),
                    Outputs    = outputs,
                    Inputs     = inputs,
                    Attributes = new TransactionAttribute[0],
                    Witnesses  = new Witness[0]
                };
                return(sign.Invoke(tx));
            }
        }
示例#19
0
        private void InitializeUsingRsa(RSA rsa, string algorithm)
        {
            // The return value for X509Certificate2.GetPrivateKey OR X509Certificate2.GetPublicKey.Key is a RSACryptoServiceProvider
            // These calls return an AsymmetricAlgorithm which doesn't have API's to do much and need to be cast.
            // RSACryptoServiceProvider is wrapped with RSACryptoServiceProviderProxy as some CryptoServideProviders (CSP's) do
            // not natively support SHA2.
#if DESKTOP
            if (rsa is RSACryptoServiceProvider rsaCryptoServiceProvider)
            {
                _useRSAOeapPadding = algorithm.Equals(SecurityAlgorithms.RsaOAEP) ||
                                     algorithm.Equals(SecurityAlgorithms.RsaOaepKeyWrap);

                RsaCryptoServiceProviderProxy = new RSACryptoServiceProviderProxy(rsaCryptoServiceProvider);
                DecryptFunction   = DecryptWithRsaCryptoServiceProviderProxy;
                EncryptFunction   = EncryptWithRsaCryptoServiceProviderProxy;
                SignatureFunction = SignWithRsaCryptoServiceProviderProxy;
                VerifyFunction    = VerifyWithRsaCryptoServiceProviderProxy;

                // RSACryptoServiceProviderProxy will track if a new RSA object is created and dispose appropriately.
                _disposeCryptoOperators = true;
                return;
            }
#endif

#if NET45
            // This case required the user to get a RSA object by calling
            // X509Certificate2.GetRSAPrivateKey() OR X509Certificate2.GetRSAPublicKey()
            // This requires 4.6+ to be installed. If a dependent library is targeting 4.5, 4.5.1, 4.5.2 or 4.6
            // they will bind to our Net45 target, but the type is RSACng.
            // The 'lightup' code will bind to the correct operators.
            else if (rsa.GetType().ToString().Equals(_rsaCngTypeName) && IsRsaCngSupported())
            {
                _useRSAOeapPadding = algorithm.Equals(SecurityAlgorithms.RsaOAEP) ||
                                     algorithm.Equals(SecurityAlgorithms.RsaOaepKeyWrap);

                _lightUpHashAlgorithmName = GetLightUpHashAlgorithmName();
                DecryptFunction           = DecryptNet45;
                EncryptFunction           = EncryptNet45;
                SignatureFunction         = Pkcs1SignData;
                VerifyFunction            = Pkcs1VerifyData;
                RSA = rsa;
                return;
            }
            else
            {
                // In NET45 we only support RSACryptoServiceProvider or "System.Security.Cryptography.RSACng"
                throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10687, LogHelper.MarkAsNonPII(typeof(RSACryptoServiceProvider).ToString()), LogHelper.MarkAsNonPII(_rsaCngTypeName), LogHelper.MarkAsNonPII(rsa.GetType().ToString()))));
            }
#endif

#if NET461 || NET472 || NETSTANDARD2_0
            if (algorithm.Equals(SecurityAlgorithms.RsaSsaPssSha256) ||
                algorithm.Equals(SecurityAlgorithms.RsaSsaPssSha256Signature) ||
                algorithm.Equals(SecurityAlgorithms.RsaSsaPssSha384) ||
                algorithm.Equals(SecurityAlgorithms.RsaSsaPssSha384Signature) ||
                algorithm.Equals(SecurityAlgorithms.RsaSsaPssSha512) ||
                algorithm.Equals(SecurityAlgorithms.RsaSsaPssSha512Signature))
            {
                RSASignaturePadding = RSASignaturePadding.Pss;
            }
            else
            {
                // default RSASignaturePadding for other supported RSA algorithms is Pkcs1
                RSASignaturePadding = RSASignaturePadding.Pkcs1;
            }

            RSAEncryptionPadding = (algorithm.Equals(SecurityAlgorithms.RsaOAEP) || algorithm.Equals(SecurityAlgorithms.RsaOaepKeyWrap))
                        ? RSAEncryptionPadding.OaepSHA1
                        : RSAEncryptionPadding.Pkcs1;
            RSA               = rsa;
            DecryptFunction   = DecryptWithRsa;
            EncryptFunction   = EncryptWithRsa;
            SignatureFunction = SignWithRsa;
            VerifyFunction    = VerifyWithRsa;
#endif
        }
示例#20
0
 public void SetSignerCallback(SignDelegate signer)
 {
     SignerCallback = signer;
 }