예제 #1
0
 private static void CheckHeader(SignatureHeader header, SignatureKind expectedKind)
 {
     if (header.Kind != expectedKind)
     {
         throw new BadImageFormatException(SR.Format(SR.UnexpectedSignatureHeader, expectedKind, header.Kind, header.RawValue));
     }
 }
예제 #2
0
 private void CheckHeader(SignatureHeader header, SignatureKind expectedKind)
 {
     if (header.Kind != expectedKind)
     {
         throw new BadImageFormatException(StarkPlatform.Reflection.Resources.SR.Format(SR.UnexpectedSignatureHeader, expectedKind, header.Kind, header.RawValue));
     }
 }
예제 #3
0
        private static void CheckMethodOrPropertyHeader(SignatureHeader header)
        {
            SignatureKind kind = header.Kind;

            if (kind != SignatureKind.Method && kind != SignatureKind.Property)
            {
                throw new BadImageFormatException(SR.Format(SR.UnexpectedSignatureHeader2, SignatureKind.Property, SignatureKind.Method, header.Kind, header.RawValue));
            }
        }
예제 #4
0
        private void CheckMethodOrPropertyHeader(SignatureHeader header)
        {
            SignatureKind kind = header.Kind;

            if (kind != SignatureKind.Method && kind != SignatureKind.Property)
            {
                throw new BadImageFormatException(StarkPlatform.Reflection.Resources.SR.Format(SR.UnexpectedSignatureHeader2, SignatureKind.Property, SignatureKind.Method, header.Kind, header.RawValue));
            }
        }
