Beispiel #1
0
        /// <summary>
        /// Executes the <paramref name="actions"/> step by step, and emits
        /// <see cref="ActionEvaluation"/> for each step.
        /// </summary>
        /// <param name="blockHash">The <see cref="Block{T}.Hash"/> of <see cref="Block{T}"/> that
        /// <paramref name="actions"/> belongs to.</param>
        /// <param name="blockIndex">The <see cref="Block{T}.Index"/> of <see cref="Block{T}"/> that
        /// <paramref name="actions"/> belongs to.</param>
        /// <param name="txid">The <see cref="Transaction{T}.Id"/> of <see cref="Transaction{T}"/>
        /// that <paramref name="actions"/> belongs to.  This can be <c>null</c> on rehearsal mode
        /// or if an action is a <see cref="IBlockPolicy{T}.BlockAction"/>.</param>
        /// <param name="previousStates">The states immediately before <paramref name="actions"/>
        /// being executed.  Note that its <see cref="IAccountStateDelta.UpdatedAddresses"/> are
        /// remained to the returned next states.</param>
        /// <param name="minerAddress">An address of block miner.</param>
        /// <param name="signer">Signer of the <paramref name="actions"/>.</param>
        /// <param name="signature"><see cref="Transaction{T}"/> signature used to generate random
        /// seeds.</param>
        /// <param name="actions">Actions to evaluate.</param>
        /// <param name="rehearsal">Pass <c>true</c> if it is intended
        /// to be dry-run (i.e., the returned result will be never used).
        /// The default value is <c>false</c>.</param>
        /// <param name="previousBlockStatesTrie">The trie to contain states at previous block.
        /// </param>
        /// <param name="blockAction">Pass <c>true</c> if it is
        /// <see cref="IBlockPolicy{T}.BlockAction"/>.</param>
        /// <returns>Enumerates <see cref="ActionEvaluation"/>s for each one in
        /// <paramref name="actions"/>.  The order is the same to the <paramref name="actions"/>.
        /// Note that each <see cref="IActionContext.Random"/> object
        /// has a unconsumed state.
        /// </returns>
        internal static IEnumerable <ActionEvaluation> EvaluateActionsGradually(
            BlockHash blockHash,
            long blockIndex,
            TxId?txid,
            IAccountStateDelta previousStates,
            Address minerAddress,
            Address signer,
            byte[] signature,
            IImmutableList <IAction> actions,
            bool rehearsal = false,
            ITrie previousBlockStatesTrie = null,
            bool blockAction = false)
        {
            ActionContext CreateActionContext(
                IAccountStateDelta prevStates,
                int randomSeed
                ) =>
            new ActionContext(
                signer: signer,
                miner: minerAddress,
                blockIndex: blockIndex,
                previousStates: prevStates,
                randomSeed: randomSeed,
                rehearsal: rehearsal,
                previousBlockStatesTrie: previousBlockStatesTrie,
                blockAction: blockAction
                );

            byte[] hashedSignature;
            using (var hasher = SHA1.Create())
            {
                hashedSignature = hasher.ComputeHash(signature);
            }

            byte[] blockHashBytes = blockHash.ToByteArray();
            int    seed           =
                (blockHashBytes.Length > 0 ? BitConverter.ToInt32(blockHashBytes, 0) : 0) ^
                (signature.Any() ? BitConverter.ToInt32(hashedSignature, 0) : 0);

            IAccountStateDelta states = previousStates;
            Exception          exc    = null;
            ILogger            logger = Log.ForContext <ActionEvaluation>();

            foreach (IAction action in actions)
            {
                ActionContext      context    = CreateActionContext(states, seed);
                IAccountStateDelta nextStates = context.PreviousStates;
                try
                {
                    DateTimeOffset actionExecutionStarted = DateTimeOffset.Now;
                    nextStates = action.Execute(context);
                    TimeSpan spent = DateTimeOffset.Now - actionExecutionStarted;
                    logger.Verbose($"{action} execution spent {spent.TotalMilliseconds} ms.");
                }
                catch (Exception e)
                {
                    if (rehearsal)
                    {
                        var msg =
                            $"The action {action} threw an exception during its " +
                            "rehearsal.  It is probably because the logic of the " +
                            $"action {action} is not enough generic so that it " +
                            "can cover every case including rehearsal mode.\n" +
                            "The IActionContext.Rehearsal property also might be " +
                            "useful to make the action can deal with the case of " +
                            "rehearsal mode.\n" +
                            "See also this exception's InnerException property.";
                        exc = new UnexpectedlyTerminatedActionException(
                            null, null, null, null, action, msg, e
                            );
                    }
                    else
                    {
                        var stateRootHash = context.PreviousStateRootHash;
                        var msg           =
                            $"The action {action} (block #{blockIndex} {blockHash}, tx {txid}, " +
                            $"state root hash {stateRootHash}) threw an exception " +
                            "during execution.  See also this exception's InnerException property.";
                        logger.Error("{Message}\nInnerException: {ExcMessage}", msg, e.Message);
                        exc = new UnexpectedlyTerminatedActionException(
                            blockHash, blockIndex, txid, stateRootHash, action, msg, e
                            );
                    }
                }

                // As IActionContext.Random is stateful, we cannot reuse
                // the context which is once consumed by Execute().
                ActionContext equivalentContext = CreateActionContext(states, seed);

                yield return(new ActionEvaluation(
                                 action,
                                 equivalentContext,
                                 nextStates,
                                 exc
                                 ));

                states = nextStates;
                unchecked
                {
                    seed++;
                }
            }
        }
 private static BlockHash H(string h) => BlockHash.FromString(h);
 public BlockHeaderMessage(byte[][] dataFrames)
 {
     GenesisHash      = new BlockHash(dataFrames[0]);
     HeaderDictionary = (Bencodex.Types.Dictionary)Codec.Decode(dataFrames[1]);
 }
