public static void Main(string[] args)
		{
			// Notes:
			// 1. All referenced assemblies shall
			//    define [assembly:Obfuscation(feature = "script")]
			// 2. Turn off "optimize code" option in release build
			// 3. All used .net APIs must be defined by ScriptCoreLibJava
			// 4. Generics are not supported.
			// 5. Check post build event
			// 6. Build in releas build configuration for java version

			Console.WriteLine("This console application can run at .net and java virtual machine!");

			var port = 18080;

			Console.WriteLine("http://127.0.0.1:" + port);


			port.ToListener(
				s =>
				{
					var request = new byte[0x1000];
					var requestc = s.Read(request, 0, request.Length);

					// StreamReader would be nice huh
					// ScriptCoreLibJava does not have it yet

					Console.WriteLine("client request " + requestc);

					// if we get the file name wrong we get a bad error message to stdout
					var data = File.ReadAllBytes("HTMLPage1.htm");
					Console.WriteLine("data length " + data.Length);

					var m = new MemoryStream();

					m.WriteLineASCII("HTTP/1.1 200 OK");
					m.WriteLineASCII("Content-Type:	text/html; charset=utf-8");
					m.WriteLineASCII("Content-Length: " + data.Length);
					m.WriteLineASCII("Connection: close");


					m.WriteLineASCII("");
					m.WriteLineASCII("");
					Console.WriteLine("headers written");

					m.WriteBytes(data);
					Console.WriteLine("data written");

					var Text = Encoding.ASCII.GetString(m.ToArray());
					m.WriteTo(s);
					Console.WriteLine("flush");

					s.Flush();
					s.Close();
				}
			);

			Console.WriteLine("press enter to exit!");
			Console.ReadLine();
		}
Beispiel #2
0
        public static byte[] SerializeCoinbase(IJob job, UInt32 extraNonce1, UInt32 extraNonce2)
        {
            var extraNonce1Buffer = BitConverter.GetBytes(extraNonce1.BigEndian());
            var extraNonce2Buffer = BitConverter.GetBytes(extraNonce2.BigEndian());

            byte[] result;

            using (var stream = new MemoryStream())
            {
                stream.WriteBytes(job.CoinbaseInitial.HexToByteArray());
                stream.WriteBytes(extraNonce1Buffer);
                stream.WriteBytes(extraNonce2Buffer);
                stream.WriteBytes(job.CoinbaseFinal.HexToByteArray());

                result = stream.ToArray();
            }

            return result;
        }
Beispiel #3
0
        public byte[] CompressChunk(Chunk chunk)
        {
            int numBlocks = (chunk.Uncompressed.Length + maxBlockSize - 1) / maxBlockSize;
            if (numBlocks > 8)
                throw new FormatException("Maximum block number exceeded");
            ChunkHeader head = new ChunkHeader();
            head.magic = -1641380927;
            head.blocksize = maxBlockSize;
            head.uncompressedsize = chunk.Uncompressed.Length;
            int pos = 0;
            MemoryStream mem = new MemoryStream();
            List<Block> blockList = new List<Block>();
            int startData = 16 + 8 * numBlocks;
            mem.Seek(startData, SeekOrigin.Begin);
            for (int i = 0; i < numBlocks; i++)
            {
                Block block = new Block();
                byte[] result, temp;
                if (i != numBlocks - 1)
                {
                    block.uncompressedsize = maxBlockSize;
                    temp = new byte[maxBlockSize];
                }
                else
                {
                    block.uncompressedsize = head.uncompressedsize - pos;
                    temp = new byte[block.uncompressedsize];
                }

                Buffer.BlockCopy(chunk.Uncompressed, pos, temp, 0, temp.Length);
                result = LZO1X.Compress(temp);
                if (result.Length == 0)
                    throw new Exception("LZO compression error!");
                block.compressedsize = result.Length;
                mem.WriteBytes(result);
                blockList.Add(block);
                pos += maxBlockSize;
            }
            head.compressedsize = (int)mem.Length;

            mem.Seek(0, SeekOrigin.Begin);
            mem.WriteValueS32(head.magic);
            mem.WriteValueS32(head.blocksize);
            mem.WriteValueS32(head.compressedsize);
            mem.WriteValueS32(head.uncompressedsize);
            foreach (Block block in blockList)
            {
                mem.WriteValueS32(block.compressedsize);
                mem.WriteValueS32(block.uncompressedsize);
            }

            return mem.ToArray();
        }
        public SignatureScript(int blockHeight, string coinbaseAuxFlags, Int64 unixTime, byte extraNoncePlaceholder, string signature)
        {
            // cook input signature script.
            // The txin's prevout script is an arbitrary byte array (it doesn't have to be a valid script, though this is commonly
            // done anyway) of 2 to 100 bytes. It has to start with a correct push of the block height (see BIP34).

            var serializedBlockHeight = Serializers.SerializeNumber(blockHeight);
            var serializedUnixTime = TransactionUtils.GetSerializedUnixDateTime(unixTime);

            using (var stream = new MemoryStream())
            {
                stream.WriteBytes(serializedBlockHeight);
                stream.WriteBytes(coinbaseAuxFlags.HexToByteArray());
                stream.WriteBytes(serializedUnixTime);
                stream.WriteByte(extraNoncePlaceholder);

                Initial = stream.ToArray();
            }

            Final = Serializers.SerializeString(signature);
        }
Beispiel #5
0
        public IDATChunk ToIDATChunk()
        {
            uint newCrc;
            using (var msCrc = new MemoryStream())
            {
                msCrc.WriteBytes(new[] {(byte) 'I', (byte) 'D', (byte) 'A', (byte) 'T'});
                msCrc.WriteBytes(FrameData);

                newCrc = CrcHelper.Calculate(msCrc.ToArray());
            }

            using (var ms = new MemoryStream())
            {
                ms.WriteUInt32(Helper.ConvertEndian(Length - 4));
                ms.WriteBytes(new[] {(byte) 'I', (byte) 'D', (byte) 'A', (byte) 'T'});
                ms.WriteBytes(FrameData);
                ms.WriteUInt32(Helper.ConvertEndian(newCrc));
                ms.Position = 0;

                return new IDATChunk(ms);
            }
        }
Beispiel #6
0
        /// <summary>
        /// Block data structure.
        /// </summary>
        /// <remarks>
        /// https://en.bitcoin.it/wiki/Protocol_specification#block
        /// </remarks>
        /// <param name="job"></param>
        /// <param name="header"></param>
        /// <param name="coinbase"></param>
        /// <returns></returns>
        public static byte[] SerializeBlock(IJob job, byte[] header, byte[] coinbase)
        {
            byte[] result;

            using (var stream = new MemoryStream())
            {
                stream.WriteBytes(header);
                stream.WriteBytes(VarInt((UInt32)job.BlockTemplate.Transactions.Length + 1));
                stream.WriteBytes(coinbase);

                foreach (var transaction in job.BlockTemplate.Transactions)
                {
                    stream.WriteBytes(transaction.Data.HexToByteArray());
                }

                // need to implement POS support too.

                result = stream.ToArray();
            }

            return result;
        }
Beispiel #7
0
        /// <summary>
        ///     Gets the frame as PNG FileStream.
        /// </summary>
        public MemoryStream GetStream()
        {
            var ihdrChunk = new IHDRChunk(IHDRChunk);
            if (fcTLChunk != null)
            {
                // Fix frame size with fcTL data.
                ihdrChunk.ModifyChunkData(0, Helper.ConvertEndian(fcTLChunk.Width));
                ihdrChunk.ModifyChunkData(4, Helper.ConvertEndian(fcTLChunk.Height));
            }

            // Write image data
            using (var ms = new MemoryStream())
            {
                ms.WriteBytes(Signature);
                ms.WriteBytes(ihdrChunk.RawData);
                otherChunks.ForEach(o => ms.WriteBytes(o.RawData));
                idatChunks.ForEach(i => ms.WriteBytes(i.RawData));
                ms.WriteBytes(IENDChunk.RawData);

                ms.Position = 0;
                return ms;
            }
        }
