Example #1
0
 public static void EncodeBlockHeader(BinaryWriter writer, BlockHeader blockHeader)
 {
     writer.WriteUInt32(blockHeader.Version);
     writer.WriteUInt256(blockHeader.PreviousBlock);
     writer.WriteUInt256(blockHeader.MerkleRoot);
     writer.WriteUInt32((uint)blockHeader.Time.ToUnixTimeSeconds());
     writer.WriteUInt32(blockHeader.Bits);
     writer.WriteUInt32(blockHeader.Nonce);
 }
Example #2
0
        public static byte[] EncodeBlockHeader(UInt32 Version, UInt256 PreviousBlock, UInt256 MerkleRoot, DateTimeOffset Time, UInt32 Bits, UInt32 Nonce)
        {
            using (var stream = new MemoryStream())
            using (var writer = new BinaryWriter(stream))
            {
                writer.WriteUInt32(Version);
                writer.WriteUInt256(PreviousBlock);
                writer.WriteUInt256(MerkleRoot);
                writer.WriteUInt32((uint)Time.ToUnixTimeSeconds());
                writer.WriteUInt32(Bits);
                writer.WriteUInt32(Nonce);

                return stream.ToArray();
            }
        }
Example #3
0
 public static void EncodeInventoryVector(BinaryWriter writer, InventoryVector invVector)
 {
     writer.WriteUInt32(invVector.Type);
     writer.WriteUInt256(invVector.Hash);
 }
		public void WriteTo(BinaryWriter w)
		{
			// http://www.pkware.com/documents/casestudies/APPNOTE.TXT

			var offsets = new Queue();
			var Items = this.Entries;
			
			#region Local file header:
			foreach (var v in Items)
			{
				// if we box unit, it will actually represent Long 
				// this is for tostring functionality

				offsets.Enqueue((uint)w.BaseStream.Position);

				//var h = v.Header;
				var file_name = Encoding.ASCII.GetBytes(v.FileName);

				//        local file header signature     4 bytes  (0x04034b50)
				w.Write(ZIPFileEntryHeader.FileHeader);
				//        version needed to extract       2 bytes
				w.Write((short)0x000A);
				//        general purpose bit flag        2 bytes
				w.Write((short)0);

				//        compression method              2 bytes
				w.Write(ZIPFileEntryHeader.UNCOMPRESSED);
				//        last mod file time              2 bytes
				//        last mod file date              2 bytes
				w.WriteUInt32(ToMsDosDateTime(DateTime.Now));

				//        crc-32                          4 bytes
				w.WriteUInt32((uint)Crc32Helper.GetCrc32(v.Data.ToArray()));

				//        compressed size                 4 bytes
				w.WriteUInt32((uint)v.Data.Length);
				//        uncompressed size               4 bytes
				w.WriteUInt32((uint)v.Data.Length);


				//        file name length                2 bytes
				w.Write((short)file_name.Length);

				//        extra field length              2 bytes
				w.Write((short)0);

				//        file name (variable size)
				w.Write(file_name);

				//        extra field (variable size)

				v.Data.WriteTo(w.BaseStream);

			}
			#endregion

			var p = w.BaseStream.Position;


			#region Central directory structure
			foreach (var v in Items)
			{
				//var h = v.Header;
				var offset = (uint)offsets.Dequeue();

				var file_name = Encoding.ASCII.GetBytes(v.FileName);


				//       central file header signature   4 bytes  (0x02014b50)
				w.Write((int)0x02014b50);
				//       version made by                 2 bytes
				w.WriteUInt16((ushort)0x0014);
				//       version needed to extract       2 bytes
				w.WriteUInt16((ushort)0x000A);
				//       general purpose bit flag        2 bytes
				w.WriteUInt16((ushort)0x0000);
				//       compression method              2 bytes
				w.Write(ZIPFileEntryHeader.UNCOMPRESSED);
				//       last mod file time              2 bytes
				//       last mod file date              2 bytes
				w.WriteUInt32(ToMsDosDateTime(DateTime.Now));
				//       crc-32                          4 bytes
				w.WriteUInt32((uint)Crc32Helper.GetCrc32(v.Data.ToArray()));
				//       compressed size                 4 bytes
				w.WriteUInt32((uint)v.Data.Length);
				//       uncompressed size               4 bytes
				w.WriteUInt32((uint)v.Data.Length);
				//       file name length                2 bytes
				w.WriteUInt16((ushort)file_name.Length);
				//       extra field length              2 bytes
				w.WriteUInt16((ushort)0x0000);
				//       file comment length             2 bytes
				w.WriteUInt16((ushort)0x0000);
				//       disk number start               2 bytes
				w.WriteUInt16((ushort)0x0000);
				//       internal file attributes        2 bytes
				w.WriteUInt16((ushort)0x0000);
				//       external file attributes        4 bytes
				w.Write((int)0x0000);
				//       relative offset of local header 4 bytes
				w.WriteUInt32((uint)offset);
				//       file name (variable size)
				w.Write(file_name);
				//       extra field (variable size)
				//       file comment (variable size)
			}
			#endregion

			//      

			var q = w.BaseStream.Position;
			var z = q - p;

			#region I.  End of central directory record:
			//end of central dir signature    4 bytes  (0x06054b50)
			w.WriteUInt32((uint)0x06054b50);

			//number of this disk             2 bytes
			w.WriteUInt16((ushort)0);
			//number of the disk with the
			//start of the central directory  2 bytes
			w.WriteUInt16((ushort)0);
			//total number of entries in the
			//central directory on this disk  2 bytes
			w.WriteUInt16((ushort)Items.Length);
			//total number of entries in
			//the central directory           2 bytes
			w.WriteUInt16((ushort)Items.Length);
			//size of the central directory   4 bytes
			w.WriteUInt32((uint)z);
			//offset of start of central
			//directory with respect to
			//the starting disk number        4 bytes
			w.WriteUInt32((uint)p);
			//.ZIP file comment length        2 bytes
			w.WriteUInt16((ushort)0);
			//.ZIP file comment       (variable size)
			#endregion


		}