Beispiel #4
0
        protected StoreFixture(IAction blockAction = null)
        {
            Path = null;

            Scheme = string.Empty;

            StoreChainId = Guid.NewGuid();

            Address1 = new Address(new byte[]
            {
                0x45, 0xa2, 0x21, 0x87, 0xe2, 0xd8, 0x85, 0x0b, 0xb3, 0x57,
                0x88, 0x69, 0x58, 0xbc, 0x3e, 0x85, 0x60, 0x92, 0x9c, 0xcc,
            });
            Address2 = new Address(new byte[]
            {
                0x55, 0xa2, 0x21, 0x87, 0xe2, 0xd8, 0x85, 0x0b, 0xb3, 0x57,
                0x88, 0x69, 0x58, 0xbc, 0x3e, 0x85, 0x60, 0x92, 0x9c, 0xdd,
            });
            Address3 = new Address(new byte[]
            {
                0xa3, 0x4b, 0x0c, 0x91, 0xda, 0x58, 0xd4, 0x73, 0xd3, 0x70,
                0xc4, 0x5b, 0xf9, 0x6f, 0x6d, 0x98, 0xa5, 0x01, 0xd9, 0x22,
            });
            Address4 = new Address(new byte[]
            {
                0xbf, 0x78, 0x67, 0x29, 0xba, 0x04, 0x1b, 0xa7, 0x6f, 0xfb,
                0xa0, 0x6c, 0x8c, 0x4d, 0xc1, 0x24, 0xee, 0x3e, 0x8c, 0x8b,
            });
            Address5 = new Address(new byte[]
            {
                0x03, 0xf0, 0x42, 0x7f, 0x2e, 0x6c, 0x0f, 0x5f, 0xdb, 0xd3,
                0x77, 0x9d, 0xb2, 0x84, 0xd6, 0x1b, 0x04, 0x38, 0xdf, 0xb6,
            });
            TxId1 = new TxId(new byte[]
            {
                0x45, 0xa2, 0x21, 0x87, 0xe2, 0xd8, 0x85, 0x0b, 0xb3, 0x57,
                0x88, 0x69, 0x58, 0xbc, 0x3e, 0x85, 0x60, 0x92, 0x9c, 0xcc,
                0x88, 0x69, 0x58, 0xbc, 0x3e, 0x85, 0x60, 0x92, 0x9c, 0xcc,
                0x9c, 0xcc,
            });
            TxId2 = new TxId(new byte[]
            {
                0x45, 0xa2, 0x21, 0x87, 0xe2, 0xd8, 0x85, 0x0b, 0xb3, 0x57,
                0x88, 0x69, 0x58, 0xbc, 0x3e, 0x85, 0x60, 0x92, 0x9c, 0xcc,
                0x88, 0x69, 0x58, 0xbc, 0x3e, 0x85, 0x60, 0x92, 0x9c, 0xcc,
                0x9c, 0xdd,
            });
            TxId3 = new TxId(new byte[]
            {
                0x45, 0xa2, 0x21, 0x87, 0xe2, 0xd8, 0x85, 0x0b, 0xb3, 0x57,
                0x88, 0x69, 0x58, 0xbc, 0x3e, 0x85, 0x60, 0x92, 0x9c, 0xcc,
                0x88, 0x69, 0x58, 0xbc, 0x3e, 0x85, 0x60, 0x92, 0x9c, 0xcc,
                0x9c, 0xee,
            });
            Hash1 = new BlockHash(new byte[]
            {
                0x45, 0xa2, 0x21, 0x87, 0xe2, 0xd8, 0x85, 0x0b, 0xb3, 0x57,
                0x88, 0x69, 0x58, 0xbc, 0x3e, 0x85, 0x60, 0x92, 0x9c, 0xcc,
                0x88, 0x69, 0x58, 0xbc, 0x3e, 0x85, 0x60, 0x92, 0x9c, 0xcc,
                0x9c, 0xcc,
            });
            Hash2 = new BlockHash(new byte[]
            {
                0x45, 0xa2, 0x21, 0x87, 0xe2, 0xd8, 0x85, 0x0b, 0xb3, 0x57,
                0x88, 0x69, 0x58, 0xbc, 0x3e, 0x85, 0x60, 0x92, 0x9c, 0xcc,
                0x88, 0x69, 0x58, 0xbc, 0x3e, 0x85, 0x60, 0x92, 0x9c, 0xcc,
                0x9c, 0xdd,
            });
            Hash3 = new BlockHash(new byte[]
            {
                0x45, 0xa2, 0x21, 0x87, 0xe2, 0xd8, 0x85, 0x0b, 0xb3, 0x57,
                0x88, 0x69, 0x58, 0xbc, 0x3e, 0x85, 0x60, 0x92, 0x9c, 0xcc,
                0x88, 0x69, 0x58, 0xbc, 0x3e, 0x85, 0x60, 0x92, 0x9c, 0xcc,
                0x9c, 0xee,
            });

            var stateStore      = new TrieStateStore(new MemoryKeyValueStore());
            var stateRootHashes = new Dictionary <BlockHash, HashDigest <SHA256> >();
            Func <BlockHash?, HashDigest <SHA256>?> rootHashGetter = bh =>
                                                                     bh is BlockHash h && stateRootHashes.TryGetValue(h, out HashDigest <SHA256> rh)
                    ? rh
                    : (HashDigest <SHA256>?)null;

            Miner        = TestUtils.GenesisMiner;
            GenesisBlock = TestUtils.MineGenesis <DumbAction>(
                GetHashAlgorithm,
                Miner.PublicKey
                ).Evaluate(Miner, blockAction, stateStore);
            stateRootHashes[GenesisBlock.Hash] = GenesisBlock.StateRootHash;
            Block1 = TestUtils.MineNextBlock(GenesisBlock, GetHashAlgorithm, miner: Miner);
            stateRootHashes[Block1.Hash] = Block1.StateRootHash;
            Block2 = TestUtils.MineNextBlock(Block1, GetHashAlgorithm, miner: Miner);
            stateRootHashes[Block2.Hash] = Block2.StateRootHash;
            Block3 = TestUtils.MineNextBlock(Block2, GetHashAlgorithm, miner: Miner);
            stateRootHashes[Block3.Hash] = Block3.StateRootHash;

            Transaction1 = MakeTransaction(new List <DumbAction>(), ImmutableHashSet <Address> .Empty);
            Transaction2 = MakeTransaction(new List <DumbAction>(), ImmutableHashSet <Address> .Empty);
            Transaction3 = MakeTransaction(new List <DumbAction>(), ImmutableHashSet <Address> .Empty);
        }
