Example #1
0
 private static void DeserializeFrom(BinaryReader reader, out FiniteFieldPolynomial x, out FiniteFieldPolynomial y)
 {
     int x_i = (int)reader.ReadVarInt();
     int expectedByteCount = (int)reader.ReadVarInt();
     byte[] y_b = reader.ReadBytes(expectedByteCount);
     IrreduciblePolynomial irp = new IrreduciblePolynomial(expectedByteCount * 8);
     x = new FiniteFieldPolynomial(irp, x_i);
     y = new FiniteFieldPolynomial(irp, y_b.ToBigIntegerFromBigEndianUnsignedBytes());
 }
Example #2
0
 public override void Deserialize(BinaryReader reader)
 {
     this.m = (int)reader.ReadVarInt();
     this.publicKeys = new ECPoint[reader.ReadVarInt()];
     for (int i = 0; i < publicKeys.Length; i++)
     {
         publicKeys[i] = ECPoint.DeserializeFrom(reader, ECCurve.Secp256r1);
     }
     base.RedeemScript = CreateMultiSigRedeemScript(m, publicKeys);
     base.PublicKeyHash = reader.ReadSerializable<UInt160>();
 }
 void ISignable.DeserializeUnsigned(BinaryReader reader)
 {
     PrevHash = reader.ReadSerializable<UInt256>();
     Miner = ECPoint.DeserializeFrom(reader, ECCurve.Secp256r1);
     NoncePieces.Clear();
     int count = (int)reader.ReadVarInt();
     for (int i = 0; i < count; i++)
     {
         ECPoint key = ECPoint.DeserializeFrom(reader, ECCurve.Secp256r1);
         byte[] value = reader.ReadBytes((int)reader.ReadVarInt());
         NoncePieces.Add(key, value);
     }
     MerkleRoot = reader.ReadSerializable<UInt256>();
 }
Example #4
0
 public static MyWallet Load(string path, string password)
 {
     MyWallet wallet = new MyWallet();
     byte[] aes_key = Encoding.UTF8.GetBytes(password).Sha256().Sha256();
     byte[] aes_iv = new byte[16];
     using (AesManaged aes = new AesManaged())
     using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
     {
         fs.Read(aes_iv, 0, aes_iv.Length);
         using (ICryptoTransform decryptor = aes.CreateDecryptor(aes_key, aes_iv))
         using (CryptoStream cs = new CryptoStream(fs, decryptor, CryptoStreamMode.Read))
         using (BinaryReader reader = new BinaryReader(cs))
         {
             int count = (int)reader.ReadVarInt();
             for (int i = 0; i < count; i++)
             {
                 byte[] privateKey = reader.ReadBytes(32);
                 bool compressed = reader.ReadBoolean();
                 ECPoint publicKey = ECCurve.Secp256k1.G * privateKey;
                 UInt160 publicKeyHash = publicKey.EncodePoint(compressed).ToScriptHash();
                 wallet.accounts.Add(new WalletEntry(privateKey, publicKey, publicKeyHash, compressed));
             }
         }
     }
     Array.Clear(aes_key, 0, aes_key.Length);
     return wallet;
 }