Beispiel #8
0
        public NpgsqlExecute(String portalName, Int32 maxRows)
        {
            int messageLength = 4 + portalName.Length + 1 + 4;
            _messageData = new byte[messageLength + 1];
            MemoryStream messageBuilder = new MemoryStream(_messageData);

            _portalName = portalName;

            messageBuilder
                .WriteBytes((byte)FrontEndMessageCode.Execute)
                .WriteInt32(messageLength)
                .WriteStringNullTerminated(_portalName)
                .WriteInt32(maxRows);
        }
        /// <summary>
        /// Block data structure.
        /// </summary>
        /// <remarks>
        /// https://en.bitcoin.it/wiki/Protocol_specification#block
        /// </remarks>
        /// <param name="job"></param>
        /// <param name="header"></param>
        /// <param name="coinbase"></param>
        /// <param name="isProofOfStakeHybrid">Are we serializing a proof-of-stake coin block</param>
        /// <returns></returns>
        public static byte[] SerializeBlock(IJob job, byte[] header, byte[] coinbase, bool isProofOfStakeHybrid = false)
        {
            byte[] result;

            using (var stream = new MemoryStream())
            {
                stream.WriteBytes(header);
                stream.WriteBytes(VarInt((UInt32)job.BlockTemplate.Transactions.Length + 1));
                stream.WriteBytes(coinbase);

                foreach (var transaction in job.BlockTemplate.Transactions)
                {
                    stream.WriteBytes(transaction.Data.HexToByteArray());
                }

                if (isProofOfStakeHybrid) // check if we are serializing a block for proof-of-stake coin.
                    stream.WriteByte(0); // proof-of-stake coins require a zero byte appended to block which the daemon replaces with signature.

                result = stream.ToArray();
            }

            return result;
        }
Beispiel #10
0
        public NpgsqlQuery(byte[] command)
        {
            // Message length: Inr32 + command length + null terminator.
            int len = 4 + command.Length + 1;

            // Length + command code ('Q').
            pgCommandBytes = new byte[1 + len];

            MemoryStream commandWriter = new MemoryStream(pgCommandBytes);

            commandWriter
                .WriteBytes((byte)FrontEndMessageCode.Query)
                .WriteInt32(len)
                .WriteBytesNullTerminated(command);

            commandBytes = command;
        }
Beispiel #11
0
        public static void Split(Stream InputStream, byte[] Separator, Action<byte[]> ChunkHandler)
        {
            byte[] Buffer = new byte[4096];

            byte[] TempDoubleBuffer = new byte[Separator.Length * 2];

            MemoryStream Chunk = new MemoryStream();

            int StartIndex = Separator.Length;
            int SkipChunkStart = 0;

            while (!InputStream.Eof()) {
                Array.Copy(TempDoubleBuffer, Separator.Length, TempDoubleBuffer, 0, Separator.Length);
                int TempDoubleBufferReaded = InputStream.Read(TempDoubleBuffer, Separator.Length, Separator.Length);

                int EndIndex = Separator.Length + TempDoubleBufferReaded;

                Chunk.Write(TempDoubleBuffer, Separator.Length, TempDoubleBufferReaded);

                int FoundIndex = FindSequence(TempDoubleBuffer, Separator, StartIndex, EndIndex);
                if (FoundIndex != -1)
                {
                    int BytesToRemoveFromChunk = EndIndex - FoundIndex;
                    int RealChunkSize = (int)(Chunk.Length - BytesToRemoveFromChunk);

                    MemoryStream NewChunk = new MemoryStream();

                    NewChunk.WriteBytes(Chunk.ReadChunk(RealChunkSize, BytesToRemoveFromChunk));
                    ChunkHandler(Chunk.ReadChunk(SkipChunkStart, RealChunkSize - SkipChunkStart));

                    SkipChunkStart = Separator.Length;

                    Chunk = NewChunk;
                }
                StartIndex = 0;
            }

            if (Chunk.Length > 0)
            {
                ChunkHandler(Chunk.ReadChunk(SkipChunkStart, (int)Chunk.Length - SkipChunkStart));
            }
        }
Beispiel #12
0
        public byte[] GetBuffer()
        {
            byte[] result;

            using (var stream = new MemoryStream())
            {
                stream.WriteBytes(Serializers.VarInt((UInt32)List.Count).ToArray());

                foreach (var transaction in List)
                {
                    stream.WriteValueU64(transaction.Value);
                    stream.WriteBytes(transaction.PublicKeyScriptLenght);
                    stream.WriteBytes(transaction.PublicKeyScript);
                }

                result = stream.ToArray();
            }

            return result;
        }
Beispiel #13
0
        /// <summary>
        /// For POW coins - used to format wallet address for use in generation transaction's output
        /// </summary>
        /// <param name="address"></param>
        /// <example>
        /// nodejs: https://github.com/zone117x/node-stratum-pool/blob/dfad9e58c661174894d4ab625455bb5b7428881c/lib/util.js#L264
        /// nodejs: https://codio.com/raistlinthewiz/bitcoin-coinbase-serializer-wallet-address-to-script
        /// </example>
        /// <returns></returns>
        public static byte[] CoinAddressToScript(string address)
        {
            byte[] decoded;

            try
            {
                decoded = Base58.Decode(address);
            }
            catch (AddressFormatException)
            {
                Log.Error("Base58 decode failed for address {0:l}", address);
                return null;
            }

            if (decoded.Length != 25)
            {
                Log.Error("invalid address length for {0:l}", address);
                return null;
            }

            var pubkey = decoded.Slice(1, -4);

            byte[] result;

            using (var stream = new MemoryStream())
            {
                stream.WriteValueU8(0x76);
                stream.WriteValueU8(0xa9);
                stream.WriteValueU8(0x14);
                stream.WriteBytes(pubkey);
                stream.WriteValueU8(0x88);
                stream.WriteValueU8(0xac);

                result = stream.ToArray();
            }

            return result;
        }
Beispiel #14
0
        private bool processFragments(WsFrame first)
        {
            using (var concatenated = new MemoryStream ())
              {
            concatenated.WriteBytes (first.PayloadData.ApplicationData);
            if (!concatenateFragmentsInto (concatenated))
              return false;

            byte [] data;
            if (_compression != CompressionMethod.NONE)
            {
              data = concatenated.DecompressToArray (_compression);
            }
            else
            {
              concatenated.Close ();
              data = concatenated.ToArray ();
            }

            OnMessage.Emit (this, new MessageEventArgs (first.Opcode, data));
            return true;
              }
        }
        public void Create()
        {
            // create the first part.
            using (var stream = new MemoryStream())
            {
                stream.WriteValueU32(Version.LittleEndian()); // write version

                // for proof-of-stake coins we need here timestamp - https://github.com/zone117x/node-stratum-pool/blob/b24151729d77e0439e092fe3a1cdbba71ca5d12e/lib/transactions.js#L210

                // write transaction input.
                stream.WriteBytes(Serializers.VarInt(InputsCount));
                stream.WriteBytes(Inputs.First().PreviousOutput.Hash.Bytes);
                stream.WriteValueU32(Inputs.First().PreviousOutput.Index.LittleEndian());

                // write signature script lenght
                var signatureScriptLenght = (UInt32)(Inputs.First().SignatureScript.Initial.Length + ExtraNonce.ExtraNoncePlaceholder.Length + Inputs.First().SignatureScript.Final.Length);
                stream.WriteBytes(Serializers.VarInt(signatureScriptLenght).ToArray());

                stream.WriteBytes(Inputs.First().SignatureScript.Initial);

                Initial = stream.ToArray();
            }

            /*  The generation transaction must be split at the extranonce (which located in the transaction input
                scriptSig). Miners send us unique extranonces that we use to join the two parts in attempt to create
                a valid share and/or block. */

            // create the second part.
            using (var stream = new MemoryStream())
            {
                // transaction input
                stream.WriteBytes(Inputs.First().SignatureScript.Final);
                stream.WriteValueU32(Inputs.First().Sequence);
                // transaction inputs end here.

                // transaction output
                var outputBuffer = Outputs.GetBuffer();
                stream.WriteBytes(outputBuffer);
                // transaction output ends here.

                stream.WriteValueU32(LockTime.LittleEndian());

                if (SupportTxMessages)
                    stream.WriteBytes(Message);

                Final = stream.ToArray();
            }
        }