Beispiel #5
0
 public bool Parse(BlockHash bh, SignedBlock sb, string extrinsic)
 {
     throw new System.NotImplementedException();
 }
Beispiel #6
0
 public void PutTxIdBlockHashIndex(TxId txId, BlockHash blockHash)
 {
     Log(nameof(PutTxIdBlockHashIndex), txId, blockHash);
     _store.PutTxIdBlockHashIndex(txId, blockHash);
 }
Beispiel #7
0
 public void SetBlockPerceivedTime(BlockHash blockHash, DateTimeOffset perceivedTime)
 {
     Log(nameof(SetBlockPerceivedTime), blockHash, perceivedTime);
     _store.SetBlockPerceivedTime(blockHash, perceivedTime);
 }
Beispiel #8
0
 public void SetBlockPerceivedTime(BlockHash blockHash, DateTimeOffset perceivedTime) =>
 _store.SetBlockPerceivedTime(blockHash, perceivedTime);
Beispiel #9
0
 /// <inheritdoc cref="IStore.GetBlockIndex(BlockHash)"/>
 public long?GetBlockIndex(BlockHash blockHash)
 {
     return(_store.GetBlockIndex(blockHash));
 }
Beispiel #10
0
 /// <inheritdoc cref="IStore.ForkBlockIndexes(Guid, Guid, BlockHash)"/>
 public void ForkBlockIndexes(
     Guid sourceChainId,
     Guid destinationChainId,
     BlockHash branchpoint
     ) =>
 _store.ForkBlockIndexes(sourceChainId, destinationChainId, branchpoint);
