示例#1
0
 public void WriteTLV(TLVWriter writer)
 {
     if (ContractId is null)
     {
         throw new InvalidOperationException("ContractId is not set");
     }
     if (CetSigs is null)
     {
         throw new InvalidOperationException("CetSigs is not set");
     }
     if (FundingSigs is null)
     {
         throw new InvalidOperationException("FundingSigs is not set");
     }
     writer.WriteU16(TLVType);
     writer.WriteUInt256(ContractId);
     CetSigs.WriteTLV(writer);
     using (var w = writer.StartWriteRecord(FundingSignaturesTLVType))
     {
         w.WriteU16(FundingSigs.Count);
         foreach (var s in FundingSigs)
         {
             w.WriteU16(s.PushCount);
             for (int i = 0; i < s.PushCount; i++)
             {
                 var p = s.GetUnsafePush(i);
                 w.WriteU16(p.Length);
                 w.WriteBytes(p);
             }
         }
     }
 }
示例#2
0
        public static void WriteObject(this InvocationContext ctx, ITLVObject obj, JsonSerializerSettings settings)
        {
            var json = ctx.ParseResult.ValueForOption <bool>("json");

            if (json)
            {
                // We need to remove the TLVJsonConverters which will
                // just serialize the type as a json string
                var oldConverters = settings.Converters;
                var newConverters = oldConverters.Where(c =>
                                                        c.GetType() is Type t &&
                                                        (!t.IsGenericType ||
                                                         (t.GetGenericTypeDefinition() is Type generic &&
                                                          generic != typeof(Messages.JsonConverters.TLVJsonConverter <>))))
                                    .ToList();
                settings.Converters = newConverters;
                var txt = JsonConvert.SerializeObject(obj, settings);
                settings.Converters = oldConverters;
                ctx.Console.Out.Write(txt);
            }
            else
            {
                var       ms     = new MemoryStream();
                TLVWriter writer = new TLVWriter(ms);
                obj.WriteTLV(writer);
                ms.Position = 0;
                ctx.Console.Out.Write(Encoders.Base64.EncodeData(ms.ToArray()));
            }
        }
示例#3
0
        public byte[] ToTLV()
        {
            var       ms     = new MemoryStream();
            TLVWriter writer = new TLVWriter(ms);

            WriteTLV(writer);
            return(ms.ToArray());
        }
示例#4
0
        public void WriteTLV(TLVWriter writer)
        {
            Span <byte> output = stackalloc byte[65 + 97];

            Signature.WriteToSpan(output);
            Proof.WriteToSpan(output.Slice(65));
            writer.WriteBytes(output);
        }
示例#5
0
 public override void WriteJson(JsonWriter writer, [AllowNull] T?value, JsonSerializer serializer)
 {
     if (value is T)
     {
         MemoryStream ms  = new MemoryStream();
         TLVWriter    tlv = new TLVWriter(ms);
         value.WriteTLV(tlv);
         ms.Position = 0;
         writer.WriteValue(Encoders.Base64.EncodeData(ms.ToArray()));
     }
 }
示例#6
0
 public static void WriteScript(this TLVWriter writer, Script?script)
 {
     if (script is null)
     {
         writer.WriteU16(0);
     }
     else
     {
         writer.WriteU16((ushort)script.Length);
         writer.WriteBytes(script.ToBytes(true));
     }
 }
示例#7
0
        public void CanReadWriteBigSize(ulong value, string hex)
        {
            var ms     = new MemoryStream(Encoders.Hex.DecodeData(hex));
            var reader = new TLVReader(ms);

            Assert.Equal(value, reader.ReadBigSize());

            ms.Position = 0;
            var writer = new TLVWriter(ms);

            writer.WriteBigSize(value);
            ms.Position = 0;
            reader      = new TLVReader(ms);
            Assert.Equal(value, reader.ReadBigSize());
        }
示例#8
0
        public void WriteTLV(TLVWriter writer)
        {
            if (TemporaryContractId is null)
            {
                throw new InvalidOperationException($"{nameof(TemporaryContractId)} is not set");
            }
            if (TotalCollateral is null)
            {
                throw new InvalidOperationException($"{nameof(TotalCollateral)} is not set");
            }
            if (PubKeys?.FundingKey is null)
            {
                throw new InvalidOperationException($"{nameof(PubKeys.FundingKey)} is not set");
            }
            if (PubKeys?.PayoutAddress is null)
            {
                throw new InvalidOperationException($"{nameof(PubKeys.PayoutAddress)} is not set");
            }
            if (FundingInputs is null)
            {
                throw new InvalidOperationException($"{nameof(FundingInputs)} is not set");
            }
            if (ChangeAddress is null)
            {
                throw new InvalidOperationException($"{nameof(ChangeAddress)} is not set");
            }
            if (CetSigs is null)
            {
                throw new InvalidOperationException($"{nameof(CetSigs)} is not set");
            }
            writer.WriteU16(TLVType);
            writer.WriteUInt256(TemporaryContractId);
            writer.WriteU64((ulong)TotalCollateral.Satoshi);
            Span <byte> buf = stackalloc byte[64];

            PubKeys.FundingKey.Compress().ToBytes(buf, out _);
            writer.WriteBytes(buf.Slice(0, 33));
            writer.WriteScript(PubKeys.PayoutAddress.ScriptPubKey);
            writer.WriteU16((ushort)FundingInputs.Length);
            foreach (var input in FundingInputs)
            {
                input.WriteTLV(writer);
            }
            writer.WriteScript(ChangeAddress.ScriptPubKey);
            CetSigs.WriteTLV(writer);
        }