Example #5
0
 void ISerializable.Deserialize(BinaryReader reader)
 {
     this.PrevHash = reader.ReadSerializable<UInt256>();
     this.PrevIndex = reader.ReadUInt32();
     this.Script = reader.ReadBytes((int)reader.ReadVarInt());
     this.Sequence = reader.ReadUInt32();
 }
 void ISignable.DeserializeUnsigned(BinaryReader reader)
 {
     PrevHash = reader.ReadSerializable<UInt256>();
     Miner = ECPoint.DeserializeFrom(reader, ECCurve.Secp256r1);
     IV = reader.ReadBytes(16);
     NoncePieces.Clear();
     int count = (int)reader.ReadVarInt();
     for (int i = 0; i < count; i++)
     {
         ECPoint key = ECPoint.DeserializeFrom(reader, ECCurve.Secp256r1);
         if (key == Miner) throw new FormatException();
         byte[] value = reader.ReadBytes((int)reader.ReadVarInt());
         NoncePieces.Add(key, value);
     }
     NonceHash = reader.ReadSerializable<UInt256>();
     TransactionHashes = reader.ReadSerializableArray<UInt256>();
 }
 public override void Deserialize(BinaryReader reader)
 {
     this.PrevHash = reader.ReadSerializable<UInt256>();
     this.Miner = Secp256r1Point.DeserializeFrom(reader);
     this.NoncePieces.Clear();
     int count = (int)reader.ReadVarInt();
     for (int i = 0; i < count; i++)
     {
         Secp256r1Point key = Secp256r1Point.DeserializeFrom(reader);
         if (key == Miner) throw new FormatException();
         byte[] value = reader.ReadBytes((int)reader.ReadVarInt());
         NoncePieces.Add(key, value);
     }
     this.NonceHash = reader.ReadSerializable<UInt256>();
     this.TransactionHashes = reader.ReadSerializableArray<UInt256>();
     this.Script = reader.ReadBytes((int)reader.ReadVarInt());
 }
Example #8
0
 protected override void DeserializeExclusiveData(BinaryReader reader)
 {
     this.AssetId = reader.ReadSerializable<UInt256>();
     this.ValueAssetId = reader.ReadSerializable<UInt256>();
     if (AssetId == ValueAssetId) throw new FormatException();
     this.Agent = reader.ReadSerializable<UInt160>();
     this.Orders = new Order[reader.ReadVarInt()];
     for (int i = 0; i < Orders.Length; i++)
     {
         Orders[i] = new Order();
         Orders[i].DeserializeInTransaction(reader, this);
     }
     ulong count = reader.ReadVarInt();
     if (count > 1) throw new FormatException();
     if (count == 0)
     {
         this.SplitOrder = null;
     }
     else
     {
         this.SplitOrder = reader.ReadSerializable<SplitOrder>();
     }
 }
Example #9
0
        public static Block DecodeBlock(BinaryReader reader)
        {
            var header = DecodeBlockHeader(null, reader.ReadExactly(80));

            var blockTxesCount = reader.ReadVarInt().ToIntChecked();
            var blockTxes = ImmutableArray.CreateBuilder<BlockTx>(blockTxesCount);
            for (var i = 0; i < blockTxesCount; i++)
            {
                var txBytes = ReadTransaction(reader);
                var encodedTx = DecodeEncodedTx(null, txBytes);
                var blockTx = new BlockTx(i, encodedTx);

                blockTxes.Add(blockTx);

            }

            return new Block(header, blockTxes.MoveToImmutable());
        }