Beispiel #11
0
 /// <inheritdoc cref="IStore.GetBlock{T}(BlockHash)"/>
 public Block <T> GetBlock <T>(BlockHash blockHash)
     where T : IAction, new()
 {
     return(_store.GetBlock <T>(blockHash));
 }
Beispiel #12
0
 /// <inheritdoc cref="IStore.AppendIndex(Guid, BlockHash)"/>
 public long AppendIndex(Guid chainId, BlockHash hash) =>
 _store.AppendIndex(chainId, hash);
Beispiel #13
0
 /// <inheritdoc cref="IStore.ContainsBlock(BlockHash)"/>
 public bool ContainsBlock(BlockHash blockHash) =>
 _blockCache.ContainsKey(blockHash) || _store.ContainsBlock(blockHash);
Beispiel #14
0
 /// <inheritdoc cref="IStore.DeleteBlock(BlockHash)"/>
 public bool DeleteBlock(BlockHash blockHash)
 {
     _blockCache.Remove(blockHash);
     return(_store.DeleteBlock(blockHash));
 }
Beispiel #15
0
 public bool ContainsBlock(BlockHash blockHash)
 {
     Log(nameof(ContainsBlock), blockHash);
     return(_store.ContainsBlock(blockHash));
 }
Beispiel #16
0
 public DateTimeOffset?GetBlockPerceivedTime(BlockHash blockHash)
 {
     return(_store.GetBlockPerceivedTime(blockHash));
 }
Beispiel #17
0
 public TxExecution GetTxExecution(BlockHash blockHash, TxId txid)
 {
     Log(nameof(GetTxExecution), blockHash, txid);
     return(_store.GetTxExecution(blockHash, txid));
 }
