public async Task CanWriteReadAndDeleteContainer()
        {
            var sut       = CreateAzureBlobRdDataStorage(out var metadataStorage);
            var dataType  = nameof(DataBlob);
            var id        = "BlobStorageTestBlob";
            var dataBlob  = new DataBlob(id, new byte[] { 0x42, 0x43, 0x44 }, "myFile.bin");
            var payload   = DataEncoder.Encode(JsonConvert.SerializeObject(dataBlob));
            var submitter = "jdoe";
            var utcNow    = DateTime.UtcNow;
            var container = new GenericDataContainer(id, submitter, utcNow, submitter, utcNow, ApiVersion.Current, payload);

            if (await sut.ExistsAsync(dataType, id))
            {
                await sut.DeleteDataContainerAsync(dataType, id);
            }

            IdReservationResult idReservation = null;

            Assert.That(async() => idReservation = await sut.ReserveIdAsync(dataType, id, submitter), Throws.Nothing);
            Assert.That(idReservation.IsReserved, Is.True);

            Assert.That(() => sut.StoreAsync(dataType, container, true), Throws.Nothing);
            metadataStorage.Setup(x => x.GetFromIdAsync(dataType, id)).Returns(Task.FromResult(container));
            Assert.That(await sut.ExistsAsync(dataType, id), Is.True);

            GenericDataContainer retreivedContainer = null;

            Assert.That(async() => retreivedContainer = await sut.GetFromIdAsync(dataType, id), Throws.Nothing);
            Assert.That(retreivedContainer, Is.Not.Null);

            Assert.That(async() => await sut.DeleteDataContainerAsync(dataType, id), Throws.Nothing);
            metadataStorage.Setup(x => x.GetFromIdAsync(dataType, id)).Returns(Task.FromResult(default(GenericDataContainer)));
            Assert.That(await sut.ExistsAsync(dataType, id), Is.False);
        }
Ejemplo n.º 2
0
        public void TestWireDecodeTransaction()
        {
            var actual      = DataDecoder.DecodeTransaction(null, TRANSACTION_1_BYTES.ToArray());
            var actualBytes = DataEncoder.EncodeTransaction(actual).TxBytes;

            CollectionAssert.AreEqual(TRANSACTION_1_BYTES.ToList(), actualBytes.ToList());
        }
