예제 #1
0
파일: Program.cs 프로젝트: mi1vus/ShtrichFR
 public Program()
 {
     //DriveCacher<CachType>.SetLogger(Logger);
     _driver    = new DrvFR();
     _tlvReader = new TLVReader(_driver);
     _printFull = true;
 }
예제 #2
0
        public static CetSigs ParseFromTLV(TLVReader reader)
        {
            CetSigs cet = new CetSigs();

            using (var r = reader.StartReadRecord())
            {
                if (r.Type != AdaptorSigsTLVType)
                {
                    throw new FormatException("Invalid TLV type, expected adaptor sigs");
                }
                List <AdaptorSignature> sigs = new List <AdaptorSignature>();
                while (!r.IsEnd)
                {
                    sigs.Add(AdaptorSignature.ParseFromTLV(reader));
                }
                cet.OutcomeSigs = sigs.ToArray();
            }
            Span <byte> buf = stackalloc byte[64];

            reader.ReadBytes(buf);
            if (!ECDSASignature.TryParseFromCompact(buf, out var sig))
            {
                throw new FormatException("Invalid DER signature");
            }
            cet.RefundSig = sig;
            return(cet);
        }
예제 #3
0
        public void ReadTLV(TLVReader reader, Network network)
        {
            if (reader.ReadU16() != TLVType)
            {
                throw new FormatException("Invalid TLV type for sign");
            }
            ContractId = reader.ReadUInt256();
            CetSigs    = CetSigs.ParseFromTLV(reader);

            using (var r = reader.StartReadRecord())
            {
                if (r.Type != FundingSignaturesTLVType)
                {
                    throw new FormatException("Invalid TLV type for funding signatures");
                }
                FundingSigs = new List <WitScript>();
                var witnesses = r.ReadU16();
                for (int i = 0; i < witnesses; i++)
                {
                    var elementsCount = reader.ReadU16();
                    var witnessBytes  = new byte[elementsCount][];
                    for (int y = 0; y < elementsCount; y++)
                    {
                        var elementSize = reader.ReadU16();
                        witnessBytes[y] = new byte[elementSize];
                        r.ReadBytes(witnessBytes[y]);
                    }
                    FundingSigs.Add(new WitScript(witnessBytes));
                }
            }
        }
예제 #4
0
        public static Offer ParseFromTLV(TLVReader reader, Network network)
        {
            var offer = new Offer();

            offer.ReadTLV(reader, network);
            return(offer);
        }
예제 #5
0
파일: Extenstions.cs 프로젝트: dgarage/NDLC
        public static Script ReadScript(this TLVReader reader)
        {
            var size = reader.ReadU16();
            var buf  = new byte[size];

            reader.ReadBytes(buf);
            return(Script.FromBytesUnsafe(buf));
        }
예제 #6
0
        public static Accept ParseFromTLV(string hexOrBase64, Network network)
        {
            var bytes  = HexEncoder.IsWellFormed(hexOrBase64) ? Encoders.Hex.DecodeData(hexOrBase64) : Encoders.Base64.DecodeData(hexOrBase64);
            var reader = new TLVReader(new MemoryStream(bytes));
            var accept = new Accept();

            accept.ReadTLV(reader, network);
            return(accept);
        }
예제 #7
0
        public static Sign ParseFromTLV(string hexOrBase64, Network network)
        {
            var bytes  = HexEncoder.IsWellFormed(hexOrBase64) ? Encoders.Hex.DecodeData(hexOrBase64) : Encoders.Base64.DecodeData(hexOrBase64);
            var reader = new TLVReader(new MemoryStream(bytes));
            var sign   = new Sign();

            sign.ReadTLV(reader, network);
            return(sign);
        }