Beispiel #16
0
 private static byte[] ConstructPacket(string response, bool print)
 {
     var oob = new byte[] { 0xFF, 0xFF, 0xFF, 0xFF };
     using (var stream = new MemoryStream())
     {
         stream.WriteBytes(oob);
         if (print)
             stream.WriteBytes(Encoding.UTF8.GetBytes(string.Format("print\n{0}", response)));
         else
             stream.WriteBytes(Encoding.UTF8.GetBytes(response));
         var trimmedpacket = new byte[(int)stream.Length];
         var packet = stream.GetBuffer();
         Array.Copy(packet, trimmedpacket, (int)stream.Length);
         return trimmedpacket;
     }
 }
Beispiel #17
0
        public void replaceImage2(string strImgSize, ImageFile im, string archiveDir)
        {
            ImageSize imgSize = ImageSize.stringToSize(strImgSize);
            if (!privateimgList.Exists(img => img.imgSize == imgSize))
                throw new FileNotFoundException("Image with resolution " + imgSize + " isn't found");

            int imageIdx = privateimgList.FindIndex(img => img.imgSize == imgSize);
            ImageInfo imgInfo = privateimgList[imageIdx];

            // check if replacing image is supported
            ImageFile imgFile = im;

            if (!Methods.CheckTextureFormat(texFormat, imgFile.format))
                throw new FormatException("Different image format, original is " + texFormat + ", new is " + imgFile.subtype());

            byte[] imgBuffer;

            // if the image is empty then recover the archive compression from the image list
            if (imgInfo.storageType == storage.empty)
            {
                imgInfo.storageType = privateimgList.Find(img => img.storageType != storage.empty && img.storageType != storage.pccSto).storageType;
                imgInfo.uncSize = imgFile.resize().Length;
                imgInfo.cprSize = imgFile.resize().Length;
            }

            switch (imgInfo.storageType)
            {
                case storage.arcCpr:
                case storage.arcUnc:
                    string archivePath = FullArcPath;
                    if (String.IsNullOrEmpty(archivePath))
                        archivePath = GetTexArchive(archiveDir);
                    if (!File.Exists(archivePath))
                        throw new FileNotFoundException("Texture archive not found in " + archivePath);

                    imgBuffer = imgFile.imgData;

                    if (imgBuffer.Length != imgInfo.uncSize)
                        throw new FormatException("image sizes do not match, original is " + imgInfo.uncSize + ", new is " + imgBuffer.Length);

                    if (arcName.Length <= CustCache.Length || arcName.Substring(0, CustCache.Length) != CustCache) // Check whether existing texture is in a custom cache
                    {
                        ChooseNewCache(archiveDir, imgBuffer.Length);
                        archivePath = FullArcPath;
                    }
                    else
                    {
                        FileInfo arc = new FileInfo(archivePath);
                        if (arc.Length + imgBuffer.Length >= 0x80000000)
                        {
                            ChooseNewCache(archiveDir, imgBuffer.Length);
                            archivePath = FullArcPath;
                        }
                    }

                    using (FileStream archiveStream = new FileStream(archivePath, FileMode.Append, FileAccess.Write))
                    {
                        int newOffset = (int)archiveStream.Position;
                        if (imgInfo.storageType == storage.arcCpr)
                        {
                            byte[] tempBuff;
                            SaltLZOHelper lzohelper = new SaltLZOHelper();
                            tempBuff = lzohelper.CompressTex(imgBuffer);
                            imgBuffer = new byte[tempBuff.Length];
                            Buffer.BlockCopy(tempBuff, 0, imgBuffer, 0, tempBuff.Length);
                            imgInfo.cprSize = imgBuffer.Length;
                        }
                        archiveStream.Write(imgBuffer, 0, imgBuffer.Length);

                        imgInfo.offset = newOffset;
                    }
                    break;
                case storage.pccSto:
                    imgBuffer = imgFile.resize();
                    using (MemoryStream dataStream = new MemoryStream())
                    {
                        dataStream.WriteBytes(imageData);
                        if (imgBuffer.Length <= imgInfo.uncSize && imgInfo.offset > 0)
                            dataStream.Seek(imgInfo.offset, SeekOrigin.Begin);
                        else
                            imgInfo.offset = (int)dataStream.Position;
                        dataStream.WriteBytes(imgBuffer);
                        imgInfo.cprSize = imgBuffer.Length;
                        imgInfo.uncSize = imgBuffer.Length;
                        imageData = dataStream.ToArray();
                    }
                    break;
            }

            privateimgList[imageIdx] = imgInfo;
        }
Beispiel #18
0
        public MemoryStream DecompressPCC(Stream raw, IPCCObject pcc)
        {
            raw.Seek(pcc.header.Length, SeekOrigin.Begin);
            int pos = 4;
            pcc.NumChunks = raw.ReadValueS32();
            List<Chunk> Chunks = new List<Chunk>();

            //DebugOutput.PrintLn("Reading chunk headers...");
            for (int i = 0; i < pcc.NumChunks; i++)
            {
                Chunk c = new Chunk();
                c.uncompressedOffset = raw.ReadValueS32();
                c.uncompressedSize = raw.ReadValueS32();
                c.compressedOffset = raw.ReadValueS32();
                c.compressedSize = raw.ReadValueS32();
                c.Compressed = new byte[c.compressedSize];
                c.Uncompressed = new byte[c.uncompressedSize];
                //DebugOutput.PrintLn("Chunk " + i + ", compressed size = " + c.compressedSize + ", uncompressed size = " + c.uncompressedSize);
                //DebugOutput.PrintLn("Compressed offset = " + c.compressedOffset + ", uncompressed offset = " + c.uncompressedOffset);
                Chunks.Add(c);
            }

            //DebugOutput.PrintLn("\tRead Chunks...");
            int count = 0;
            for (int i = 0; i < Chunks.Count; i++)
            {
                Chunk c = Chunks[i];
                raw.Seek(c.compressedOffset, SeekOrigin.Begin);
                c.Compressed = raw.ReadBytes(c.compressedSize);

                ChunkHeader h = new ChunkHeader();
                h.magic = BitConverter.ToInt32(c.Compressed, 0);
                if (h.magic != -1641380927)
                    throw new FormatException("Chunk magic number incorrect");
                h.blocksize = BitConverter.ToInt32(c.Compressed, 4);
                h.compressedsize = BitConverter.ToInt32(c.Compressed, 8);
                h.uncompressedsize = BitConverter.ToInt32(c.Compressed, 12);
                //DebugOutput.PrintLn("Chunkheader read: Magic = " + h.magic + ", Blocksize = " + h.blocksize + ", Compressed Size = " + h.compressedsize + ", Uncompressed size = " + h.uncompressedsize);
                pos = 16;
                int blockCount = (h.uncompressedsize % h.blocksize == 0)
                    ?
                    h.uncompressedsize / h.blocksize
                    :
                    h.uncompressedsize / h.blocksize + 1;
                List<Block> BlockList = new List<Block>();
                //DebugOutput.PrintLn("\t\t" + count + " Read Blockheaders...");
                for (int j = 0; j < blockCount; j++)
                {
                    Block b = new Block();
                    b.compressedsize = BitConverter.ToInt32(c.Compressed, pos);
                    b.uncompressedsize = BitConverter.ToInt32(c.Compressed, pos + 4);
                    //DebugOutput.PrintLn("Block " + j + ", compressed size = " + b.compressedsize + ", uncompressed size = " + b.uncompressedsize);
                    pos += 8;
                    BlockList.Add(b);
                }
                int outpos = 0;
                //DebugOutput.PrintLn("\t\t" + count + " Read and decompress Blocks...");
                foreach (Block b in BlockList)
                {
                    byte[] datain = new byte[b.compressedsize];
                    byte[] dataout = new byte[b.uncompressedsize];
                    for (int j = 0; j < b.compressedsize; j++)
                        datain[j] = c.Compressed[pos + j];
                    pos += b.compressedsize;

                    try
                    {
                        LZO1X.Decompress(datain, dataout);
                    }
                    catch
                    {
                        throw new Exception("LZO decompression failed!");
                    }
                    for (int j = 0; j < b.uncompressedsize; j++)
                        c.Uncompressed[outpos + j] = dataout[j];
                    outpos += b.uncompressedsize;
                }
                c.header = h;
                c.blocks = BlockList;
                count++;
                Chunks[i] = c;
            }

            MemoryStream result = new MemoryStream();
            foreach (Chunk c in Chunks)
            {
                result.Seek(c.uncompressedOffset, SeekOrigin.Begin);
                result.WriteBytes(c.Uncompressed);
            }

            return result;
        }