Ejemplo n.º 3
0
 /// <summary>
 /// 压缩Json并保存
 /// </summary>
 /// <param name="FilePath"></param>
 /// <param name="JsonStr"></param>
 /// <returns></returns>
 private bool ZipStringAndSave(string FilePath, string JsonStr)
 {
     try
     {
         if (File.Exists(FilePath))
         {
             File.Delete(FilePath);
         }
         FileStream _FileStream = new FileStream(FilePath, FileMode.CreateNew);
         try
         {
             if (!string.IsNullOrEmpty(JsonStr) && JsonStr.Length > 0)
             {
                 string tempEncoder = DataEncoder.GZipCompressString(JsonStr);
                 byte[] temp        = System.Text.Encoding.UTF8.GetBytes(tempEncoder);
                 _FileStream.Write(temp, 0, temp.Length);
                 _FileStream.Flush();
                 _FileStream.Close();
                 _FileStream = null;
             }
         }
         catch (Exception exf)
         {
             _FileStream.Close();
             _FileStream = null;
             throw exf;
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
     return(false);
 }
Ejemplo n.º 4
0
        public IEnumerable <KeyValuePair <TxOutputKey, TxOutput> > UnspentOutputs()
        {
            Api.JetBeginTransaction2(this.jetSession, BeginTransactionGrbit.ReadOnly);
            try
            {
                //Api.JetSetCurrentIndex(this.jetSession, this.unspentTxOutputsTableId, "IX_TxOutputKey");
                Api.MoveBeforeFirst(this.jetSession, this.unspentTxOutputsTableId);
                while (Api.TryMoveNext(this.jetSession, this.unspentTxOutputsTableId))
                {
                    var txOutputKey   = DataEncoder.DecodeTxOutputKey(Api.RetrieveColumn(this.jetSession, this.unspentTxOutputsTableId, this.txOutputKeyColumnId));
                    var txOutputBytes = Api.RetrieveColumn(this.jetSession, this.unspentTxOutputsTableId, this.txOutputSmallColumnId);
                    if (txOutputBytes == null)
                    {
                        txOutputBytes = Api.RetrieveColumn(this.jetSession, this.unspentTxOutputsTableId, this.txOutputLargeColumnId);
                    }
                    var txOutput = DataEncoder.DecodeTxOutput(txOutputBytes);

                    yield return(new KeyValuePair <TxOutputKey, TxOutput>(txOutputKey, txOutput));
                }
            }
            finally
            {
                Api.JetCommitTransaction(this.jetSession, CommitTransactionGrbit.LazyFlush);
            }
        }
Ejemplo n.º 5
0
        public bool TryAddChainedHeader(ChainedHeader chainedHeader)
        {
            var key = MakeHeaderKey(chainedHeader.Hash);

            Slice existingValue;

            if (db.TryGet(ReadOptions.Default, key, out existingValue))
            {
                return(false);
            }

            var writeBatch = new WriteBatch();

            try
            {
                writeBatch.Put(key, DataEncoder.EncodeChainedHeader(chainedHeader));
                writeBatch.Put(MakeTotalWorkKey(chainedHeader.Hash, chainedHeader.TotalWork), new byte[1]);

                db.Write(WriteOptions.Default, writeBatch);
            }
            finally
            {
                writeBatch.Dispose();
            }

            return(true);
        }
Ejemplo n.º 6
0
        public void RoundtripPreservesData()
        {
            var sut       = new BinaryDataObjectSplitter(nameof(DataBlob.Data));
            var id        = IdGenerator.FromGuid();
            var dataBlob  = new DataBlob(id, new byte[] { 0x42, 0x43, 0x44 }, "myFile.bin");
            var payload   = DataEncoder.Encode(JsonConvert.SerializeObject(dataBlob));
            var utcNow    = DateTime.UtcNow;
            var container = new GenericDataContainer(id, "jdoe", utcNow, "jdoe", utcNow, "1.5.9", payload);
            BinaryDataObjectSplitterResult result = null;

            Assert.That(() => result = sut.Split(container), Throws.Nothing);
            Assert.That(result, Is.Not.Null);
            Assert.That(result.BinaryData, Is.EqualTo(dataBlob.Data));
            var containerWithoutBinaryData = result.ContainerWithoutBinaryData;

            Assert.That(containerWithoutBinaryData.Id, Is.EqualTo(container.Id));
            Assert.That(containerWithoutBinaryData.Submitter, Is.EqualTo(container.Submitter));
            Assert.That(containerWithoutBinaryData.SubmissionTimeUtc, Is.EqualTo(container.SubmissionTimeUtc));
            Assert.That(containerWithoutBinaryData.ApiVersion, Is.EqualTo(container.ApiVersion));
            Assert.That(containerWithoutBinaryData.Data, Is.Not.Null);
            Assert.That(containerWithoutBinaryData.Data.GetValue(nameof(DataBlob.Data)), Is.EqualTo(BsonString.Empty));

            var reconstructedContainer = sut.Reassemble(containerWithoutBinaryData, result.BinaryData);

            Assert.That(reconstructedContainer.Id, Is.EqualTo(container.Id));
            Assert.That(reconstructedContainer.Submitter, Is.EqualTo(container.Submitter));
            Assert.That(reconstructedContainer.SubmissionTimeUtc, Is.EqualTo(container.SubmissionTimeUtc));
            Assert.That(reconstructedContainer.ApiVersion, Is.EqualTo(container.ApiVersion));
            Assert.That(reconstructedContainer.Data, Is.Not.Null);
            var reconstructedDataBlob = JsonConvert.DeserializeObject <DataBlob>(reconstructedContainer.Data.ToJson());

            Assert.That(reconstructedDataBlob.Id, Is.EqualTo(dataBlob.Id));
            Assert.That(reconstructedDataBlob.Filename, Is.EqualTo(dataBlob.Filename));
            Assert.That(reconstructedDataBlob.Data, Is.EqualTo(dataBlob.Data));
        }
Ejemplo n.º 7
0
        public bool TryRemoveUnspentTx(UInt256 txHash)
        {
            if (!this.inTransaction)
            {
                throw new InvalidOperationException();
            }

            Api.JetSetCurrentIndex(this.jetSession, this.unspentTxTableId, "IX_TxHash");
            Api.MakeKey(this.jetSession, this.unspentTxTableId, DbEncoder.EncodeUInt256(txHash), MakeKeyGrbit.NewKey);
            if (Api.TrySeek(this.jetSession, this.unspentTxTableId, SeekGrbit.SeekEQ))
            {
                var addedBlockIndex = Api.RetrieveColumnAsInt32(this.jetSession, this.unspentTxTableId, this.blockIndexColumnId).Value;
                var txIndex         = Api.RetrieveColumnAsInt32(this.jetSession, this.unspentTxTableId, this.txIndexColumnId).Value;
                var outputStates    = DataEncoder.DecodeOutputStates(Api.RetrieveColumn(this.jetSession, this.unspentTxTableId, this.outputStatesColumnId));

                Api.JetDelete(this.jetSession, this.unspentTxTableId);

                // decrease unspent tx count
                Api.EscrowUpdate(this.jetSession, this.globalsTableId, this.unspentTxCountColumnId, -1);

                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 8
0
        public WebRequest ToWebRequest(IClient client)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }
            //Make a request
            WebRequest request = WebRequest.Create(GetUri(client));

            request.Method = "GET";
            if (Type == RequestType.Activate)
            {
                request.Method      = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                using (Stream requestStream = request.GetRequestStream())
                {
                    using (var writer = new StreamWriter(requestStream))
                    {
                        writer.Write(string.Format("{1}={0}&",
                                                   DataEncoder.ToString(client.GetCertificateExports()),
                                                   "cert"));
                        writer.Write(string.Format("{1}={0}", DataEncoder.ToString(LicenseKey),
                                                   "lid"));
                    }
                }
            }
            return(request);
        }
Ejemplo n.º 9
0
 public string ToOfflineData()
 {
     using (var memoryStream = new MemoryStream())
     {
         using (var writer = new BinaryWriter(memoryStream))
         {
             var header = (byte)((byte)Type << 7 | ClientId.Length);
             writer.Write(header);
             writer.Write(ClientId);
             if (Type == RequestType.Activate)
             {
                 //Write cert and license data
                 writer.Write((ushort)Certificate.Length);
                 writer.Write(Certificate);
                 if (LicenseKey.Length > 0)
                 {
                     writer.Write((ushort)LicenseKey.Length);
                     writer.Write(LicenseKey);
                 }
             }
             var data       = memoryStream.ToArray();
             var signBuffer = RSASigner.GetSignBuffer(data, new[] { HashSecret.GetSecret() });
             writer.Write(SHA512.Create().ComputeHash(signBuffer));
             return(DataEncoder.ToHexString(memoryStream.ToArray()));
         }
     }
 }
Ejemplo n.º 10
0
        public SpentTransactionsStorage(string baseDirectory)
            : base(baseDirectory, "SpentTransactions",
                   keyPairs =>
        {
            using (var stream = new MemoryStream())
            {
                foreach (var keyPair in keyPairs)
                {
                    DataEncoder.EncodeUInt256(stream, keyPair.Key);
                    DataEncoder.EncodeSpentTx(stream, keyPair.Value);
                }

                return(stream.ToArray());
            }
        },
                   (blockHash, bytes) =>
        {
            using (var stream = new MemoryStream(bytes))
            {
                var keyPairs = ImmutableList.CreateBuilder <KeyValuePair <UInt256, SpentTx> >();

                while (stream.Position < stream.Length)
                {
                    var txHash  = DataEncoder.DecodeUInt256(stream);
                    var spentTx = DataEncoder.DecodeSpentTx(stream);

                    keyPairs.Add(new KeyValuePair <UInt256, SpentTx>(txHash, spentTx));
                }

                return(keyPairs.ToImmutable());
            }
        })
        { }
        public WriteBatch CreateWriteBatch()
        {
            var writeBatch = new WriteBatch();

            try
            {
                foreach (var update in updates)
                {
                    var txIndex     = update.Key;
                    var blockTxNode = update.Value;

                    var key = DbEncoder.EncodeBlockHashTxIndex(blockHash, txIndex);
                    if (blockTxNode != null)
                    {
                        writeBatch.Put(key, DataEncoder.EncodeBlockTxNode(blockTxNode));
                    }
                    else
                    {
                        writeBatch.Delete(key);
                    }
                }

                return(writeBatch);
            }
            catch (Exception)
            {
                writeBatch.Dispose();
                throw;
            }
        }
Ejemplo n.º 12
0
 public UpOrderPacker(string simnum)
 {
     this.simnum  = simnum;
     this.encoder = new DataEncoder();
     this.decoder = new DataDecoder();
     this.orderID = (ushort)DateTime.Now.Millisecond;
 }
Ejemplo n.º 13
0
        public ChainedHeader FindMaxTotalWork()
        {
            using (var handle = this.cursorCache.TakeItem())
            {
                var cursor = handle.Item;

                Api.JetSetCurrentIndex(cursor.jetSession, cursor.blockHeadersTableId, "IX_TotalWork");

                // IX_TotalWork is in reverse order, so higher total work comes first
                if (Api.TryMoveFirst(cursor.jetSession, cursor.blockHeadersTableId))
                {
                    do
                    {
                        // check if this block is valid
                        var valid = Api.RetrieveColumnAsBoolean(cursor.jetSession, cursor.blockHeadersTableId, cursor.blockHeaderValidColumnId);
                        if (valid == null || valid.Value)
                        {
                            // decode chained header with most work and return
                            var chainedHeader = DataEncoder.DecodeChainedHeader(Api.RetrieveColumn(cursor.jetSession, cursor.blockHeadersTableId, cursor.blockHeaderBytesColumnId));
                            return(chainedHeader);
                        }
                    } while (Api.TryMoveNext(cursor.jetSession, cursor.blockHeadersTableId));
                }

                // no valid chained header found
                return(null);
            }
        }
Ejemplo n.º 14
0
        public bool TryAddBlockUnmintedTxes(UInt256 blockHash, IImmutableList <UnmintedTx> unmintedTxes)
        {
            CheckWriteTransaction();

            try
            {
                using (SetSessionContext())
                    using (var jetUpdate = this.jetSession.BeginUpdate(this.unmintedTxTableId, JET_prep.Insert))
                    {
                        byte[] unmintedTxesBytes;
                        using (var stream = new MemoryStream())
                            using (var writer = new BinaryWriter(stream))
                            {
                                writer.WriteList(unmintedTxes, unmintedTx => DataEncoder.EncodeUnmintedTx(writer, unmintedTx));
                                unmintedTxesBytes = stream.ToArray();
                            }

                        Api.SetColumns(this.jetSession, this.unmintedTxTableId,
                                       new BytesColumnValue {
                            Columnid = this.unmintedBlockHashColumnId, Value = DbEncoder.EncodeUInt256(blockHash)
                        },
                                       new BytesColumnValue {
                            Columnid = this.unmintedDataColumnId, Value = unmintedTxesBytes
                        });

                        jetUpdate.Save();
                    }

                return(true);
            }
            catch (EsentKeyDuplicateException)
            {
                return(false);
            }
        }
Ejemplo n.º 15
0
        public static LicenseInfo Deserialize(string serialized)
        {
            var info = new LicenseInfo();

            try
            {
                var doc = XDocument.Parse(serialized).Root;
                info.Issued   = DateTime.FromFileTimeUtc(long.Parse(doc.Element("issued").Value));
                info.ValidTo  = DateTime.FromFileTimeUtc(long.Parse(doc.Element("valid").Value));
                info.Features = doc.Element("params").Elements("feature").ToDictionary(x => x.Attribute("name").Value,
                                                                                       y => y.Attribute("value").Value);
                info.Limits = doc.Element("params").Elements("limit").ToDictionary(x => x.Attribute("name").Value,
                                                                                   y => y.Attribute("value").Value);
                info.CodeExecutionChain = doc.Element("params").Elements("execute").ToDictionary(x => x.Attribute("entry").Value,
                                                                                                 y => DataEncoder.FromString(y.Value));

                info.CustomValidators =
                    doc.Element("params").Elements("validate").Select(x => DataEncoder.FromString(x.Value)).ToList();
                //Try execute
                foreach (var codeExec in info.CodeExecutionChain)
                {
                    var asembly      = Assembly.Load(codeExec.Value);
                    var typeToCreate = asembly.GetType(codeExec.Key, true);
                    Activator.CreateInstance(typeToCreate);
                }
            }
            catch (Exception e)
            {
                throw new LicenseValidationException("Can't parse", e);
            }
            return(info);
        }
Ejemplo n.º 16
0
        public bool TryAddUnspentTxOutput(TxOutputKey txOutputKey, TxOutput txOutput)
        {
            CheckWriteTransaction();

            using (SetSessionContext())
            {
                try
                {
                    using (var jetUpdate = this.jetSession.BeginUpdate(this.unspentTxOutputTableId, JET_prep.Insert))
                    {
                        Api.SetColumns(this.jetSession, this.unspentTxOutputTableId,
                                       new BytesColumnValue {
                            Columnid = this.txOutputKeyColumnId, Value = DbEncoder.EncodeTxOutputKey(txOutputKey)
                        },
                                       new BytesColumnValue {
                            Columnid = this.txOutputBytesColumnId, Value = DataEncoder.EncodeTxOutput(txOutput)
                        });

                        jetUpdate.Save();
                    }

                    return(true);
                }
                catch (EsentKeyDuplicateException)
                {
                    return(false);
                }
            }
        }
Ejemplo n.º 17
0
        public bool TryAddBlockSpentTxes(int blockIndex, BlockSpentTxes spentTxes)
        {
            CheckWriteTransaction();

            try
            {
                using (SetSessionContext())
                    using (var jetUpdate = this.jetSession.BeginUpdate(this.spentTxTableId, JET_prep.Insert))
                    {
                        byte[] spentTxesBytes;
                        using (var stream = new MemoryStream())
                            using (var writer = new BinaryWriter(stream))
                            {
                                writer.WriteList <SpentTx>(spentTxes, spentTx => DataEncoder.EncodeSpentTx(writer, spentTx));
                                spentTxesBytes = stream.ToArray();
                            }

                        Api.SetColumns(this.jetSession, this.spentTxTableId,
                                       new Int32ColumnValue {
                            Columnid = this.spentSpentBlockIndexColumnId, Value = blockIndex
                        },
                                       new BytesColumnValue {
                            Columnid = this.spentDataColumnId, Value = spentTxesBytes
                        });

                        jetUpdate.Save();
                    }

                return(true);
            }
            catch (EsentKeyDuplicateException)
            {
                return(false);
            }
        }
Ejemplo n.º 18
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jObject = JObject.Load(reader);

            //var jObject = reader.Value as JObject;
            return(DataEncoder.Encode(jObject?.ToString()));
        }
Ejemplo n.º 19
0
        public bool TryAddHeader(ChainedHeader header)
        {
            CheckWriteTransaction();

            try
            {
                using (SetSessionContext())
                    using (var jetUpdate = this.jetSession.BeginUpdate(this.headersTableId, JET_prep.Insert))
                    {
                        Api.SetColumns(this.jetSession, this.headersTableId,
                                       new BytesColumnValue {
                            Columnid = this.headerBlockHashColumnId, Value = DbEncoder.EncodeUInt256(header.Hash)
                        },
                                       new BytesColumnValue {
                            Columnid = this.headerBytesColumnId, Value = DataEncoder.EncodeChainedHeader(header)
                        });

                        jetUpdate.Save();
                    }

                return(true);
            }
            catch (EsentKeyDuplicateException)
            {
                return(false);
            }
        }
Ejemplo n.º 20
0
        public SpentOutputsStorage(string baseDirectory)
            : base(baseDirectory, "SpentOutputs",
                   keyPairs =>
        {
            using (var stream = new MemoryStream())
            {
                foreach (var keyPair in keyPairs)
                {
                    DataEncoder.EncodeTxOutputKey(stream, keyPair.Key);
                    DataEncoder.EncodeTxOutput(stream, keyPair.Value);
                }

                return(stream.ToArray());
            }
        },
                   (blockHash, bytes) =>
        {
            using (var stream = new MemoryStream(bytes))
            {
                var keyPairs = ImmutableList.CreateBuilder <KeyValuePair <TxOutputKey, TxOutput> >();
                while (stream.Position < stream.Length)
                {
                    var txOutputKey = DataEncoder.DecodeTxOutputKey(stream);
                    var txOutput    = DataEncoder.DecodeTxOutput(stream);
                    keyPairs.Add(new KeyValuePair <TxOutputKey, TxOutput>(txOutputKey, txOutput));
                }

                return(keyPairs.ToImmutable());
            }
        })
        { }
Ejemplo n.º 21
0
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var bsonDocument = value as BsonDocument;
            var json         = DataEncoder.DecodeToJson(bsonDocument);

            writer.WriteRawValue(json);
        }
    private static void WriteFile(string path)
    {
        string[] channels = { "up", "down", "top", "bottom", "charm", "strange" };
        var      rand     = new Random(123456);

        int totalPoints = 0, totalChannels = 0;

        using (var encoder = new DataEncoder(path, "My file"))
        {
            for (int i = 0; i < 100; i++)
            {
                var channel = new Channel {
                    Name = channels[rand.Next(channels.Length)]
                };
                int count = rand.Next(1, 50);
                var data  = new List <float>(count);
                for (int j = 0; j < count; j++)
                {
                    data.Add((float)rand.NextDouble());
                }
                channel.Points = data;
                encoder.AddChannel(channel);
                totalPoints += count;
                totalChannels++;
            }
        }

        Console.WriteLine("Wrote: {0} points in {1} channels; {2} bytes", totalPoints, totalChannels, new FileInfo(path).Length);
    }