예제 #8
0
        public static Offer ParseFromTLV(string hexOrBase64, Network network)
        {
            var bytes  = HexEncoder.IsWellFormed(hexOrBase64) ? Encoders.Hex.DecodeData(hexOrBase64) : Encoders.Base64.DecodeData(hexOrBase64);
            var reader = new TLVReader(new MemoryStream(bytes));
            var offer  = new Offer();

            offer.ReadTLV(reader, network);
            return(offer);
        }
예제 #9
0
 private ushort GetTLVType(string hexOrBase64)
 {
     try
     {
         var data = HexEncoder.IsWellFormed(hexOrBase64) ? Encoders.Hex.DecodeData(hexOrBase64) : Encoders.Base64.DecodeData(hexOrBase64);
         var r    = new TLVReader(new MemoryStream(data));
         return(r.ReadU16());
     }
     catch
     {
     }
     return(0);
 }
예제 #10
0
        public static AdaptorSignature ParseFromTLV(TLVReader reader)
        {
            Span <byte> output = stackalloc byte[65 + 97];

            reader.ReadBytes(output);
            if (!SecpECDSAAdaptorSignature.TryCreate(output.Slice(0, 65), out var sig))
            {
                throw new FormatException("Invalid adaptor signature");
            }
            if (!SecpECDSAAdaptorProof.TryCreate(output.Slice(65), out var proof))
            {
                throw new FormatException("Invalid adaptor proof");
            }
            return(new AdaptorSignature(sig, proof));
        }
예제 #11
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());
        }
예제 #12
0
        public override T?ReadJson(JsonReader reader, Type objectType, [AllowNull] T?existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            if (reader.TokenType is JsonToken.Null)
            {
                return(null);
            }
            if (!(reader.Value is string))
            {
                return(null);
            }
            var obj    = new T();
            var base64 = (string)reader.Value;
            var bytes  = Encoders.Base64.DecodeData(base64);
            var r      = new TLVReader(new MemoryStream(bytes));

            obj.ReadTLV(r, network);
            return(obj);
        }
예제 #13
0
        public void ReadTLV(TLVReader reader, Network network)
        {
            if (reader.ReadU16() != TLVType)
            {
                throw new FormatException("Invalid TLV type for accept");
            }
            TemporaryContractId = reader.ReadUInt256();
            TotalCollateral     = Money.Satoshis(reader.ReadU64());
            PubKeys             = new PubKeyObject();
            var pk = new byte[33];

            reader.ReadBytes(pk);
            PubKeys.FundingKey    = new PubKey(pk, true);
            PubKeys.PayoutAddress = reader.ReadScript().GetDestinationAddress(network);
            var inputLen = reader.ReadU16();

            FundingInputs = new FundingInput[inputLen];
            for (int i = 0; i < inputLen; i++)
            {
                FundingInputs[i] = FundingInput.ParseFromTLV(reader, network);
            }
            ChangeAddress = reader.ReadScript().GetDestinationAddress(network);
            CetSigs       = CetSigs.ParseFromTLV(reader);
        }