Beispiel #19
0
        protected SimpleClientMessage(FrontEndMessageCode MessageCode)
        {
            _messageData = new byte[5];
            MemoryStream messageBuilder = new MemoryStream(_messageData);

            messageBuilder
                .WriteBytes((byte)MessageCode)
                .WriteInt32(4);
        }
Beispiel #20
0
        private void LoadHelper(MemoryStream tempStream)
        {
            tempStream.Seek(12, SeekOrigin.Begin);
            int tempNameSize = tempStream.ReadValueS32();
            tempStream.Seek(64 + tempNameSize, SeekOrigin.Begin);
            int tempGenerator = tempStream.ReadValueS32();
            tempStream.Seek(36 + tempGenerator * 12, SeekOrigin.Current);
            int tempPos = (int)tempStream.Position + 4;
            tempStream.Seek(0, SeekOrigin.Begin);
            header = tempStream.ReadBytes(tempPos);
            tempStream.Seek(0, SeekOrigin.Begin);

            if (magic != ZBlock.magic && magic.Swap() != ZBlock.magic)
            {
                DebugOutput.PrintLn("Magic number incorrect: " + magic);
                throw new FormatException("This is not a pcc file. The magic number is incorrect.");
            }

            if (bCompressed)
            {
                DebugOutput.PrintLn("File is compressed");
                listsStream = lzo.DecompressPCC(tempStream, this);

                //Correct the header
                bCompressed = false;
                listsStream.Seek(0, SeekOrigin.Begin);
                listsStream.WriteBytes(header);

                // Set numblocks to zero
                listsStream.WriteValueS32(0);
                //Write the magic number
                listsStream.WriteBytes(new byte[] { 0xF2, 0x56, 0x1B, 0x4E });
                // Write 4 bytes of 0
                listsStream.WriteValueS32(0);
            }
            else
            {
                DebugOutput.PrintLn("File already decompressed. Reading decompressed data.");
                //listsStream = tempStream;
                listsStream = new MemoryStream();
                tempStream.WriteTo(listsStream);
            }
            tempStream.Dispose();
            ReadNames(listsStream);
            ReadImports(listsStream);
            ReadExports(listsStream);
            LoadExports();
        }
        /// <summary>
        ///     decompress an entire ME3 pcc file into a new stream
        /// </summary>
        /// <param name="input">pcc file passed in stream format</param>
        /// <returns>a decompressed array of bytes</returns>
        public static MemoryStream DecompressME3(Stream input)
        {
            input.Seek(0, SeekOrigin.Begin);
            var magic = input.ReadValueU32(Endian.Little);
            if (magic != 0x9E2A83C1 &&
                magic.Swap() != 0x9E2A83C1)
            {
                throw new FormatException("not a pcc file");
            }
            var endian = magic == 0x9E2A83C1 ? Endian.Little : Endian.Big;

            var versionLo = input.ReadValueU16(endian);
            var versionHi = input.ReadValueU16(endian);

            if (versionLo != 684 &&
                versionHi != 194)
            {
                throw new FormatException("unsupported pcc version");
            }

            long headerSize = 8;

            input.Seek(4, SeekOrigin.Current);
            headerSize += 4;

            var folderNameLength = input.ReadValueS32(endian);
            headerSize += 4;

            var folderNameByteLength =
                folderNameLength >= 0 ? folderNameLength : (-folderNameLength * 2);
            input.Seek(folderNameByteLength, SeekOrigin.Current);
            headerSize += folderNameByteLength;

            var packageFlagsOffset = input.Position;
            var packageFlags = input.ReadValueU32(endian);
            headerSize += 4;

            if ((packageFlags & 0x02000000u) == 0)
            {
                throw new FormatException("pcc file is already decompressed");
            }

            if ((packageFlags & 8) != 0)
            {
                input.Seek(4, SeekOrigin.Current);
                headerSize += 4;
            }

            uint nameCount = input.ReadValueU32(endian);
            uint nameOffset = input.ReadValueU32(endian);

            input.Seek(52, SeekOrigin.Current);
            headerSize += 60;

            var generationsCount = input.ReadValueU32(endian);
            input.Seek(generationsCount * 12, SeekOrigin.Current);
            headerSize += generationsCount * 12;

            input.Seek(20, SeekOrigin.Current);
            headerSize += 24;

            var blockCount = input.ReadValueU32(endian);
            int headBlockOff = (int)input.Position;
            var afterBlockTableOffset = headBlockOff + (blockCount * 16);
            var indataOffset = afterBlockTableOffset + 8;
            byte[] buff;

            input.Seek(0, SeekOrigin.Begin);
            MemoryStream output = new MemoryStream();
            output.Seek(0, SeekOrigin.Begin);

            output.WriteFromStream(input, headerSize);
            output.WriteValueU32(0, endian); // block count

            input.Seek(afterBlockTableOffset, SeekOrigin.Begin);
            output.WriteFromStream(input, 8);

            //check if has extra name list (don't know it's usage...)
            if ((packageFlags & 0x10000000) != 0)
            {
                long curPos = output.Position;
                output.WriteFromStream(input, nameOffset - curPos);
            }

            //decompress blocks in parallel
            Task<byte[]>[] tasks = new Task<byte[]>[blockCount];
            uint[] uncompressedOffsets = new uint[blockCount];
            for (int i = 0; i < blockCount; i++)
            {
                input.Seek(headBlockOff, SeekOrigin.Begin);
                uncompressedOffsets[i] = input.ReadValueU32(endian);
                var uncompressedSize = input.ReadValueU32(endian);
                var compressedOffset = input.ReadValueU32(endian);
                var compressedSize = input.ReadValueU32(endian);
                headBlockOff = (int)input.Position;

                buff = new byte[compressedSize];
                input.Seek(compressedOffset, SeekOrigin.Begin);
                input.Read(buff, 0, buff.Length);

                tasks[i] = ZBlock.DecompressAsync(buff);
            }
            Task.WaitAll(tasks);
            for (int i = 0; i < blockCount; i++)
            {
                output.Seek(uncompressedOffsets[i], SeekOrigin.Begin);
                output.WriteBytes(tasks[i].Result);
            }

            output.Seek(packageFlagsOffset, SeekOrigin.Begin);
            output.WriteValueU32(packageFlags & ~0x02000000u, endian);
            return output;
        }
        private byte[] GetExecuteCommandText()
        {
            NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "GetPreparedCommandText");

            MemoryStream result = new MemoryStream();

            result.WriteString("EXECUTE {0}", planName);

            if(parameters.Count != 0)
            {
                result.WriteByte((byte)ASCIIBytes.ParenLeft);

                for (int i = 0 ; i < Parameters.Count ; i++)
                {
                    var p = Parameters[i];

                    if (i > 0)
                    {
                        result.WriteByte((byte)ASCIIBytes.Comma);
                    }

                    // Add parentheses wrapping parameter value before the type cast to avoid problems with Int16.MinValue, Int32.MinValue and Int64.MinValue
                    // See bug #1010543
                    result.WriteByte((byte)ASCIIBytes.ParenLeft);

                    byte[] serialization;

                    serialization = p.TypeInfo.ConvertToBackend(p.Value, false, Connector.NativeToBackendTypeConverterOptions);

                    result
                        .WriteBytes(serialization)
                        .WriteBytes((byte)ASCIIBytes.ParenRight);

                    if (p.UseCast)
                    {
                        PGUtil.WriteString(result, string.Format("::{0}", p.TypeInfo.CastName));

                        if (p.TypeInfo.UseSize && (p.Size > 0))
                        {
                            result.WriteString("({0})", p.Size);
                        }
                    }
                }

                result.WriteByte((byte)ASCIIBytes.ParenRight);
            }

            return result.ToArray();
        }
        /// <summary>
        /// Process this.commandText, trimming each distinct command and substituting paramater
        /// tokens.
        /// </summary>
        /// <param name="prepare"></param>
        /// <returns>UTF8 encoded command ready to be sent to the backend.</returns>
        private byte[] GetCommandText(bool prepare)
        {
            NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "GetCommandText");

            MemoryStream commandBuilder = new MemoryStream();

            if (commandType == CommandType.TableDirect)
            {
                foreach (var table in commandText.Split(';'))
                {
                    if (table.Trim().Length == 0)
                    {
                        continue;
                    }

                    commandBuilder
                        .WriteString("SELECT * FROM ")
                        .WriteString(table)
                        .WriteString(";");
                }
            }
            else if (commandType == CommandType.StoredProcedure)
            {
                if (!prepare && !functionChecksDone)
                {
                    functionNeedsColumnListDefinition = Parameters.Count != 0 && CheckFunctionNeedsColumnDefinitionList();

                    functionChecksDone = true;
                }

                commandBuilder.WriteString("SELECT * FROM ");

                if (commandText.TrimEnd().EndsWith(")"))
                {
                    if (!AppendCommandReplacingParameterValues(commandBuilder, commandText, prepare, false))
                    {
                        throw new NpgsqlException("Multiple queries not supported for stored procedures");
                    }
                }
                else
                {
                    commandBuilder
                        .WriteString(commandText)
                        .WriteBytes((byte)ASCIIBytes.ParenLeft);

                    if (prepare)
                    {
                        AppendParameterPlaceHolders(commandBuilder);
                    }
                    else
                    {
                        AppendParameterValues(commandBuilder);
                    }

                    commandBuilder.WriteBytes((byte)ASCIIBytes.ParenRight);
                }

                if (!prepare && functionNeedsColumnListDefinition)
                {
                    AddFunctionColumnListSupport(commandBuilder);
                }
            }
            else
            {
                if (!AppendCommandReplacingParameterValues(commandBuilder, commandText, prepare, !prepare))
                {
                    throw new NpgsqlException("Multiple queries not supported for prepared statements");
                }
            }

            return commandBuilder.ToArray();
        }
        private bool processFragments(WebSocketFrame first)
        {
            using (var buff = new MemoryStream ()) {
            buff.WriteBytes (first.PayloadData.ApplicationData);
            if (!concatenateFragmentsInto (buff))
              return false;

            byte[] data;
            if (_compression != CompressionMethod.None) {
              data = buff.DecompressToArray (_compression);
            }
            else {
              buff.Close ();
              data = buff.ToArray ();
            }

            enqueueToMessageEventQueue (new MessageEventArgs (first.Opcode, data));
            return true;
              }
        }
        public byte[] ToArray(uint pccExportDataOffset, ME3PCCObject pcc)
        {
            using (MemoryStream tempStream = new MemoryStream())
            {
                tempStream.WriteBytes(headerData);

                // Whilst testing get rid of this
                // Heff: Seems like the shadowmap was the best solution in most cases,
                // adding an exception for known problematic animated textures for now.
                // (See popup in tpftools)
                if (properties.ContainsKey("LODGroup"))
                    properties["LODGroup"].Value.String2 = "TEXTUREGROUP_Shadowmap";
                else
                {
                    tempStream.WriteValueS64(pcc.addName2("LODGroup"));
                    tempStream.WriteValueS64(pcc.addName2("ByteProperty"));
                    tempStream.WriteValueS64(8);
                    tempStream.WriteValueS64(pcc.addName2("TextureGroup"));
                    tempStream.WriteValueS64(pcc.addName2("TEXTUREGROUP_Shadowmap"));
                }

                foreach (KeyValuePair<string, SaltPropertyReader.Property> kvp in properties)
                {
                    SaltPropertyReader.Property prop = kvp.Value;

                    if (prop.Name == "UnpackMin")
                    {
                        for (int i = 0; i < UnpackNum; i++)
                        {
                            tempStream.WriteValueS64(pcc.addName2(prop.Name));
                            tempStream.WriteValueS64(pcc.addName2(prop.TypeVal.ToString()));
                            tempStream.WriteValueS32(prop.Size);
                            tempStream.WriteValueS32(i);
                            tempStream.WriteValueF32(prop.Value.FloatValue);
                        }
                        continue;
                    }

                    tempStream.WriteValueS64(pcc.addName2(prop.Name));

                    if (prop.Name == "None")
                        continue;

                    tempStream.WriteValueS64(pcc.addName2(prop.TypeVal.ToString()));
                    tempStream.WriteValueS64(prop.Size);

                    switch (prop.TypeVal)
                    {
                        case SaltPropertyReader.Type.FloatProperty:
                            tempStream.WriteValueF32(prop.Value.FloatValue);
                            break;
                        case SaltPropertyReader.Type.IntProperty:
                            tempStream.WriteValueS32(prop.Value.IntValue);
                            break;
                        case SaltPropertyReader.Type.NameProperty:
                            tempStream.WriteValueS64(pcc.addName2(prop.Value.StringValue));
                            // Heff: Modified to handle name references.
                            //var nameIndex = pcc.addName2(prop.Value.StringValue);
                            //tempStream.WriteValueS32(nameIndex);
                            //tempStream.WriteValueS32(prop.Value.NameValue.count);
                            break;
                        case SaltPropertyReader.Type.ByteProperty:
                            tempStream.WriteValueS64(pcc.addName2(prop.Value.StringValue));
                            tempStream.WriteValueS64(pcc.addName2(prop.Value.String2));
                            // Heff: Modified to handle name references.
                            //var valueIndex = pcc.addName2(prop.Value.String2);
                            //tempStream.WriteValueS32(valueIndex);
                            //tempStream.WriteValueS32(prop.Value.NameValue.count);

                            //tempStream.WriteValueS32(pcc.addName2(prop.Value.String2));
                            //byte[] footer = new byte[4];
                            //Buffer.BlockCopy(prop.raw, prop.raw.Length - 4, footer, 0, 4);
                            //tempStream.WriteBytes(footer);
                            break;
                        case SaltPropertyReader.Type.BoolProperty:
                            tempStream.WriteValueBoolean(prop.Value.Boolereno);
                            break;
                        case SaltPropertyReader.Type.StructProperty:
                            tempStream.WriteValueS64(pcc.addName2(prop.Value.StringValue));
                            for (int i = 0; i < prop.Size; i++)
                                tempStream.WriteByte((byte)prop.Value.Array[i].IntValue);
                            break;
                        default:
                            throw new NotImplementedException("Property type: " + prop.TypeVal + ", not yet implemented. TELL ME ABOUT THIS!");
                    }
                }

                //Remove empty textures
                List<ImageInfo> tempList = new List<ImageInfo>();
                foreach (ImageInfo imgInfo in privateimgList)
                {
                    if (imgInfo.storageType != storage.empty)
                        tempList.Add(imgInfo);
                }
                privateimgList = tempList;
                numMipMaps = (uint)privateimgList.Count;

                tempStream.WriteValueU32(numMipMaps);
                foreach (ImageInfo imgInfo in privateimgList)
                {
                    tempStream.WriteValueS32((int)imgInfo.storageType);
                    tempStream.WriteValueS32(imgInfo.uncSize);
                    tempStream.WriteValueS32(imgInfo.cprSize);
                    if (imgInfo.storageType == storage.pccSto)
                    {
                        tempStream.WriteValueS32((int)(imgInfo.offset + pccExportDataOffset + dataOffset));
                        tempStream.Write(imageData, imgInfo.offset, imgInfo.uncSize);
                    }
                    else
                        tempStream.WriteValueS32(imgInfo.offset);
                    tempStream.WriteValueU32(imgInfo.imgSize.width);
                    tempStream.WriteValueU32(imgInfo.imgSize.height);
                }
                //// Texture2D footer, 24 bytes size - changed to 20
                //tempStream.Write(imageData, imageData.Length - 20, 20);
                tempStream.WriteBytes(footerData);
                return tempStream.ToArray();
            }

            #region Unused Code
            /*
            bool lodExists = false;
            foreach (KeyValuePair<string, PropertyReader.Property> kvp in properties)
            {
                PropertyReader.Property property = kvp.Value;
                if (kvp.Key == "LODGroup")
                {
                    lodExists = true;
                    break;
                }
            }

            MemoryStream buffer = new MemoryStream();
            buffer.Write(headerData, 0, headerData.Length);

            if (lodExists)
            {
                // extracting values from LODGroup Property
                PropertyReader.Property LODGroup = properties["LODGroup"];
                string textureGroupName = pcc.Names[LODGroup.Value.IntValue];
                bool nameExists = false;
                string newTextureGroupName = "TEXTUREGROUP_Shadowmap";
                if (String.Compare(newTextureGroupName, textureGroupName) != 0)
                {
                    textureGroupName = newTextureGroupName;
                    if (!pcc.Names.Exists(name => name == newTextureGroupName))
                        pcc.Names.Add(newTextureGroupName);
                    using (MemoryStream rawStream = new MemoryStream(LODGroup.raw))
                    {
                        rawStream.Seek(32, SeekOrigin.Begin);
                        rawStream.WriteValueS32(pcc.Names.FindIndex(name => name == newTextureGroupName));
                        rawStream.WriteValueS32(0);
                        properties["LODGroup"].raw = rawStream.ToArray();
                    }
                }
                else
                    nameExists = true;
                //MemoryStream buffer = new MemoryStream();
                //buffer.Write(headerData, 0, headerData.Length);
                foreach (KeyValuePair<string, PropertyReader.Property> kvp in properties)
                {
                    PropertyReader.Property property = kvp.Value;

                    if (kvp.Key == "LODBias")
                        continue;
                    if (kvp.Key == "InternalFormatLODBias")
                        continue;
                    if (kvp.Key == "LODGroup" && nameExists == false)
                    {
                        int name;
                        if (!nameExists)
                            name = pcc.Names.Count - 1;                 //Warranty Voiders Name redirect hack^^
                        else
                            name = LODGroup.Value.IntValue;
                        ME3_HR_Patch.Helper.BitConverter.IsLittleEndian = true;
                        byte[] buff = ME3_HR_Patch.Helper.BitConverter.GetBytes(name);
                        for (int i = 0; i < 4; i++)
                            property.raw[i + 24] = buff[i];
                    }
                    buffer.Write(property.raw, 0, property.raw.Length);
                    if (kvp.Key == "UnpackMin")
                    {
                        buffer.Write(property.raw, 0, property.raw.Length);
                        buffer.Write(property.raw, 0, property.raw.Length);
                    }
                }
            }
            else
            {
                //MemoryStream buffer = new MemoryStream();
                //buffer.Write(headerData, 0, headerData.Length);
                int lodID = pcc.findName("LODGroup");
                if (lodID == -1)
                {
                    pcc.addName("LODGroup");
                    lodID = pcc.Names.Count - 1;
                }
                buffer.WriteBytes(ME3_HR_Patch.Helper.BitConverter.GetBytes(lodID));
                buffer.WriteBytes(ME3_HR_Patch.Helper.BitConverter.GetBytes((int)0));
                lodID = pcc.findName("ByteProperty");
                buffer.WriteBytes(ME3_HR_Patch.Helper.BitConverter.GetBytes(lodID));
                buffer.WriteBytes(ME3_HR_Patch.Helper.BitConverter.GetBytes((int)0));
                //Write an int
                buffer.WriteBytes(ME3_HR_Patch.Helper.BitConverter.GetBytes((int)8));
                buffer.WriteBytes(ME3_HR_Patch.Helper.BitConverter.GetBytes((int)0));

                lodID = pcc.findName("TextureGroup");
                if (lodID == -1)
                {
                    pcc.addName("TextureGroup");
                    lodID = pcc.Names.Count - 1;
                }
                buffer.WriteBytes(ME3_HR_Patch.Helper.BitConverter.GetBytes(lodID));
                buffer.WriteBytes(ME3_HR_Patch.Helper.BitConverter.GetBytes((int)0));

                lodID = pcc.findName("TEXTUREGROUP_Shadowmap");
                if (lodID == -1)
                {
                    pcc.addName("TEXTUREGROUP_Shadowmap");
                    lodID = pcc.Names.Count - 1;
                }
                buffer.WriteBytes(ME3_HR_Patch.Helper.BitConverter.GetBytes(lodID));
                buffer.WriteBytes(ME3_HR_Patch.Helper.BitConverter.GetBytes((int)0));

                foreach (KeyValuePair<string, PropertyReader.Property> kvp in properties)
                {
                    PropertyReader.Property property = kvp.Value;

                    if (kvp.Key == "LODBias")
                        continue;
                    if (kvp.Key == "InternalFormatLODBias")
                        continue;
                    if (kvp.Key == "LODGroup")
                    {
                        int name = pcc.Names.Count - 1;                 //Warranty Voiders Name redirect hack^^
                        ME3_HR_Patch.Helper.BitConverter.IsLittleEndian = true;
                        byte[] buff = ME3_HR_Patch.Helper.BitConverter.GetBytes(name);
                        for (int i = 0; i < 4; i++)
                            property.raw[i + 24] = buff[i];
                    }
                    buffer.Write(property.raw, 0, property.raw.Length);
                    if (kvp.Key == "UnpackMin")
                    {
                        buffer.Write(property.raw, 0, property.raw.Length);
                        buffer.Write(property.raw, 0, property.raw.Length);
                    }
                }
            }

            buffer.WriteValueU32(numMipMaps);
            foreach (ImageInfo imgInfo in imgList)
            {
                buffer.WriteValueS32((int)imgInfo.storageType);
                buffer.WriteValueS32(imgInfo.uncSize);
                buffer.WriteValueS32(imgInfo.cprSize);
                if (imgInfo.storageType == storage.pccSto)
                {
                    buffer.WriteValueS32((int)(imgInfo.offset + pccExportDataOffset + dataOffset));
                    buffer.Write(imageData, imgInfo.offset, imgInfo.uncSize);
                }
                else
                    buffer.WriteValueS32(imgInfo.offset);
                buffer.WriteValueU32(imgInfo.imgSize.width);
                buffer.WriteValueU32(imgInfo.imgSize.height);
            }
            // Texture2D footer, 24 bytes size
            buffer.Write(imageData, imageData.Length - 24, 24);
            byte[] rawData = buffer.ToArray();
            return rawData;
            */
            #endregion
        }
        public void replaceImage2(string strImgSize, ImageFile im, string archiveDir)
        {
            ImageSize imgSize = ImageSize.stringToSize(strImgSize);
            if (!privateimgList.Exists(img => img.imgSize == imgSize))
                throw new FileNotFoundException("Image with resolution " + imgSize + " isn't found");

            int imageIdx = privateimgList.FindIndex(img => img.imgSize == imgSize);
            ImageInfo imgInfo = privateimgList[imageIdx];

            // check if replacing image is supported
            ImageFile imgFile = im;

            // check if images have same format type
            if (texFormat != imgFile.format && texFormat != "G8")
                throw new FormatException("Different image format, original is " + texFormat + ", new is " + imgFile.subtype());

            byte[] imgBuffer;

            // if the image is empty then recover the archive compression from the image list
            if (imgInfo.storageType == storage.empty)
            {
                imgInfo.storageType = privateimgList.Find(img => img.storageType != storage.empty && img.storageType != storage.pccSto).storageType;
                imgInfo.uncSize = imgFile.resize().Length;
                imgInfo.cprSize = imgFile.resize().Length;
            }

            switch (imgInfo.storageType)
            {
                case storage.arcCpr:
                case storage.arcUnc:
                    //string archivePath = GetTexArchive(archiveDir);
                    string archivePath = FullArcPath;
                    if (String.IsNullOrEmpty(archivePath))
                        archivePath = GetTexArchive(archiveDir);
                    if (archivePath == null)
                        throw new FileNotFoundException("Teture archive not found!");
                    if (!File.Exists(archivePath))
                        throw new FileNotFoundException("Texture archive not found in " + archivePath);

                    if (getFileFormat() == ".tga")
                        imgBuffer = imgFile.resize(); // shrink image to essential data
                    else
                        imgBuffer = imgFile.imgData;

                    if (imgBuffer.Length != imgInfo.uncSize)
                        throw new FormatException("image sizes do not match, original is " + imgInfo.uncSize + ", new is " + imgBuffer.Length);

                    if (arcName.Length <= CustCache.Length || arcName.Substring(0, CustCache.Length) != CustCache) // Check whether existing texture is in a custom cache
                    {
                        ChooseNewCache(archiveDir, imgBuffer.Length);
                        archivePath = FullArcPath;
                    }
                    else
                    {
                        FileInfo arc = new FileInfo(archivePath);
                        if (arc.Length + imgBuffer.Length >= 0x80000000)
                        {
                            ChooseNewCache(archiveDir, imgBuffer.Length);
                            archivePath = FullArcPath;
                        }
                    }
                    /* FileInfo arc = new FileInfo(archivePath);
                    if (arc.Length + imgBuffer.Length >= 0x80000000)
                    {
                        //2GB fix
                        ChooseNewCache(archiveDir, imgBuffer.Length);
                        archivePath = archiveDir + "\\" + arcName + ".tfc";
                    } */

                    using (FileStream archiveStream = new FileStream(archivePath, FileMode.Append, FileAccess.Write))
                    {
                        int newOffset = (int)archiveStream.Position;

                        if (imgInfo.storageType == storage.arcCpr)
                        {
                            imgBuffer = ZBlock.Compress(imgBuffer);
                            imgInfo.cprSize = imgBuffer.Length;
                        }
                        archiveStream.Write(imgBuffer, 0, imgBuffer.Length);

                        imgInfo.offset = newOffset;
                    }
                    break;
                case storage.pccSto:
                    imgBuffer = imgFile.imgData; // copy image data as-is
                    /*if (imgBuffer.Length != imgInfo.uncSize)
                        throw new FormatException("image sizes do not match, original is " + imgInfo.uncSize + ", new is " + imgBuffer.Length);*/
                    using (MemoryStream dataStream = new MemoryStream())
                    {
                        dataStream.WriteBytes(imageData);
                        if (imgBuffer.Length <= imgInfo.uncSize && imgInfo.offset > 0)
                            dataStream.Seek(imgInfo.offset, SeekOrigin.Begin);
                        else
                            imgInfo.offset = (int)dataStream.Position;
                        dataStream.WriteBytes(imgBuffer);
                        imgInfo.cprSize = imgBuffer.Length;
                        imgInfo.uncSize = imgBuffer.Length;
                        imageData = dataStream.ToArray();
                    }
                    #region Old code
                    /*
                    try
                    {
                        using (MemoryStream dataStream = new MemoryStream(imageData))
                        {
                            dataStream.Seek(imgInfo.offset, SeekOrigin.Begin);
                            dataStream.Write(imgBuffer, 0, imgBuffer.Length);
                        }
                    }
                    catch (NotSupportedException)
                    {
                        MemoryStream dataStream = new MemoryStream();
                        dataStream.WriteBytes(imgBuffer);
                        dataStream.WriteBytes(imageData);
                        imageData = dataStream.ToArray();
                        dataStream.Close();
                        for (int i = 1; i < imgList.Count; i++)
                        {
                            ImageInfo img = imgList[i];
                            img.offset += imgBuffer.Length;
                            imgList[i] = img;
                        }
                    }
                    */
                    #endregion
                    break;
            }

            privateimgList[imageIdx] = imgInfo;
            //this.hasChanged = true;
        }
        public void CopyImgList(ME3SaltTexture2D inTex, ME3PCCObject pcc)
        {
            imageData = inTex.imageData;
            privateimgList = inTex.privateimgList;
            numMipMaps = inTex.numMipMaps;

            //Copy Properties
            byte[] buff;
            using (MemoryStream tempMem = new MemoryStream())
            {
                tempMem.WriteBytes(headerData);
                for (int i = 0; i < inTex.properties.Count; i++)
                {
                    SaltPropertyReader.Property prop = inTex.properties.ElementAt(i).Value;

                    if (prop.Name == "UnpackMin")
                    {
                        for (int j = 0; j < inTex.UnpackNum; j++)
                        {
                            tempMem.WriteValueS64(pcc.addName2(prop.Name));
                            tempMem.WriteValueS64(pcc.addName2(prop.TypeVal.ToString()));
                            tempMem.WriteValueS32(prop.Size);
                            tempMem.WriteValueS32(j);
                            tempMem.WriteValueF32(prop.Value.FloatValue);
                        }
                        continue;
                    }

                    tempMem.WriteValueS64(pcc.addName2(prop.Name));

                    if (prop.Name == "None")
                        continue;


                    tempMem.WriteValueS64(pcc.addName2(prop.TypeVal.ToString()));
                    tempMem.WriteValueS64(prop.Size);

                    switch (prop.TypeVal)
                    {
                        case SaltPropertyReader.Type.FloatProperty:
                            tempMem.WriteValueF32(prop.Value.FloatValue);
                            break;
                        case SaltPropertyReader.Type.IntProperty:
                            tempMem.WriteValueS32(prop.Value.IntValue);
                            break;
                        case SaltPropertyReader.Type.NameProperty:
                            tempMem.WriteValueS64(pcc.addName2(prop.Value.StringValue));
                            // Heff: Modified to handle name references.
                            //var index = pcc.addName2(prop.Value.StringValue);
                            //tempMem.WriteValueS32(index);
                            //tempMem.WriteValueS32(prop.Value.NameValue.count);
                            break;
                        case SaltPropertyReader.Type.ByteProperty:
                            tempMem.WriteValueS64(pcc.addName2(prop.Value.StringValue));
                            tempMem.WriteValueS32(pcc.addName2(prop.Value.String2));
                            byte[] footer = new byte[4];
                            Buffer.BlockCopy(prop.raw, prop.raw.Length - 4, footer, 0, 4);
                            tempMem.WriteBytes(footer);
                            break;
                        case SaltPropertyReader.Type.BoolProperty:
                            tempMem.WriteValueBoolean(prop.Value.Boolereno);
                            break;
                        case SaltPropertyReader.Type.StructProperty:
                            tempMem.WriteValueS64(pcc.addName2(prop.Value.StringValue));
                            for (int k = 0; k < prop.Size; k++)
                                tempMem.WriteByte((byte)prop.Value.Array[k].IntValue);
                            break;
                        default:
                            throw new NotImplementedException("Property type: " + prop.TypeVal + ", not yet implemented. TELL ME ABOUT THIS!");
                    }
                }
                buff = tempMem.ToArray();
            }

            properties = new Dictionary<string, SaltPropertyReader.Property>();

            List<SaltPropertyReader.Property> tempProperties = SaltPropertyReader.ReadProp(pcc, buff, headerData.Length);
            for (int i = 0; i < tempProperties.Count; i++)
            {
                SaltPropertyReader.Property property = tempProperties[i];
                if (property.Name == "UnpackMin")
                    UnpackNum++;

                if (!properties.ContainsKey(property.Name))
                    properties.Add(property.Name, property);

                switch (property.Name)
                {
                    case "Format":
                        texFormat = Textures.Methods.ParseFormat(pcc.Names[property.Value.IntValue].Substring(3));
                        break;
                    case "TextureFileCacheName": arcName = property.Value.NameValue.Name; break;
                    case "LODGroup": LODGroup = property.Value.NameValue.Name; break;
                    case "None": dataOffset = (uint)(property.offsetval + property.Size); break;
                }
            }

            // if "None" property isn't found throws an exception
            if (dataOffset == 0)
                throw new Exception("\"None\" property not found");
        }