Example #10
0
        private Message WireDecodeMessage(UInt32 magic, Stream stream)
        {
            byte[] payload;
            Message message;
            using (var reader = new BinaryReader(stream, Encoding.ASCII, leaveOpen: true))
            {
                var command = reader.ReadFixedString(12);
                var payloadSize = reader.Read4Bytes();
                var payloadChecksum = reader.Read4Bytes();

                payload = reader.ReadBytes(payloadSize.ToIntChecked());

                if (!Messaging.VerifyPayloadChecksum(payloadChecksum, payload))
                    throw new Exception(string.Format("Checksum failed for {0}", command));

                message = new Message
                (
                    Magic: magic,
                    Command: command,
                    PayloadSize: payloadSize,
                    PayloadChecksum: payloadChecksum,
                    Payload: payload.ToImmutableArray()
                );
            }

            switch (message.Command)
            {
                case "addr":
                    {
                        var addressPayload = NetworkEncoder.DecodeAddressPayload(payload.ToMemoryStream());

                        var handler = this.OnReceivedAddresses;
                        if (handler != null)
                            handler(addressPayload.NetworkAddresses);
                    }
                    break;

                case "alert":
                    {
                        var alertPayload = NetworkEncoder.DecodeAlertPayload(payload.ToMemoryStream());
                    }
                    break;

                case "block":
                    {
                        var block = NetworkEncoder.DecodeBlock(payload.ToMemoryStream());

                        var handler = this.OnBlock;
                        if (handler != null)
                            handler(block);
                    }
                    break;

                case "getblocks":
                    {
                        var getBlocksPayload = NetworkEncoder.DecodeGetBlocksPayload(payload.ToMemoryStream());

                        var handler = this.OnGetBlocks;
                        if (handler != null)
                            handler(getBlocksPayload);
                    }
                    break;

                case "getheaders":
                    {
                        var getHeadersPayload = NetworkEncoder.DecodeGetBlocksPayload(payload.ToMemoryStream());

                        var handler = this.OnGetHeaders;
                        if (handler != null)
                            handler(getHeadersPayload);
                    }
                    break;

                case "headers":
                    {
                        var headerStream = payload.ToMemoryStream();
                        using (var reader = new BinaryReader(headerStream))
                        {
                            var headerCount = reader.ReadVarInt().ToIntChecked();

                            for (var i = 0; i < headerCount; i++)
                            {
                                var blockHeader = NetworkEncoder.DecodeBlockHeader(headerStream);
                                //TODO wiki says this is a byte and a var int, which is it?
                                var txCount = reader.ReadVarInt();

                                var handler = this.OnBlockHeader;
                                if (handler != null)
                                    handler(blockHeader);
                            }
                        }
                    }
                    break;

                case "inv":
                    {
                        var invPayload = NetworkEncoder.DecodeInventoryPayload(payload.ToMemoryStream());

                        var handler = this.OnInventoryVectors;
                        if (handler != null)
                            handler(invPayload.InventoryVectors);
                    }
                    break;

                case "notfound":
                    {
                        var invPayload = NetworkEncoder.DecodeInventoryPayload(payload.ToMemoryStream());

                        var handler = this.OnNotFound;
                        if (handler != null)
                            handler(invPayload.InventoryVectors);
                    }
                    break;

                case "ping":
                    {
                        var handler = this.OnPing;
                        if (handler != null)
                            handler(payload.ToImmutableArray());
                    }
                    break;

                case "tx":
                    {
                        var tx = NetworkEncoder.DecodeTransaction(payload.ToMemoryStream());

                        var handler = this.OnTransaction;
                        if (handler != null)
                            handler(tx);
                    }
                    break;

                case "version":
                    {
                        var versionPayload = NetworkEncoder.DecodeVersionPayload(payload.ToMemoryStream(), payload.Length);
                        //Debug.WriteLine(string.Format("{0}, {1}", versionPayload.RemoteAddress.ToIPEndPoint(), this.socket.RemoteEndPoint));

                        var handler = this.OnVersion;
                        if (handler != null)
                            handler(versionPayload);
                    }
                    break;

                case "verack":
                    {
                        var handler = this.OnVersionAcknowledged;
                        if (handler != null)
                            handler();
                    }
                    break;

                default:
                    {
                        Debug.WriteLine("Unhandled incoming message: {0}".Format2(message.Command));
                    }
                    break;
            }

            //TODO
            //if (payloadStream.Position != payloadStream.Length)
            //{
            //    var exMessage = string.Format("Wrong number of bytes read for {0}, parser error: read {1} bytes from a {2} byte payload", message.Command, payloadStream.Position, payloadStream.Length);
            //    Debug.WriteLine(exMessage);
            //    throw new Exception(exMessage);
            //}

            return message;
        }