예제 #14
0
        public void ReadTLV(TLVReader reader, Network network)
        {
            if (reader.ReadU16() != TLVType)
            {
                throw new FormatException("Invalid TLV type for offer");
            }
            reader.ReadByte();             // contract_flags
            ChainHash = reader.ReadUInt256();
            if (network.GenesisHash != network.GenesisHash)
            {
                throw new FormatException("Invalid ChainHash");
            }
            Span <byte> buf = stackalloc byte[64];

            using (var ciRecord = reader.StartReadRecord())
            {
                if (ciRecord.Type != TLVContractInfoType)
                {
                    throw new FormatException("Invalid TLV type for contract info");
                }
                List <ContractInfo> cis = new List <ContractInfo>();
                while (!ciRecord.IsEnd)
                {
                    ciRecord.ReadBytes(buf.Slice(0, 32));
                    var sats = ciRecord.ReadU64();
                    cis.Add(new Messages.ContractInfo(new DiscreteOutcome(buf.Slice(0, 32).ToArray()), Money.Satoshis(sats)));
                }
                ContractInfo = cis.ToArray();
            }
            using (var oracleRecord = reader.StartReadRecord())
            {
                if (oracleRecord.Type != TLVOracleInfoType)
                {
                    throw new FormatException("Invalid TLV type for oracle info");
                }
                oracleRecord.ReadBytes(buf.Slice(0, 64));
                OracleInfo = OracleInfo.Create(buf);
            }
            PubKeys = new PubKeyObject();
            reader.ReadBytes(buf.Slice(0, 33));
            PubKeys.FundingKey    = new PubKey(buf.Slice(0, 33).ToArray());
            PubKeys.PayoutAddress = reader.ReadScript().GetDestinationAddress(network);
            if (PubKeys.PayoutAddress is null)
            {
                throw new FormatException("Invalid script");
            }
            TotalCollateral = Money.Satoshis(reader.ReadU64());
            var fiCount             = reader.ReadU16();
            List <FundingInput> fis = new List <FundingInput>();

            while (fiCount > 0)
            {
                fis.Add(FundingInput.ParseFromTLV(reader, network));
                fiCount--;
            }
            FundingInputs = fis.ToArray();
            ChangeAddress = reader.ReadScript().GetDestinationAddress(network);
            if (ChangeAddress is null)
            {
                throw new FormatException("Invalid script");
            }
            FeeRate  = new FeeRate(Money.Satoshis(reader.ReadU64()), 1);
            Timeouts = new Timeouts()
            {
                ContractMaturity = reader.ReadU32(),
                ContractTimeout  = reader.ReadU32()
            };
        }