Ejemplo n.º 23
0
        public void NormalOutputTest(CodeState state, byte expectedByte)
        {
            var output = new DataEncoder().EncodeUseCodeResponse(state);

            Assert.AreEqual(1, output.Length);
            Assert.AreEqual(expectedByte, output[0]);
        }
Ejemplo n.º 24
0
        public override int Read(byte[] buffer, int offset, int count)
        {
            while (
                unreadBytes.Count < count &&
                this.unspentTransactions.MoveNext()
                )
            {
                var unspentTx = this.unspentTransactions.Current;
                unreadBytes.AddRange(DataEncoder.EncodeUnspentTx(unspentTx));
            }

            var available = unreadBytes.Count;

            if (available >= count)
            {
                unreadBytes.CopyTo(0, buffer, offset, count);
                unreadBytes.RemoveRange(0, count);
                this.totalBytes += count;
                return(count);
            }
            else
            {
                unreadBytes.CopyTo(0, buffer, offset, available);
                unreadBytes.Clear();
                this.totalBytes += available;
                return(available);
            }
        }
Ejemplo n.º 25
0
        public bool TryGetOutput(TxOutputKey txOutputKey, out TxOutput txOutput)
        {
            Api.JetBeginTransaction2(this.jetSession, BeginTransactionGrbit.ReadOnly);
            try
            {
                //Api.JetSetCurrentIndex(this.jetSession, this.unspentTxOutputsTableId, "IX_TxOutputKey");
                Api.MakeKey(this.jetSession, this.unspentTxOutputsTableId, DataEncoder.EncodeTxOutputKey(txOutputKey), MakeKeyGrbit.NewKey);
                if (Api.TrySeek(this.jetSession, this.unspentTxOutputsTableId, SeekGrbit.SeekEQ))
                {
                    var txOutputBytes = Api.RetrieveColumn(this.jetSession, this.unspentTxOutputsTableId, this.txOutputSmallColumnId);
                    if (txOutputBytes == null)
                    {
                        txOutputBytes = Api.RetrieveColumn(this.jetSession, this.unspentTxOutputsTableId, this.txOutputLargeColumnId);
                    }

                    txOutput = DataEncoder.DecodeTxOutput(txOutputBytes);
                    return(true);
                }
                else
                {
                    txOutput = default(TxOutput);
                    return(false);
                }
            }
            finally
            {
                Api.JetCommitTransaction(this.jetSession, CommitTransactionGrbit.LazyFlush);
            }
        }