Example #5
0
        private int PrepareSaveData(byte[] destBuf)
        {
            using (var stream = new MemoryStream(destBuf))
            {
                using (var bw = new BinaryWriter(stream))
                {
                    bw.BaseStream.Seek(4, SeekOrigin.Begin);
                    bw.WriteUInt32(SaveFileRevision);
                    bw.WriteUInt32((uint) SystemVars.Instance.GameVersion.Version.Minor);

                    bw.WriteUInt16(_skySound.SaveSounds[0]);
                    bw.WriteUInt16(_skySound.SaveSounds[1]);

                    bw.WriteUInt32(_skyMusic.CurrentMusic);
                    bw.WriteUInt32(_savedCharSet);
                    bw.WriteUInt32(_savedMouse);
                    bw.WriteUInt32(SystemVars.Instance.CurrentPalette);
                    for (var cnt = 0; cnt < Logic.NumSkyScriptVars; cnt++)
                        bw.WriteUInt32(_skyLogic.ScriptVariables[cnt]);
                    var loadedFilesList = _skyDisk.LoadedFilesList;

                    for (var cnt = 0; cnt < 60; cnt++)
                        bw.WriteUInt32(loadedFilesList[cnt]);

                    for (var cnt = 0; cnt < _skyCompact.SaveIds.Length; cnt++)
                    {
                        var rawCpt = _skyCompact.FetchCptRaw(_skyCompact.SaveIds[cnt]);
                        bw.WriteBytes(rawCpt, rawCpt.Length);
                    }

                    var length = bw.BaseStream.Position;
                    bw.BaseStream.Seek(0, SeekOrigin.Begin);
                    bw.WriteUInt32((uint) length);
                    return (int) length;
                }
            }
        }
Example #6
0
        public static byte[] EncodeTransaction(UInt32 Version, ImmutableArray<TxInput> Inputs, ImmutableArray<TxOutput> Outputs, UInt32 LockTime)
        {
            using (var stream = new MemoryStream())
            using (var writer = new BinaryWriter(stream))
            {
                writer.WriteUInt32(Version);
                writer.WriteList(Inputs, input => EncodeTxInput(writer, input));
                writer.WriteList(Outputs, output => EncodeTxOutput(writer, output));
                writer.WriteUInt32(LockTime);

                return stream.ToArray();
            }
        }
Example #7
0
 public static void EncodePrevTxOutput(BinaryWriter writer, PrevTxOutput txOutput)
 {
     writer.WriteUInt64(txOutput.Value);
     writer.WriteVarBytes(txOutput.ScriptPublicKey.ToArray());
     writer.WriteInt32(txOutput.BlockHeight);
     writer.WriteInt32(txOutput.TxIndex);
     writer.WriteUInt32(txOutput.TxVersion);
     writer.WriteBool(txOutput.IsCoinbase);
 }
Example #8
0
        public static void EncodeVersionPayload(BinaryWriter writer, VersionPayload versionPayload, bool withRelay)
        {
            writer.WriteUInt32(versionPayload.ProtocolVersion);
            writer.WriteUInt64(versionPayload.ServicesBitfield);
            writer.WriteUInt64((ulong)versionPayload.Time.ToUnixTimeSeconds());
            EncodeNetworkAddress(writer, versionPayload.RemoteAddress);
            EncodeNetworkAddress(writer, versionPayload.LocalAddress);
            writer.WriteUInt64(versionPayload.Nonce);
            writer.WriteVarString(versionPayload.UserAgent);
            writer.WriteUInt32(versionPayload.StartBlockHeight);

            if (withRelay)
                writer.WriteBool(versionPayload.Relay);
        }