Beispiel #18
0
 public DateTimeOffset?GetBlockPerceivedTime(BlockHash blockHash)
 {
     Log(nameof(GetBlockPerceivedTime), blockHash);
     return(_store.GetBlockPerceivedTime(blockHash));
 }
Beispiel #19
0
 public void DeleteTxIdBlockHashIndex(TxId txId, BlockHash blockHash)
 {
     Log(nameof(DeleteTxIdBlockHashIndex), txId, blockHash);
     _store.DeleteTxIdBlockHashIndex(txId, blockHash);
 }
Beispiel #20
0
 public Block <T> GetBlock <T>(HashAlgorithmGetter hashAlgorithmGetter, BlockHash blockHash)
     where T : IAction, new()
 {
     Log(nameof(GetBlock), blockHash);
     return(_store.GetBlock <T>(hashAlgorithmGetter, blockHash));
 }
Beispiel #21
0
 public bool ContainsBlockStates(BlockHash blockHash)
 {
     Log(nameof(ContainsBlockStates), blockHash);
     return(_stateStore.ContainsBlockStates(blockHash));
 }
Beispiel #22
0
 public long?GetBlockIndex(BlockHash blockHash)
 {
     Log(nameof(GetBlockIndex), blockHash);
     return(_store.GetBlockIndex(blockHash));
 }