示例#9
0
 public void WriteTLV(TLVWriter writer)
 {
     if (OutcomeSigs is null)
     {
         throw new InvalidOperationException("OutcomeSigs is null");
     }
     if (RefundSig is null)
     {
         throw new InvalidOperationException("RefundSig is null");
     }
     using (var record = writer.StartWriteRecord(AdaptorSigsTLVType))
     {
         foreach (var sig in OutcomeSigs)
         {
             sig.WriteTLV(record);
         }
     }
     writer.WriteBytes(RefundSig.ToCompact());
 }
示例#10
0
        public void WriteTLV(TLVWriter writer)
        {
            if (ChainHash is null)
            {
                throw new InvalidOperationException($"{nameof(ChainHash)} is not set");
            }
            if (ContractInfo is null)
            {
                throw new InvalidOperationException($"{nameof(ContractInfo)} is not set");
            }
            if (OracleInfo is null)
            {
                throw new InvalidOperationException($"{nameof(OracleInfo)} is not set");
            }
            if (TotalCollateral is null)
            {
                throw new InvalidOperationException($"{nameof(TotalCollateral)} is not set");
            }
            if (PubKeys?.FundingKey is null)
            {
                throw new InvalidOperationException($"{nameof(PubKeys.FundingKey)} is not set");
            }
            if (PubKeys?.PayoutAddress is null)
            {
                throw new InvalidOperationException($"{nameof(PubKeys.PayoutAddress)} is not set");
            }
            if (FundingInputs is null)
            {
                throw new InvalidOperationException($"{nameof(FundingInputs)} is not set");
            }
            if (ChangeAddress is null)
            {
                throw new InvalidOperationException($"{nameof(ChangeAddress)} is not set");
            }
            if (FeeRate is null)
            {
                throw new InvalidOperationException($"{nameof(FeeRate)} is not set");
            }
            if (Timeouts is null)
            {
                throw new InvalidOperationException($"{nameof(Timeouts)} is not set");
            }
            writer.WriteU16(TLVType);
            writer.WriteByte(0);             // contract_flags
            writer.WriteUInt256(ChainHash);
            using (var ciRecord = writer.StartWriteRecord(TLVContractInfoType))
            {
                foreach (var ci in ContractInfo)
                {
                    ciRecord.WriteBytes(ci.Outcome.Hash);
                    ciRecord.WriteU64((ulong)ci.Payout.Satoshi);
                }
            }
            Span <byte> buf = stackalloc byte[64];

            using (var oracleRecord = writer.StartWriteRecord(TLVOracleInfoType))
            {
                OracleInfo.WriteToBytes(buf);
                oracleRecord.WriteBytes(buf);
            }
            PubKeys.FundingKey.Compress().ToBytes(buf, out _);
            writer.WriteBytes(buf.Slice(0, 33));
            writer.WriteScript(PubKeys.PayoutAddress.ScriptPubKey);
            writer.WriteU64((ulong)TotalCollateral.Satoshi);
            writer.WriteU16((ushort)FundingInputs.Length);
            foreach (var input in FundingInputs)
            {
                input.WriteTLV(writer);
            }
            writer.WriteScript(ChangeAddress.ScriptPubKey);
            writer.WriteU64((ulong)FeeRate.SatoshiPerByte);
            writer.WriteU32((uint)Timeouts.ContractMaturity);
            writer.WriteU32((uint)Timeouts.ContractTimeout);
        }
        public byte[] Serialize(LeveledFileLogger LeveledLog)
        {
            TLVWriter ArticleWriter = new TLVWriter();

              // анализ флагов перед сериализацией
              if (Quantity.Value != Quantity.Initial || PriceWithoutDiscount.Value != PriceWithoutDiscount.Initial) // количество товара или цена без скидки была изменено
            Flags.Value |= FiscalArticleFlags.Changed; // устанавливаем флаг того, что позиция была изменена

              if (Price < 0) throw new ArgumentException("Цена товара не может быть отрицательной", "Цена товара");

              //if (Quantity != 0 && Amount != 0) убрал 10.12.2013 при тестировании событий "добавления товара с нулевой ценой" и "удаления товара путем обнуления количества"
              {
            ArticleWriter.AppendTLVString((byte)OCPFiscalArticleTags.GoodsCode, GoodsCode, EncodingName); LeveledLog.Message("GoodsCode = '{0}'", GoodsCode);
            if (GoodsName.Length != 0)
            {
              ArticleWriter.AppendTLVString((byte)OCPFiscalArticleTags.GoodsName, GoodsName, EncodingName);
              LeveledLog.Message("GoodsName = '{0}'", GoodsName);
            }
            ArticleWriter.AppendTLVInt32((byte)OCPFiscalArticleTags.Quantity, Quantity.Value); LeveledLog.Message("Quantity = {0}", Quantity.Value);
            ArticleWriter.AppendTLVInt32((byte)OCPFiscalArticleTags.PriceWithoutDiscount, PriceWithoutDiscount.Value); LeveledLog.Message("PriceWithoutDiscount = {0}", PriceWithoutDiscount.Value);
            ArticleWriter.AppendTLVInt32((byte)OCPFiscalArticleTags.AmountWithoutDiscount, AmountWithoutDiscount.Value); LeveledLog.Message("AmountWithoutDiscount = {0}", AmountWithoutDiscount.Value);

            if (QuantityPrecision != 3)
            {
              ArticleWriter.AppendTLVByte((byte)OCPFiscalArticleTags.QuantityPrecision, QuantityPrecision); LeveledLog.Message("QuantityPrecision = {0}", QuantityPrecision);
            }
            if (Flags.Value != FiscalArticleFlags.None)
            {
              ArticleWriter.AppendTLVByte((byte)OCPFiscalArticleTags.Flags, (byte)Flags.Value); LeveledLog.Message("Flags = {0} ({1})", Flags.Value, (int)Flags.Value);
            }
            if (DiscountForPriceCurrent.Value != 0)
            {
              ArticleWriter.AppendTLVInt32((byte)OCPFiscalArticleTags.DiscountForPrice, DiscountForPriceCurrent.Value);
              LeveledLog.Message("DiscountForPriceCurrent = {0}", DiscountForPriceCurrent.Value);
            }
            if (DiscountForAmount.Value != 0)
            {
              ArticleWriter.AppendTLVInt32((byte)OCPFiscalArticleTags.DiscountForAmount, DiscountForAmount.Value);
              LeveledLog.Message("DiscountForAmount = {0}", DiscountForAmount.Value);
            }
            if (Bonuses.Value != 0)
            {
              ArticleWriter.AppendTLVInt32((byte)OCPFiscalArticleTags.Bonuses, Bonuses.Value);
              LeveledLog.Message("Bonuses = {0}", Bonuses.Value);
            }

            if (Fiscal.Payments.IsMixedPayment || paymentType.Received) // тип оплаты возвращаем тогда, когда используется смешанная оплату
            {
              ArticleWriter.AppendTLVByte((byte)OCPFiscalArticleTags.PaymentType, (byte)PaymentType.Value);
              LeveledLog.Message("PaymentType = {0} ({1})", PaymentType.Value, (int)PaymentType.Value);
            }

            //ArticleWriter.AppendTLVString((byte)CMPFiscalArticleTags.MeasureUnit, MeasureUnit, EncodingName); LeveledLog.Message("MeasureUnit = {0}", MeasureUnit); не передаётся обратно для экономии трафика
              }

              return ArticleWriter.Bytes;
        }
        public byte[] Serialize(LeveledFileLogger LeveledLog)
        {
            var NextLeveledLog = LeveledLog.CloneNextLevel();
              TLVWriter FiscalWriter = new TLVWriter();

              if (Quantity > 0 && Articles.Count > 0) // сериализуем только если есть позиции в чеке и они ненулевые
              {
            foreach (FiscalArticle Article in Articles)
            {
              LeveledLog.Message("Article = {");
              FiscalWriter.AppendTLV((byte)CMPFiscalReceiptTags.Article, Article.Serialize(NextLeveledLog));
              LeveledLog.Message("}");
            }

            if (Flags.Value != FiscalReceiptFlags.None)
            {
              FiscalWriter.AppendTLVByte((byte)CMPFiscalReceiptTags.Flags, (byte)Flags.Value);
              LeveledLog.Message("Flags = {0} ({1})", Flags.Value, (byte)Flags.Value);
            }
            if (AmountWithoutDiscount.Value != 0 || Articles.Count > 0)
            {
              FiscalWriter.AppendTLVInt32((byte)CMPFiscalReceiptTags.AmountWithoutDiscount, (Int32)AmountWithoutDiscount.Value);
              LeveledLog.Message("AmountWithoutDiscount = {0}", AmountWithoutDiscount.Value);
            }
            if (DiscountForAmount.Value != 0)
            {
              FiscalWriter.AppendTLVInt32((byte)CMPFiscalReceiptTags.DiscountForAmount, (Int32)DiscountForAmount.Value);
              LeveledLog.Message("DiscountForAmount = {0}", DiscountForAmount.Value);
            }
            LeveledLog.Message("Payments = {");
            FiscalWriter.AppendTLV((byte)CMPFiscalReceiptTags.Payments, Payments.Serialize(NextLeveledLog));
            LeveledLog.Message("}");
              }

              return FiscalWriter.Bytes;
        }