Example #9
0
        public static DecodedTx EncodeTransaction(UInt32 Version, ImmutableArray<TxInput> Inputs, ImmutableArray<TxOutput> Outputs, UInt32 LockTime)
        {
            using (var stream = new MemoryStream())
            using (var writer = new BinaryWriter(stream))
            {
                writer.WriteUInt32(Version);
                writer.WriteList(Inputs, input => EncodeTxInput(writer, input));
                writer.WriteList(Outputs, output => EncodeTxOutput(writer, output));
                writer.WriteUInt32(LockTime);

                var txBytes = stream.ToArray();
                var txHash = new UInt256(SHA256Static.ComputeDoubleHash(txBytes));
                var tx = new Transaction(Version, Inputs, Outputs, LockTime, txHash);

                return new DecodedTx(txBytes.ToImmutableArray(), tx);
            }
        }
Example #10
0
 public static void EncodeTxInput(BinaryWriter writer, TxInput txInput)
 {
     writer.WriteUInt256(txInput.PrevTxOutputKey.TxHash);
     writer.WriteUInt32(txInput.PrevTxOutputKey.TxOutputIndex);
     writer.WriteVarBytes(txInput.ScriptSignature.ToArray());
     writer.WriteUInt32(txInput.Sequence);
 }
Example #11
0
 public static void EncodeTransaction(BinaryWriter writer, Transaction tx)
 {
     writer.WriteUInt32(tx.Version);
     writer.WriteList(tx.Inputs, input => EncodeTxInput(writer, input));
     writer.WriteList(tx.Outputs, output => EncodeTxOutput(writer, output));
     writer.WriteUInt32(tx.LockTime);
 }
Example #12
0
        public byte[] TxSignature(byte[] scriptPubKey, Transaction tx, int inputIndex, byte hashType)
        {
            ///TODO
            Debug.Assert(inputIndex < tx.Inputs.Length);

            // Blank out other inputs' signatures
            var empty = ImmutableArray.Create<byte>();
            var newInputs = ImmutableArray.CreateBuilder<TxInput>(tx.Inputs.Length);
            for (var i = 0; i < tx.Inputs.Length; i++)
            {
                var oldInput = tx.Inputs[i];
                var newInput = oldInput.With(scriptSignature: i == inputIndex ? scriptPubKey.ToImmutableArray() : empty);
                newInputs.Add(newInput);
            }

            //// Blank out some of the outputs
            //if ((hashType & 0x1F) == (int)ScriptHashType.SIGHASH_NONE)
            //{
            //    //TODO
            //    Debug.Assert(false);

            //    // Wildcard payee

            //    // Let the others update at will
            //}
            //else if ((hashType & 0x1F) == (int)ScriptHashType.SIGHASH_SINGLE)
            //{
            //    //TODO
            //    Debug.Assert(false);

            //    // Only lock-in the txout payee at same index as txin

            //    // Let the others update at will
            //}

            //// Blank out other inputs completely, not recommended for open transactions
            //if ((hashType & 0x80) == (int)ScriptHashType.SIGHASH_ANYONECANPAY)
            //{
            //    //TODO
            //    Debug.Assert(false);
            //}

            // create simplified transaction
            var newTx = tx.With(Inputs: newInputs.ToImmutable());

            // return wire-encoded simplified transaction with the 4-byte hashType tacked onto the end
            using (var stream = new MemoryStream())
            using (var writer = new BinaryWriter(stream))
            {
                writer.WriteBytes(DataEncoder.EncodeTransaction(newTx));
                writer.WriteUInt32(hashType);

                return stream.ToArray();
            }
        }
Example #13
0
 public static void EncodeNetworkAddressWithTime(BinaryWriter writer, NetworkAddressWithTime networkAddressWithTime)
 {
     writer.WriteUInt32(networkAddressWithTime.Time);
     EncodeNetworkAddress(writer, networkAddressWithTime.NetworkAddress);
 }
Example #14
0
 public static void EncodeMessage(BinaryWriter writer, Message message)
 {
     writer.WriteUInt32(message.Magic);
     writer.WriteFixedString(12, message.Command);
     writer.WriteUInt32(message.PayloadSize);
     writer.WriteUInt32(message.PayloadChecksum);
     writer.WriteBytes(message.PayloadSize.ToIntChecked(), message.Payload.ToArray());
 }