Beispiel #23
0
        protected override void DoTest()
        {
            OpenDocument("Rat_plasma.sky");

            RunUI(SkylineWindow.ShowAuditLog);
            var auditLogForm = WaitForOpenForm <AuditLogForm>();

            Assert.IsFalse(SkylineWindow.Document.Settings.DataSettings.AuditLogging);
            RunUI(() => auditLogForm.EnableAuditLogging(true));

            // Test that initial hash is correct
            var expectedHash = BlockHash.SafeToBase64(new byte[]
            {
                0xFE, 0x0F, 0x0C, 0x54,
                0xA0, 0x77, 0xE5, 0x8F,
                0x77, 0xDC, 0x8B, 0xEE,
                0x44, 0xB6, 0x65, 0x6D,
                0x98, 0x31, 0xAA, 0x35
            });
            var actualHash = GetDocumentHash();

            Assert.AreEqual(expectedHash, actualHash);

            // Test that the hash is the same as if the document was simply read and hashed
            // The document is really small (<20KB) so it's fine to read it all into memory
            var bytes = File.ReadAllBytes(SkylineWindow.DocumentFilePath);
            var hash  = Hash(bytes);

            Assert.AreEqual(expectedHash, hash);

            // Make sure that there's an entry describing 1) number of nodes and 2) settings changes from default settings
            Assert.AreEqual(1, SkylineWindow.Document.AuditLog.AuditLogEntries.Count);

            if (!RecordNewestEntry())
            {
                RunUI(() => { LOG_ENTRY_MESSAGES[0].AssertEquals(SkylineWindow.Document.AuditLog.AuditLogEntries); });
            }

            // Modify and save the document so that the audit log gets saved
            ChangeSettings(settings => settings.ChangePeptideFilter(filter => filter.ChangeExcludeNTermAAs(3))); // Change from 2 to 3

            RunUI(() => SkylineWindow.SaveDocument());

            RecordNewestEntry();

            Assert.IsTrue(File.Exists(SrmDocument.GetAuditLogPath(SkylineWindow.DocumentFilePath)), "Audit log does not exist after saving document");
            AssertEx.ValidateAuditLogAgainstSchema(File.ReadAllText(SrmDocument.GetAuditLogPath(SkylineWindow.DocumentFilePath)));

            // Also validate an old document
            AssertEx.ValidateAuditLogAgainstSchema(File.ReadAllText(TestFilesDir.GetTestPath("old_rat_plasma.skyl")));

            // Modify document outside of skyline
            var docPath = SkylineWindow.DocumentFilePath;

            RunUI(() => SkylineWindow.NewDocument(true));

            // Audit logging should be enabled since the previous settings will be used
            Assert.IsTrue(SkylineWindow.Document.Settings.DataSettings.AuditLogging);

            // Perform the following action manually:
            // Settings > Peptide Settings -- Filter > Exclude N-Terminal AA's changed from "3" to "4"

            var text = File.ReadAllText(docPath);

            var match = Regex.Match(text, "<peptide_filter .*start=\"3\"");

            Assert.IsTrue(match.Success);
            Assert.IsFalse(match.NextMatch().Success);
            var sb = new StringBuilder(text);

            sb[match.Index + match.Length - 2] = '4';

            File.WriteAllText(docPath, sb.ToString());

            var oldRef = SkylineWindow.Document;

            // Add an entry describing this change
            OpenDocumentNoWait("Rat_plasma.sky");
            var alert = WaitForOpenForm <AlertDlg>();

            OkDialog(alert, alert.ClickYes);
            var logForm = WaitForOpenForm <DocumentChangeLogEntryDlg>();

            RunUI(() => { logForm.LogMessage = "Changed Exlude N-Terminal AA's from 3 to 4 manually"; });
            OkDialog(logForm, logForm.OkDialog);
            // Wait until document gets switched, otherwise WaitForDocumentLoaded will think that the document is already loaded
            // since we're not waiting for the document to open (OpenDocumentNoWait)
            WaitForCondition(() => !ReferenceEquals(oldRef, SkylineWindow.Document));
            Assert.AreNotEqual(expectedHash, SkylineWindow.Document.DocumentHash); // If this wasn't the case the dialogs would never show up, but check anyways
            WaitForDocumentLoaded();
            RunUI(() => SkylineWindow.SaveDocument());                             // Save so that hash in audit log matches document now

            // Now audit logging should be enabled
            Assert.IsTrue(SkylineWindow.Document.Settings.DataSettings.AuditLogging);

            // Make sure the entry was actually added
            Assert.AreEqual(3, SkylineWindow.Document.AuditLog.AuditLogEntries.Count);

            // Check that this entry got saved and read correctly, we don't record here
            if (!IsRecordMode)
            {
                RunUI(() => { LOG_ENTRY_MESSAGES[1].AssertEquals(SkylineWindow.Document.AuditLog.AuditLogEntries.Parent); });
            }

            if (!RecordNewestEntry())
            {
                RunUI(() => { LOG_ENTRY_MESSAGES[2].AssertEquals(SkylineWindow.Document.AuditLog.AuditLogEntries); });
            }

            var fasta = FastaImporter.ToFasta(PROTEINLIST_CLIPBOARD_TEXT, TextUtil.SEPARATOR_TSV);

            RunDlg <EmptyProteinsDlg>(() => SkylineWindow.Paste(fasta), dlg => dlg.KeepEmptyProteins());

            if (!RecordNewestEntry())
            {
                RunUI(() => { LOG_ENTRY_MESSAGES[3].AssertEquals(SkylineWindow.Document.AuditLog.AuditLogEntries); });
            }

            RunUI(SkylineWindow.ShowAuditLog);
            var auditLogForm1 = WaitForOpenForm <AuditLogForm>();

            RunUI(() => auditLogForm1.ChooseView(AuditLogStrings.AuditLogForm_MakeAuditLogForm_Undo_Redo));
            AuditLogUtil.WaitForAuditLogForm(auditLogForm1);

            // Show extra info for this entry
            RunDlg <AuditLogExtraInfoForm>(() =>
            {
                Assert.AreEqual(4, auditLogForm1.DataGridView.RowCount);
                var fastaRow    = auditLogForm1.DataGridView.Rows[0];
                var undoRedoCol = auditLogForm1.FindColumn(nameof(AuditLogRow.UndoRedoMessage));
                Assert.IsNotNull(undoRedoCol);
                var auditLogRowText = fastaRow.Cells[undoRedoCol.Index].Value as AuditLogRow.AuditLogRowText;
                Assert.IsNotNull(auditLogRowText);
                var col = auditLogForm1.DataGridView.Columns[undoRedoCol.Index] as AuditLogColumn;
                Assert.IsNotNull(col);
                Assert.IsTrue(col.ShouldDisplay(auditLogRowText, (int)AuditLogColumn.ImageIndex.extra_info));
                col.Click(auditLogRowText, (int)AuditLogColumn.ImageIndex.extra_info);
            }, form =>
            {
                var entry = SkylineWindow.DocumentUI.AuditLog.AuditLogEntries;
                Assert.AreEqual(form.Message, entry.UndoRedo.ToString());
                Assert.AreEqual(form.ExtraInfo, entry.ExtraInfo);
                form.OkDialog();
            });

            // Disable audit logging, this should warn the user
            RunDlg <AlertDlg>(() => { auditLogForm1.EnableAuditLogging(false); }, alertDlg => { alertDlg.ClickYes(); });
            AuditLogUtil.WaitForAuditLogForm(auditLogForm1);
            Assert.AreEqual(0, SkylineWindow.Document.AuditLog.AuditLogEntries.Count);
            Assert.IsFalse(SkylineWindow.Document.Settings.DataSettings.AuditLogging);

            // Re-open document without saving
            RunUI(() => SkylineWindow.NewDocument(true));

            OpenDocument("Rat_plasma.sky");
            RunUI(SkylineWindow.ShowAuditLog);
            var auditLogForm2 = WaitForOpenForm <AuditLogForm>();

            RunUI(() => auditLogForm2.ChooseView(AuditLogStrings.AuditLogForm_MakeAuditLogForm_Undo_Redo));
            AuditLogUtil.WaitForAuditLogForm(auditLogForm2);
            RunUI(() =>
            {
                // Audit logging shold be back on and the entries should still be there
                Assert.IsTrue(SkylineWindow.DocumentUI.Settings.DataSettings.AuditLogging);
                Assert.AreEqual(3, SkylineWindow.DocumentUI.AuditLog.AuditLogEntries.Count);
            });

            // Disable again, this time save
            RunDlg <AlertDlg>(() => { auditLogForm2.EnableAuditLogging(false); }, alertDlg => { alertDlg.ClickYes(); });
            RunUI(() => SkylineWindow.SaveDocument());
            // audit log should be gone
            Assert.IsFalse(File.Exists(SrmDocument.GetAuditLogPath(SkylineWindow.DocumentFilePath)));
        }