Beispiel #28
0
        /// <summary>
        /// For POS coins - used to format wallet address pubkey to use in generation transaction's output.
        /// </summary>
        /// <param name="key"></param>
        /// <example>
        /// nodejs: https://github.com/zone117x/node-stratum-pool/blob/3586ec0d7374b2acc5a72d5ef597da26f0e39d54/lib/util.js#L243
        /// nodejs: http://runnable.com/me/VCFHE0RrZnwbsQ6y
        /// </example>
        /// <returns></returns>
        public static byte[] PubKeyToScript(string key)
        {
            var pubKey = key.HexToByteArray();

            if (pubKey.Length != 33)
            {
                Log.Error("invalid pubkey length for {0:l}", key);
                return null;
            }

            byte[] result;

            using (var stream = new MemoryStream())
            {
                stream.WriteValueU8(0x21);
                stream.WriteBytes(pubKey);
                stream.WriteValueU8(0xac);
                result = stream.ToArray();
            }

            return result;
        }
        public void replaceImage(string strImgSize, ImageFile im, string archiveDir)
        {
            //DebugOutput.PrintLn( "\nIn replace image...\n");
            ImageSize imgSize = ImageSize.stringToSize(strImgSize);
            if (!privateimgList.Exists(img => img.imgSize == imgSize))
                throw new FileNotFoundException("Image with resolution " + imgSize + " isn't found");

            int imageIdx = privateimgList.FindIndex(img => img.imgSize == imgSize);
            ImageInfo imgInfo = privateimgList[imageIdx];

            ImageFile imgFile = im;
            ImageEngineFormat imgFileFormat = Textures.Methods.ParseFormat(imgFile.format);

            // check if images have same format type
            if (texFormat != imgFileFormat && texFormat != ImageEngineFormat.DDS_G8_L8)
                throw new FormatException("Different image format, original is " + texFormat + ", new is " + imgFile.subtype());

            byte[] imgBuffer;

            // if the image is empty then recover the archive compression from the image list
            if (imgInfo.storageType == storage.empty)
            {
                imgInfo.storageType = privateimgList.Find(img => img.storageType != storage.empty && img.storageType != storage.pccSto).storageType;
                imgInfo.uncSize = imgFile.resize().Length;
                imgInfo.cprSize = imgFile.resize().Length;
            }

            switch (imgInfo.storageType)
            {
                case storage.arcCpr:
                case storage.arcUnc:
                    //string archivePath = GetTexArchive(archiveDir);
                    string archivePath = FullArcPath;
                    if (String.IsNullOrEmpty(archivePath))
                        archivePath = GetTexArchive(archiveDir);
                    if (archivePath == null)
                        throw new FileNotFoundException("Teture archive not found!");
                    if (!File.Exists(archivePath))
                        throw new FileNotFoundException("Texture archive not found in " + archivePath);

                    if (getFileFormat() == ".tga")
                        imgBuffer = imgFile.resize(); // shrink image to essential data
                    else
                        imgBuffer = imgFile.imgData;

                    if (imgBuffer.Length != imgInfo.uncSize)
                        throw new FormatException("image sizes do not match, original is " + imgInfo.uncSize + ", new is " + imgBuffer.Length);

                    //DebugOutput.PrintLn( "\nOK here's the stuff we came for. About to change/add cache.\n");
                    //DebugOutput.PrintLn( "Initial arcname = " + arcName + "   custCache = " + CustCache + "\n");
                    if (!arcName.ToLower().Contains(Path.GetFileNameWithoutExtension(MEDirectories.MEDirectories.CachePath.ToLower())))  // CachePath is usually CustTextures, but arcName can be CustTextures#, so check for substring
                    {
                        ChooseNewCache(archiveDir, imgBuffer.Length);
                        archivePath = FullArcPath;
                    }
                    else
                    {
                        FileInfo arc = new FileInfo(archivePath);
                        //DebugOutput.PrintLn( "Extra bits maybe:  " + arc.Length + "\n");
                        if (arc.Length + imgBuffer.Length >= 0x80000000)
                        {
                            ChooseNewCache(archiveDir, imgBuffer.Length);
                            archivePath = FullArcPath;
                        }
                    }
                    /* FileInfo arc = new FileInfo(archivePath);
                    if (arc.Length + imgBuffer.Length >= 0x80000000)
                    {
                        //2GB fix
                        ChooseNewCache(archiveDir, imgBuffer.Length);
                        archivePath = archiveDir + "\\" + arcName + ".tfc";
                    } */

                    using (FileStream archiveStream = new FileStream(archivePath, FileMode.Append, FileAccess.Write))
                    {
                        int newOffset = (int)archiveStream.Position;

                        if (imgInfo.storageType == storage.arcCpr)
                        {
                            imgBuffer = ZBlock.Compress(imgBuffer);
                            imgInfo.cprSize = imgBuffer.Length;
                        }
                        archiveStream.Write(imgBuffer, 0, imgBuffer.Length);

                        imgInfo.offset = newOffset;
                    }
                    break;
                case storage.pccSto:
                    imgBuffer = imgFile.imgData; // copy image data as-is
                    if (imgBuffer.Length != imgInfo.uncSize)
                        throw new FormatException("image sizes do not match, original is " + imgInfo.uncSize + ", new is " + imgBuffer.Length);
                    using (MemoryStream dataStream = new MemoryStream())
                    {
                        dataStream.WriteBytes(imageData);
                        if (imgBuffer.Length <= imgInfo.uncSize && imgInfo.offset > 0)
                            dataStream.Seek(imgInfo.offset, SeekOrigin.Begin);
                        else
                            imgInfo.offset = (int)dataStream.Position;
                        dataStream.WriteBytes(imgBuffer);
                        imgInfo.cprSize = imgBuffer.Length;
                        imgInfo.uncSize = imgBuffer.Length;
                        imageData = dataStream.ToArray();
                    }
                    #region Old code
                    /*
                    try
                    {
                        using (MemoryStream dataStream = new MemoryStream(imageData))
                        {
                            dataStream.Seek(imgInfo.offset, SeekOrigin.Begin);
                            dataStream.Write(imgBuffer, 0, imgBuffer.Length);
                        }
                    }
                    catch (NotSupportedException)
                    {
                        MemoryStream dataStream = new MemoryStream();
                        dataStream.WriteBytes(imgBuffer);
                        dataStream.WriteBytes(imageData);
                        imageData = dataStream.ToArray();
                        dataStream.Close();
                        for (int i = 1; i < imgList.Count; i++)
                        {
                            ImageInfo img = imgList[i];
                            img.offset += imgBuffer.Length;
                            imgList[i] = img;
                        }
                    }
                    */
                    #endregion
                    break;
            }

            privateimgList[imageIdx] = imgInfo;
            //this.hasChanged = true;
        }
Beispiel #30
0
 /// <summary>
 /// 
 /// </summary>
 /// <returns></returns>
 public MemoryStream GetIplData()
 {
     var MemoryStream = new MemoryStream();
     foreach (var BlockOffset in GetIplOffsets().ToArray())
     {
         //Console.WriteLine(BlockOffset);
         Stream.Position = NandReader.BytesPerBlock * BlockOffset;
         MemoryStream.WriteBytes(Stream.ReadBytes(NandReader.BytesPerBlock));
     }
     MemoryStream.Position = 0;
     return MemoryStream;
 }