Example #15
0
 public static void EncodeUnspentTx(BinaryWriter writer, UnspentTx unspentTx)
 {
     writer.WriteUInt256(unspentTx.TxHash);
     writer.WriteInt32(unspentTx.BlockIndex);
     writer.WriteInt32(unspentTx.TxIndex);
     writer.WriteUInt32(unspentTx.TxVersion);
     writer.WriteBool(unspentTx.IsCoinbase);
     writer.WriteVarBytes(unspentTx.OutputStates.ToByteArray());
     writer.WriteInt32(unspentTx.OutputStates.Length);
 }
Example #16
0
 public static void EncodeNetworkAddressWithTime(BinaryWriter writer, NetworkAddressWithTime networkAddressWithTime)
 {
     writer.WriteUInt32((uint)networkAddressWithTime.Time.ToUnixTimeSeconds()); //TODO is time LE or BE on network messages?
     EncodeNetworkAddress(writer, networkAddressWithTime.NetworkAddress);
 }
Example #17
0
 public static void EncodeTxOutputKey(BinaryWriter writer, TxOutputKey txOutputKey)
 {
     writer.WriteUInt256(txOutputKey.TxHash);
     writer.WriteUInt32(txOutputKey.TxOutputIndex);
 }
Example #18
0
 public static void EncodeGetBlocksPayload(BinaryWriter writer, GetBlocksPayload getBlocksPayload)
 {
     writer.WriteUInt32(getBlocksPayload.Version);
     writer.WriteList(getBlocksPayload.BlockLocatorHashes, locatorHash => writer.WriteUInt256(locatorHash));
     writer.WriteUInt256(getBlocksPayload.HashStop);
 }
Example #19
0
        private void SaveGameToFile(byte slot)
        {
            ushort cnt;
            var fName = $"sword1.{slot:D3}";
            ushort[] liveBuf = new ushort[ObjectMan.TOTAL_SECTIONS];

            using (var stream = _saveFileMan.OpenForSaving(fName))
            using (var outf = new BinaryWriter(stream))
            {
                //if (!outf)
                //{
                //    // Display an error message and do nothing
                //    displayMessage(0, "Unable to create file '%s'. (%s)", fName, _saveFileMan.popErrorDesc().c_str());
                //    return;
                //}

                outf.WriteUInt32((uint)SAVEGAME_HEADER);

                outf.Write(StrToBytes(_saveNames[slot], 40));
                outf.WriteByte(SAVEGAME_VERSION);

                if (!IsPanelShown()) // Generate a thumbnail only if we are outside of game menu
                    SaveThumbnail(outf);

                // Date / time
                DateTime curTime = DateTime.Now;

                uint saveDate =
                    (uint)
                        ((curTime.Day & 0xFF) << 24 | ((curTime.Month + 1) & 0xFF) << 16 |
                         ((curTime.Year + 1900) & 0xFFFF));
                ushort saveTime = (ushort)((curTime.Hour & 0xFF) << 8 | ((curTime.Minute) & 0xFF));

                outf.WriteUInt32BigEndian(saveDate);
                outf.WriteUInt16BigEndian(saveTime);

                // TODO: outf.WriteUInt32BigEndian(g_engine.getTotalPlayTime() / 1000); replaced by 0
                outf.WriteUInt32BigEndian(0);

                _objMan.SaveLiveList(liveBuf);
                for (cnt = 0; cnt < ObjectMan.TOTAL_SECTIONS; cnt++)
                    outf.WriteUInt16(liveBuf[cnt]);

                var cpt = _objMan.FetchObject(Logic.PLAYER);
                Logic.ScriptVars[(int)ScriptVariableNames.CHANGE_DIR] = (uint)cpt.dir;
                Logic.ScriptVars[(int)ScriptVariableNames.CHANGE_X] = (uint)cpt.xcoord;
                Logic.ScriptVars[(int)ScriptVariableNames.CHANGE_Y] = (uint)cpt.ycoord;
                Logic.ScriptVars[(int)ScriptVariableNames.CHANGE_STANCE] = StaticRes.STAND;
                Logic.ScriptVars[(int)ScriptVariableNames.CHANGE_PLACE] = (uint)cpt.place;

                for (cnt = 0; cnt < Logic.NUM_SCRIPT_VARS; cnt++)
                    outf.WriteUInt32(Sword1.Logic.ScriptVars[cnt]);

                uint playerSize = (SwordObject.Size - 12000) / 4;
                var playerRaw = new UIntAccess(cpt.Data, cpt.Offset);
                for (var cnt2 = 0; cnt2 < playerSize; cnt2++)
                    outf.WriteUInt32(playerRaw[cnt2]);
            }
            // TODO: error
            //if (outf.err())
            //    displayMessage(0, "Couldn't write to file '%s'. Device full? (%s)", fName, _saveFileMan.popErrorDesc().c_str());
            //delete outf;
        }