Beispiel #24
0
 public BlockDigest?GetBlockDigest(BlockHash blockHash)
 {
     Log(nameof(GetBlockDigest), blockHash);
     return(_store.GetBlockDigest(blockHash));
 }
Beispiel #25
0
        public BlockQuery()
        {
            Field <NonNullGraphType <ListGraphType <NonNullGraphType <BlockType <T> > > > >(
                "blocks",
                arguments: new QueryArguments(
                    new QueryArgument <BooleanGraphType>
            {
                Name         = "desc",
                DefaultValue = false,
            },
                    new QueryArgument <IntGraphType>
            {
                Name         = "offset",
                DefaultValue = 0,
            },
                    new QueryArgument <IntGraphType> {
                Name = "limit"
            },
                    new QueryArgument <BooleanGraphType>
            {
                Name         = "excludeEmptyTxs",
                DefaultValue = false,
            },
                    new QueryArgument <AddressType> {
                Name = "miner"
            }
                    ),
                resolve: context =>
            {
                bool desc            = context.GetArgument <bool>("desc");
                long offset          = context.GetArgument <long>("offset");
                int?limit            = context.GetArgument <int?>("limit", null);
                bool excludeEmptyTxs = context.GetArgument <bool>("excludeEmptyTxs");
                Address?miner        = context.GetArgument <Address?>("miner", null);
                return(Query <T> .ListBlocks(desc, offset, limit, excludeEmptyTxs, miner));
            }
                );

            Field <BlockType <T> >(
                "block",
                arguments: new QueryArguments(
                    new QueryArgument <IdGraphType> {
                Name = "hash"
            },
                    new QueryArgument <IdGraphType> {
                Name = "index"
            }
                    ),
                resolve: context =>
            {
                string hash = context.GetArgument <string>("hash");
                long?index  = context.GetArgument <long?>("index", null);

                if (!(hash is null ^ index is null))
                {
                    throw new GraphQL.ExecutionError(
                        "The parameters hash and index are mutually exclusive; " +
                        "give only one at a time.");
                }

                if (hash is string hashNotNull)
                {
                    return(Query <T> .GetBlockByHash(BlockHash.FromString(hashNotNull)));
                }

                if (index is long indexNotNull)
                {
                    return(Query <T> .GetBlockByIndex(indexNotNull));
                }

                throw new GraphQL.ExecutionError("Unexpected block query");
            }
Beispiel #26
0
 public long AppendIndex(Guid chainId, BlockHash hash)
 {
     Log(nameof(AppendIndex), chainId, hash);
     return(_store.AppendIndex(chainId, hash));
 }
 public BlockHeaderMessage(BlockHash genesisHash, BlockHeader header)
 {
     GenesisHash      = genesisHash;
     HeaderDictionary = header.MarshalBlockHeader();
 }
Beispiel #28
0
 public bool DeleteBlock(BlockHash blockHash)
 {
     Log(nameof(DeleteBlock), blockHash);
     return(_store.DeleteBlock(blockHash));
 }
Beispiel #29
0
        public bool Parse(BlockHash bh, SignedBlock sb, string extrinsic)
        {
            var parse = extrinsic;

            parse = parse.Substring(2);
            var t1 = Scale.DecodeCompactInteger(ref parse);

            // delimiter
            Scale.NextByte(ref parse);
            Scale.NextByte(ref parse);

            // 32 * 2
            var senderPublic = parse.Substring(0, 64);

            parse = parse.Substring(64);
            sk    = senderPublic;
            var era = Scale.NextByte(ref parse);

            var signature = parse.Substring(0, 128);

            parse = parse.Substring(128);

            var err = Scale.DecodeCompactInteger(ref parse).Value;

            var nonce = Scale.DecodeCompactInteger(ref parse).Value;

            Scale.NextByte(ref parse);

            bool   result = false;
            string moduleName = string.Empty, methodName = string.Empty;

            var moduleInd = Scale.NextByte(ref parse);
            var methodInd = Scale.NextByte(ref parse);

            FunctionCallArgV8[] paramsInfo = null;

            // try parse transaction if catch exception that transaction is not supported
            try
            {
                paramsInfo = _metadata.GetModuleCallParamsByIds(moduleInd, methodInd);
                var r1 = _metadata.GetModuleCallNameByIds(moduleInd, methodInd);
                moduleName = r1.Item1;
                methodName = r1.Item2;
                if (moduleName.Equals("Staking", StringComparison.InvariantCultureIgnoreCase) &&
                    methodName.Equals("withdraw_unbonded", StringComparison.InvariantCultureIgnoreCase))
                {
                    result = true;
                }
            }
            catch (Exception)
            {
                return(false);
            }

            _pex = new ExtrinsicInfo
            {
                BlockNumber  = (int)sb.Block.Header.Number,
                BlockHash    = bh.Hash,
                Raw          = extrinsic,
                ModuleIndex  = moduleInd,
                ModuleName   = moduleName,
                MethodIndex  = methodInd,
                MethodName   = methodName,
                Nonce        = nonce,
                ExtrinsicEra = 0,
                Signature    = signature,
                Status       = err,
                Params       = parse,
                Unknown      = result,
                ParamsInfo   = paramsInfo
            };

            return(result);
        }
Beispiel #30
0
 public BlockHeader(ulong number, BlockHash parentHash, Hash transactionsHash)
 {
     this.number           = number;
     this.parentHash       = parentHash;
     this.transactionsHash = transactionsHash;
 }