Example #11
0
        private Message WireDecodeMessage(UInt32 magic, Stream stream)
        {
            byte[] payload;
            Message message;
            using (var reader = new BinaryReader(stream, Encoding.ASCII, leaveOpen: true))
            {
                var command = reader.ReadFixedString(12);
                var payloadSize = reader.ReadUInt32();
                var payloadChecksum = reader.ReadUInt32();

                payload = reader.ReadBytes(payloadSize.ToIntChecked());

                if (!Messaging.VerifyPayloadChecksum(payloadChecksum, payload))
                    throw new Exception($"Checksum failed for {command}");

                message = new Message
                (
                    Magic: magic,
                    Command: command,
                    PayloadSize: payloadSize,
                    PayloadChecksum: payloadChecksum,
                    Payload: payload.ToImmutableArray()
                );
            }

            switch (message.Command)
            {
                case "addr":
                    {
                        var addressPayload = NodeEncoder.DecodeAddressPayload(payload);

                        this.OnReceivedAddresses?.Invoke(addressPayload.NetworkAddresses);
                    }
                    break;

                case "alert":
                    {
                        var alertPayload = NodeEncoder.DecodeAlertPayload(payload);
                    }
                    break;

                case "block":
                    {
                        var block = DataEncoder.DecodeBlock(payload);

                        this.OnBlock?.Invoke(this.owner, block);
                    }
                    break;

                case "getblocks":
                    {
                        var getBlocksPayload = NodeEncoder.DecodeGetBlocksPayload(payload);

                        this.OnGetBlocks?.Invoke(getBlocksPayload);
                    }
                    break;

                case "getheaders":
                    {
                        var getHeadersPayload = NodeEncoder.DecodeGetBlocksPayload(payload);

                        this.OnGetHeaders?.Invoke(getHeadersPayload);
                    }
                    break;

                case "getdata":
                    {
                        var invPayload = NodeEncoder.DecodeInventoryPayload(payload);

                        this.OnGetData?.Invoke(invPayload);
                    }
                    break;

                case "headers":
                    {
                        var blockHeaders = ImmutableList.CreateBuilder<BlockHeader>();

                        using (var headerStream = new MemoryStream(payload))
                        using (var reader = new BinaryReader(headerStream))
                        {
                            var headerCount = reader.ReadVarInt().ToIntChecked();

                            for (var i = 0; i < headerCount; i++)
                            {
                                var blockHeader = DataEncoder.DecodeBlockHeader(reader);
                                //TODO wiki says this is a byte and a var int, which is it?
                                var txCount = reader.ReadVarInt();

                                blockHeaders.Add(blockHeader);
                            }
                        }

                        this.OnBlockHeaders?.Invoke(this.owner, blockHeaders.ToImmutable());
                    }
                    break;

                case "inv":
                    {
                        var invPayload = NodeEncoder.DecodeInventoryPayload(payload);

                        this.OnInventoryVectors?.Invoke(invPayload.InventoryVectors);
                    }
                    break;

                case "notfound":
                    {
                        var invPayload = NodeEncoder.DecodeInventoryPayload(payload);

                        this.OnNotFound?.Invoke(invPayload.InventoryVectors);
                    }
                    break;

                case "ping":
                    {
                        this.OnPing?.Invoke(payload.ToImmutableArray());
                    }
                    break;

                case "tx":
                    {
                        var tx = DataEncoder.DecodeTransaction(payload);

                        this.OnTransaction?.Invoke(tx);
                    }
                    break;

                case "version":
                    {
                        var versionPayload = NodeEncoder.DecodeVersionPayload(payload, payload.Length);

                        this.OnVersion?.Invoke(versionPayload);
                    }
                    break;

                case "verack":
                    {
                        this.OnVersionAcknowledged?.Invoke();
                    }
                    break;

                default:
                    {
                        logger.Warn($"Unhandled incoming message: {message.Command}");
                    }
                    break;
            }

            //TODO
            //if (payloadStream.Position != payloadStream.Length)
            //{
            //    var exMessage = $"Wrong number of bytes read for {message.Command}, parser error: read {payloadStream.Position} bytes from a {payloadStream.Length} byte payload";
            //    Debug.WriteLine(exMessage);
            //    throw new Exception(exMessage);
            //}

            return message;
        }