Ejemplo n.º 26
0
        public bool TryGetTransaction(UInt256 txHash, out UnspentTx unspentTx)
        {
            Api.JetBeginTransaction2(this.jetSession, BeginTransactionGrbit.ReadOnly);
            try
            {
                //Api.JetSetCurrentIndex(this.jetSession, this.unspentTxTableId, "IX_TxHash");
                Api.MakeKey(this.jetSession, this.unspentTxTableId, txHash.ToByteArray(), MakeKeyGrbit.NewKey);
                if (Api.TrySeek(this.jetSession, this.unspentTxTableId, SeekGrbit.SeekEQ))
                {
                    var confirmedBlockHash = new UInt256(Api.RetrieveColumn(this.jetSession, this.unspentTxTableId, this.confirmedBlockHashColumnId));
                    var outputStates       = DataEncoder.DecodeOutputStates(Api.RetrieveColumn(this.jetSession, this.unspentTxTableId, this.outputStatesColumnId));

                    unspentTx = new UnspentTx(confirmedBlockHash, outputStates);
                    return(true);
                }
                else
                {
                    unspentTx = default(UnspentTx);
                    return(false);
                }
            }
            finally
            {
                Api.JetCommitTransaction(this.jetSession, CommitTransactionGrbit.LazyFlush);
            }
        }