예제 #15
0
파일: Program.cs 프로젝트: mi1vus/ShtrichFR
        static void Main(string[] args)
        {
            var data = new CachType();

            data.Add(123, new TLVReader.ТЛВОтчет());
            data.Add(456, new TLVReader.ТЛВОтчет());

            if (DriveCacher <CachType> .Serialize(data))
            {
                var data2 = DriveCacher <CachType> .Deserialize();
            }
            var driver = new DrvFR();

            //PrintBar(msg);

            PrintStatus(driver);
            var tlvReader = new TLVReader(driver);

            //var doc = tlvReader.ReadTLVDoc(796/*GetLastDocNumber(driver)*/);

            if (GetStatus(driver) == StateType.ЗакрытаяСмена)
            {
                TestMode(driver, IsTest);
                Open(driver);
            }

            for (int i = 0; i < 1; ++i)
            {
                PrintStatus(driver);
                if (GetStatus(driver) == StateType.ОткрытаяСмена24ЧасаНеКончились)
                {
                    var cash = GetCash(driver);
                    Console.WriteLine($"Наличных в кассе: {cash}");
                    TestMode(driver, IsTest);
                    CashIncome(driver, 10016);
                    TestMode(driver, IsTest);
                    OpenCheck(driver, CheckType.Sale);
                }
                if (GetStatus(driver) == StateType.ОткрытыйДокумент)
                {
                    TestMode(driver, IsTest);
                    Sale(driver, 12.5, 126.58m, 1, $"Супер товар за {126.58m}");
                    Sale(driver, 10, 325.63m, 1, $"Супер товар за {325.63m}");
                    for (int j = 0; j < 2; ++j)
                    {
                        Sale(driver, 5, 36.12m, 1, $"Супер товар за {36.12m}");
                    }

                    decimal roundSumm = ((int)(Summ / 100)) * 100;
                    decimal delta     = (Summ - roundSumm);

                    if (delta > 0)
                    {
                        Discount(driver, delta);
                    }

                    SetCustomerEMail(driver, "*****@*****.**");

                    CloseCheck(driver, Math.Abs(Summ), $"Все хватит :{Math.Abs(Summ)}");
                    tlvReader.ReadTLVDoc(GetLastDocNumber(driver));
                }

                PrintStatus(driver);
                if (GetStatus(driver) == StateType.ОткрытаяСмена24ЧасаНеКончились)
                {
                    TestMode(driver, IsTest);
                    OpenCheck(driver, CheckType.ReturnSale);
                }
                if (GetStatus(driver) == StateType.ОткрытыйДокумент)
                {
                    TestMode(driver, IsTest);
                    for (int j = 0; j < 3; ++j)
                    {
                        ReturnSale(driver, 12.5, 12, 1, $"Супер товар возврат {12}");
                    }

                    PrintStatus(driver);

                    SetCustomerEMail(driver, "*****@*****.**");
                    CloseCheck(driver, Math.Abs(Summ), $"Все хватит :{Math.Abs(Summ)}");
                    tlvReader.ReadTLVDoc(GetLastDocNumber(driver));
                }
            }
            if (GetStatus(driver) == StateType.ОткрытаяСмена24ЧасаНеКончились)
            {
                TestMode(driver, IsTest);

                var cash = GetCash(driver);
                Console.WriteLine($"Наличных в кассе: {cash}");
                CashOutcome(driver, cash);
            }
            if (GetStatus(driver) == StateType.ОткрытаяСмена24ЧасаНеКончились)
            {
                TestMode(driver, IsTest);
                PrintReport(driver);
                PrintStatus(driver);

                TestMode(driver, IsTest);
                Close(driver);

                //for (int i = 666; i < 667; ++i)
                //{
                //doc = tlvReader.ReadTLVDoc(GetLastDocNumber(driver));
                //}

                TestMode(driver, IsTest);
                PrintCheck(driver, _testMsg, "01012323454567678989", BarcodePosition.Top);
            }

            Console.WriteLine($"Решение: {driver.ResultCode}, {driver.ResultCodeDescription}");
            Console.ReadLine();
        }
        /*private void LeveledLog.Message(string Message)
        {
          const byte Level = 4;
          SessionLog.Message("".PadLeft(Level * 2) + Message);
        }
        private void LeveledLog.Message(string Message, params object[] Arguments)
        {
          LeveledLog.Message(string.Format(Message, Arguments));
        }*/
        public void Deserialize(byte[] Data, LeveledFileLogger LeveledLog)
        {
            byte Tag = 0;
              byte[] Value = null;

              TLVReader ArticleReader = new TLVReader(Data);
              while (ArticleReader.NextValue(out Tag, out Value))
            switch ((OCPFiscalArticleTags)Tag)
            {
              case OCPFiscalArticleTags.GoodsCode:
            GoodsCode = TLVReader.ValueToString(Value, EncodingName);
            LeveledLog.Message("GoodsCode = '{0}'", GoodsCode);
            break;
              case OCPFiscalArticleTags.Quantity:
            Quantity.Receive(TLVReader.ValueToInt32(Value));
            LeveledLog.Message("Quantity = {0}", Quantity.Value);
            break;
              case OCPFiscalArticleTags.PriceWithoutDiscount:
            PriceWithoutDiscount.Receive(TLVReader.ValueToUInt32(Value));
            LeveledLog.Message("PriceWithoutDiscount = {0}", PriceWithoutDiscount.Value);
            break;
              case OCPFiscalArticleTags.AmountWithoutDiscount:
            AmountWithoutDiscount.Receive(TLVReader.ValueToInt32(Value));
            LeveledLog.Message("AmountWithoutDiscount = {0}", AmountWithoutDiscount.Value);
            break;
              case OCPFiscalArticleTags.GoodsName:
            GoodsName = TLVReader.ValueToString(Value, EncodingName);
            LeveledLog.Message("GoodsName = '{0}'", GoodsName);
            break;
              case OCPFiscalArticleTags.Flags:
            Flags.Receive((FiscalArticleFlags)TLVReader.ValueToByte(Value));
            LeveledLog.Message("Flags = {0} {1}", Flags.Value, (int)Flags.Value);
            break;
              case OCPFiscalArticleTags.DiscountForPrice:
            DiscountForPriceCurrent.Receive(TLVReader.ValueToInt32(Value));
            LeveledLog.Message("DiscountForPrice = {0}", DiscountForPriceCurrent.Value);
            break;
              case OCPFiscalArticleTags.DiscountForAmount:
            DiscountForAmount.Receive(TLVReader.ValueToInt32(Value));
            LeveledLog.Message("DiscountForAmount = {0}", DiscountForAmount.Value);
            break;
              case OCPFiscalArticleTags.Bonuses:
            Bonuses.Receive(TLVReader.ValueToInt32(Value));
            LeveledLog.Message("Bonuses = {0}", Bonuses.Value);
            break;
              case OCPFiscalArticleTags.PaymentType:
            paymentType.Receive((PaymentTypes)TLVReader.ValueToByte(Value));
            LeveledLog.Message("PaymentType = {0} ({1})", paymentType.Value, (int)paymentType.Value);
            break;
              case OCPFiscalArticleTags.MeasureUnit:
            MeasureUnit = Functions.LimitString(TLVReader.ValueToString(Value, EncodingName), 8).ToLower();
            LeveledLog.Message("MeasureUnit = '{0}'", MeasureUnit);
            break;
              case OCPFiscalArticleTags.QuantityPrecision:
            QuantityPrecision = TLVReader.ValueToByte(Value);
            LeveledLog.Message("QuantityPrecision = {0}", QuantityPrecision);
            if (QuantityPrecision < 0 || QuantityPrecision > 3)
              Fiscal.ErrorMessage.Add("Неверное значение QuantityPrecision = {0}", QuantityPrecision);
            break;
              default:
            throw new Exception(string.Format("Unknown tag 0x{0:X} received", Tag));
            }
        }
        // parse TLV for fiscal receipt
        internal void Deserialize(byte[] Data, LeveledFileLogger LeveledLog)
        {
            var NextLeveledLog = LeveledLog.CloneNextLevel();
              PaymentsReceived = false;

              byte Tag = 0;
              byte[] Value = null;
              TLVReader FiscalReader = new TLVReader(Data);
              while (FiscalReader.NextValue(out Tag, out Value))
            switch ((CMPFiscalReceiptTags)Tag)
            {
              case CMPFiscalReceiptTags.Article: // может быть несколько позиций чека
            FiscalArticle Article = new FiscalArticle(this);
            LeveledLog.Message("Article = {");
            Article.Deserialize(Value, NextLeveledLog); // в артикуле у нас все полученные значения
            LeveledLog.Message("}");
            this.Articles.Add(Article);
            break;
              case CMPFiscalReceiptTags.Flags:
            Flags.Receive((FiscalReceiptFlags)TLVReader.ValueToByte(Value));
            LeveledLog.Message("Flags = {0} ({1})", Flags.Value, (int)Flags.Value);
            break;
              case CMPFiscalReceiptTags.AmountWithoutDiscount:
            AmountWithoutDiscount.Receive(TLVReader.ValueToInt32(Value));
            LeveledLog.Message("AmountWithoutDiscount = {0}", AmountWithoutDiscount.Value);
            break;
              case CMPFiscalReceiptTags.DiscountForAmount:
            DiscountForAmount.Receive(TLVReader.ValueToInt32(Value));
            LeveledLog.Message("DiscountForAmount = {0}", DiscountForAmount.Value);
            break;
              case CMPFiscalReceiptTags.Payments: // performed payments
            LeveledLog.Message("Payments = {");
            Payments.Deserialize(Value, NextLeveledLog);
            LeveledLog.Message("}");
            PaymentsReceived = true;
            break;
              default:
            throw new Exception(string.Format("Unknown tag 0x{0:X} received", Tag));
            }
        }