Example #12
0
 public void Deserialize(BinaryReader reader)
 {
     int x = (int)reader.ReadVarInt();
     int expectedByteCount = (int)reader.ReadVarInt();
     byte[] y = reader.ReadBytes(expectedByteCount);
     IrreduciblePolynomial irp = new IrreduciblePolynomial(expectedByteCount * 8);
     this.X = new FiniteFieldPolynomial(irp, x);
     this.Y = new FiniteFieldPolynomial(irp, y.ToBigIntegerFromBigEndianUnsignedBytes());
 }
Example #13
0
 void ISerializable.Deserialize(BinaryReader reader)
 {
     StackScript = reader.ReadBytes((int)reader.ReadVarInt());
     RedeemScript = reader.ReadBytes((int)reader.ReadVarInt());
 }
Example #14
0
        public static byte[] ReadTransaction(BinaryReader reader)
        {
            var txBytes = new byte[1024];
            var offset = 0;

            // read version
            reader.ReadExactly(txBytes, offset, 4);
            offset += 4;

            // read inputs
            var inputCount = reader.ReadVarInt(ref txBytes, ref offset).ToIntChecked();
            for (var i = 0; i < inputCount; i++)
            {
                // read prevTxHash and prevTxOutputIndex
                SizeAtLeast(ref txBytes, offset + 36);
                reader.ReadExactly(txBytes, offset, 36);
                offset += 36;

                // read scriptSignatureLength
                var scriptSignatureLength = reader.ReadVarInt(ref txBytes, ref offset).ToIntChecked();

                // read scriptSignature
                SizeAtLeast(ref txBytes, offset + scriptSignatureLength);
                reader.ReadExactly(txBytes, offset, scriptSignatureLength);
                offset += scriptSignatureLength;

                // read sequence
                SizeAtLeast(ref txBytes, offset + 4);
                reader.ReadExactly(txBytes, offset, 4);
                offset += 4;
            }

            // read outputs
            var outputCount = reader.ReadVarInt(ref txBytes, ref offset).ToIntChecked();
            for (var i = 0; i < outputCount; i++)
            {
                // read value
                SizeAtLeast(ref txBytes, offset + 8);
                reader.ReadExactly(txBytes, offset, 8);
                offset += 8;

                // read scriptPublicKeyLength
                var scriptPublicKeyLength = reader.ReadVarInt(ref txBytes, ref offset).ToIntChecked();

                // read scriptPublicKey
                SizeAtLeast(ref txBytes, offset + scriptPublicKeyLength);
                reader.ReadExactly(txBytes, offset, scriptPublicKeyLength);
                offset += scriptPublicKeyLength;
            }

            // read lockTime
            SizeAtLeast(ref txBytes, offset + 4);
            reader.ReadExactly(txBytes, offset, 4);
            offset += 4;

            // resize raw tx bytes to final size
            Array.Resize(ref txBytes, offset);

            return txBytes;
        }
Example #15
0
 void ISerializable.Deserialize(BinaryReader reader)
 {
     this.Value = reader.ReadSerializable<Fixed8>();
     this.Script = reader.ReadBytes((int)reader.ReadVarInt());
 }
 public override void Deserialize(BinaryReader reader)
 {
     ((ISignable)this).DeserializeUnsigned(reader);
     this.Script = reader.ReadBytes((int)reader.ReadVarInt());
 }
 void ISignable.FromUnsignedArray(byte[] value)
 {
     using (MemoryStream ms = new MemoryStream(value, false))
     using (BinaryReader reader = new BinaryReader(ms))
     {
         this.PrevHash = reader.ReadSerializable<UInt256>();
         this.Miner = Secp256r1Point.DeserializeFrom(reader);
         this.NoncePieces.Clear();
         int count = (int)reader.ReadVarInt();
         for (int i = 0; i < count; i++)
         {
             Secp256r1Point key = Secp256r1Point.DeserializeFrom(reader);
             if (key == Miner) throw new FormatException();
             value = reader.ReadBytes((int)reader.ReadVarInt());
             NoncePieces.Add(key, value);
         }
         this.NonceHash = reader.ReadSerializable<UInt256>();
         this.TransactionHashes = reader.ReadSerializableArray<UInt256>();
     }
 }