Ejemplo n.º 27
0
        public BlockHeader MineBlockHeader(BlockHeader blockHeader, UInt256 hashTarget)
        {
            var blockHeaderBytes = DataEncoder.EncodeBlockHeader(blockHeader);

            var hashTargetBytes = hashTarget.ToByteArray();

            var start      = 0;
            var finish     = UInt32.MaxValue;
            var total      = 0L;
            var nonceIndex = 76;
            var minedNonce = (UInt32?)null;

            this.logger.Debug("Starting mining: {0}".Format2(DateTime.Now.ToString("hh:mm:ss")));

            var stopwatch = Stopwatch.StartNew();

            Parallel.For(
                start, finish,
                new ParallelOptions {
                MaxDegreeOfParallelism = Environment.ProcessorCount * 2
            },
                () => new LocalMinerState(blockHeaderBytes),
                (nonceLong, loopState, localState) =>
            {
                localState.total++;

                var nonce      = (UInt32)nonceLong;
                var nonceBytes = Bits.GetBytes(nonce);
                Buffer.BlockCopy(nonceBytes, 0, localState.headerBytes, nonceIndex, 4);

                var headerBytes = localState.headerBytes;
                var sha256      = localState.sha256;
                var hashBytes   = sha256.ComputeDoubleHash(headerBytes);

                if (BytesCompareLE(hashBytes, hashTargetBytes) < 0)
                {
                    minedNonce = nonce;
                    loopState.Stop();
                }

                return(localState);
            },
                localState => { Interlocked.Add(ref total, localState.total); });

            stopwatch.Stop();

            var hashRate = ((float)total / 1000 / 1000) / ((float)stopwatch.ElapsedMilliseconds / 1000);

            if (minedNonce != null)
            {
                this.logger.Debug("Found block in {0} hh:mm:ss at Nonce {1}, Hash Rate: {2} mHash/s, Total Hash Attempts: {3}, Found Hash: {4}".Format2(stopwatch.Elapsed.ToString(@"hh\:mm\:ss"), minedNonce, hashRate, total.ToString("#,##0"), blockHeader.With(Nonce: minedNonce).Hash));
                return(blockHeader.With(Nonce: minedNonce));
            }
            else
            {
                this.logger.Debug("No block found in {0} hh:mm:ss, Hash Rate: {1} mHash/s, Total Hash Attempts: {2}, Found Hash: {3}".Format2(stopwatch.Elapsed.ToString(@"hh\:mm\:ss"), hashRate, total.ToString("#,##0"), blockHeader.With(Nonce: minedNonce).Hash));
                return(null);
            }
        }
Ejemplo n.º 28
0
        public async Task SendBlock(Block block)
        {
            await Task.Yield();

            var sendBlockMessage = Messaging.ConstructMessage("block", DataEncoder.EncodeBlock(block));

            await SendMessageAsync(sendBlockMessage);
        }
Ejemplo n.º 29
0
        public async Task SendTransaction(Transaction transaction)
        {
            await Task.Yield();

            var sendTxMessage = Messaging.ConstructMessage("tx", DataEncoder.EncodeTransaction(transaction));

            await SendMessageAsync(sendTxMessage);
        }
Ejemplo n.º 30
0
        private byte[] GetCallbackDescriptionFrame(Message message)
        {
            var entryCount = (ushort)message.CallbackPoint.Count();
            var offset     = GetCallbacksStartFrame(message);

            return(DataEncoder.Combine(offset, entryCount, FramesPerCallbackEntry)
                   .GetBytes());
        }