예제 #5
0
        private void CheckHeader(SignatureHeader header, SignatureKind expectedKind)
        {
            if (header.Kind != expectedKind)
            {
#if SRM
                throw new BadImageFormatException(SR.Format(SR.UnexpectedSignatureHeader, expectedKind, header.Kind, header.RawValue));
#else
                throw new BadImageFormatException();
#endif
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="FunctionSignatureBuilder" /> class.
 /// </summary>
 /// <param name="functionSignature">The signature.</param>
 public FunctionSignatureBuilder([NotNull] Function functionSignature)
 {
     _newName                  = functionSignature.Name;
     _newNativeEntrypoint      = functionSignature.NativeName;
     _newCategory              = functionSignature.Categories;
     _newExtension             = functionSignature.ExtensionName;
     _newAttributes            = functionSignature.Attributes;
     _newParameters            = functionSignature.Parameters;
     _newReturnType            = functionSignature.ReturnType;
     _newGenericTypeParameters = functionSignature.GenericTypeParameters;
     _newDoc           = functionSignature.Doc;
     _newAccessibility = functionSignature.Accessibility;
     _newKind          = functionSignature.Kind;
 }
예제 #7
0
        internal unsafe Signature(AsnEncodedData data, SignatureKind kind)
        {
            Kind = kind;
            fixed(byte *pin = data.RawData)
            {
                EncodingType          encodingType;
                CryptQueryContentType contentType;
                CryptQueryFormatType  formatType;
                CryptMsgSafeHandle    msgHandle;
                var blob = new CRYPTOAPI_BLOB
                {
                    cbData = (uint)data.RawData.Length,
                    pbData = new IntPtr(pin)
                };
                var result = Crypt32.CryptQueryObject(
                    CryptQueryObjectType.CERT_QUERY_OBJECT_BLOB,
                    ref blob,
                    CryptQueryContentFlagType.CERT_QUERY_CONTENT_FLAG_ALL,
                    CryptQueryFormatFlagType.CERT_QUERY_FORMAT_FLAG_BINARY,
                    CryptQueryObjectFlags.NONE,
                    out encodingType,
                    out contentType,
                    out formatType,
                    IntPtr.Zero,
                    out msgHandle,
                    IntPtr.Zero);

                if (!result)
                {
                    msgHandle.Dispose();
                    throw new InvalidOperationException("Unable to read signature.");
                }
                var signerSize = 0u;

                if (!Crypt32.CryptMsgGetParam(msgHandle, CryptMsgParamType.CMSG_SIGNER_INFO_PARAM, 0, LocalBufferSafeHandle.Zero, ref signerSize))
                {
                    throw new InvalidOperationException();
                }
                using (var signerHandle = LocalBufferSafeHandle.Alloc(signerSize))
                {
                    if (!Crypt32.CryptMsgGetParam(msgHandle, CryptMsgParamType.CMSG_SIGNER_INFO_PARAM, 0, signerHandle, ref signerSize))
                    {
                        throw new InvalidOperationException();
                    }
                    InitFromHandles(msgHandle, signerHandle);
                }
            }
        }
        public static IEnumerable <ISignature> VisitAll(this ISignature signature, SignatureKind kind)
        {
            foreach (var nested in signature.GetNestedSignatures())
            {
                if ((nested.Kind & kind) > 0)
                {
                    yield return(nested);

                    foreach (var nestVisit in nested.VisitAll(kind))
                    {
                        yield return(nestVisit);
                    }
                }
                else if ((kind & SignatureKind.Deep) == SignatureKind.Deep)
                {
                    foreach (var nestVisit in nested.VisitAll(kind))
                    {
                        yield return(nestVisit);
                    }
                }
            }
        }
예제 #9
0
        public static void WriteSignature(this BinaryWriter writer, Signature signature)
        {
            SignatureKind kind = signature != null ? signature.Kind : SignatureKind.None;

            writer.Write((byte)kind);

            switch (signature.Kind)
            {
            case SignatureKind.Ed25519:
                writer.WriteByteArray(((Ed25519Signature)signature).Bytes);
                break;

            case SignatureKind.Ring:
                var rs = (RingSignature)signature;
                writer.WriteBigInteger(rs.Y0);
                writer.WriteBigInteger(rs.S);
                writer.WriteVarInt(rs.C.Length);
                foreach (var entry in rs.C)
                {
                    writer.WriteBigInteger(entry);
                }
                break;
            }
        }
예제 #10
0
        private static unsafe Entry CacheMiss(IntPtr context, IntPtr signature, SignatureKind signatureKind = SignatureKind.GenericDictionary, object contextObject = null)
        {
            IntPtr result = IntPtr.Zero, auxResult = IntPtr.Zero;
            bool   previouslyCached = false;

            //
            // Try to find the entry in the previous version of the cache that is kept alive by weak reference
            //
            if (s_previousCache.IsAllocated)
            {
                Entry[] previousCache = (Entry[])s_previousCache.Target;
                if (previousCache != null)
                {
                    Entry previousEntry = LookupInCache(previousCache, context, signature);
                    if (previousEntry != null)
                    {
                        result           = previousEntry.Result;
                        auxResult        = previousEntry.AuxResult;
                        previouslyCached = true;
                    }
                }
            }

            //
            // Call into the type loader to compute the target
            //
            if (!previouslyCached)
            {
                switch (signatureKind)
                {
                case SignatureKind.GenericDictionary:
                    result = RuntimeAugments.TypeLoaderCallbacks.GenericLookupFromContextAndSignature(context, signature, out auxResult);
                    break;

                case SignatureKind.GenericVirtualMethod:
                    result = Internal.Runtime.CompilerServices.GenericVirtualMethodSupport.GVMLookupForSlot(new RuntimeTypeHandle(new EETypePtr(context)), *(RuntimeMethodHandle *)&signature);
                    break;

                case SignatureKind.OpenInstanceResolver:
                    result = Internal.Runtime.CompilerServices.OpenMethodResolver.ResolveMethodWorker(signature, contextObject);
                    break;

                case SignatureKind.DefaultConstructor:
                {
                    result = RuntimeAugments.TypeLoaderCallbacks.TryGetDefaultConstructorForType(new RuntimeTypeHandle(new EETypePtr(context)));
                    if (result == IntPtr.Zero)
                    {
                        result = RuntimeAugments.GetFallbackDefaultConstructor();
                    }
                }
                break;

                case SignatureKind.GenericDelegateThunk:
                    result = RuntimeAugments.TypeLoaderCallbacks.GetDelegateThunk((Delegate)contextObject, (int)signature);
                    break;

                default:
                    result = RawCalliHelper.Call <IntPtr>(s_resolutionFunctionPointers[(int)signatureKind], context, signature, contextObject, out auxResult);
                    break;
                }
            }

            //
            // Update the cache under the lock
            //
            if (s_lock == null)
            {
                Interlocked.CompareExchange(ref s_lock, new Lock(), null);
            }

            s_lock.Acquire();
            try
            {
                // Avoid duplicate entries
                Entry existingEntry = LookupInCache(s_cache, context, signature);
                if (existingEntry != null)
                {
                    return(existingEntry);
                }

                // Resize cache as necessary
                Entry[] cache = ResizeCacheForNewEntryAsNecessary();

                int key = ((context.GetHashCode() >> 4) ^ signature.GetHashCode()) & (cache.Length - 1);

                Entry newEntry = new Entry()
                {
                    Context = context, Signature = signature, Result = result, AuxResult = auxResult, Next = cache[key]
                };
                cache[key] = newEntry;
                return(newEntry);
            }
            finally
            {
                s_lock.Release();
            }
        }
예제 #11
0
 // TOOD: add ctor to SignatureHeader
 internal static SignatureHeader SignatureHeader(SignatureKind kind, SignatureCallingConvention convention, SignatureAttributes attributes)
 {
     return new SignatureHeader((byte)((int)kind | (int)convention | (int)attributes));
 }
예제 #12
0
        internal static IEnumerable <ICmsSignature> VisitAll(this ICmsSignature signature, SignatureKind kind, bool deep)
        {
            foreach (var nested in signature.GetNestedSignatures())
            {
                if ((nested.Kind & kind) > 0)
                {
                    yield return(nested);

                    foreach (var nestVisit in nested.VisitAll(kind, deep))
                    {
                        yield return(nestVisit);
                    }
                }
                else if (deep)
                {
                    foreach (var nestVisit in nested.VisitAll(kind, deep))
                    {
                        yield return(nestVisit);
                    }
                }
            }
        }
예제 #13
0
 internal static IEnumerable <ICmsSignature> VisitAll(this IReadOnlyList <ICmsSignature> signatures, SignatureKind kind, bool deep)
 {
     foreach (var signature in signatures)
     {
         if ((signature.Kind & kind) > 0)
         {
             yield return(signature);
         }
         foreach (var nested in VisitAll(signature, kind, deep))
         {
             yield return(nested);
         }
     }
 }
예제 #14
0
 internal Signature(SignatureKind kind, CryptMsgSafeHandle messageHandle, LocalBufferSafeHandle signerHandle)
 {
     Kind = kind;
     InitFromHandles(messageHandle, signerHandle);
 }
예제 #15
0
 public SignatureHeader(SignatureKind kind, SignatureCallingConvention convention, SignatureAttributes attributes)
     : this((byte)((int)kind | (int)convention | (int)attributes))
 {
 }
예제 #16
0
    /// <summary>
    /// To signed some type of data
    /// </summary>
    /// <param name="data">String with the data you want to sign</param>
    /// <param name="callback"></param>
    /// <param name="platform"></param>
    /// <param name="signature"></param>
    public void SignData(string data, Action <bool, string, string, string> callback = null, PlatformKind platform = PlatformKind.Phantasma, SignatureKind signature = SignatureKind.Ed25519)
    {
        if (!Enabled)
        {
            callback(true, "not logged in", "", "");
            return;
        }
        if (data == null)
        {
            callback(true, "invalid data, sorry :(", "", "");
            return;
        }
        if (data.Length >= 1024)
        {
            callback(true, "data too big, sorry :(", "", "");
            return;
        }

        var dataConverted = Base16.Encode(Encoding.UTF8.GetBytes(data));

        SendLinkRequest($"signData/{dataConverted}/{signature}/{platform}", (result) => {
            var success = result.GetBool("success");
            if (success)
            {
                var random     = result.GetString("random");
                var signedData = result.GetString("signature");
                callback?.Invoke(false, signedData, random, dataConverted);
            }
            else
            {
                var msg = result.GetString("message");
                callback?.Invoke(true, "transaction rejected: " + msg, "", "");
            }
        });
    }
예제 #17
0
    /// <summary>
    /// Send Transaction.
    /// </summary>
    /// <param name="chain"></param>
    /// <param name="script"></param>
    /// <param name="payload"></param>
    /// <param name="callback"></param>
    public void SendTransaction(string chain, byte[] script, byte[] payload, Action <Hash, string> callback = null, PlatformKind platform = PlatformKind.Phantasma, SignatureKind signature = SignatureKind.Ed25519)
    {
        SetMessage("Relaying transaction...");

        if (script.Length >= 8192)
        {
            callback(Hash.Null, "script too big");
            return;
        }

        var hexScript  = Base16.Encode(script);
        var hexPayload = payload != null && payload.Length > 0 ? Base16.Encode(payload) : ""; // is empty string for payload ok?
        var requestStr = $"{chain}/{hexScript}/{hexPayload}";

        if (Version >= 2)
        {
            requestStr = $"{requestStr}/{signature}/{platform}";
        }
        else
        {
            requestStr = $"{this.Nexus}/{requestStr}";
        }

        SendLinkRequest($"signTx/{requestStr}", (result) =>
        {
            var success = result.GetBool("success");
            if (success)
            {
                var hashStr = result.GetString("hash");
                var hash    = Hash.Parse(hashStr);
                callback?.Invoke(hash, null);
            }
            else
            {
                var msg = result.GetString("message");
                callback?.Invoke(Hash.Null, "transaction rejected: " + msg);
            }
        });
    }
예제 #18
0
        protected override void SignTransaction(string platform, SignatureKind kind, string chain, byte[] script, byte[] payload, int id, Action <Hash, string> callback)
        {
            var accountManager = AccountManager.Instance;

            var targetPlatform = RequestPlatform(platform);

            if (targetPlatform == PlatformKind.None)
            {
                callback(Hash.Null, "Unsupported platform: " + platform);
                return;
            }

            var state = AccountManager.Instance.CurrentState;

            if (state == null)
            {
                callback(Hash.Null, "not logged in");
                return;
            }

            var nexus   = AccountManager.Instance.Settings.nexusName;
            var account = AccountManager.Instance.CurrentAccount;

            WalletGUI.Instance.CallOnUIThread(() =>
            {
                try
                {
                    WalletGUI.Instance.StartCoroutine(DescriptionUtils.GetDescription(script, (description, error) => {
                        if (description == null)
                        {
                            WalletGUI.Instance.MessageBox(MessageKind.Error, "Error during description parsing.\nContact the developers.\nDetails: " + error);
                            callback(Hash.Null, "description parsing error");
                            return;
                        }

                        WalletGUI.Instance.Prompt("Allow dapp to send a transaction on your behalf?\n" + description, (success) =>
                        {
                            if (success)
                            {
                                WalletGUI.Instance.SendTransaction(description, script, payload, chain, ProofOfWork.None, (hash) =>
                                {
                                    AppFocus.Instance.EndFocus();

                                    if (hash != Hash.Null)
                                    {
                                        callback(hash, null);
                                    }
                                    else
                                    {
                                        callback(Hash.Null, "something bad happend while sending");
                                    }
                                });
                            }
                            else
                            {
                                AppFocus.Instance.EndFocus();
                                callback(Hash.Null, "user rejected");
                            }
                        });
                    }));
                }
                catch (Exception e)
                {
                    WalletGUI.Instance.MessageBox(MessageKind.Error, "Error during description parsing.\nContact the developers.\nDetails: " + e.Message);
                    callback(Hash.Null, "description parsing error");
                    return;
                }
            });
        }
 public static IEnumerable <ISignature> VisitAll(this IReadOnlyList <ISignature> signatures, SignatureKind kind)
 {
     foreach (var signature in signatures)
     {
         if ((signature.Kind & kind) > 0)
         {
             yield return(signature);
         }
         foreach (var nested in VisitAll(signature, kind))
         {
             yield return(nested);
         }
     }
 }
예제 #20
0
        protected override void SignData(string platform, SignatureKind kind, byte[] data, int id, Action <string, string, string> callback)
        {
            var accountManager = AccountManager.Instance;

            var targetPlatform = RequestPlatform(platform);

            if (targetPlatform == PlatformKind.None)
            {
                callback(null, null, "Unsupported platform: " + platform);
                return;
            }

            var state = AccountManager.Instance.CurrentState;

            if (state == null)
            {
                callback(null, null, "not logged in");
                return;
            }

            if (kind != SignatureKind.Ed25519)
            {
                callback(null, null, kind + " signatures unsupported");
                return;
            }

            var account = AccountManager.Instance.CurrentAccount;

            WalletGUI.Instance.CallOnUIThread(() =>
            {
                var description = System.Text.Encoding.UTF8.GetString(data);

                WalletGUI.Instance.Prompt("The dapp wants to sign the following data. Accept?\n" + description, (success) =>
                {
                    AppFocus.Instance.EndFocus();

                    if (success)
                    {
                        var phantasmaKeys = PhantasmaKeys.FromWIF(account.GetWif(AccountManager.Instance.CurrentPasswordHash));

                        var randomValue = UnityEngine.Random.Range(0, int.MaxValue);
                        var randomBytes = BitConverter.GetBytes(randomValue);

                        var msg       = ByteArrayUtils.ConcatBytes(randomBytes, data);
                        var signature = phantasmaKeys.Sign(msg);

                        byte[] sigBytes = null;

                        using (var stream = new MemoryStream())
                        {
                            using (var writer = new BinaryWriter(stream))
                            {
                                writer.WriteSignature(signature);
                            }

                            sigBytes = stream.ToArray();
                        }

                        var hexSig  = Base16.Encode(sigBytes);
                        var hexRand = Base16.Encode(randomBytes);

                        callback(hexSig, hexRand, null);
                    }
                    else
                    {
                        callback(null, null, "user rejected");
                    }
                });
            });
        }
예제 #21
0
 void ISymbolDisplayBuilder.BuildSignatureDisplay(ISignature signatures, ISymbolWriter writer, INode enclosingDeclaration, TypeFormatFlags flags, SignatureKind kind)
 {
     BuildSignatureDisplay(signatures, writer, enclosingDeclaration, flags, kind, symbolStack: null);
 }
예제 #22
0
 // NOTE for security, signData should not be usable as a way of signing transaction. That way the wallet is responsible for appending random bytes to the message, and return those in callback
 protected abstract void SignData(byte[] data, SignatureKind kind, int id, Action <string, string, string> callback);
 /// <summary>
 /// Sets a new function signature kind.
 /// </summary>
 /// <param name="kind">The new signature kind.</param>
 /// <returns>The builder, with the change applied.</returns>
 public FunctionSignatureBuilder WithKind(SignatureKind kind)
 {
     _newKind = kind;
     return(this);
 }
예제 #24
0
 // TOOD: add ctor to SignatureHeader
 internal static SignatureHeader SignatureHeader(SignatureKind kind, SignatureCallingConvention convention, SignatureAttributes attributes)
 {
     return(new SignatureHeader((byte)((int)kind | (int)convention | (int)attributes)));
 }
예제 #25
0
 protected abstract void SignTransaction(string platform, SignatureKind kind, string chain, byte[] script, byte[] payload, int id, Action <Hash, string> callback);